Compare commits

..

17 Commits

Author SHA1 Message Date
63f1aa8125 release alpha2 2024-03-27 02:36:13 +02:00
3c8bf1baf1 test cases update 2024-03-27 02:30:08 +02:00
3f20aa8878 massive qml edit 2024-03-27 01:45:35 +02:00
4fcea42e8e qml improvements 2024-03-26 15:41:34 +02:00
0b2b58bd33 gpu support 2024-03-26 10:39:09 +02:00
7b60e8a42f disablle deskttop soourec 2024-03-25 15:31:42 +02:00
161ff64293 Release 4.0.0 2024-03-25 14:04:30 +02:00
115bef3dbe correct subscription processing 2024-03-24 00:42:03 +02:00
b6ade7310a extend temperature sensors 2024-03-23 15:30:35 +02:00
0555185044 add time source 2024-03-23 15:11:49 +02:00
23e197789f make it build together 2024-03-23 13:57:28 +02:00
67640cccdc do not derive from qwidget in aggregates 2024-03-22 16:57:47 +02:00
33a41bb6c0 do not derive from qwidget 2024-03-21 16:51:29 +02:00
42c11a6b60 port dataengin 2024-03-20 18:45:17 +02:00
423597dbd9 port widget to dbus 2024-03-15 15:51:23 +02:00
0fcfb7d7e4 port library 2024-03-08 16:22:00 +02:00
5fd3a4a21a update to plasma 6 support 2024-03-07 12:09:46 +02:00
232 changed files with 4688 additions and 3052 deletions

View File

@ -2,11 +2,9 @@ name: build & tests
on:
push:
branches:
- master
branches: [ development, master ]
pull_request:
branches:
- master
branches: [ development, master ]
env:
BUILD_TYPE: Release
@ -26,7 +24,7 @@ jobs:
- uses: actions/checkout@v3
- name: create build environment
run: pacman -Syu --noconfirm base-devel cmake extra-cmake-modules python util-linux-libs xorg-server-xvfb
run: pacman -Sy --noconfirm base-devel cmake extra-cmake-modules python util-linux-libs xorg-server-xvfb
- name: install dependencies
run: pacman -S --noconfirm plasma-workspace

View File

@ -6,20 +6,27 @@ for more details. To avoid manual labor there is automatic cmake target named
`clangformat` (see below). Some additional detail see below.
* Indent is only spaces. 4 spaces.
* Any private variable should start with `m_` prefix (`m_foo`). The only one exception is `Ui` object which should be named as `ui`.
* Any private variable should start with `m_` prefix (`m_foo`). The only one
exception is `Ui` object which should be named as `ui`.
* Avoid to create a large methods. Exception: if method contains lambda functions.
* If some method is called only once, it is recommended to use lambda functions.
Exception is `Q_INVOKABLE` methods.
* STL containers are not recommended, use Qt ones instead.
* In other hand Qt specific variables types (`qint`, `qfloat`, etc) are not recommended.
* In other hand Qt specific variables types (`qint`, `qfloat`, etc) are not
recommended.
* Do not repeat yourself ([DRY](https://en.wikipedia.org/wiki/Don't_repeat_yourself)).
* Headers declaration:
* Include only those headers which are strictly necessary inside headers. Use forward class declaration instead. Exception is base class header declaration.
* In a`*.cpp` file header declaration should have the following order separated by a new line in the alphabet order:
* Include only those headers which are strictly necessary inside headers. Use
forward class declaration instead. Exception is base class header declaration.
* In a`*.cpp` file header declaration should have the following order separated
by a new line in the alphabet order:
1. Class header.
2. KDE specific headers.
3. Qt specific headers.
4. Third party headers.
5. Project headers.
* Any header should have `#pragma once`.
* Any header should have [include guard](https://en.wikipedia.org/wiki/Include_guard)
named as `CLASSNAMECAPS_H`
* If any `#if` directive is used condition should be mentioned in `#endif`:
```
@ -29,60 +36,80 @@ for more details. To avoid manual labor there is automatic cmake target named
```
* `Q_PROPERTY` macro is allowed and recommended for QObject based classes.
* Qt macros (e.g. `signals`, `slots`, `Q_OBJECT`, etc) are allowed. In other hand `Q_FOREACH` (`foreach`) is not allowed use `for (auto &foo : bar)` instead.
* Current project standard is **C++23**.
* Qt macros (e.g. `signals`, `slots`, `Q_OBJECT`, etc) are allowed. In other hand
`Q_FOREACH` (`foreach`) is not allowed use `for (auto &foo : bar)` instead.
* Current project standard is **C++17**.
* Do not use C-like code:
* C-like style iteration if possible. Use `for (auto &foo : bar)` and `std::for_each` instead if possible. It is also recommended to use iterators.
* C-like casts, use `const_cast`, `static_cast`, `dymanic_Cast` instead. Using of `reinterpret_cast` is not recommended. It is highly recommended to use `dynamic_cast` with the exception catching. It is also possible to use `qvariant_cast` if required.
* C-like style iteration if possible. Use `for (auto &foo : bar)` and
`std::for_each` instead if possible. It is also recommended to use iterators.
* C-like casts, use `const_cast`, `static_cast`, `dymanic_Cast` instead. Using
of `reinterpret_cast` is not recommended. It is highly recommended to use
`dynamic_cast` with the exception catching. It is also possible to use
`qvariant_cast` if required.
* C-like `NULL`, use `nullptr` instead.
* C-like constant definition, use `static const vartype foo = bar` definition instead.
* C-like constant definition, use `const vartype foo = bar` definition instead.
* Abstract classes (which have at least one pure virtual method) are allowed.
* Templates are allowed and recommended. Templates usually should be described inside header not source code file.
* Hardcode is not recommended. But it is possible to use cmake variables to configure some items during build time.
* Templates are allowed and recommended. Templates usually should be described
inside header not source code file.
* Hardcode is not recommended. But it is possible to use cmake variables to
configure some items during build time.
* Build should not require any additional system variable declaration/changing.
* Any line should not end with space.
* Do not hesitate move public methods to private one if possible.
* Do not hesitate use `const` modifier. In other hand `volatile` modifier is not recommended.
* Do not hesitate use `const` modifier. In other hand `volatile` modifier is not
recommended.
* New lines rules:
* One line after license header.
* One line between header group declaration (see above).
* Two lines after header declaration and before declaration at the end of a file.
* Two lines after header declaration and before declaration at the end of a
file.
* One line after class and types forward declarations in headers.
* One line before each method modifiers (`public`, `public slots`, etc).
* Two lines between methods inside source code (`*.cpp`).
* One line after `qCDebug()` information (see below).
* One line inside a method to improve code reading.
* Each destructor should be virtual.
* Class constructor should have default arguments. Use `QObject *_parent` property for QObject based classes.
* Class constructor should have default arguments. Use `QObject *parent` property
for QObject based classes.
* QObject based classes constructors should have explicit modifier.
* Create one file (source and header) per class.
* `else if` construction is allowed and recommended.
* 'true ? foo : bar' construction is allowed and recommended for one-line assignment.
* Any global pointer should be assigned to `nullptr` after deletion and before initialization. Exception: if object is deleted into class destructor.
* Any global pointer should be assign to `nullptr` after deletion and before
initialization. Exception: if object is deleted into class destructor.
* Do not use semicolon in qml files unless it is required.
* Any method argument including class constructors should start with `_`.
Comments
--------
Please do not hesitate to use comments inside source code (especially in non-obvious blocks). Comments also may use the following keywords:
Please do not hesitate to use comments inside source code (especially in non-obvious
blocks). Comments also may use the following keywords:
* **TODO** - indicates that some new code should be implemented here later. Please note that usually these methods should be implemented before the next release.
* **TODO** - indicates that some new code should be implemented here later. Please
note that usually these methods should be implemented before the next release.
* **FIXME** - some dirty hacks and/or methods which should be done better.
* **HACK** - hacks inside code which requires to avoid some restrictions and/or which adds additional non-obvious optimizations.
* **HACK** - hacks inside code which requires to avoid some restrictions and/or
which adds additional non-obvious optimizations.
Do not use dots at the end of the comment line.
Development
-----------
* Officially the latest libraries versions should be used. In addition, it is possible to add workarounds for all versions (usually by using preprocessor directives); in this case patches should be placed to `packages` directory.
* Officially the latest libraries versions should be used. In addition it is
possible to add workarounds for all versions (usually by using preprocessor
directives); in this case patches should be placed to `packages` directory.
* Build should not contain any warning.
* Try to minimize message in Release build with logging disabled. It is highly recommended to fix KDE/Qt specific warning if possible
* Do not use dependency to KDE libraries if there are no any strictly necessary. Exceptions are KNotification and KI18n libraries.
* Try to minimize message in Release build with logging disabled. It is highly
recommended to fix KDE/Qt specific warning if possible
* Do not use dependency to KDE libraries if there are no any strictly necessary.
Exceptions are KNotification and KI18n libraries.
* It is highly recommended to use submodules for third party libraries if possible.
* The main branch is **master**.
* For experimental features development new branch `feature/foo` creation is allowed and recommended.
* The main branch is **development**. Changes in this branch may be merged to the
master one only if it is a 'stable' build.
* For experimental features development new branch `feature-foo` creation is allowed
and recommended.
* Experimental features should be added inside `BUILD_FUTURE` definition:
```
@ -91,41 +118,54 @@ Development
#endif /* BUILD_FUTURE */
```
* Any project specific build variable should be mentioned inside `version.h` as well.
* Any project specific build variable should be mentioned inside `version.h` as
well.
* Recommended compiler is `clang`.
HIG
---
The recommended HIG is [KDE one](https://techbase.kde.org/Projects/Usability/HIG). Avoid to paint interfaces inside plugin because QML and C++ parts may have different theming.
The recommended HIG is [KDE one](https://techbase.kde.org/Projects/Usability/HIG).
Avoid to paint interfaces inside plugin because QML and C++ parts may have different
theming.
Licensing
---------
All files should be licensed under GPLv3, the owner of the license should be the project (i.e. **awesome-widgets**). See **Tools** section for more details.
All files should be licensed under GPLv3, the owner of the license should be the
project (i.e. **awesome-widgets**). See **Tools** section for more details.
Logging
-------
For logging please use [QLoggingCategory](http://doc.qt.io/qt-5/qloggingcategory.html). Available categories should be declared in `awdebug.*` files. The following log levels should be used:
For logging please use [QLoggingCategory](http://doc.qt.io/qt-5/qloggingcategory.html).
Available categories should be declared in `awdebug.*` files. The following log
levels should be used:
* **debug** (`qCDebug()`) - method arguments information. Please note that it is recommended to logging all arguments in the one line.
* **debug** (`qCDebug()`) - method arguments information. Please note that it
is recommended to logging all arguments in the one line.
* **info** (`qCInfo()`) - additional information inside methods.
* **warning** (`qCWarning()`) - not critical information, which may be caused by mistakes in configuration for example.
* **critical** (`qCCritical()`) - a critical error. After this error program may be terminated.
* **warning** (`qCWarning()`) - not critical information, which may be caused by
mistakes in configuration for example.
* **critical** (`qCCritical()`) - a critical error. After this error program may
be terminated.
The empty log string (e.g. `qCDebug();`) is not allowed because the method names will be stripped by compiler with `Release` build type. To log class constructor and destructor use `__PRETTY_FUNCTION__` macro.
The empty log string (e.g. `qCDebug();`) is not allowed because the method names
will be stripped by compiler with `Release` build type. To log class constructor
and destructor use `__PRETTY_FUNCTION__` macro.
Testing
-------
* Any changes should be tested by using `plasmawindowed` and `plasmashell` applications. (It is also possible to use `plasmaengineexplorer` and `plasmoidviewer` in addition.)
* Any changes should be tested by using `plasmawindowed` and `plasmashell` applications.
(It is also possible to use `plasmaengineexplorer` and `plasmoidviewer` in addition.)
* Any test should be performed on real (not Virtual Machine) system.
* Test builds should be:
1. `-DCMAKE_BUILD_TYPE=Debug`.
2. `-DCMAKE_BUILD_TYPE=Debug -DBUILD_TESTING=ON`.
3. `-DCMAKE_BUILD_TYPE=Release`.
* Additional test functions should be declated and used only inside `BUILD_TESTING` definition.
* Additional test functions should be declated and used only inside `BUILD_TESTING`
definition.
Tools
-----
@ -182,6 +222,7 @@ Tools
// declare with default value
bool m_prop = false;
```
* Use `cppcheck` to avoid common errors in the code. To start application just run `make cppcheck`.
* Use `clang-format` to apply valid code format. To start application just run `make clangformat`.
* use `-DCMAKE_CXX_COMPILER=clang++` in order to enable clang-tidy checks.
* Use `cppcheck` to avoid common errors in the code. To start application just
run `make cppcheck`.
* Use `clang-format` to apply valid code format. To start application just run
`make clangformat`.

View File

@ -14,11 +14,11 @@ A collection of minimalistic widgets which looks like Awesome Window Manager wid
Features
========
* easy and fully configurable native Plasma widget which may be used as desktop or panel widget
* additionnal widget which shows active desktop status
* clear text configuration with html tags support
* easy and fully configurable native Plasma widget which may be used as Conky widget or as Awesome-like information panel
* panel which shows active desktop status
* clear Conky-like configuration with html tags support
* custom command support (it may be simple action as well as special custom tag)
* graphical widgets support - tooltips, bars
* graphical item support - tooltips, bars
See [links](#Links) for more details.
@ -30,11 +30,15 @@ Instruction
Dependencies
------------
* plasma-workspace
* plasma-framework
* ksysguard (since plasma 5.22)
Optional dependencies
---------------------
* proprietary video driver
* hddtemp
* smartmontools
* music player (mpd or MPRIS supported)
* wireless_tools
@ -44,20 +48,19 @@ Make dependencies
* cmake
* extra-cmake-modules
In addition, some distros might require to install some -dev packages, e.g. the list of required packages for deb-based distros can be found [here](https://github.com/arcan1s/awesome-widgets/blob/development/.docker/Dockerfile-ubuntu-amd64#L7).
In addition some distros might require to install some -dev packages, e.g. the list of required packages for deb-based distros can be found [here](https://github.com/arcan1s/awesome-widgets/blob/development/.docker/Dockerfile-ubuntu-amd64#L7).
Installation
------------
* download sources
* build package
* install
cmake -B build -S sources -DCMAKE_BUILD_TYPE=Release
cmake --build build
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr ../sources
make && sudo make install
* install package
cmake --install build
**NOTE** on Plasma 5 it very likely requires `-DKDE_INSTALL_USE_QT_SYS_PATHS=ON` flag
Additional information
======================

View File

@ -9,8 +9,7 @@ arch=('x86_64')
url="https://arcanis.me/projects/awesome-widgets"
license=('GPL3')
depends=('plasma-workspace')
optdepends=("mpd: for music player monitor"
"wireless_tools: wifi information")
optdepends=("mpd: for music player monitor")
makedepends=('cmake' 'extra-cmake-modules' 'python')
source=(https://github.com/arcan1s/awesome-widgets/releases/download/${pkgver}/${_pkgname}-${pkgver}-src.tar.xz)
install="$pkgname.install"

View File

@ -58,7 +58,7 @@ CFontDialog::CFontDialog(QWidget *parent, bool needWeight, bool needItalic)
setLayout(mainGrid);
colorBox = new QComboBox(this);
connect(colorBox, &QComboBox::currentTextChanged, this, &CFontDialog::updateColor);
connect(colorBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateColor(QString)));
QStringList colorNames = QColor::colorNames();
int index = 0;
for (int i=0; i<colorNames.count(); i++) {
@ -81,8 +81,8 @@ CFontDialog::CFontDialog(QWidget *parent, bool needWeight, bool needItalic)
buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
Qt::Horizontal, this);
QObject::connect(buttons, &QDialogButtonBox::accepted, this, &CFontDialog::accept);
QObject::connect(buttons, &QDialogButtonBox::rejected, this, &CFontDialog::reject);
QObject::connect(buttons, SIGNAL(accepted()), this, SLOT(accept()));
QObject::connect(buttons, SIGNAL(rejected()), this, SLOT(reject()));
mainGrid->addWidget(buttons, 1, 0, 1, 5);
italicBox->setHidden(!needItalic);

View File

@ -15,7 +15,8 @@
* License along with this library. *
***************************************************************************/
#pragma once
#ifndef FONTDIALOG_H
#define FONTDIALOG_H
#include <QComboBox>
#include <QDialog>
@ -71,3 +72,6 @@ private:
QSpinBox *sizeBox;
QSpinBox *weightBox;
};
#endif /* FONTDIALOG_H */

View File

@ -12,7 +12,7 @@ QReplyTimeout::QReplyTimeout(QNetworkReply *reply, const int timeout)
void QReplyTimeout::timeout()
{
auto reply = dynamic_cast<QNetworkReply *>(parent());
auto *reply = dynamic_cast<QNetworkReply *>(parent());
if (reply->isRunning())
reply->close();
}

View File

@ -9,9 +9,6 @@ endif ()
if (POLICY CMP0071)
cmake_policy(SET CMP0071 NEW)
endif ()
if (POLICY CMP0160)
cmake_policy(SET CMP0160 OLD)
endif ()
project(awesomewidgets)
set(PROJECT_AUTHOR "Evgeniy Alekseev")

View File

@ -41,32 +41,35 @@ QString AWDebug::getAboutText(const QString &_type)
} else if (_type == "description") {
text = i18n("A set of minimalistic plasmoid widgets");
} else if (_type == "links") {
text = i18n("Links:") + "<ul>" + QString("<li><a href=\"%1\">%2</a></li>").arg(HOMEPAGE, i18n("Homepage"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(REPOSITORY, i18n("Repository"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(BUGTRACKER, i18n("Bugtracker"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(TRANSLATION, i18n("Translation issue"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(AUR_PACKAGES, i18n("AUR packages"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(OPENSUSE_PACKAGES, i18n("openSUSE packages")) + "</ul>";
text = i18n("Links:") + "<ul>" + QString("<li><a href=\"%1\">%2</a></li>").arg(HOMEPAGE).arg(i18n("Homepage"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(REPOSITORY).arg(i18n("Repository"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(BUGTRACKER).arg(i18n("Bugtracker"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(TRANSLATION).arg(i18n("Translation issue"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(AUR_PACKAGES).arg(i18n("AUR packages"))
+ QString("<li><a href=\"%1\">%2</a></li>").arg(OPENSUSE_PACKAGES).arg(i18n("openSUSE packages"))
+ "</ul>";
} else if (_type == "copy") {
text = QString("<small>&copy; %1 <a href=\"mailto:%2\">%3</a><br>").arg(DATE, EMAIL, AUTHOR)
+ i18n("This software is licensed under %1", LICENSE) + "</small>";
text = QString("<small>&copy; %1 <a href=\"mailto:%2\">%3</a><br>").arg(DATE).arg(EMAIL).arg(AUTHOR)
+ i18nc("This software is licensed under %1", LICENSE) + "</small>";
} else if (_type == "translators") {
auto translatorList = QString(TRANSLATORS).split(',');
QStringList translatorList = QString(TRANSLATORS).split(',');
for (auto &translator : translatorList)
translator = QString("<li>%1</li>").arg(translator);
text = i18n("Translators:") + "<ul>" + translatorList.join("") + "</ul>";
} else if (_type == "3rdparty") {
auto trdPartyList = QString(TRDPARTY_LICENSE).split(';', Qt::SkipEmptyParts);
for (auto i = 0; i < trdPartyList.count(); ++i)
QStringList trdPartyList = QString(TRDPARTY_LICENSE).split(';', Qt::SkipEmptyParts);
for (int i = 0; i < trdPartyList.count(); i++)
trdPartyList[i] = QString("<li><a href=\"%3\">%1</a> (%2 license)</li>")
.arg(trdPartyList.at(i).split(',')[0], trdPartyList.at(i).split(',')[1],
trdPartyList.at(i).split(',')[2]);
.arg(trdPartyList.at(i).split(',')[0])
.arg(trdPartyList.at(i).split(',')[1])
.arg(trdPartyList.at(i).split(',')[2]);
text = i18n("This software uses:") + "<ul>" + trdPartyList.join("") + "</ul>";
} else if (_type == "thanks") {
auto thanks = QString(SPECIAL_THANKS).split(';', Qt::SkipEmptyParts);
for (auto i = 0; i < thanks.count(); ++i)
thanks[i]
= QString("<li><a href=\"%2\">%1</a></li>").arg(thanks.at(i).split(',')[0], thanks.at(i).split(',')[1]);
QStringList thanks = QString(SPECIAL_THANKS).split(';', Qt::SkipEmptyParts);
for (int i = 0; i < thanks.count(); i++)
thanks[i] = QString("<li><a href=\"%2\">%1</a></li>")
.arg(thanks.at(i).split(',')[0])
.arg(thanks.at(i).split(',')[1]);
text = i18n("Special thanks to:") + "<ul>" + thanks.join("") + "</ul>";
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWDEBUG_H
#define AWDEBUG_H
#include <QLoggingCategory>
@ -40,3 +42,6 @@ Q_DECLARE_LOGGING_CATEGORY(LOG_DP)
Q_DECLARE_LOGGING_CATEGORY(LOG_ESM)
Q_DECLARE_LOGGING_CATEGORY(LOG_ESS)
Q_DECLARE_LOGGING_CATEGORY(LOG_LIB)
#endif /* AWDEBUG_H */

View File

@ -51,12 +51,6 @@ ConfigModel {
source: "dataengine.qml"
}
ConfigCategory {
name: i18n("Report bug")
icon: "tools-report-bug"
source: "bug.qml"
}
ConfigCategory {
name: i18n("About")
icon: "help-about"

View File

@ -44,6 +44,9 @@
<entry name="interval" type="Int">
<default>1000</default>
</entry>
<entry name="queueLimit" type="Int">
<default>0</default>
</entry>
<entry name="tempUnits" type="String">
<default>Celsius</default>
</entry>
@ -59,9 +62,15 @@
<entry name="acOffline" type="String">
<default>( )</default>
</entry>
<entry name="historyCount" type="Int">
<entry name="telemetryCount" type="Int">
<default>100</default>
</entry>
<entry name="telemetryRemote" type="Bool">
<default>false</default>
</entry>
<entry name="telemetryId" type="String">
<default></default>
</entry>
</group>
<group name="Tooltip">

View File

@ -18,8 +18,7 @@
import QtQuick 2.15
import org.kde.kcmutils as KCM
import org.kde.plasma.awesomewidgets
import org.kde.plasma.private.awesomewidget
import org.kde.plasma.private.awesomewidget 1.0
KCM.SimpleKCM {

View File

@ -19,16 +19,15 @@ import QtQuick 2.15
import QtQuick.Controls
import org.kde.kcmutils as KCM
import org.kde.plasma.awesomewidgets
import org.kde.plasma.private.awesomewidget
import org.kde.plasma.private.awesomewidget 1.0
KCM.SimpleKCM {
id: advancedPage
// backend
AWConfigHelper {
id: awConfig
AWActions {
id: awActions
}
property alias cfg_background: background.checked
@ -41,14 +40,18 @@ KCM.SimpleKCM {
property alias cfg_height: widgetHeight.value
property alias cfg_width: widgetWidth.value
property alias cfg_interval: update.value
property alias cfg_queueLimit: queueLimit.value
property string cfg_tempUnits: tempUnits.value
property alias cfg_customTime: customTime.value
property alias cfg_customUptime: customUptime.value
property alias cfg_acOnline: acOnline.value
property alias cfg_acOffline: acOffline.value
property alias cfg_historyCount: historyCount.value
property alias cfg_telemetryCount: telemetryCount.value
property alias cfg_telemetryRemote: telemetryRemote.checked
property alias cfg_telemetryId: telemetryId.value
Column {
id: pageColumn
anchors.fill: parent
CheckBoxSelector {
@ -113,6 +116,15 @@ KCM.SimpleKCM {
value: plasmoid.configuration.interval
}
IntegerSelector {
id: queueLimit
maximumValue: 99
minimumValue: 0
stepSize: 1
text: i18n("Messages queue limit")
value: plasmoid.configuration.queueLimit
}
ComboBoxSelector {
id: tempUnits
model: [
@ -185,7 +197,7 @@ KCM.SimpleKCM {
ButtonSelector {
value: i18n("Drop key cache")
onButtonActivated: awConfig.dropCache()
onButtonActivated: awActions.dropCache()
}
ButtonSelector {
@ -214,19 +226,30 @@ KCM.SimpleKCM {
GroupBox {
height: implicitHeight
width: parent.width
title: i18n("History")
title: i18n("Telemetry")
Column {
height: implicitHeight
width: parent.width
CheckBoxSelector {
id: telemetryRemote
text: i18n("Enable remote telemetry")
}
IntegerSelector {
id: historyCount
id: telemetryCount
maximumValue: 10000
minimumValue: 0
stepSize: 50
text: i18n("History count")
value: plasmoid.configuration.historyCount
value: plasmoid.configuration.telemetryCount
}
LineSelector {
id: telemetryId
text: i18n("Telemetry ID")
value: plasmoid.configuration.telemetryId
}
}
}

View File

@ -18,8 +18,8 @@
import QtQuick 2.15
import org.kde.kcmutils as KCM
import org.kde.plasma.awesomewidgets
import org.kde.plasma.private.awesomewidget
import org.kde.plasma.private.awesomewidget 1.0
import "."
KCM.SimpleKCM {
@ -42,6 +42,7 @@ KCM.SimpleKCM {
property string cfg_textStyle: textStyle.value
Column {
id: pageColumn
anchors.fill: parent
FontSelector {

View File

@ -19,8 +19,7 @@ import QtQuick 2.15
import QtQuick.Controls
import org.kde.kcmutils as KCM
import org.kde.plasma.awesomewidgets
import org.kde.plasma.private.awesomewidget
import org.kde.plasma.private.awesomewidget 1.0
KCM.SimpleKCM {
@ -37,6 +36,7 @@ KCM.SimpleKCM {
property variant cfg_dataengine: awConfig.readDataEngineConfiguration()
Column {
id: pageColumn
anchors.fill: parent
GroupBox {
@ -190,6 +190,10 @@ KCM.SimpleKCM {
Component.onCompleted: {
// init submodule
awKeys.updateCache()
// update hdd model
hdd.model = awKeys.getHddDevices()
hdd.onCompleted
}
Component.onDestruction: {

View File

@ -16,12 +16,14 @@
***************************************************************************/
import QtQuick 2.15
import QtQuick.Controls
import QtQuick.Dialogs
import QtQuick.Layouts
import org.kde.plasma.core as PlasmaCore
import org.kde.plasma.plasmoid 2.0
import org.kde.plasma.awesomewidgets
import org.kde.plasma.private.awesomewidget
import org.kde.plasma.private.awesomewidget 1.0
import "."
PlasmoidItem {
@ -37,6 +39,9 @@ PlasmoidItem {
AWTelemetryHandler {
id: awTelemetryHandler
}
BugReport {
id: bugReport
}
property variant tooltipSettings: {
"tooltipNumber": plasmoid.configuration.tooltipNumber,
@ -87,7 +92,7 @@ PlasmoidItem {
color: plasmoid.configuration.fontColor
font.family: plasmoid.configuration.fontFamily
font.italic: plasmoid.configuration.fontStyle === "italic"
font.italic: plasmoid.configuration.fontStyle === "italic" ? true : false
font.pointSize: plasmoid.configuration.fontSize
font.weight: General.fontWeight[plasmoid.configuration.fontWeight]
@ -106,11 +111,35 @@ PlasmoidItem {
}
}
Dialog {
id: tagSelector
title: i18n("Select tag")
ComboBox {
id: tagSelectorBox
width: parent.width
editable: true
}
onAccepted: {
const tag = tagSelectorBox.editText
let message = i18n("Tag: %1", tag)
message += "<br>"
message += i18n("Value: %1", awKeys.valueByKey(tag))
message += "<br>"
message += i18n("Info: %1", awKeys.infoByKey(tag))
awActions.sendNotification("tag", message)
}
}
Plasmoid.contextualActions: [
PlasmaCore.Action {
text: i18n("Run monitor")
text: i18n("Request key")
icon.name: "utilities-system-monitor"
onTriggered: awActions.runCmd("plasma-systemmonitor", [])
onTriggered: {
tagSelectorBox.model = awKeys.dictKeys(true)
tagSelector.open()
}
},
PlasmaCore.Action {
text: i18n("Show README")
@ -121,6 +150,14 @@ PlasmoidItem {
text: i18n("Check updates")
icon.name: "system-software-update"
onTriggered: awActions.checkUpdates(true)
},
PlasmaCore.Action {
text: i18n("Report bug")
icon.name: "tools-report-bug"
onTriggered: {
bugReport.reset()
bugReport.open()
}
}
]
@ -168,7 +205,8 @@ PlasmoidItem {
// init submodule
awKeys.initDataAggregator(tooltipSettings)
awKeys.initKeys(plasmoid.configuration.text, plasmoid.configuration.interval, plasmoid.configuration.optimize)
awKeys.initKeys(plasmoid.configuration.text, plasmoid.configuration.interval,
plasmoid.configuration.queueLimit, plasmoid.configuration.optimize)
awKeys.setWrapNewLines(plasmoid.configuration.wrapNewLines)
// configure aggregator
awKeys.setAggregatorProperty("acOffline", plasmoid.configuration.acOffline)
@ -177,8 +215,22 @@ PlasmoidItem {
awKeys.setAggregatorProperty("customUptime", plasmoid.configuration.customUptime)
awKeys.setAggregatorProperty("tempUnits", plasmoid.configuration.tempUnits)
awKeys.setAggregatorProperty("translate", plasmoid.configuration.translateStrings)
// update telemetry ID
if (plasmoid.configuration.telemetryId.length === 0)
plasmoid.configuration.telemetryId = generateUuid()
// save telemetry
awTelemetryHandler.init(plasmoid.configuration.historyCount)
awTelemetryHandler.put("awwidgetconfig", plasmoid.configuration.text)
awTelemetryHandler.init(plasmoid.configuration.telemetryCount,
plasmoid.configuration.telemetryRemote,
plasmoid.configuration.telemetryId)
if (awTelemetryHandler.put("awwidgetconfig", plasmoid.configuration.text))
awTelemetryHandler.uploadTelemetry("awwidgetconfig", plasmoid.configuration.text)
}
// code from http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
function generateUuid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
let r = Math.random() * 16 | 0, v = c === "x" ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}

View File

@ -0,0 +1,27 @@
# Do not edit qmldir directly it will be overrided during compilation,
# edit qml/qmldir.in file instead.
# common QML constants
singleton General 1.0 file:///usr/share/awesomewidgets/qml/General.qml
# custom QML UI classes
AboutTab file:///usr/share/awesomewidgets/qml/AboutTab.qml
AWExtensions file:///usr/share/awesomewidgets/qml/AWExtensions.qml
AWInfoLabel file:///usr/share/awesomewidgets/qml/AWInfoLabel.qml
AWTagSelector file:///usr/share/awesomewidgets/qml/AWTagSelector.qml
AWTextEditor file:///usr/share/awesomewidgets/qml/AWTextEditor.qml
BugReport file:///usr/share/awesomewidgets/qml/BugReport.qml
ButtonSelector file:///usr/share/awesomewidgets/qml/ButtonSelector.qml
CheckBoxSelector file:///usr/share/awesomewidgets/qml/CheckBoxSelector.qml
ColorSelector file:///usr/share/awesomewidgets/qml/ColorSelector.qml
ComboBoxSelector file:///usr/share/awesomewidgets/qml/ComboBoxSelector.qml
ExportDialog file:///usr/share/awesomewidgets/qml/ExportDialog.qml
FontSelector file:///usr/share/awesomewidgets/qml/FontSelector.qml
HtmlDefaultFunctionsBar file:///usr/share/awesomewidgets/qml/HtmlDefaultFunctionsBar.qml
HtmlEditorButton file:///usr/share/awesomewidgets/qml/HtmlEditorButton.qml
HtmlEditorColor file:///usr/share/awesomewidgets/qml/HtmlEditorColor.qml
HtmlEditorFont file:///usr/share/awesomewidgets/qml/HtmlEditorFont.qml
ImportDialog file:///usr/share/awesomewidgets/qml/ImportDialog.qml
IntegerSelector file:///usr/share/awesomewidgets/qml/IntegerSelector.qml
LineSelector file:///usr/share/awesomewidgets/qml/LineSelector.qml

View File

@ -19,8 +19,7 @@ import QtQuick 2.15
import QtQuick.Controls
import org.kde.kcmutils as KCM
import org.kde.plasma.awesomewidgets
import org.kde.plasma.private.awesomewidget
import org.kde.plasma.private.awesomewidget 1.0
KCM.SimpleKCM {
@ -45,6 +44,7 @@ KCM.SimpleKCM {
property alias cfg_batInTooltipColor: batInTooltipColor.value
Column {
id: pageColumn
anchors.fill: parent
Label {

View File

@ -19,8 +19,8 @@ import QtQuick 2.15
import QtQuick.Controls
import org.kde.kcmutils as KCM
import org.kde.plasma.awesomewidgets
import org.kde.plasma.private.awesomewidget
import org.kde.plasma.private.awesomewidget 1.0
import "."
KCM.SimpleKCM {
@ -40,6 +40,7 @@ KCM.SimpleKCM {
signal needTextUpdate(string newText)
Column {
id: pageColumn
anchors.fill: parent
AWInfoLabel {}

View File

@ -37,13 +37,13 @@ AWAbstractPairConfig::AWAbstractPairConfig(QWidget *_parent, const bool _hasEdit
ui->setupUi(this);
connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &AWAbstractPairConfig::accept);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &AWAbstractPairConfig::reject);
connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(ui->buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
// edit feature
if (m_hasEdit) {
m_editButton = ui->buttonBox->addButton(i18n("Edit"), QDialogButtonBox::ActionRole);
connect(m_editButton, &QPushButton::clicked, [this]() { return edit(); });
connect(m_editButton, SIGNAL(clicked(bool)), this, SLOT(edit()));
}
}
@ -58,12 +58,6 @@ AWAbstractPairConfig::~AWAbstractPairConfig()
}
void AWAbstractPairConfig::setHelper(std::unique_ptr<AWAbstractPairHelper> _helper)
{
m_helper = std::move(_helper);
}
void AWAbstractPairConfig::showDialog()
{
// update dialog
@ -90,14 +84,14 @@ void AWAbstractPairConfig::edit()
void AWAbstractPairConfig::updateUi()
{
auto current = dynamic_cast<AWAbstractSelector *>(sender())->current();
auto index = m_selectors.indexOf(dynamic_cast<AWAbstractSelector *>(sender()));
QPair<QString, QString> current = dynamic_cast<AWAbstractSelector *>(sender())->current();
int index = m_selectors.indexOf(dynamic_cast<AWAbstractSelector *>(sender()));
if ((current.first.isEmpty()) && (current.second.isEmpty())) {
// remove current selector if it is empty and does not last
if (sender() == m_selectors.last())
return;
auto selector = m_selectors.takeAt(index);
AWAbstractSelector *selector = m_selectors.takeAt(index);
ui->verticalLayout->removeWidget(selector);
selector->deleteLater();
} else {
@ -115,18 +109,18 @@ void AWAbstractPairConfig::addSelector(const QStringList &_keys, const QStringLi
{
qCDebug(LOG_AW) << "Add selector with keys" << _keys << "values" << _values << "and current ones" << _current;
auto selector = new AWAbstractSelector(ui->scrollAreaWidgetContents, m_editable);
auto *selector = new AWAbstractSelector(ui->scrollAreaWidgetContents, m_editable);
selector->init(_keys, _values, _current);
ui->verticalLayout->insertWidget(ui->verticalLayout->count() - 1, selector);
connect(selector, &AWAbstractSelector::selectionChanged, this, &AWAbstractPairConfig::updateUi);
connect(selector, SIGNAL(selectionChanged()), this, SLOT(updateUi()));
m_selectors.append(selector);
}
void AWAbstractPairConfig::clearSelectors()
{
for (auto selector : m_selectors) {
disconnect(selector, &AWAbstractSelector::selectionChanged, this, &AWAbstractPairConfig::updateUi);
for (auto &selector : m_selectors) {
disconnect(selector, SIGNAL(selectionChanged()), this, SLOT(updateUi()));
ui->verticalLayout->removeWidget(selector);
selector->deleteLater();
}
@ -136,10 +130,10 @@ void AWAbstractPairConfig::clearSelectors()
void AWAbstractPairConfig::execDialog()
{
auto ret = exec();
int ret = exec();
QHash<QString, QString> data;
for (auto selector : m_selectors) {
auto select = selector->current();
for (auto &selector : m_selectors) {
QPair<QString, QString> select = selector->current();
if (select.first.isEmpty())
continue;
data[select.first] = select.second;
@ -166,12 +160,11 @@ QPair<QStringList, QStringList> AWAbstractPairConfig::initKeys() const
QStringList left = {""};
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.sort();
return {left, right};
return QPair<QStringList, QStringList>(left, right);
}
@ -182,7 +175,7 @@ void AWAbstractPairConfig::updateDialog()
auto keys = initKeys();
for (auto &key : m_helper->keys())
addSelector(keys.first, keys.second, {key, pairs[key]});
addSelector(keys.first, keys.second, QPair<QString, QString>(key, m_helper->pairs()[key]));
// empty one
addSelector(keys.first, keys.second, {});
addSelector(keys.first, keys.second, QPair<QString, QString>());
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWABSTRACTPAIRCONFIG_H
#define AWABSTRACTPAIRCONFIG_H
#include <QDialog>
@ -33,9 +35,14 @@ class AWAbstractPairConfig : public QDialog
Q_OBJECT
public:
explicit AWAbstractPairConfig(QWidget *_parent = nullptr, bool _hasEdit = false, QStringList _keys = {});
explicit AWAbstractPairConfig(QWidget *_parent = nullptr, bool _hasEdit = false, QStringList _keys = QStringList());
~AWAbstractPairConfig() override;
void setHelper(std::unique_ptr<AWAbstractPairHelper> _helper);
template <class T> void initHelper()
{
delete m_helper;
m_helper = new T(this);
}
void showDialog();
// properties
void setEditable(bool _first, bool _second);
@ -47,7 +54,7 @@ private slots:
private:
QPushButton *m_editButton = nullptr;
Ui::AWAbstractPairConfig *ui = nullptr;
std::unique_ptr<AWAbstractPairHelper> m_helper;
AWAbstractPairHelper *m_helper = nullptr;
QList<AWAbstractSelector *> m_selectors;
// properties
QPair<bool, bool> m_editable = {false, false};
@ -60,3 +67,6 @@ private:
[[nodiscard]] QPair<QStringList, QStringList> initKeys() const;
void updateDialog();
};
#endif /* AWABSTRACTPAIRCONFIG_H */

View File

@ -34,6 +34,12 @@ AWAbstractPairHelper::AWAbstractPairHelper(QString _filePath, QString _section)
}
AWAbstractPairHelper::~AWAbstractPairHelper()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
QStringList AWAbstractPairHelper::keys() const
{
return m_pairs.keys();
@ -63,16 +69,16 @@ void AWAbstractPairHelper::initItems()
{
m_pairs.clear();
auto configs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, m_filePath);
QStringList configs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, m_filePath);
for (auto &fileName : configs) {
QSettings settings(fileName, QSettings::IniFormat);
qCInfo(LOG_AW) << "Configuration file" << settings.fileName();
settings.beginGroup(m_section);
auto keys = settings.childKeys();
QStringList keys = settings.childKeys();
for (auto &key : keys) {
auto value = settings.value(key).toString();
QString value = settings.value(key).toString();
qCInfo(LOG_AW) << "Found key" << key << "for value" << value << "in" << settings.fileName();
if (value.isEmpty()) {
qCInfo(LOG_AW) << "Skip empty value for" << key;
@ -89,8 +95,8 @@ bool AWAbstractPairHelper::writeItems(const QHash<QString, QString> &_configurat
{
qCDebug(LOG_AW) << "Write configuration" << _configuration;
auto fileName
= QString("%1/%2").arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation), 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;
@ -101,7 +107,7 @@ bool AWAbstractPairHelper::writeItems(const QHash<QString, QString> &_configurat
settings.sync();
return settings.status() == QSettings::NoError;
return (settings.status() == QSettings::NoError);
}
@ -109,13 +115,14 @@ bool AWAbstractPairHelper::removeUnusedKeys(const QStringList &_keys) const
{
qCDebug(LOG_AW) << "Remove keys" << _keys;
auto fileName
= QString("%1/%2").arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation), 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;
settings.beginGroup(m_section);
for (auto &key : settings.childKeys()) {
QStringList foundKeys = settings.childKeys();
for (auto &key : foundKeys) {
if (_keys.contains(key))
continue;
settings.remove(key);
@ -124,5 +131,5 @@ bool AWAbstractPairHelper::removeUnusedKeys(const QStringList &_keys) const
settings.sync();
return settings.status() == QSettings::NoError;
return (settings.status() == QSettings::NoError);
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWABSTRACTPAIRHELPER_H
#define AWABSTRACTPAIRHELPER_H
#include <QHash>
@ -24,7 +26,7 @@ class AWAbstractPairHelper
{
public:
explicit AWAbstractPairHelper(QString _filePath = "", QString _section = "");
virtual ~AWAbstractPairHelper() = default;
virtual ~AWAbstractPairHelper();
[[nodiscard]] QStringList keys() const;
[[nodiscard]] QHash<QString, QString> pairs() const;
[[nodiscard]] QStringList values() const;
@ -44,3 +46,6 @@ private:
QString m_filePath;
QString m_section;
};
#endif /* AWABSTRACTPAIRHELPER_H */

View File

@ -31,8 +31,8 @@ AWAbstractSelector::AWAbstractSelector(QWidget *_parent, const QPair<bool, bool>
ui->comboBox_key->setEditable(_editable.first);
ui->comboBox_value->setEditable(_editable.second);
connect(ui->comboBox_key, &QComboBox::currentIndexChanged, this, &AWAbstractSelector::selectionChanged);
connect(ui->comboBox_value, &QComboBox::currentIndexChanged, this, &AWAbstractSelector::selectionChanged);
connect(ui->comboBox_key, SIGNAL(currentIndexChanged(int)), this, SIGNAL(selectionChanged()));
connect(ui->comboBox_value, SIGNAL(currentIndexChanged(int)), this, SIGNAL(selectionChanged()));
}
@ -46,10 +46,10 @@ AWAbstractSelector::~AWAbstractSelector()
QPair<QString, QString> AWAbstractSelector::current() const
{
auto key = ui->comboBox_key->currentText();
auto value = ui->comboBox_value->currentText();
QString key = ui->comboBox_key->currentText();
QString value = ui->comboBox_value->currentText();
return {key, value};
return QPair<QString, QString>(key, value);
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWABSTRACTSELECTOR_H
#define AWABSTRACTSELECTOR_H
#include <QWidget>
@ -41,3 +43,6 @@ signals:
private:
Ui::AWAbstractSelector *ui = nullptr;
};
#endif /* AWABSTRACTSELECTOR_H */

View File

@ -40,6 +40,12 @@ AWActions::AWActions(QObject *_parent)
}
AWActions::~AWActions()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
void AWActions::checkUpdates(const bool _showAnyway)
{
qCDebug(LOG_AW) << "Show anyway" << _showAnyway;
@ -59,7 +65,7 @@ QString AWActions::getFileContent(const QString &_path)
return "";
}
auto output = inputFile.readAll();
QString output = inputFile.readAll();
inputFile.close();
return output;
}
@ -69,7 +75,7 @@ bool AWActions::runCmd(const QString &_cmd, const QStringList &_args)
{
qCDebug(LOG_AW) << "Cmd" << _cmd << "args" << _args;
sendNotification("system", i18n("Run %1", _cmd));
sendNotification(QString("Info"), i18n("Run %1", _cmd));
return QProcess::startDetached(_cmd, _args);
}
@ -82,6 +88,20 @@ void AWActions::showReadme()
}
void AWActions::showLegacyInfo()
{
auto *msgBox = new QMessageBox(nullptr);
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->setStandardButtons(QMessageBox::Ok);
msgBox->setIcon(QMessageBox::Information);
msgBox->open();
}
// HACK: this method uses variables from version.h
QString AWActions::getAboutText(const QString &_type)
{
@ -96,10 +116,10 @@ QVariantMap AWActions::getFont(const QVariantMap &_defaultFont)
qCDebug(LOG_AW) << "Default font is" << _defaultFont;
QVariantMap fontMap;
auto ret = 0;
auto defaultCFont = CFont(_defaultFont["family"].toString(), _defaultFont["size"].toInt(), 400, false,
_defaultFont["color"].toString());
auto font = CFontDialog::getFont(i18n("Select font"), defaultCFont, false, false, &ret);
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);
fontMap["applied"] = ret;
fontMap["color"] = font.color().name();
@ -115,6 +135,7 @@ void AWActions::sendNotification(const QString &_eventId, const QString &_messag
{
qCDebug(LOG_AW) << "Event" << _eventId << "with message" << _message;
auto event = KNotification::event(_eventId, QString("Awesome Widget ::: %1").arg(_eventId), _message);
event->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

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWACTIONS_H
#define AWACTIONS_H
#include <QMap>
#include <QObject>
@ -29,10 +31,11 @@ class AWActions : public QObject
public:
explicit AWActions(QObject *_parent = nullptr);
~AWActions() override = default;
~AWActions() override;
Q_INVOKABLE void checkUpdates(bool _showAnyway = false);
Q_INVOKABLE static QString getFileContent(const QString &_path);
Q_INVOKABLE static bool runCmd(const QString &_cmd, const QStringList &_args);
Q_INVOKABLE static void showLegacyInfo();
Q_INVOKABLE static void showReadme();
// configuration slots
Q_INVOKABLE static QString getAboutText(const QString &_type);
@ -44,3 +47,6 @@ public slots:
private:
AWUpdateHelper *m_updateHelper = nullptr;
};
#endif /* AWACTIONS_H */

View File

@ -18,7 +18,6 @@
#include "awbugreporter.h"
#include <KI18n/KLocalizedString>
#include <KNotifications/KNotification>
#include <QDesktopServices>
#include <QJsonDocument>
@ -33,24 +32,19 @@ AWBugReporter::AWBugReporter(QObject *_parent)
: QObject(_parent)
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_manager = new QNetworkAccessManager(nullptr);
connect(m_manager, &QNetworkAccessManager::finished, this, &AWBugReporter::issueReplyReceived);
}
AWBugReporter::~AWBugReporter()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_manager->deleteLater();
}
void AWBugReporter::doConnect() const
void AWBugReporter::doConnect()
{
// additional method for testing needs
connect(this, &AWBugReporter::replyReceived, this, &AWBugReporter::showInformation);
connect(this, SIGNAL(replyReceived(const int, const QString &)), this, SLOT(showInformation(int, const QString &)));
}
@ -77,24 +71,26 @@ void AWBugReporter::sendBugReport(const QString &_title, const QString &_body)
{
qCDebug(LOG_AW) << "Send bug report with title" << _title << "and body" << _body;
auto *manager = new QNetworkAccessManager(nullptr);
connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(issueReplyRecieved(QNetworkReply *)));
auto request = QNetworkRequest(QUrl(BUGTRACKER_API));
QNetworkRequest request = QNetworkRequest(QUrl(BUGTRACKER_API));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// generate payload
QVariantMap payload;
payload["title"] = _title;
payload["body"] = _body;
payload["labels"] = QStringList({"from application"});
payload["labels"] = QStringList() << "from application";
// convert to QByteArray to send request
auto data = QJsonDocument::fromVariant(payload).toJson(QJsonDocument::Compact);
QByteArray data = QJsonDocument::fromVariant(payload).toJson(QJsonDocument::Compact);
qCInfo(LOG_AW) << "Send request with _body" << data.data() << "and size" << data.size();
m_manager->post(request, data);
manager->post(request, data);
}
void AWBugReporter::issueReplyReceived(QNetworkReply *_reply)
void AWBugReporter::issueReplyRecieved(QNetworkReply *_reply)
{
if (_reply->error() != QNetworkReply::NoError) {
qCWarning(LOG_AW) << "An error occurs" << _reply->error() << "with message" << _reply->errorString();
@ -102,7 +98,7 @@ void AWBugReporter::issueReplyReceived(QNetworkReply *_reply)
}
QJsonParseError error{};
auto 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, ""));
@ -110,20 +106,14 @@ void AWBugReporter::issueReplyReceived(QNetworkReply *_reply)
_reply->deleteLater();
// convert to map
auto response = jsonDoc.toVariant().toMap();
auto url = response["html_url"].toString();
auto number = response["number"].toInt();
QVariantMap response = jsonDoc.toVariant().toMap();
QString url = response["html_url"].toString();
int number = response["number"].toInt();
return emit(replyReceived(number, url));
}
void AWBugReporter::openBugReport()
{
QDesktopServices::openUrl(m_lastBugUrl);
}
void AWBugReporter::showInformation(const int _number, const QString &_url)
{
qCDebug(LOG_AW) << "Created issue with number" << _number << "and url" << _url;
@ -131,9 +121,29 @@ void AWBugReporter::showInformation(const int _number, const QString &_url)
// cache url first
m_lastBugUrl = _url;
auto event = KNotification::event("system", i18n("Issue created"), i18n("Issue %1 has been created", _number));
event->setComponentName("plasma-applet-org.kde.plasma.awesome-widget");
auto *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->setStandardButtons(QMessageBox::Open | QMessageBox::Close);
msgBox->setIcon(QMessageBox::Information);
auto action = event->addAction(i18n("Details"));
connect(action, &KNotificationAction::activated, this, &AWBugReporter::openBugReport);
msgBox->open(this, SLOT(userReplyOnBugReport(QAbstractButton *)));
}
void AWBugReporter::userReplyOnBugReport(QAbstractButton *_button)
{
QMessageBox::ButtonRole ret = dynamic_cast<QMessageBox *>(sender())->buttonRole(_button);
qCInfo(LOG_AW) << "User select" << ret;
switch (ret) {
case QMessageBox::AcceptRole:
QDesktopServices::openUrl(m_lastBugUrl);
break;
case QMessageBox::RejectRole:
default:
break;
}
}

View File

@ -15,12 +15,14 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWBUGREPORTER_H
#define AWBUGREPORTER_H
#include <QObject>
class QNetworkAccessManager;
class QAbstractButton;
class QNetworkReply;
class AWBugReporter : public QObject
@ -30,7 +32,7 @@ class AWBugReporter : public QObject
public:
explicit AWBugReporter(QObject *_parent = nullptr);
~AWBugReporter() override;
Q_INVOKABLE void doConnect() const;
Q_INVOKABLE void doConnect();
Q_INVOKABLE static QString generateText(const QString &_description, const QString &_reproduce,
const QString &_expected, const QString &_logs);
Q_INVOKABLE void sendBugReport(const QString &_title, const QString &_body);
@ -39,11 +41,13 @@ signals:
void replyReceived(int _number, const QString &_url);
private slots:
void issueReplyReceived(QNetworkReply *_reply);
void openBugReport();
void issueReplyRecieved(QNetworkReply *_reply);
void showInformation(int _number, const QString &_url);
void userReplyOnBugReport(QAbstractButton *_button);
private:
QString m_lastBugUrl;
QNetworkAccessManager *m_manager = nullptr;
};
#endif /* AWBUGREPORTER_H */

View File

@ -34,11 +34,17 @@ AWConfigHelper::AWConfigHelper(QObject *_parent)
}
AWConfigHelper::~AWConfigHelper()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
QString AWConfigHelper::configurationDirectory()
{
// get readable directory
auto 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;
@ -53,7 +59,7 @@ QString AWConfigHelper::configurationDirectory()
bool AWConfigHelper::dropCache()
{
auto fileName
QString fileName
= QString("%1/awesomewidgets.ndx").arg(QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation));
return QFile(fileName).remove();
@ -66,10 +72,10 @@ bool AWConfigHelper::exportConfiguration(QObject *_nativeConfig, const QString &
QSettings settings(_fileName, QSettings::IniFormat);
// plasmoid configuration
auto configuration = dynamic_cast<const QQmlPropertyMap *>(_nativeConfig);
const auto *configuration = dynamic_cast<const QQmlPropertyMap *>(_nativeConfig);
settings.beginGroup("plasmoid");
for (auto &key : configuration->keys()) {
auto value = configuration->value(key);
QVariant value = configuration->value(key);
if (!value.isValid())
continue;
settings.setValue(key, value);
@ -78,7 +84,8 @@ bool AWConfigHelper::exportConfiguration(QObject *_nativeConfig, const QString &
// extensions
for (auto &item : m_dirs) {
auto items = QDir(QString("%1/%2").arg(m_baseDir, item)).entryList({"*.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);
@ -156,7 +163,7 @@ QVariantMap AWConfigHelper::importConfiguration(const QString &_fileName, const
QVariantMap AWConfigHelper::readDataEngineConfiguration()
{
auto 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;
@ -180,8 +187,8 @@ bool AWConfigHelper::writeDataEngineConfiguration(const QVariantMap &_configurat
{
qCDebug(LOG_AW) << "Configuration" << _configuration;
auto fileName = QString("%1/plasma-dataengine-extsysmon.conf")
.arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation));
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();
@ -204,15 +211,15 @@ void AWConfigHelper::copyConfigs(const QString &_localDir)
{
qCDebug(LOG_AW) << "Local directory" << _localDir;
auto 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;
auto files = QDir(dir).entryList(QDir::Files);
QStringList files = QDir(dir).entryList(QDir::Files);
for (auto &source : files) {
auto destination = QString("%1/%2").arg(_localDir, source);
auto status = QFile::copy(QString("%1/%2").arg(dir, source), destination);
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;
}
}
@ -225,7 +232,7 @@ void AWConfigHelper::copyExtensions(const QString &_item, const QString &_type,
qCDebug(LOG_AW) << "Extension" << _item << "has type" << _type << "inverse copying" << _inverse;
_settings.beginGroup(_item);
QSettings itemSettings(QString("%1/%2/%3").arg(m_baseDir, _type, _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);
@ -252,7 +259,7 @@ void AWConfigHelper::readFile(QSettings &_settings, const QString &_key, const Q
QFile file(_fileName);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
auto text = QString::fromUtf8(file.readAll());
QString text = QString::fromUtf8(file.readAll());
file.close();
_settings.setValue(_key, text);
} else {

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWCONFIGHELPER_H
#define AWCONFIGHELPER_H
#include <QObject>
#include <QVariant>
@ -29,7 +31,7 @@ class AWConfigHelper : public QObject
public:
explicit AWConfigHelper(QObject *_parent = nullptr);
~AWConfigHelper() override = default;
~AWConfigHelper() override;
Q_INVOKABLE [[nodiscard]] static QString configurationDirectory();
Q_INVOKABLE static bool dropCache();
Q_INVOKABLE bool exportConfiguration(QObject *_nativeConfig, const QString &_fileName) const;
@ -50,3 +52,6 @@ private:
QString m_baseDir;
QStringList m_dirs = {"desktops", "quotes", "scripts", "upgrade", "weather", "formatters"};
};
#endif /* AWCONFIGHELPER_H */

View File

@ -27,5 +27,11 @@ AWCustomKeysConfig::AWCustomKeysConfig(QWidget *_parent, const QStringList &_key
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
setEditable(true, false);
setHelper(std::make_unique<AWCustomKeysHelper>());
initHelper<AWCustomKeysHelper>();
}
AWCustomKeysConfig::~AWCustomKeysConfig()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWCUSTOMKEYSCONFIG_H
#define AWCUSTOMKEYSCONFIG_H
#include "awabstractpairconfig.h"
@ -26,5 +28,8 @@ class AWCustomKeysConfig : public AWAbstractPairConfig
public:
explicit AWCustomKeysConfig(QWidget *_parent = nullptr, const QStringList &_keys = QStringList());
~AWCustomKeysConfig() override = default;
~AWCustomKeysConfig() override;
};
#endif /* AWCUSTOMKEYSCONFIG_H */

View File

@ -30,6 +30,12 @@ AWCustomKeysHelper::AWCustomKeysHelper(QObject *_parent)
}
AWCustomKeysHelper::~AWCustomKeysHelper()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
QString AWCustomKeysHelper::source(const QString &_key) const
{
qCDebug(LOG_AW) << "Get source by key" << _key;

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWCUSTOMKEYSHELPER_H
#define AWCUSTOMKEYSHELPER_H
#include <QObject>
@ -28,7 +30,7 @@ class AWCustomKeysHelper : public QObject, public AWAbstractPairHelper
public:
explicit AWCustomKeysHelper(QObject *_parent = nullptr);
~AWCustomKeysHelper() override = default;
~AWCustomKeysHelper() override;
// get
[[nodiscard]] QString source(const QString &_key) const;
[[nodiscard]] QStringList sources() const;
@ -37,4 +39,9 @@ public:
void editPairs() override{};
QStringList leftKeys() override;
QStringList rightKeys() override;
private:
};
#endif /* AWCUSTOMKEYSHELPER_H */

View File

@ -50,8 +50,7 @@ AWDataAggregator::~AWDataAggregator()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_toolTipView->deleteLater();
m_toolTipScene->deleteLater();
delete m_toolTipScene;
}
@ -85,26 +84,26 @@ void AWDataAggregator::setParameters(const QVariantMap &_settings)
// resize tooltip image
m_toolTipView->resize(100 * m_counts, 105);
m_requiredKeys.clear();
requiredKeys.clear();
if (m_configuration["cpuTooltip"].toBool())
m_requiredKeys.append("cpuTooltip");
requiredKeys.append("cpuTooltip");
if (m_configuration["cpuclTooltip"].toBool())
m_requiredKeys.append("cpuclTooltip");
requiredKeys.append("cpuclTooltip");
if (m_configuration["memTooltip"].toBool())
m_requiredKeys.append("memTooltip");
requiredKeys.append("memTooltip");
if (m_configuration["swapTooltip"].toBool())
m_requiredKeys.append("swapTooltip");
requiredKeys.append("swapTooltip");
if (m_configuration["downkbTooltip"].toBool())
m_requiredKeys.append("downkbTooltip");
requiredKeys.append("downkbTooltip");
if (m_configuration["upkbTooltip"].toBool())
m_requiredKeys.append("upkbTooltip");
requiredKeys.append("upkbTooltip");
if (m_configuration["batTooltip"].toBool())
m_requiredKeys.append("batTooltip");
requiredKeys.append("batTooltip");
// background
m_toolTipScene->setBackgroundBrush(m_configuration["useTooltipBackground"].toBool()
? QColor(m_configuration["tooltipBackground"].toString())
: Qt::NoBrush);
? QBrush(QColor(m_configuration["tooltipBackground"].toString()))
: QBrush(Qt::NoBrush));
}
@ -113,42 +112,34 @@ QPixmap AWDataAggregator::tooltipImage()
// create image
m_toolTipScene->clear();
QPen pen;
auto shift = 0.0;
for (auto i = 0; i < m_requiredKeys.count(); ++i) {
auto key = m_requiredKeys[i];
bool down = false;
for (auto &key : requiredKeys) {
// create frame
auto normX = 100.0 / static_cast<float>(m_values[key].count());
auto normY = 100.0 / (1.5 * m_boundaries[key]);
float normX = 100.0f / static_cast<float>(m_values[key].count());
float normY = 100.0f / (1.5f * m_boundaries[key]);
float shift = static_cast<float>(requiredKeys.indexOf(key)) * 100.0f;
if (down)
shift -= 100.0;
// apply pen color
if (key != "batTooltip")
pen.setColor(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
auto x1 = j * normX + shift;
auto y1 = -std::fabs(m_values[key].at(j)) * normY + 5.0;
auto x2 = (j + 1) * normX + shift;
auto y2 = -std::fabs(m_values[key].at(j + 1)) * normY + 5.0;
// apply color for the battery tooltip based on charge/discharge
float x1 = j * normX + shift;
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 == "batTooltip") {
if (m_values[key].at(j + 1) > 0)
pen.setColor(QColor(m_configuration["batTooltipColor"].toString()));
else
pen.setColor(QColor(m_configuration["batInTooltipColor"].toString()));
}
m_toolTipScene->addLine(x1, y1, x2, y2, pen);
}
// increase frame shift if not downkbtooltip
// Additional workaround is required because there is frame (uokb and downkb) which contains two charts
// with the same shift
if (key != "downkbTooltip")
shift += 100.0;
if (key == "downkbTooltip")
down = true;
}
return m_toolTipView->grab();
@ -163,7 +154,7 @@ void AWDataAggregator::dataUpdate(const QVariantHash &_values)
}
void AWDataAggregator::checkValue(const QString &_source, const double _value, const double _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;
@ -236,27 +227,25 @@ 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"].toDouble());
setData(_values["ac"].toString() == m_configuration["acOnline"], "batTooltip", _values["bat"].toFloat());
// usual case
setData("cpuTooltip", _values["cpu"].toDouble(), 90.0);
setData("cpuclTooltip", _values["cpucl"].toDouble());
setData("memTooltip", _values["mem"].toDouble(), 80.0);
setData("swapTooltip", _values["swap"].toDouble(), 0.0);
setData("downkbTooltip", _values["downkb"].toDouble());
setData("upkbTooltip", _values["upkb"].toDouble());
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
auto currentNetworkDevice = _values["netdev"].toString();
checkValue("netdev", m_currentNetworkDevice, currentNetworkDevice);
m_currentNetworkDevice = currentNetworkDevice;
[this](const QString &value) {
checkValue("netdev", m_currentNetworkDevice, value);
m_currentNetworkDevice = value;
}(_values["netdev"].toString());
// additional check for GPU load
checkValue("gpu", _values["gpu"].toDouble(), 90.0);
[this](const float value) { checkValue("gpu", value, 90.0); }(_values["gpu"].toFloat());
}
void AWDataAggregator::setData(const QString &_source, double _value, const double _extremum)
void AWDataAggregator::setData(const QString &_source, float _value, const float _extremum)
{
qCDebug(LOG_AW) << "Source" << _source << "to value" << _value << "with extremum" << _extremum;
@ -272,20 +261,16 @@ void AWDataAggregator::setData(const QString &_source, double _value, const doub
m_values[_source].append(_value);
if (_source == "downkbTooltip") {
// to avoid copying of objects to another list we find max elements in each sequence and compare them
auto downMax = m_values["downkbTooltip"].empty()
? 1.0
: *std::max_element(m_values["downkbTooltip"].cbegin(), m_values["downkbTooltip"].cend());
auto upMax = m_values["upkbTooltip"].empty()
? 1.0
: *std::max_element(m_values["upkbTooltip"].cbegin(), m_values["upkbTooltip"].cend());
// assign both
m_boundaries["upkbTooltip"] = m_boundaries["downkbTooltip"] = 1.2 * std::max(downMax, upMax);
QList<float> netValues = m_values["downkbTooltip"] + m_values["upkbTooltip"];
// to avoid inf value of normY
netValues << 1.0;
m_boundaries["downkbTooltip"] = 1.2f * *std::max_element(netValues.cbegin(), netValues.cend());
m_boundaries["upkbTooltip"] = m_boundaries["downkbTooltip"];
}
}
void AWDataAggregator::setData(const bool _dontInvert, const QString &_source, double _value)
void AWDataAggregator::setData(const bool _dontInvert, const QString &_source, float _value)
{
qCDebug(LOG_AW) << "Do not invert" << _dontInvert << "value" << _value << "for source" << _source;

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWTOOLTIP_H
#define AWTOOLTIP_H
#include <QObject>
#include <QVariant>
@ -24,6 +26,7 @@
class QGraphicsScene;
class QGraphicsView;
class QPixmap;
class QThreadPool;
class AWDataAggregator : public QObject
{
@ -46,22 +49,25 @@ private:
// ui
QGraphicsScene *m_toolTipScene = nullptr;
QGraphicsView *m_toolTipView = nullptr;
void checkValue(const QString &_source, double _value, double _extremum) const;
void checkValue(const QString &_source, float _value, float _extremum) const;
void checkValue(const QString &_source, const QString &_current, const QString &_received) const;
void initScene();
static QString notificationText(const QString &_source, float _value);
static QString notificationText(const QString &_source, const QString &_value);
// main method
void setData(const QVariantHash &_values);
void setData(const QString &_source, double _value, double _extremum = -1.0);
void setData(const QString &_source, float _value, float _extremum = -1.0f);
// different signature for battery device
void setData(bool _dontInvert, const QString &_source, double _value);
void setData(bool _dontInvert, const QString &_source, float _value);
// variables
int m_counts = 0;
QVariantHash m_configuration;
QString m_currentNetworkDevice = "lo";
QHash<QString, double> m_boundaries;
QHash<QString, QList<double>> m_values;
QHash<QString, float> m_boundaries;
QHash<QString, QList<float>> m_values;
bool m_enablePopup = false;
QStringList m_requiredKeys;
QStringList requiredKeys;
};
#endif /* AWTOOLTIP_H */

View File

@ -139,7 +139,7 @@ void AWDataEngineAggregator::sensorRemoved(const QString &_sensor)
}
void AWDataEngineAggregator::updateData(const KSysGuard::SensorDataList &_data)
void AWDataEngineAggregator::updateData(KSysGuard::SensorDataList _data)
{
emit(dataUpdated(m_sensors, _data));
}
@ -147,9 +147,9 @@ void AWDataEngineAggregator::updateData(const KSysGuard::SensorDataList &_data)
void AWDataEngineAggregator::updateSensors(const QHash<QString, KSysGuard::SensorInfo> &_sensors)
{
for (auto [source, sensor] : _sensors.asKeyValueRange()) {
if (!isValidSensor(sensor))
for (auto sensor = _sensors.cbegin(); sensor != _sensors.cend(); ++sensor) {
if (!isValidSensor(sensor.value()))
continue;
m_sensors.insert(source, sensor);
m_sensors.insert(sensor.key(), sensor.value());
}
}

View File

@ -49,7 +49,7 @@ public slots:
void dropSource(const QString &_source);
void sensorAdded(const QString &_sensor);
void sensorRemoved(const QString &_sensor);
void updateData(const KSysGuard::SensorDataList &_data);
void updateData(KSysGuard::SensorDataList _data);
void updateSensors(const QHash<QString, KSysGuard::SensorInfo> &_sensors);
private:

View File

@ -52,6 +52,12 @@ AWDataEngineMapper::AWDataEngineMapper(QObject *_parent, AWFormatterHelper *_cus
}
AWDataEngineMapper::~AWDataEngineMapper()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
AWKeysAggregator::FormatterType AWDataEngineMapper::formatter(const QString &_key) const
{
qCDebug(LOG_AW) << "Get formatter for key" << _key;
@ -76,18 +82,18 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source, const KSy
qCDebug(LOG_AW) << "Source" << _source << "with units" << _units;
// regular expressions
static auto cpuRegExp = QRegularExpression("^cpu/cpu.*/usage$");
static auto cpuclRegExp = QRegularExpression("^cpu/cpu.*/frequency$");
static auto cpuTempRegExp = QRegularExpression("^cpu/cpu.*/temperature$");
static auto gpuRegExp = QRegularExpression("^gpu/gpu.*/usage$");
static auto gpuTempRegExp = QRegularExpression("^gpu/gpu.*/temperature$");
static auto hddrRegExp = QRegularExpression("^disk/.*/read$");
static auto hddwRegExp = QRegularExpression("^disk/.*/write$");
static auto mountFillRegExp = QRegularExpression("^disk/.*/usedPercent$");
static auto mountFreeRegExp = QRegularExpression("^disk/.*/free$");
static auto mountUsedRegExp = QRegularExpression("^disk/.*/used$");
static auto netRegExp = QRegularExpression("^network/.*/(download|upload)$");
static auto netTotalRegExp = QRegularExpression("^network/.*/(totalDownload|totalUpload)$");
auto cpuRegExp = QRegularExpression("^cpu/cpu.*/usage$");
auto cpuclRegExp = QRegularExpression("^cpu/cpu.*/frequency$");
auto cpuTempRegExp = QRegularExpression("^cpu/cpu.*/temperature$");
auto gpuRegExp = QRegularExpression("^gpu/gpu.*/usage$");
auto gpuTempRegExp = QRegularExpression("^gpu/gpu.*/temperature$");
auto hddrRegExp = QRegularExpression("^disk/.*/read$");
auto hddwRegExp = QRegularExpression("^disk/.*/write$");
auto mountFillRegExp = QRegularExpression("^disk/.*/usedPercent$");
auto mountFreeRegExp = QRegularExpression("^disk/.*/free$");
auto mountUsedRegExp = QRegularExpression("^disk/.*/used$");
auto netRegExp = QRegularExpression("^network/.*/(download|upload)$");
auto netTotalRegExp = QRegularExpression("^network/.*/(totalDownload|totalUpload)$");
if (_source == "extsysmon/battery/ac") {
// AC
@ -147,7 +153,7 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source, const KSy
if (index > -1) {
QString key = QString("hddr%1").arg(index);
m_map.insert(_source, key);
m_formatter[key] = AWKeysAggregator::FormatterType::MemKBFormat;
m_formatter[key] = AWKeysAggregator::FormatterType::Integer;
}
} else if (_source.contains(hddwRegExp)) {
// write speed
@ -157,7 +163,7 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source, const KSy
if (index > -1) {
QString key = QString("hddw%1").arg(index);
m_map.insert(_source, key);
m_formatter[key] = AWKeysAggregator::FormatterType::MemKBFormat;
m_formatter[key] = AWKeysAggregator::FormatterType::Integer;
}
} else if (_source == "gpu/all/usage") {
// gpu load
@ -203,7 +209,7 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source, const KSy
auto index = m_devices["mount"].indexOf(device);
if (index > -1) {
// mb
auto key = QString("hddfreemb%1").arg(index);
QString key = QString("hddfreemb%1").arg(index);
m_map.insert(_source, key);
m_formatter[key] = AWKeysAggregator::FormatterType::MemMBFormat;
// gb
@ -218,7 +224,7 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source, const KSy
auto index = m_devices["mount"].indexOf(device);
if (index > -1) {
// mb
auto key = QString("hddmb%1").arg(index);
QString key = QString("hddmb%1").arg(index);
m_map.insert(_source, key);
m_formatter[key] = AWKeysAggregator::FormatterType::MemMBFormat;
// gb
@ -279,7 +285,7 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source, const KSy
// kb
auto key = QString("%1kb%2").arg(type).arg(index);
m_map.insert(_source, key);
m_formatter[key] = AWKeysAggregator::FormatterType::MemKBFormat;
m_formatter[key] = AWKeysAggregator::FormatterType::Integer;
// smart
key = QString("%1%2").arg(type).arg(index);
m_map.insert(_source, key);
@ -297,7 +303,7 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source, const KSy
// kb
auto key = QString("%1totkb%2").arg(type).arg(index);
m_map.insert(_source, key);
m_formatter[key] = AWKeysAggregator::FormatterType::MemKBFormat;
m_formatter[key] = AWKeysAggregator::FormatterType::Integer;
// mb
key = QString("%1tot%2").arg(type).arg(index);
m_map.insert(_source, key);
@ -429,7 +435,7 @@ QStringList AWDataEngineMapper::registerSource(const QString &_source, const KSy
// drop key from dictionary if no one user requested key required it
qCInfo(LOG_AW) << "Looking for keys" << foundKeys << "in" << _keys;
auto required = _keys.isEmpty() || std::any_of(foundKeys.cbegin(), foundKeys.cend(), [&_keys](auto &key) {
auto required = _keys.isEmpty() || std::any_of(foundKeys.cbegin(), foundKeys.cend(), [&_keys](const QString &key) {
return _keys.contains(key);
});
if (!required) {

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWDATAENGINEMAPPER_H
#define AWDATAENGINEMAPPER_H
#include <ksysguard/formatter/Unit.h>
@ -33,12 +35,12 @@ class AWDataEngineMapper : public QObject
public:
explicit AWDataEngineMapper(QObject *_parent = nullptr, AWFormatterHelper *_custom = nullptr);
~AWDataEngineMapper() override = default;
~AWDataEngineMapper() override;
// get methods
[[nodiscard]] AWKeysAggregator::FormatterType formatter(const QString &_key) const;
[[nodiscard]] QStringList keysFromSource(const QString &_source) const;
// set methods
QStringList registerSource(const QString &_source, KSysGuard::Unit _units, const QStringList &_keys);
QStringList registerSource(const QString &_source, const KSysGuard::Unit _units, const QStringList &_keys);
void setDevices(const QHash<QString, QStringList> &_devices);
private:
@ -48,3 +50,6 @@ private:
QHash<QString, AWKeysAggregator::FormatterType> m_formatter;
QMultiHash<QString, QString> m_map;
};
#endif /* AWDATAENGINEMAPPER_H */

View File

@ -32,20 +32,27 @@ AWDBusAdaptor::AWDBusAdaptor(AWKeys *_parent)
}
AWDBusAdaptor::~AWDBusAdaptor()
{
qCDebug(LOG_DBUS) << __PRETTY_FUNCTION__;
}
QStringList AWDBusAdaptor::ActiveServices()
{
auto 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 {};
}
auto arguments = listServices.arguments().first().toStringList();
QStringList arguments = listServices.arguments().first().toStringList();
return std::accumulate(arguments.cbegin(), arguments.cend(), QStringList(), [](auto source, auto &service) {
if (service.startsWith(AWDBUS_SERVICE))
source.append(service);
return source;
});
return std::accumulate(arguments.cbegin(), arguments.cend(), QStringList(),
[](QStringList source, const QString &service) {
if (service.startsWith(AWDBUS_SERVICE))
source.append(service);
return source;
});
}
@ -96,6 +103,6 @@ void AWDBusAdaptor::SetLogLevel(const QString &what, const QString &level, const
return;
}
auto state = enabled ? "true" : "false";
QLoggingCategory::setFilterRules(QString("%1.%2=%3").arg(what, level, state));
QString state = enabled ? "true" : "false";
QLoggingCategory::setFilterRules(QString("%1.%2=%3").arg(what).arg(level).arg(state));
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWDBUSADAPTOR_H
#define AWDBUSADAPTOR_H
#include <QDBusAbstractAdaptor>
@ -31,7 +33,7 @@ class AWDBusAdaptor : public QDBusAbstractAdaptor
public:
explicit AWDBusAdaptor(AWKeys *_parent = nullptr);
~AWDBusAdaptor() override = default;
~AWDBusAdaptor() override;
public slots:
// get methods
@ -48,3 +50,6 @@ private:
AWKeys *m_plugin = nullptr;
QStringList m_logLevels = {"debug", "info", "warning", "critical"};
};
#endif /* AWDBUSADAPTOR_H */

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWPLUGIN_H
#define AWPLUGIN_H
#include <QQmlExtensionPlugin>
@ -28,3 +30,6 @@ class AWPlugin : public QQmlExtensionPlugin
public:
void registerTypes(const char *uri) override;
};
#endif /* AWPLUGIN_H */

View File

@ -27,5 +27,11 @@ AWFormatterConfig::AWFormatterConfig(QWidget *_parent, const QStringList &_keys)
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
setEditable(false, false);
setHelper(std::make_unique<AWFormatterHelper>());
initHelper<AWFormatterHelper>();
}
AWFormatterConfig::~AWFormatterConfig()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWFORMATTERCONFIG_H
#define AWFORMATTERCONFIG_H
#include "awabstractpairconfig.h"
@ -26,5 +28,8 @@ class AWFormatterConfig : public AWAbstractPairConfig
public:
explicit AWFormatterConfig(QWidget *_parent = nullptr, const QStringList &_keys = QStringList());
~AWFormatterConfig() override = default;
~AWFormatterConfig() override;
};
#endif /* AWFORMATTERCONFIG_H */

View File

@ -33,7 +33,7 @@
#include "awstringformatter.h"
AWFormatterHelper::AWFormatterHelper(QObject *_parent)
AWFormatterHelper::AWFormatterHelper(QWidget *_parent)
: AbstractExtItemAggregator(_parent, "formatters")
, AWAbstractPairHelper("awesomewidgets/formatters/formatters.ini", "Formatters")
{
@ -58,7 +58,8 @@ void AWFormatterHelper::initItems()
// assign internal storage
m_formatters.clear();
for (auto [key, name] : pairs().asKeyValueRange()) {
for (auto &key : pairs().keys()) {
auto name = pairs()[key];
if (!m_formattersClasses.contains(name)) {
qCWarning(LOG_AW) << "Invalid formatter" << name << "found in" << key;
continue;
@ -86,7 +87,7 @@ QStringList AWFormatterHelper::definedFormatters() const
QList<AbstractExtItem *> AWFormatterHelper::items() const
{
QList<AbstractExtItem *> converted;
for (auto item : m_formattersClasses.values())
for (auto &item : m_formattersClasses.values())
converted.append(item);
return converted;
@ -122,7 +123,7 @@ AWAbstractFormatter::FormatterClass AWFormatterHelper::defineFormatterClass(cons
{
qCDebug(LOG_AW) << "Define formatter class for" << _stringType;
auto formatter = AWAbstractFormatter::FormatterClass::NoFormat;
AWAbstractFormatter::FormatterClass formatter = AWAbstractFormatter::FormatterClass::NoFormat;
if (_stringType == "DateTime")
formatter = AWAbstractFormatter::FormatterClass::DateTime;
else if (_stringType == "Float")
@ -150,17 +151,17 @@ void AWFormatterHelper::initFormatters()
auto dirs = directories();
for (auto &dir : dirs) {
auto files = QDir(dir).entryList(QDir::Files, QDir::Name);
QStringList files = QDir(dir).entryList(QDir::Files, QDir::Name);
for (auto &file : files) {
// check filename
if (!file.endsWith(".desktop"))
continue;
qCInfo(LOG_AW) << "Found file" << file << "in" << dir;
auto filePath = QString("%1/%2").arg(dir, file);
QString filePath = QString("%1/%2").arg(dir).arg(file);
// check if already exists
auto values = m_formattersClasses.values();
if (std::any_of(values.cbegin(), values.cend(),
[&filePath](auto item) { return (item->filePath() == filePath); }))
[&filePath](const AWAbstractFormatter *item) { return (item->fileName() == filePath); }))
continue;
auto metadata = readMetadata(filePath);
@ -197,14 +198,13 @@ QPair<QString, AWAbstractFormatter::FormatterClass> AWFormatterHelper::readMetad
qCDebug(LOG_AW) << "Read initial parameters from" << _filePath;
QSettings settings(_filePath, QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
auto name = settings.value("Name", _filePath).toString();
auto type = settings.value("X-AW-Type", "NoFormat").toString();
auto formatter = defineFormatterClass(type);
settings.endGroup();
return {name, formatter};
return QPair<QString, AWAbstractFormatter::FormatterClass>(name, formatter);
}
@ -219,7 +219,7 @@ void AWFormatterHelper::doCreateItem(QListWidget *_widget)
}
qCInfo(LOG_AW) << "Selected type" << select;
auto formatter = defineFormatterClass(select);
AWAbstractFormatter::FormatterClass formatter = defineFormatterClass(select);
switch (formatter) {
case AWAbstractFormatter::FormatterClass::DateTime:
return createItem<AWDateTimeFormatter>(_widget);

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWFORMATTERHELPER_H
#define AWFORMATTERHELPER_H
#include "abstractextitemaggregator.h"
#include "awabstractformatter.h"
@ -27,7 +29,7 @@ class AWFormatterHelper : public AbstractExtItemAggregator, public AWAbstractPai
Q_OBJECT
public:
explicit AWFormatterHelper(QObject *_parent = nullptr);
explicit AWFormatterHelper(QWidget *_parent = nullptr);
~AWFormatterHelper() override;
// read-write methods
void initItems() override;
@ -54,3 +56,6 @@ private:
QHash<QString, AWAbstractFormatter *> m_formatters;
QHash<QString, AWAbstractFormatter *> m_formattersClasses;
};
#endif /* AWFORMATTERHELPER_H */

View File

@ -44,7 +44,7 @@ bool AWKeyCache::addKeyToCache(const QString &_type, const QString &_key)
if (_type == "net") {
auto rawInterfaceList = QNetworkInterface::allInterfaces();
for (auto &interface : rawInterfaceList) {
auto device = interface.name();
QString device = interface.name();
if (cachedValues.contains(device))
continue;
qCInfo(LOG_AW) << "Found new key" << device << "for type" << _type;
@ -74,11 +74,10 @@ QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys, const QStringL
used.unite(QSet(_bars.cbegin(), _bars.cend()));
used.unite(QSet(_userKeys.cbegin(), _userKeys.cend()));
// insert keys from tooltip
for (auto [key, value] : _tooltip.asKeyValueRange()) {
if ((key.endsWith("Tooltip")) && value.toBool()) {
auto local = key;
local.remove("Tooltip");
used << local;
for (auto &key : _tooltip.keys()) {
if ((key.endsWith("Tooltip")) && (_tooltip[key].toBool())) {
key.remove("Tooltip");
used << key;
}
}
@ -134,7 +133,7 @@ QStringList AWKeyCache::getRequiredKeys(const QStringList &_keys, const QStringL
used << filtered;
}
// netdev key
if (std::any_of(netKeys.cbegin(), netKeys.cend(), [&used](auto &key) { return used.contains(key); }))
if (std::any_of(netKeys.cbegin(), netKeys.cend(), [&used](const QString &key) { return used.contains(key); }))
used << "netdev";
// HACK append dummy if there are no other keys. This hack is required

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWKEYCACHE_H
#define AWKEYCACHE_H
#include <QHash>
#include <QString>
@ -29,3 +31,6 @@ QStringList getRequiredKeys(const QStringList &_keys, const QStringList &_bars,
const QStringList &_userKeys, const QStringList &_allKeys);
QHash<QString, QStringList> loadKeysFromCache();
} // namespace AWKeyCache
#endif /* AWKEYCACHE_H */

View File

@ -40,12 +40,18 @@ AWKeyOperations::AWKeyOperations(QObject *_parent)
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_customKeys = new AWCustomKeysHelper(this);
m_graphicalItems = new ExtItemAggregator<GraphicalItem>(this, "desktops");
m_extNetRequest = new ExtItemAggregator<ExtNetworkRequest>(this, "requests");
m_extQuotes = new ExtItemAggregator<ExtQuotes>(this, "quotes");
m_extScripts = new ExtItemAggregator<ExtScript>(this, "scripts");
m_extUpgrade = new ExtItemAggregator<ExtUpgrade>(this, "upgrade");
m_extWeather = new ExtItemAggregator<ExtWeather>(this, "weather");
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");
m_extWeather = new ExtItemAggregator<ExtWeather>(nullptr, "weather");
}
AWKeyOperations::~AWKeyOperations()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
@ -74,7 +80,7 @@ QStringList AWKeyOperations::dictKeys() const
{
QStringList allKeys;
// weather
for (auto item : m_extWeather->activeItems()) {
for (auto &item : m_extWeather->activeItems()) {
allKeys.append(item->tag("weatherId"));
allKeys.append(item->tag("weather"));
allKeys.append(item->tag("humidity"));
@ -83,20 +89,20 @@ QStringList AWKeyOperations::dictKeys() const
allKeys.append(item->tag("timestamp"));
}
// cpuclock & cpu
for (auto i = 0; i < QThread::idealThreadCount(); ++i) {
for (auto i = 0; i < QThread::idealThreadCount(); i++) {
allKeys.append(QString("cpucl%1").arg(i));
allKeys.append(QString("cpu%1").arg(i));
}
// temperature
for (auto i = 0; i < m_devices["temp"].count(); ++i)
for (auto i = 0; i < m_devices["temp"].count(); i++)
allKeys.append(QString("temp%1").arg(i));
// gpu
for (auto i = 0; i < m_devices["gpu"].count(); ++i) {
for (auto i = 0; i < m_devices["gpu"].count(); i++) {
allKeys.append(QString("gpu%1").arg(i));
allKeys.append(QString("gputemp%1").arg(i));
}
// hdd
for (auto i = 0; i < m_devices["mount"].count(); ++i) {
for (auto 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));
@ -106,12 +112,12 @@ QStringList AWKeyOperations::dictKeys() const
allKeys.append(QString("hdd%1").arg(i));
}
// hdd speed
for (auto i = 0; i < m_devices["disk"].count(); ++i) {
for (auto i = 0; i < m_devices["disk"].count(); i++) {
allKeys.append(QString("hddr%1").arg(i));
allKeys.append(QString("hddw%1").arg(i));
}
// network
for (auto i = 0; i < m_devices["net"].count(); ++i) {
for (auto 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("downtotkb%1").arg(i));
@ -126,7 +132,7 @@ QStringList AWKeyOperations::dictKeys() const
// battery
auto allBatteryDevices = QDir("/sys/class/power_supply")
.entryList(QStringList({"BAT*"}), QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
for (int i = 0; i < allBatteryDevices.count(); ++i) {
for (int i = 0; i < allBatteryDevices.count(); i++) {
allKeys.append(QString("bat%1").arg(i));
allKeys.append(QString("batleft%1").arg(i));
allKeys.append(QString("batnow%1").arg(i));
@ -134,10 +140,10 @@ QStringList AWKeyOperations::dictKeys() const
allKeys.append(QString("battotal%1").arg(i));
}
// package manager
for (auto item : m_extUpgrade->activeItems())
for (auto &item : m_extUpgrade->activeItems())
allKeys.append(item->tag("pkgcount"));
// quotes
for (auto item : m_extQuotes->activeItems()) {
for (auto &item : m_extQuotes->activeItems()) {
allKeys.append(item->tag("price"));
allKeys.append(item->tag("pricechg"));
allKeys.append(item->tag("percpricechg"));
@ -146,13 +152,13 @@ QStringList AWKeyOperations::dictKeys() const
allKeys.append(item->tag("percvolumechg"));
}
// custom
for (auto item : m_extScripts->activeItems())
for (auto &item : m_extScripts->activeItems())
allKeys.append(item->tag("custom"));
// network requests
for (auto item : m_extNetRequest->activeItems())
for (auto &item : m_extNetRequest->activeItems())
allKeys.append(item->tag("response"));
// bars
for (auto item : m_graphicalItems->activeItems())
for (auto &item : m_graphicalItems->activeItems())
allKeys.append(item->tag("bar"));
// user defined keys
allKeys.append(m_customKeys->keys());
@ -199,50 +205,40 @@ QString AWKeyOperations::infoByKey(const QString &_key) const
{
qCDebug(LOG_AW) << "Requested key" << _key;
static auto numberRegExp = QRegularExpression("\\d+");
auto stripped = _key;
stripped.remove(numberRegExp);
stripped.remove(QRegularExpression("\\d+"));
QString output;
static auto hddRegExp = QRegularExpression("^hdd(|mb|gb|freemb|freegb|totmb|totgb)");
static auto hddrwRegExp = QRegularExpression("^hdd[rw]");
static auto hddMatchRegExp = QRegularExpression("^hdd([0-9]|mb|gb|freemb|freegb|totmb|totgb)");
static auto netRegExp = QRegularExpression("^(down|up)");
static auto netMatchRegExp = QRegularExpression("^(down|up)[0-9]");
static auto quotesRegExp = QRegularExpression("^(|perc)(ask|bid|price)(chg|)");
static auto weatherRegExp = QRegularExpression("^(weather|weatherId|humidity|pressure|temperature)");
if (_key.startsWith("bar")) {
auto item = m_graphicalItems->itemByTag(_key, stripped);
auto *item = m_graphicalItems->itemByTag(_key, stripped);
if (item)
output = item->uniq();
} else if (_key.startsWith("custom")) {
auto item = m_extScripts->itemByTag(_key, stripped);
auto *item = m_extScripts->itemByTag(_key, stripped);
if (item)
output = item->uniq();
} else if (_key.contains(hddrwRegExp)) {
} else if (_key.contains(QRegularExpression("^hdd[rw]"))) {
auto index = _key;
index.remove(hddrwRegExp);
index.remove(QRegularExpression("hdd[rw]"));
output = m_devices["disk"][index.toInt()];
} else if (_key.contains(hddMatchRegExp)) {
} else if (_key.contains(QRegularExpression("^hdd([0-9]|mb|gb|freemb|freegb|totmb|totgb)"))) {
auto index = _key;
index.remove(hddRegExp);
index.remove(QRegularExpression("^hdd(|mb|gb|freemb|freegb|totmb|totgb)"));
output = m_devices["mount"][index.toInt()];
} else if (_key.contains(netMatchRegExp)) {
} else if (_key.contains(QRegularExpression("^(down|up)[0-9]"))) {
auto index = _key;
index.remove(netRegExp);
index.remove(QRegularExpression("^(down|up)"));
output = m_devices["net"][index.toInt()];
} else if (_key.startsWith("pkgcount")) {
auto item = m_extUpgrade->itemByTag(_key, stripped);
auto *item = m_extUpgrade->itemByTag(_key, stripped);
if (item)
output = item->uniq();
} else if (_key.contains(quotesRegExp)) {
auto item = m_extQuotes->itemByTag(_key, stripped);
} else if (_key.contains(QRegularExpression("(^|perc)(ask|bid|price)(chg|)"))) {
auto *item = m_extQuotes->itemByTag(_key, stripped);
if (item)
output = item->uniq();
} else if (_key.contains(weatherRegExp)) {
auto item = m_extWeather->itemByTag(_key, stripped);
} else if (_key.contains(QRegularExpression("(weather|weatherId|humidity|pressure|temperature)"))) {
auto *item = m_extWeather->itemByTag(_key, stripped);
if (item)
output = item->uniq();
} else if (_key.startsWith("temp")) {
@ -250,7 +246,7 @@ QString AWKeyOperations::infoByKey(const QString &_key) const
index.remove("temp");
output = m_devices["temp"][index.toInt()];
} else if (_key.startsWith("response")) {
auto item = m_extNetRequest->itemByTag(_key, stripped);
auto *item = m_extNetRequest->itemByTag(_key, stripped);
if (item)
output = item->uniq();
} else {
@ -279,10 +275,8 @@ void AWKeyOperations::editItem(const QString &_type)
{
qCDebug(LOG_AW) << "Item type" << _type;
static auto supportsGraphicalRegExp = QRegularExpression("^(cpu(?!cl).*|gpu$|mem$|swap$|hdd[0-9].*|bat.*)");
if (_type == "graphicalitem") {
auto keys = dictKeys().filter(supportsGraphicalRegExp);
QStringList keys = dictKeys().filter(QRegularExpression("^(cpu(?!cl).*|gpu$|mem$|swap$|hdd[0-9].*|bat.*)"));
keys.sort();
m_graphicalItems->setConfigArgs(keys);
return m_graphicalItems->editItems();
@ -304,10 +298,10 @@ void AWKeyOperations::addDevice(const QString &_source)
{
qCDebug(LOG_AW) << "Source" << _source;
static auto diskRegexp = QRegularExpression("^disk/.*/read$");
static auto mountRegexp = QRegularExpression("^disk/.*/usedPercent$");
static auto cpuTempRegExp = QRegularExpression("^cpu/cpu.*/temperature$");
static auto gpuRegExp = QRegularExpression("^gpu/gpu.*/usage$");
auto diskRegexp = QRegularExpression("^disk/.*/read$");
auto mountRegexp = QRegularExpression("^disk/.*/usedPercent$");
auto cpuTempRegExp = QRegularExpression("^cpu/cpu.*/temperature$");
auto gpuRegExp = QRegularExpression("^gpu/gpu.*/usage$");
if (_source.contains(diskRegexp)) {
auto device = _source;
@ -350,7 +344,7 @@ void AWKeyOperations::reinitKeys()
m_extWeather->initItems();
// init
auto allKeys = dictKeys();
QStringList allKeys = dictKeys();
// apply aw_* functions
m_pattern = AWPatternFunctions::insertAllKeys(m_pattern, allKeys);

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWKEYOPERATIONS_H
#define AWKEYOPERATIONS_H
#include <QObject>
@ -37,7 +39,7 @@ class AWKeyOperations : public QObject
public:
explicit AWKeyOperations(QObject *_parent = nullptr);
~AWKeyOperations() override = default;
~AWKeyOperations() override;
[[nodiscard]] QStringList devices(const QString &_type) const;
[[nodiscard]] QHash<QString, QStringList> devices() const;
void updateCache();
@ -76,3 +78,6 @@ private:
QHash<QString, QStringList> m_devices;
QString m_pattern;
};
#endif /* AWKEYOPERATIONS_H */

View File

@ -19,8 +19,9 @@
#include <QDBusConnection>
#include <QDBusError>
#include <QRegularExpression>
#include <QThread>
#include <QTimer>
#include <QtConcurrent/QtConcurrent>
#include "awdataaggregator.h"
#include "awdataengineaggregator.h"
@ -41,6 +42,9 @@ AWKeys::AWKeys(QObject *_parent)
for (auto &metadata : AWDebug::getBuildData())
qCDebug(LOG_AW) << metadata;
// thread pool
m_threadPool = new QThreadPool(this);
m_aggregator = new AWKeysAggregator(this);
m_dataAggregator = new AWDataAggregator(this);
m_dataEngineAggregator = new AWDataEngineAggregator(this);
@ -87,12 +91,14 @@ void AWKeys::initDataAggregator(const QVariantMap &_tooltipParams)
}
void AWKeys::initKeys(const QString &_currentPattern, const int _interval, 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 << "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);
// child objects
m_aggregator->initFormatters();
m_keyOperator->setPattern(_currentPattern);
@ -147,6 +153,26 @@ QStringList AWKeys::dictKeys(const bool _sorted, const QString &_regexp) const
}
QVariantList AWKeys::getHddDevices() const
{
QStringList hddDevices = m_keyOperator->devices("hdd");
// required by selector in the UI
hddDevices.insert(0, "disable");
hddDevices.insert(0, "auto");
// build model
QVariantList devices;
for (auto &device : hddDevices) {
QVariantMap model;
model["label"] = device;
model["name"] = device;
devices.append(model);
}
return devices;
}
QString AWKeys::infoByKey(const QString &_key) const
{
qCDebug(LOG_AW) << "Requested info for key" << _key;
@ -176,13 +202,12 @@ void AWKeys::editItem(const QString &_type)
void AWKeys::dataUpdated(const QHash<QString, KSysGuard::SensorInfo> &_sensors, const KSysGuard::SensorDataList &_data)
{
qCDebug(LOG_AW) << "Update data for" << _data.count() << "items";
for (auto &data : _data) {
if (!_sensors.contains(data.sensorProperty))
continue;
auto sensor = _sensors[data.sensorProperty];
setDataBySource(data.sensorProperty, sensor, data.payload);
for (auto &single : _data) {
if (_sensors.contains(single.sensorProperty)) {
setDataBySource(single.sensorProperty, _sensors.value(single.sensorProperty), single);
}
// TODO use QtConcurrent::map or something like that
// QtConcurrent::run(m_threadPool, this, &AWKeys::setDataBySource, "ss", sensor);
}
}
@ -198,7 +223,7 @@ void AWKeys::reinitKeys(const QStringList &_currentKeys)
// generate list of required keys for bars
QStringList barKeys;
for (auto &bar : m_foundBars) {
auto item = m_keyOperator->giByKey(bar);
GraphicalItem *item = m_keyOperator->giByKey(bar);
if (item->isCustom())
item->setUsedKeys(AWPatternFunctions::findKeys(item->bar(), _currentKeys, false));
else
@ -218,10 +243,12 @@ void AWKeys::reinitKeys(const QStringList &_currentKeys)
void AWKeys::updateTextData()
{
// do not do it in parallel to avoid race condition
m_mutex.lock();
calculateValues();
auto text = parsePattern(m_keyOperator->pattern());
// update tooltip values under lock
m_dataAggregator->dataUpdate(m_values);
m_mutex.unlock();
emit(needTextToBeUpdated(text));
}
@ -232,9 +259,9 @@ void AWKeys::updateTextData()
void AWKeys::calculateValues()
{
// hddtot*
auto mountDevices = m_keyOperator->devices("mount");
QStringList mountDevices = m_keyOperator->devices("mount");
for (auto &device : mountDevices) {
auto index = mountDevices.indexOf(device);
int index = mountDevices.indexOf(device);
m_values[QString("hddtotmb%1").arg(index)] = m_values[QString("hddfreemb%1").arg(index)].toDouble()
+ m_values[QString("hddmb%1").arg(index)].toDouble();
m_values[QString("hddtotgb%1").arg(index)] = m_values[QString("hddfreegb%1").arg(index)].toDouble()
@ -245,10 +272,10 @@ void AWKeys::calculateValues()
m_values["memtotmb"] = m_values["memusedmb"].toLongLong() + m_values["memfreemb"].toLongLong();
m_values["memtotgb"] = m_values["memusedgb"].toDouble() + m_values["memfreegb"].toDouble();
// mem
m_values["mem"] = 100.0 * m_values["memmb"].toDouble() / m_values["memtotmb"].toDouble();
m_values["mem"] = 100.0f * m_values["memmb"].toDouble() / m_values["memtotmb"].toDouble();
// up, down, upkb, downkb, upunits, downunits
auto 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)];
@ -264,7 +291,7 @@ void AWKeys::calculateValues()
m_values["swaptotmb"] = m_values["swapmb"].toLongLong() + m_values["swapfreemb"].toLongLong();
m_values["swaptotgb"] = m_values["swapgb"].toDouble() + m_values["swapfreegb"].toDouble();
// swap
m_values["swap"] = 100.0 * m_values["swapmb"].toDouble() / m_values["swaptotmb"].toDouble();
m_values["swap"] = 100.0f * m_values["swapmb"].toDouble() / m_values["swaptotmb"].toDouble();
// user defined keys
for (auto &key : m_keyOperator->userKeys())
@ -282,7 +309,7 @@ void AWKeys::createDBusInterface()
auto id = reinterpret_cast<qlonglong>(this);
// create session
auto instanceBus = QDBusConnection::sessionBus();
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))) {
@ -293,7 +320,7 @@ void AWKeys::createDBusInterface()
}
// and same instance but for id independent service
auto commonBus = QDBusConnection::sessionBus();
QDBusConnection commonBus = QDBusConnection::sessionBus();
if (commonBus.registerService(AWDBUS_SERVICE))
commonBus.registerObject(AWDBUS_PATH, new AWDBusAdaptor(this), QDBusConnection::ExportAllContents);
}
@ -314,10 +341,10 @@ QString AWKeys::parsePattern(QString _pattern) const
// bars
for (auto &bar : m_foundBars) {
auto item = m_keyOperator->giByKey(bar);
auto image = item->isCustom() ? item->image(
AWPatternFunctions::expandLambdas(item->bar(), m_aggregator, m_values, item->usedKeys()))
: item->image(m_values[item->bar()]);
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()]);
_pattern.replace(QString("$%1").arg(bar), image);
}
@ -330,9 +357,10 @@ QString AWKeys::parsePattern(QString _pattern) const
}
void AWKeys::setDataBySource(const QString &_source, const KSysGuard::SensorInfo &_sensor, const QVariant &_value)
void AWKeys::setDataBySource(const QString &_source, const KSysGuard::SensorInfo &_sensor,
const KSysGuard::SensorData &_data)
{
qCDebug(LOG_AW) << "Source" << _source << _sensor.name << "with data" << _value;
qCDebug(LOG_AW) << "Source" << _source << _sensor.name << "with data" << _data.payload;
// first list init
auto tags = m_aggregator->keysFromSource(_source);
@ -345,5 +373,7 @@ void AWKeys::setDataBySource(const QString &_source, const KSysGuard::SensorInfo
return emit(dropSourceFromDataengine(_source));
}
std::for_each(tags.cbegin(), tags.cend(), [this, _value](const QString &tag) { m_values[tag] = _value; });
m_mutex.lock();
std::for_each(tags.cbegin(), tags.cend(), [this, &_data](const QString &tag) { m_values[tag] = _data.payload; });
m_mutex.unlock();
}

View File

@ -15,8 +15,11 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWKEYS_H
#define AWKEYS_H
#include <QMutex>
#include <QObject>
#include <ksysguard/systemstats/SensorInfo.h>
@ -26,6 +29,7 @@ class AWDataAggregator;
class AWDataEngineAggregator;
class AWKeyOperations;
class AWKeysAggregator;
class QThreadPool;
class QTimer;
class AWKeys : public QObject
@ -36,7 +40,7 @@ public:
explicit AWKeys(QObject *_parent = nullptr);
~AWKeys() override;
Q_INVOKABLE void initDataAggregator(const QVariantMap &_tooltipParams);
Q_INVOKABLE void initKeys(const QString &_currentPattern, int _interval, bool _optimize);
Q_INVOKABLE void initKeys(const QString &_currentPattern, int _interval, int _limit, bool _optimize);
Q_INVOKABLE void setAggregatorProperty(const QString &_key, const QVariant &_value);
Q_INVOKABLE void setWrapNewLines(bool _wrap);
// additional method to force load keys from Qml UI. Used in some
@ -44,19 +48,22 @@ public:
Q_INVOKABLE void updateCache();
// keys
Q_INVOKABLE [[nodiscard]] QStringList dictKeys(bool _sorted = false, const QString &_regexp = "") const;
Q_INVOKABLE [[nodiscard]] QVariantList getHddDevices() const;
// values
Q_INVOKABLE [[nodiscard]] QString infoByKey(const QString &_key) const;
Q_INVOKABLE [[nodiscard]] QString valueByKey(const QString &_key) const;
// configuration
Q_INVOKABLE void editItem(const QString &_type);
public slots:
void dataUpdated(const QHash<QString, KSysGuard::SensorInfo> &_sensors, const KSysGuard::SensorDataList &_data);
signals:
void dropSourceFromDataengine(const QString &_source);
void needTextToBeUpdated(const QString &_newText) const;
void needToolTipToBeUpdated(const QString &_newText) const;
private slots:
void dataUpdated(const QHash<QString, KSysGuard::SensorInfo> &_sensors, const KSysGuard::SensorDataList &_data);
void reinitKeys(const QStringList &_currentKeys);
void updateTextData();
@ -65,7 +72,8 @@ private:
void calculateValues();
void createDBusInterface();
[[nodiscard]] QString parsePattern(QString _pattern) const;
void setDataBySource(const QString &_source, const KSysGuard::SensorInfo &_sensor, const QVariant &_value);
void setDataBySource(const QString &_source, const KSysGuard::SensorInfo &_sensor,
const KSysGuard::SensorData &_data);
// objects
AWDataAggregator *m_dataAggregator = nullptr;
AWDataEngineAggregator *m_dataEngineAggregator = nullptr;
@ -78,4 +86,10 @@ private:
QVariantHash m_values;
bool m_optimize = false;
bool m_wrapNewLines = false;
// multithread features
QThreadPool *m_threadPool = nullptr;
QMutex m_mutex;
};
#endif /* AWKEYS_H */

View File

@ -33,7 +33,7 @@ AWKeysAggregator::AWKeysAggregator(QObject *_parent)
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_customFormatters = new AWFormatterHelper(this);
m_customFormatters = new AWFormatterHelper(nullptr);
m_mapper = new AWDataEngineMapper(this, m_customFormatters);
// sort time keys
@ -43,6 +43,12 @@ AWKeysAggregator::AWKeysAggregator(QObject *_parent)
}
AWKeysAggregator::~AWKeysAggregator()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
void AWKeysAggregator::initFormatters()
{
m_customFormatters->initItems();
@ -79,24 +85,21 @@ QString AWKeysAggregator::formatter(const QVariant &_data, const QString &_key,
output = _data.toBool() ? m_acOnline : m_acOffline;
break;
case FormatterType::MemGBFormat:
output = QString("%1").arg(_data.toDouble() / GBinBytes, 5, 'f', 1);
output = QString("%1").arg(_data.toDouble() / (1024.0 * 1024.0), 5, 'f', 1);
break;
case FormatterType::MemMBFormat:
output = QString("%1").arg(_data.toDouble() / MBinBytes, 5, 'f', 0);
break;
case FormatterType::MemKBFormat:
output = QString("%1").arg(_data.toDouble() / KBinBytes, 5, 'f', 0);
output = QString("%1").arg(_data.toDouble() / 1024.0, 5, 'f', 0);
break;
case FormatterType::NetSmartFormat:
output = [](const double value) {
if (value > MBinBytes)
return QString("%1").arg(value / MBinBytes, 4, 'f', 1);
output = [](const float value) {
if (value > 1024.0)
return QString("%1").arg(value / 1024.0, 4, 'f', 1);
else
return QString("%1").arg(value / KBinBytes, 4, 'f', 0);
return QString("%1").arg(value, 4, 'f', 0);
}(_data.toDouble());
break;
case FormatterType::NetSmartUnits:
if (_data.toDouble() > MBinBytes)
if (_data.toDouble() > 1024.0)
output = m_translate ? i18n("MB/s") : "MB/s";
else
output = m_translate ? i18n("KB/s") : "KB/s";
@ -134,19 +137,17 @@ QString AWKeysAggregator::formatter(const QVariant &_data, const QString &_key,
case FormatterType::Uptime:
case FormatterType::UptimeCustom:
output =
[](auto source, auto uptime) {
auto seconds = uptime - uptime % 60;
auto minutes = seconds / 60 % 60;
auto hours = ((seconds / 60) - minutes) / 60 % 24;
auto days = (((seconds / 60) - minutes) / 60 - hours) / 24;
[](QString source, const int uptime) {
int seconds = uptime - uptime % 60;
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("$d", QString("%1").arg(days));
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("$m", QString("%1").arg(minutes));
return source;
}(m_mapper->formatter(_key) == FormatterType::Uptime ? "$ddd$hhh$mmm" : m_customUptime,
static_cast<int>(_data.toDouble()));
@ -233,7 +234,7 @@ void AWKeysAggregator::setTranslate(const bool _translate)
}
QStringList AWKeysAggregator::registerSource(const QString &_source, const KSysGuard::Unit _units,
QStringList AWKeysAggregator::registerSource(const QString &_source, const KSysGuard::Unit &_units,
const QStringList &_keys)
{
qCDebug(LOG_AW) << "Source" << _source << "with units" << _units;
@ -242,24 +243,24 @@ QStringList AWKeysAggregator::registerSource(const QString &_source, const KSysG
}
double AWKeysAggregator::temperature(const double temp) const
float AWKeysAggregator::temperature(const float temp) const
{
qCDebug(LOG_AW) << "Temperature value" << temp;
auto converted = temp;
float converted = temp;
if (m_tempUnits == "Celsius") {
} else if (m_tempUnits == "Fahrenheit") {
converted = temp * 9.0f / 5.0 + 32.0;
converted = temp * 9.0f / 5.0f + 32.0f;
} else if (m_tempUnits == "Kelvin") {
converted = temp + 273.15;
converted = temp + 273.15f;
} else if (m_tempUnits == "Reaumur") {
converted = temp * 0.8;
converted = temp * 0.8f;
} else if (m_tempUnits == "cm^-1") {
converted = (temp + 273.15) * 0.695;
converted = (temp + 273.15f) * 0.695f;
} else if (m_tempUnits == "kJ/mol") {
converted = (temp + 273.15) * 8.31;
converted = (temp + 273.15f) * 8.31f;
} else if (m_tempUnits == "kcal/mol") {
converted = (temp + 273.15) * 1.98;
converted = (temp + 273.15f) * 1.98f;
} else {
qCWarning(LOG_AW) << "Invalid units" << m_tempUnits;
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWKEYSAGGREGATOR_H
#define AWKEYSAGGREGATOR_H
#include <ksysguard/formatter/Unit.h>
@ -51,7 +53,6 @@ public:
ACFormat,
MemGBFormat,
MemMBFormat,
MemKBFormat,
NetSmartFormat,
NetSmartUnits,
Quotes,
@ -66,12 +67,8 @@ public:
UptimeCustom
};
static constexpr double KBinBytes = 1024.0;
static constexpr double MBinBytes = 1024.0 * KBinBytes;
static constexpr double GBinBytes = 1024.0 * MBinBytes;
explicit AWKeysAggregator(QObject *_parent = nullptr);
~AWKeysAggregator() override = default;
~AWKeysAggregator() override;
void initFormatters();
// get methods
[[nodiscard]] QString formatter(const QVariant &_data, const QString &_key, bool replaceSpace) const;
@ -86,10 +83,10 @@ public:
void setTranslate(bool _translate);
public slots:
QStringList registerSource(const QString &_source, KSysGuard::Unit _units, const QStringList &_keys);
QStringList registerSource(const QString &_source, const KSysGuard::Unit &_units, const QStringList &_keys);
private:
[[nodiscard]] double temperature(double temp) const;
[[nodiscard]] float temperature(float temp) const;
AWFormatterHelper *m_customFormatters = nullptr;
AWDataEngineMapper *m_mapper = nullptr;
QStringList m_timeKeys;
@ -101,3 +98,6 @@ private:
QString m_tempUnits;
bool m_translate = false;
};
#endif /* AWKEYSAGGREGATOR_H */

View File

@ -29,9 +29,15 @@ AWPairConfigFactory::AWPairConfigFactory(QObject *_parent)
}
AWPairConfigFactory::~AWPairConfigFactory()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
void AWPairConfigFactory::showFormatterDialog(const QStringList &_keys)
{
auto config = new AWFormatterConfig(nullptr, _keys);
auto *config = new AWFormatterConfig(nullptr, _keys);
config->showDialog();
config->deleteLater();
}
@ -39,7 +45,7 @@ void AWPairConfigFactory::showFormatterDialog(const QStringList &_keys)
void AWPairConfigFactory::showKeysDialog(const QStringList &_keys)
{
auto config = new AWCustomKeysConfig(nullptr, _keys);
auto *config = new AWCustomKeysConfig(nullptr, _keys);
config->showDialog();
config->deleteLater();
}

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWPAIRCONFIGFACTORY_H
#define AWPAIRCONFIGFACTORY_H
#include <QObject>
@ -26,9 +28,12 @@ class AWPairConfigFactory : public QObject
public:
explicit AWPairConfigFactory(QObject *_parent = nullptr);
~AWPairConfigFactory() override = default;
~AWPairConfigFactory() override;
Q_INVOKABLE static void showFormatterDialog(const QStringList &_keys);
Q_INVOKABLE static void showKeysDialog(const QStringList &_keys);
private:
};
#endif /* AWPAIRCONFIGFACTORY_H */

View File

@ -36,7 +36,7 @@ QString AWPatternFunctions::expandLambdas(QString _code, AWKeysAggregator *_aggr
for (auto &lambdaKey : _usedKeys)
_code.replace(QString("$%1").arg(lambdaKey), _aggregator->formatter(_metadata[lambdaKey], lambdaKey, false));
qCInfo(LOG_AW) << "Expression" << _code;
auto result = engine.evaluate(_code);
QJSValue result = engine.evaluate(_code);
if (result.isError()) {
qCWarning(LOG_AW) << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":"
<< result.toString();
@ -52,17 +52,17 @@ QString AWPatternFunctions::expandTemplates(QString _code)
qCDebug(LOG_AW) << "Expand templates in" << _code;
// match the following construction $template{{some code here}}
static QRegularExpression templatesRegexp(R"(\$template\{\{(?<body>.*?)\}\})");
QRegularExpression templatesRegexp(R"(\$template\{\{(?<body>.*?)\}\})");
templatesRegexp.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
auto it = templatesRegexp.globalMatch(_code);
QRegularExpressionMatchIterator it = templatesRegexp.globalMatch(_code);
while (it.hasNext()) {
auto match = it.next();
auto body = match.captured("body");
QRegularExpressionMatch match = it.next();
QString body = match.captured("body");
QJSEngine engine;
qCInfo(LOG_AW) << "Expression" << body;
auto result = engine.evaluate(body);
QJSValue result = engine.evaluate(body);
QString templateResult = "";
if (result.isError()) {
qCWarning(LOG_AW) << "Uncaught exception at line" << result.property("lineNumber").toInt() << ":"
@ -94,20 +94,20 @@ QList<AWPatternFunctions::AWFunction> AWPatternFunctions::findFunctionCalls(cons
regex.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
QList<AWPatternFunctions::AWFunction> foundFunctions;
auto it = regex.globalMatch(_code);
QRegularExpressionMatchIterator it = regex.globalMatch(_code);
while (it.hasNext()) {
auto match = it.next();
QRegularExpressionMatch match = it.next();
AWPatternFunctions::AWFunction metadata;
// work with args
auto argsString = match.captured("args");
QString argsString = match.captured("args");
if (argsString.isEmpty()) {
metadata.args = QStringList();
} else {
// replace '$,' to 0x1d
argsString.replace("$,", QChar(0x1d));
auto args = argsString.split(',');
std::for_each(args.begin(), args.end(), [](auto &arg) { arg.replace(QChar(0x1d), ","); });
QStringList args = argsString.split(',');
std::for_each(args.begin(), args.end(), [](QString &arg) { arg.replace(QChar(0x1d), ","); });
metadata.args = args;
}
// other variables
@ -127,11 +127,11 @@ QString AWPatternFunctions::insertAllKeys(QString _code, const QStringList &_key
{
qCDebug(LOG_AW) << "Looking for keys in code" << _code << "using list" << _keys;
auto found = AWPatternFunctions::findFunctionCalls("aw_all", _code);
QList<AWPatternFunctions::AWFunction> found = AWPatternFunctions::findFunctionCalls("aw_all", _code);
for (auto &function : found) {
auto separator = function.args.isEmpty() ? "," : function.args.at(0);
auto required = _keys.filter(QRegularExpression(function.body));
std::for_each(required.begin(), required.end(), [](auto &value) { value = QString("%1: $%1").arg(value); });
QString separator = function.args.isEmpty() ? "," : function.args.at(0);
QStringList required = _keys.filter(QRegularExpression(function.body));
std::for_each(required.begin(), required.end(), [](QString &value) { value = QString("%1: $%1").arg(value); });
_code.replace(function.what, required.join(separator));
}
@ -144,9 +144,9 @@ QString AWPatternFunctions::insertKeyCount(QString _code, const QStringList &_ke
{
qCDebug(LOG_AW) << "Looking for count in code" << _code << "using list" << _keys;
auto found = AWPatternFunctions::findFunctionCalls("aw_count", _code);
QList<AWPatternFunctions::AWFunction> found = AWPatternFunctions::findFunctionCalls("aw_count", _code);
for (auto &function : found) {
auto count = _keys.filter(QRegularExpression(function.body)).count();
int count = _keys.filter(QRegularExpression(function.body)).count();
_code.replace(function.what, QString::number(count));
}
@ -159,10 +159,10 @@ QString AWPatternFunctions::insertKeyNames(QString _code, const QStringList &_ke
{
qCDebug(LOG_AW) << "Looking for key names in code" << _code << "using list" << _keys;
auto found = AWPatternFunctions::findFunctionCalls("aw_names", _code);
QList<AWPatternFunctions::AWFunction> found = AWPatternFunctions::findFunctionCalls("aw_names", _code);
for (auto &function : found) {
auto separator = function.args.isEmpty() ? "," : function.args.at(0);
auto required = _keys.filter(QRegularExpression(function.body));
QString separator = function.args.isEmpty() ? "," : function.args.at(0);
QStringList required = _keys.filter(QRegularExpression(function.body));
_code.replace(function.what, required.join(separator));
}
@ -175,11 +175,11 @@ QString AWPatternFunctions::insertKeys(QString _code, const QStringList &_keys)
{
qCDebug(LOG_AW) << "Looking for keys in code" << _code << "using list" << _keys;
auto found = AWPatternFunctions::findFunctionCalls("aw_keys", _code);
QList<AWPatternFunctions::AWFunction> found = AWPatternFunctions::findFunctionCalls("aw_keys", _code);
for (auto &function : found) {
auto separator = function.args.isEmpty() ? "," : function.args.at(0);
auto required = _keys.filter(QRegularExpression(function.body));
std::for_each(required.begin(), required.end(), [](auto &value) { value = QString("$%1").arg(value); });
QString separator = function.args.isEmpty() ? "," : function.args.at(0);
QStringList required = _keys.filter(QRegularExpression(function.body));
std::for_each(required.begin(), required.end(), [](QString &value) { value = QString("$%1").arg(value); });
_code.replace(function.what, required.join(separator));
}
@ -192,25 +192,26 @@ QString AWPatternFunctions::insertMacros(QString _code)
{
qCDebug(LOG_AW) << "Looking for macros in code" << _code;
auto found = AWPatternFunctions::findFunctionCalls("aw_macro", _code);
QList<AWPatternFunctions::AWFunction> found = AWPatternFunctions::findFunctionCalls("aw_macro", _code);
for (auto &macro : found) {
// get macro params
if (macro.args.isEmpty()) {
qCWarning(LOG_AW) << "No macro name found for" << macro.what;
continue;
}
auto name = macro.args.takeFirst();
QString name = macro.args.takeFirst();
// find macro usage
auto macroUsage = AWPatternFunctions::findFunctionCalls(QString("aw_macro_%1").arg(name), _code);
QList<AWPatternFunctions::AWFunction> macroUsage
= 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;
continue;
}
// generate body to replace
auto result = macro.body;
std::for_each(macro.args.cbegin(), macro.args.cend(), [&result, macro, function](auto &arg) {
auto index = macro.args.indexOf(arg);
QString result = macro.body;
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));
});
// do replace
@ -230,7 +231,7 @@ QStringList AWPatternFunctions::findKeys(const QString &_code, const QStringList
qCDebug(LOG_AW) << "Looking for keys in code" << _code << "using list" << _keys;
QStringList selectedKeys;
auto replacedCode = _code;
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;
@ -250,13 +251,13 @@ QStringList AWPatternFunctions::findLambdas(const QString &_code)
QStringList selectedKeys;
// match the following construction ${{some code here}}
static QRegularExpression lambdaRegexp(R"(\$\{\{(?<body>.*?)\}\})");
QRegularExpression lambdaRegexp(R"(\$\{\{(?<body>.*?)\}\})");
lambdaRegexp.setPatternOptions(QRegularExpression::DotMatchesEverythingOption);
auto it = lambdaRegexp.globalMatch(_code);
QRegularExpressionMatchIterator it = lambdaRegexp.globalMatch(_code);
while (it.hasNext()) {
auto match = it.next();
auto lambda = match.captured("body");
QRegularExpressionMatch match = it.next();
QString lambda = match.captured("body");
// append
qCInfo(LOG_AW) << "Found lambda" << lambda;

View File

@ -15,7 +15,9 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWPATTERNFUNCTIONS_H
#define AWPATTERNFUNCTIONS_H
#include <QString>
#include <QVariant>
@ -45,3 +47,6 @@ QString insertMacros(QString _code);
QStringList findKeys(const QString &_code, const QStringList &_keys, bool _isBars);
QStringList findLambdas(const QString &_code);
} // namespace AWPatternFunctions
#endif /* AWPATTERNFUNCTIONS_H */

View File

@ -18,6 +18,8 @@
#include "awtelemetryhandler.h"
#include <QJsonDocument>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QSettings>
#include <QStandardPaths>
#include <QUuid>
@ -25,13 +27,23 @@
#include "awdebug.h"
AWTelemetryHandler::AWTelemetryHandler(QObject *_parent)
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));
// override client id if any
if (!_clientId.isEmpty())
m_clientId = _clientId;
}
AWTelemetryHandler::~AWTelemetryHandler()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
@ -59,11 +71,14 @@ QString AWTelemetryHandler::getLast(const QString &_group) const
}
void AWTelemetryHandler::init(const int _count)
void AWTelemetryHandler::init(const int _count, const bool _enableRemote, const QString &_clientId)
{
qCDebug(LOG_AW) << "Init telemetry with count" << _count;
qCDebug(LOG_AW) << "Init telemetry with count" << _count << "enable remote" << _enableRemote << "client ID"
<< _clientId;
m_storeCount = _count;
m_uploadEnabled = _enableRemote;
m_clientId = _clientId;
}
@ -91,7 +106,7 @@ bool AWTelemetryHandler::put(const QString &_group, const QString &_value) const
settings.remove("");
// and save now
for (auto &val : saved) {
auto key = getKey(settings.childKeys().count());
QString key = getKey(settings.childKeys().count());
settings.setValue(key, val);
}
@ -103,6 +118,59 @@ bool AWTelemetryHandler::put(const QString &_group, const QString &_value) const
}
void AWTelemetryHandler::uploadTelemetry(const QString &_group, const QString &_value)
{
qCDebug(LOG_AW) << "Upload data with group" << _group << "and value" << _value;
if (!m_uploadEnabled) {
qCInfo(LOG_AW) << "Upload disabled by configuration";
return;
}
auto *manager = new QNetworkAccessManager(nullptr);
connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(telemetryReplyRecieved(QNetworkReply *)));
QUrl url(REMOTE_TELEMETRY_URL);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// generate payload
QVariantMap payload;
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);
qCInfo(LOG_AW) << "Send request with body" << data.data() << "and size" << data.size();
manager->post(request, data);
}
void AWTelemetryHandler::telemetryReplyRecieved(QNetworkReply *_reply)
{
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);
if (error.error != QJsonParseError::NoError) {
qCWarning(LOG_AW) << "Parse error" << error.errorString();
return;
}
_reply->deleteLater();
// convert to map
QVariantMap response = jsonDoc.toVariant().toMap();
QString message = response["message"].toString();
qCInfo(LOG_AW) << "Server reply on telemetry" << message;
return emit(replyReceived(message));
}
QString AWTelemetryHandler::getKey(const int _count)
{
qCDebug(LOG_AW) << "Get key for keys count" << _count;

View File

@ -15,25 +15,43 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWTELEMETRYHANDLER_H
#define AWTELEMETRYHANDLER_H
#include <QObject>
class QNetworkReply;
class AWTelemetryHandler : public QObject
{
Q_OBJECT
public:
explicit AWTelemetryHandler(QObject *_parent = nullptr);
~AWTelemetryHandler() override = default;
const char *REMOTE_TELEMETRY_URL = "https://arcanis.me/telemetry";
explicit AWTelemetryHandler(QObject *_parent = nullptr, const QString &_clientId = "");
~AWTelemetryHandler() override;
Q_INVOKABLE [[nodiscard]] QStringList get(const QString &_group) const;
Q_INVOKABLE [[nodiscard]] QString getLast(const QString &_group) const;
Q_INVOKABLE void init(int _count);
Q_INVOKABLE void init(int _count, bool _enableRemote, const QString &_clientId);
Q_INVOKABLE [[nodiscard]] 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);
private slots:
void telemetryReplyRecieved(QNetworkReply *_reply);
private:
static QString getKey(int _count);
QString m_clientId;
QString m_localFile;
int m_storeCount = 0;
bool m_uploadEnabled = false;
};
#endif /* AWTELEMETRYHANDLER_H */

View File

@ -18,7 +18,6 @@
#include "awupdatehelper.h"
#include <KI18n/KLocalizedString>
#include <KNotifications/KNotification>
#include <QDesktopServices>
#include <QJsonDocument>
@ -41,15 +40,21 @@ AWUpdateHelper::AWUpdateHelper(QObject *_parent)
}
AWUpdateHelper::~AWUpdateHelper()
{
qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
}
void AWUpdateHelper::checkUpdates(const bool _showAnyway)
{
qCDebug(LOG_AW) << "Show anyway" << _showAnyway;
// showAnyway options required to show message if no updates found on direct
// showAnyway options requires to show message if no updates found on direct
// request. In case of automatic check no message will be shown
auto manager = new QNetworkAccessManager(nullptr);
auto *manager = new QNetworkAccessManager(nullptr);
connect(manager, &QNetworkAccessManager::finished,
[_showAnyway, this](QNetworkReply *reply) { return versionReplyReceived(reply, _showAnyway); });
[_showAnyway, this](QNetworkReply *reply) { return versionReplyRecieved(reply, _showAnyway); });
manager->get(QNetworkRequest(QUrl(VERSION_API)));
}
@ -58,14 +63,15 @@ void AWUpdateHelper::checkUpdates(const bool _showAnyway)
bool AWUpdateHelper::checkVersion()
{
QSettings settings(m_genericConfig, QSettings::IniFormat);
auto 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;
if ((version != m_foundVersion) && (!QString(CHANGELOG).isEmpty())) {
sendNotification(i18n("Changelog of %1", VERSION), QString(CHANGELOG).replace('@', '\n'));
genMessageBox(i18nc("Changelog of %1", VERSION), QString(CHANGELOG).replace('@', '\n'), QMessageBox::Ok)
->open();
return true;
} else if (version != m_foundVersion) {
qCWarning(LOG_AW) << "No changelog information provided";
@ -78,40 +84,49 @@ bool AWUpdateHelper::checkVersion()
}
void AWUpdateHelper::openReleasesPage()
{
QDesktopServices::openUrl(QString(RELEASES) + m_foundVersion.toString());
}
void AWUpdateHelper::showInfo(const QVersionNumber &_version)
{
qCDebug(LOG_AW) << "Version" << _version;
auto 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));
sendNotification(i18n("No new version found"), text);
return genMessageBox(i18n("No new version found"), text, QMessageBox::Ok)->open();
}
void AWUpdateHelper::showUpdates(const QVersionNumber &_version) const
void AWUpdateHelper::showUpdates(const QVersionNumber &_version)
{
qCDebug(LOG_AW) << "Version" << _version;
QString text;
text += i18n("Current version : %1", VERSION);
text += i18nc("Current version : %1", VERSION);
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");
auto event = sendNotification(i18n("There are updates"), text);
auto action = event->addAction(i18n("Details"));
connect(action, &KNotificationAction::activated, this, &AWUpdateHelper::openReleasesPage);
genMessageBox(i18n("There are updates"), text, QMessageBox::Ok | QMessageBox::Cancel)
->open(this, SLOT(userReplyOnUpdates(QAbstractButton *)));
}
void AWUpdateHelper::versionReplyReceived(QNetworkReply *_reply, const bool _showAnyway)
void AWUpdateHelper::userReplyOnUpdates(QAbstractButton *_button)
{
QMessageBox::ButtonRole ret = dynamic_cast<QMessageBox *>(sender())->buttonRole(_button);
qCInfo(LOG_AW) << "User select" << ret;
switch (ret) {
case QMessageBox::AcceptRole:
QDesktopServices::openUrl(QString(RELEASES) + m_foundVersion.toString());
break;
case QMessageBox::RejectRole:
default:
break;
}
}
void AWUpdateHelper::versionReplyRecieved(QNetworkReply *_reply, const bool _showAnyway)
{
qCDebug(LOG_AW) << "Show message anyway" << _showAnyway;
if (_reply->error() != QNetworkReply::NoError) {
@ -119,23 +134,22 @@ void AWUpdateHelper::versionReplyReceived(QNetworkReply *_reply, const bool _sho
return;
}
auto error = QJsonParseError();
auto jsonDoc = QJsonDocument::fromJson(_reply->readAll(), &error);
QJsonParseError error = QJsonParseError();
QJsonDocument jsonDoc = QJsonDocument::fromJson(_reply->readAll(), &error);
if (error.error != QJsonParseError::NoError) {
qCWarning(LOG_AW) << "Parse error" << error.errorString();
return;
}
_reply->deleteLater();
_reply->manager()->deleteLater(); // remember to delete manager too
// convert to map
auto firstRelease = jsonDoc.toVariant().toList().first().toMap();
auto version = firstRelease["tag_name"].toString();
QVariantMap firstRelease = jsonDoc.toVariant().toList().first().toMap();
QString version = firstRelease["tag_name"].toString();
version.remove("V.");
m_foundVersion = QVersionNumber::fromString(version);
qCInfo(LOG_AW) << "Update found version to" << m_foundVersion;
auto oldVersion = QVersionNumber::fromString(VERSION);
QVersionNumber oldVersion = QVersionNumber::fromString(VERSION);
if (oldVersion < m_foundVersion)
return showUpdates(m_foundVersion);
else if (_showAnyway)
@ -144,12 +158,18 @@ void AWUpdateHelper::versionReplyReceived(QNetworkReply *_reply, const bool _sho
// additional method which is used to show message box which does not block UI
KNotification *AWUpdateHelper::sendNotification(const QString &_title, const QString &_body)
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;
auto event = KNotification::event("system", _title, _body);
event->setComponentName("plasma-applet-org.kde.plasma.awesome-widget");
auto *msgBox = new QMessageBox(nullptr);
msgBox->setAttribute(Qt::WA_DeleteOnClose);
msgBox->setModal(false);
msgBox->setWindowTitle(_title);
msgBox->setText(_body);
msgBox->setStandardButtons(_buttons);
msgBox->setIcon(QMessageBox::Information);
return event;
return msgBox;
}

View File

@ -15,13 +15,15 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWUPDATEHELPER_H
#define AWUPDATEHELPER_H
#include <QMessageBox>
#include <QObject>
#include <QVersionNumber>
class KNotification;
class QNetworkReply;
class AWUpdateHelper : public QObject
@ -30,18 +32,22 @@ class AWUpdateHelper : public QObject
public:
explicit AWUpdateHelper(QObject *_parent = nullptr);
~AWUpdateHelper() override = default;
~AWUpdateHelper() override;
void checkUpdates(bool _showAnyway = false);
bool checkVersion();
private slots:
void openReleasesPage();
static void showInfo(const QVersionNumber &_version);
void showUpdates(const QVersionNumber &_version) const;
void versionReplyReceived(QNetworkReply *_reply, bool _showAnyway);
void showUpdates(const QVersionNumber &_version);
void userReplyOnUpdates(QAbstractButton *_button);
void versionReplyRecieved(QNetworkReply *_reply, bool _showAnyway);
private:
static KNotification *sendNotification(const QString &_title, const QString &_body);
static QMessageBox *genMessageBox(const QString &_title, const QString &_body,
QMessageBox::StandardButtons _buttons);
QVersionNumber m_foundVersion;
QString m_genericConfig;
};
#endif /* AWUPDATEHELPER_H */

View File

@ -29,19 +29,13 @@
AbstractExtItem::AbstractExtItem(QObject *_parent, const QString &_filePath)
: QObject(_parent)
, m_filePath(_filePath)
, m_fileName(_filePath)
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
qCDebug(LOG_LIB) << "Desktop name" << _filePath;
m_name = m_filePath;
m_scheduler = new QCronScheduler(this);
connect(m_scheduler, &QCronScheduler::activated, this, &AbstractExtItem::requestDataUpdate);
m_socket = new QLocalServer(this);
connect(m_socket, &QLocalServer::newConnection, this, &AbstractExtItem::requestDataUpdate);
m_name = m_fileName;
}
@ -49,11 +43,11 @@ AbstractExtItem::~AbstractExtItem()
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
m_scheduler->stop();
m_scheduler->deleteLater();
m_socket->close();
m_socket->deleteLater();
if (m_socket) {
m_socket->close();
QLocalServer::removeServer(socket());
m_socket->deleteLater();
}
}
@ -101,11 +95,10 @@ void AbstractExtItem::startTimer()
}
QString AbstractExtItem::writableConfig() const
QString AbstractExtItem::writtableConfig() const
{
auto path = m_filePath;
auto name = fileName();
// extract subdirectory
auto path = m_fileName;
auto name = QFileInfo(path).fileName();
path.remove(path.length() - name.length() - 1, name.length() + 1);
auto dir = QFileInfo(path).fileName();
@ -134,13 +127,7 @@ QString AbstractExtItem::cron() const
QString AbstractExtItem::fileName() const
{
return QFileInfo(filePath()).fileName();
}
QString AbstractExtItem::filePath() const
{
return m_filePath;
return m_fileName;
}
@ -209,14 +196,20 @@ void AbstractExtItem::setComment(const QString &_comment)
void AbstractExtItem::setCron(const QString &_cron)
{
qCDebug(LOG_LIB) << "Cron string" << _cron;
// deinit module first
if (m_scheduler) {
disconnect(m_scheduler, SIGNAL(activated()), this, SIGNAL(requestDataUpdate()));
delete m_scheduler;
}
m_cron = _cron;
if (m_cron.isEmpty()) { // disable cron timer
m_scheduler->stop();
} else {
m_scheduler->parse(m_cron);
m_scheduler->start();
}
if (cron().isEmpty())
return;
// init scheduler
m_scheduler = new QCronScheduler(this);
m_scheduler->parse(cron());
connect(m_scheduler, SIGNAL(activated()), this, SIGNAL(requestDataUpdate()));
}
@ -241,11 +234,11 @@ void AbstractExtItem::setName(const QString &_name)
void AbstractExtItem::setNumber(int _number)
{
qCDebug(LOG_LIB) << "Number" << _number;
auto generateNumber = (_number == -1);
bool generateNumber = (_number == -1);
if (generateNumber) {
_number = []() {
qCWarning(LOG_LIB) << "Number is empty, generate new one";
auto n = QRandomGenerator::global()->bounded(1000);
auto n = QRandomGenerator::global()->generate() % 1000;
qCInfo(LOG_LIB) << "Generated number is" << n;
return n;
}();
@ -260,24 +253,40 @@ void AbstractExtItem::setNumber(int _number)
void AbstractExtItem::setSocket(const QString &_socket)
{
qCDebug(LOG_LIB) << "Socket" << _socket;
// remove old socket first
deinitSocket();
m_socketFile = _socket;
}
void AbstractExtItem::deinitSocket()
{
if (!m_socket)
return;
m_socket->close();
QLocalServer::removeServer(socket());
disconnect(m_socket, SIGNAL(newConnection()), this, SLOT(newConnectionReceived()));
delete m_socket;
}
void AbstractExtItem::initSocket()
{
// reload local socket
m_socket->close();
// remove old socket first
deinitSocket();
auto listening = m_socket->listen(m_socketFile);
qCInfo(LOG_LIB) << "Server listening on" << m_socketFile << listening;
m_socket = new QLocalServer(this);
bool listening = m_socket->listen(socket());
qCInfo(LOG_LIB) << "Server listening on" << socket() << listening;
connect(m_socket, SIGNAL(newConnection()), this, SLOT(newConnectionReceived()));
}
void AbstractExtItem::readConfiguration()
{
QSettings settings(m_filePath, QSettings::IniFormat);
QSettings settings(m_fileName, QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setName(settings.value("Name", name()).toString());
@ -294,8 +303,8 @@ void AbstractExtItem::readConfiguration()
bool AbstractExtItem::tryDelete() const
{
auto status = QFile::remove(m_filePath);
qCInfo(LOG_LIB) << "Remove file" << m_filePath << status;
bool status = QFile::remove(m_fileName);
qCInfo(LOG_LIB) << "Remove file" << m_fileName << status;
return status;
}
@ -303,7 +312,7 @@ bool AbstractExtItem::tryDelete() const
void AbstractExtItem::writeConfiguration() const
{
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");
@ -320,3 +329,9 @@ void AbstractExtItem::writeConfiguration() const
settings.sync();
}
void AbstractExtItem::newConnectionReceived()
{
emit(requestDataUpdate());
}

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef ABSTRACTEXTITEM_H
#define ABSTRACTEXTITEM_H
#include <QVariant>
@ -32,7 +33,6 @@ class AbstractExtItem : public QObject
Q_PROPERTY(QString comment READ comment WRITE setComment)
Q_PROPERTY(QString cron READ cron WRITE setCron)
Q_PROPERTY(QString fileName READ fileName)
Q_PROPERTY(QString filePath READ filePath)
Q_PROPERTY(int interval READ interval WRITE setInterval)
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(int number READ number WRITE setNumber)
@ -46,13 +46,12 @@ public:
virtual AbstractExtItem *copy(const QString &_fileName, int _number) = 0;
virtual void copyDefaults(AbstractExtItem *_other) const;
virtual void startTimer();
[[nodiscard]] QString writableConfig() const;
[[nodiscard]] QString writtableConfig() const;
// get methods
[[nodiscard]] int apiVersion() const;
[[nodiscard]] QString comment() const;
[[nodiscard]] QString cron() const;
[[nodiscard]] QString fileName() const;
[[nodiscard]] QString filePath() const;
[[nodiscard]] int interval() const;
[[nodiscard]] bool isActive() const;
[[nodiscard]] QString name() const;
@ -75,6 +74,7 @@ signals:
void requestDataUpdate();
public slots:
virtual void deinitSocket();
virtual void initSocket();
virtual void readConfiguration();
virtual QVariantHash run() = 0;
@ -82,9 +82,12 @@ public slots:
[[nodiscard]] virtual bool tryDelete() const;
virtual void writeConfiguration() const;
private slots:
void newConnectionReceived();
private:
QCronScheduler *m_scheduler = nullptr;
QString m_filePath = "";
QString m_fileName = "/dev/null";
int m_times = 0;
// FIXME find a better way to do it
virtual void translate(void *_ui) = 0;
@ -99,3 +102,6 @@ private:
QLocalServer *m_socket = nullptr;
QString m_socketFile = "";
};
#endif /* ABSTRACTEXTITEM_H */

View File

@ -35,7 +35,8 @@ AbstractExtItemAggregator::AbstractExtItemAggregator(QObject *_parent, QString _
// create directory at $HOME
auto localDir = QString("%1/awesomewidgets/%2")
.arg(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation), type());
if (QDir().mkpath(localDir))
QDir localDirectory;
if (localDirectory.mkpath(localDir))
qCInfo(LOG_LIB) << "Created directory" << localDir;
}
@ -101,13 +102,18 @@ int AbstractExtItemAggregator::exec()
auto createButton = ui->buttonBox->addButton(i18n("Create"), QDialogButtonBox::ActionRole);
auto deleteButton = ui->buttonBox->addButton(i18n("Remove"), QDialogButtonBox::ActionRole);
connect(copyButton, &QPushButton::clicked, [this, ui]() { copyItem(ui->listWidget); });
connect(createButton, &QPushButton::clicked, [this, ui]() { doCreateItem(ui->listWidget); });
connect(deleteButton, &QPushButton::clicked, [this, ui]() { deleteItem(ui->listWidget); });
connect(ui->buttonBox, &QDialogButtonBox::accepted, [this, ui]() { editItem(ui->listWidget); });
connect(ui->buttonBox, &QDialogButtonBox::clicked, [&](QAbstractButton *_button) {
if (dynamic_cast<QPushButton *>(_button) == copyButton)
copyItem(ui->listWidget);
else if (dynamic_cast<QPushButton *>(_button) == createButton)
doCreateItem(ui->listWidget);
else if (dynamic_cast<QPushButton *>(_button) == deleteButton)
deleteItem(ui->listWidget);
else if (ui->buttonBox->buttonRole(_button) == QDialogButtonBox::AcceptRole)
editItem(ui->listWidget);
});
connect(ui->buttonBox, &QDialogButtonBox::rejected, [dialog]() { dialog->reject(); });
connect(ui->listWidget, &QListWidget::itemActivated, [this, ui](QListWidgetItem *) { editItem(ui->listWidget); });
connect(ui->listWidget, &QListWidget::itemActivated, [&](QListWidgetItem *) { editItem(ui->listWidget); });
repaintList(ui->listWidget);
auto ret = dialog->exec();
@ -139,8 +145,8 @@ AbstractExtItem *AbstractExtItemAggregator::itemFromWidget(QListWidget *_widget)
return nullptr;
AbstractExtItem *found = nullptr;
for (auto item : items()) {
auto fileName = item->fileName();
for (auto &item : items()) {
auto fileName = QFileInfo(item->fileName()).fileName();
if (fileName != widgetItem->text())
continue;
found = item;
@ -156,8 +162,8 @@ AbstractExtItem *AbstractExtItemAggregator::itemFromWidget(QListWidget *_widget)
void AbstractExtItemAggregator::repaintList(QListWidget *_widget) const
{
_widget->clear();
for (auto _item : items()) {
QString fileName = _item->fileName();
for (auto &_item : items()) {
QString fileName = QFileInfo(_item->fileName()).fileName();
auto item = new QListWidgetItem(fileName, _widget);
QStringList tooltip;
tooltip.append(i18n("Name: %1", _item->name()));
@ -172,10 +178,9 @@ void AbstractExtItemAggregator::repaintList(QListWidget *_widget) const
int AbstractExtItemAggregator::uniqNumber() const
{
QList<int> tagList;
for (auto item : items())
for (auto &item : items())
tagList.append(item->number());
auto number = 0;
int number = 0;
while (tagList.contains(number))
number++;
@ -191,8 +196,10 @@ QVariant AbstractExtItemAggregator::configArgs() const
QStringList AbstractExtItemAggregator::directories() const
{
return QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QString("awesomewidgets/%1").arg(type()),
QStandardPaths::LocateDirectory);
auto dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QString("awesomewidgets/%1").arg(type()),
QStandardPaths::LocateDirectory);
return dirs;
}

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef ABSTRACTEXTITEMAGGREGATOR_H
#define ABSTRACTEXTITEMAGGREGATOR_H
#include <QStandardPaths>
@ -23,6 +24,7 @@
#include "awdebug.h"
class QAbstractButton;
class QListWidget;
class QListWidgetItem;
@ -58,7 +60,7 @@ public:
void deleteItem(QListWidget *_widget);
void editItem(QListWidget *_widget);
[[nodiscard]] int exec();
[[nodiscard]] static QString getName();
QString getName();
virtual void initItems() = 0;
[[nodiscard]] AbstractExtItem *itemFromWidget(QListWidget *_widget) const;
void repaintList(QListWidget *_widget) const;
@ -78,3 +80,6 @@ private:
// ui methods
virtual void doCreateItem(QListWidget *_widget) = 0;
};
#endif /* ABSTRACTEXTITEMAGGREGATOR_H */

View File

@ -15,17 +15,31 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef ABSTRACTQUOTESPROVIDER_H
#define ABSTRACTQUOTESPROVIDER_H
#include <QObject>
#include <QUrl>
#include <QVariant>
#include "abstractextitem.h"
class AbstractQuotesProvider
class AbstractQuotesProvider : public QObject
{
Q_OBJECT
public:
virtual ~AbstractQuotesProvider() = default;
explicit AbstractQuotesProvider(QObject *_parent)
: QObject(_parent){};
~AbstractQuotesProvider() override = default;
virtual void initUrl(const QString &_asset) = 0;
[[nodiscard]] virtual QVariantHash parse(const QByteArray &_source) = 0;
[[nodiscard]] virtual QVariantHash parse(const QByteArray &_source, const QVariantHash &_oldValues) const = 0;
[[nodiscard]] QString tag(const QString &_type) const
{
return dynamic_cast<AbstractExtItem *>(parent())->tag(_type);
};
[[nodiscard]] virtual QUrl url() const = 0;
};
#endif /* ABSTRACTQUOTESPROVIDER_H */

View File

@ -15,17 +15,31 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef ABSTRACTWEATHERPROVIDER_H
#define ABSTRACTWEATHERPROVIDER_H
#include <QObject>
#include <QUrl>
#include <QVariant>
#include "abstractextitem.h"
class AbstractWeatherProvider
class AbstractWeatherProvider : public QObject
{
Q_OBJECT
public:
virtual ~AbstractWeatherProvider() = default;
explicit AbstractWeatherProvider(QObject *_parent)
: QObject(_parent){};
~AbstractWeatherProvider() override = default;
virtual void initUrl(const QString &_city, const QString &_country, int _ts) = 0;
[[nodiscard]] virtual QVariantHash parse(const QVariantMap &_json) const = 0;
[[nodiscard]] QString tag(const QString &_type) const
{
return dynamic_cast<AbstractExtItem *>(parent())->tag(_type);
};
[[nodiscard]] virtual QUrl url() const = 0;
};
#endif /* ABSTRACTWEATHERPROVIDER_H */

View File

@ -113,7 +113,7 @@ void AWAbstractFormatter::readConfiguration()
{
AbstractExtItem::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setStrType(settings.value("X-AW-Type", strType()).toString());
@ -125,7 +125,7 @@ void AWAbstractFormatter::writeConfiguration() const
{
AbstractExtItem::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWABSTRACTFORMATTER_H
#define AWABSTRACTFORMATTER_H
#include <QRegularExpression>
@ -51,3 +52,6 @@ private:
// properties
FormatterClass m_type = FormatterClass::NoFormat;
};
#endif /* AWABSTRACTFORMATTER_H */

View File

@ -50,7 +50,6 @@ AWDateTimeFormatter *AWDateTimeFormatter::copy(const QString &_fileName, const i
auto item = new AWDateTimeFormatter(parent(), _fileName);
AWAbstractFormatter::copyDefaults(item);
item->setFormat(format());
item->setTranslateString(translateString());
item->setNumber(_number);
@ -92,7 +91,7 @@ void AWDateTimeFormatter::readConfiguration()
{
AWAbstractFormatter::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setFormat(settings.value("X-AW-Format", format()).toString());
@ -141,7 +140,7 @@ void AWDateTimeFormatter::writeConfiguration() const
{
AWAbstractFormatter::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWDATETIMEFORMATTER_H
#define AWDATETIMEFORMATTER_H
#include <QLocale>
@ -51,3 +52,6 @@ private:
QString m_format = "";
bool m_translate = true;
};
#endif /* AWDATETIMEFORMATTER_H */

View File

@ -54,7 +54,6 @@ AWFloatFormatter *AWFloatFormatter::copy(const QString &_fileName, const int _nu
auto item = new AWFloatFormatter(parent(), _fileName);
AWAbstractFormatter::copyDefaults(item);
item->setCount(count());
item->setFormat(format());
item->setFillChar(fillChar());
@ -175,7 +174,7 @@ void AWFloatFormatter::readConfiguration()
{
AWAbstractFormatter::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setCount(settings.value("X-AW-Width", count()).toInt());
@ -239,7 +238,7 @@ void AWFloatFormatter::writeConfiguration() const
{
AWAbstractFormatter::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWFLOATFORMATTER_H
#define AWFLOATFORMATTER_H
#include "awabstractformatter.h"
@ -67,3 +68,6 @@ private:
int m_precision = -1;
double m_summand = 0.0;
};
#endif /* AWFLOATFORMATTER_H */

View File

@ -41,10 +41,10 @@ QString AWJsonFormatter::convert(const QVariant &_value) const
qCDebug(LOG_LIB) << "Convert value" << _value;
// check if _value is string and parse first if required
auto json = _value.userType() == QMetaType::QString ? QJsonDocument::fromJson(_value.toString().toUtf8())
: QJsonDocument::fromVariant(_value);
auto converted = json.toVariant();
for (auto &element : m_path)
QJsonDocument json = _value.userType() == QMetaType::QString ? QJsonDocument::fromJson(_value.toString().toUtf8())
: QJsonDocument::fromVariant(_value);
QVariant converted = json.toVariant();
for (auto &element : m_splittedPath)
converted = getFromJson(converted, element);
return converted.toString();
@ -57,7 +57,6 @@ AWJsonFormatter *AWJsonFormatter::copy(const QString &_fileName, const int _numb
auto item = new AWJsonFormatter(parent(), _fileName);
AWAbstractFormatter::copyDefaults(item);
item->setNumber(_number);
item->setPath(path());
@ -67,8 +66,7 @@ AWJsonFormatter *AWJsonFormatter::copy(const QString &_fileName, const int _numb
QString AWJsonFormatter::path() const
{
return std::accumulate(m_path.cbegin(), m_path.cend(), QString(""),
[](auto acc, auto &value) { return QString("%1.%2").arg(acc, value.toString()); });
return m_path;
}
@ -76,14 +74,8 @@ void AWJsonFormatter::setPath(const QString &_path)
{
qCDebug(LOG_LIB) << "Path" << _path;
m_path.clear();
auto elements = _path.split('.', Qt::SkipEmptyParts);
for (auto &element : elements) {
bool ok;
auto number = element.toInt(&ok);
m_path.append(ok ? QVariant(number) : QVariant(element));
}
m_path = _path;
initPath();
}
@ -91,7 +83,7 @@ void AWJsonFormatter::readConfiguration()
{
AWAbstractFormatter::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setPath(settings.value("X-AW-Path", path()).toString());
@ -137,7 +129,7 @@ void AWJsonFormatter::writeConfiguration() const
{
AWAbstractFormatter::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");
@ -179,6 +171,19 @@ QVariant AWJsonFormatter::getFromMap(const QVariant &_value, const QString &_key
}
void AWJsonFormatter::initPath()
{
m_splittedPath.clear();
QStringList splittedByDot = m_path.split('.', Qt::SkipEmptyParts);
for (auto &element : splittedByDot) {
bool ok;
int number = element.toInt(&ok);
m_splittedPath.append(ok ? QVariant(number) : QVariant(element));
}
}
void AWJsonFormatter::translate(void *_ui)
{
auto ui = reinterpret_cast<Ui::AWJsonFormatter *>(_ui);

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWJSONFORMATTER_H
#define AWJSONFORMATTER_H
#include "awabstractformatter.h"
@ -42,7 +43,12 @@ private:
static QVariant getFromJson(const QVariant &_value, const QVariant &_element);
static QVariant getFromList(const QVariant &_value, int _index);
static QVariant getFromMap(const QVariant &_value, const QString &_key);
void initPath();
void translate(void *_ui) override;
// properties
QVariantList m_path;
QString m_path;
QVariantList m_splittedPath;
};
#endif /* AWJSONFORMATTER_H */

View File

@ -53,7 +53,6 @@ AWListFormatter *AWListFormatter::copy(const QString &_fileName, const int _numb
auto item = new AWListFormatter(parent(), _fileName);
AWAbstractFormatter::copyDefaults(item);
item->setFilter(filter());
item->setSeparator(separator());
item->setSorted(isSorted());
@ -92,7 +91,7 @@ void AWListFormatter::setFilter(const QString &_filter)
void AWListFormatter::setSeparator(const QString &_separator)
{
qCDebug(LOG_LIB) << "Separator" << _separator;
qCDebug(LOG_LIB) << "Separtor" << _separator;
m_separator = _separator;
}
@ -110,7 +109,7 @@ void AWListFormatter::readConfiguration()
{
AWAbstractFormatter::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setFilter(settings.value("X-AW-Filter", filter()).toString());
@ -162,7 +161,7 @@ void AWListFormatter::writeConfiguration() const
{
AWAbstractFormatter::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWLISTFORMATTER_H
#define AWLISTFORMATTER_H
#include "awabstractformatter.h"
@ -52,3 +53,6 @@ private:
bool m_sorted = false;
QRegularExpression m_regex;
};
#endif /* AWLISTFORMATTER_H */

View File

@ -47,7 +47,6 @@ AWNoFormatter *AWNoFormatter::copy(const QString &_fileName, const int _number)
auto item = new AWNoFormatter(parent(), _fileName);
AWAbstractFormatter::copyDefaults(item);
item->setNumber(_number);
return item;

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWNOFORMATTER_H
#define AWNOFORMATTER_H
#include "awabstractformatter.h"
@ -34,4 +35,8 @@ public slots:
private:
void translate(void *_ui) override;
// properties
};
#endif /* AWNOFORMATTER_H */

View File

@ -61,7 +61,6 @@ AWScriptFormatter *AWScriptFormatter::copy(const QString &_fileName, const int _
auto item = new AWScriptFormatter(parent(), _fileName);
AWAbstractFormatter::copyDefaults(item);
item->setAppendCode(appendCode());
item->setCode(code());
item->setHasReturn(hasReturn());
@ -126,7 +125,7 @@ void AWScriptFormatter::readConfiguration()
{
AWAbstractFormatter::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setAppendCode(settings.value("X-AW-AppendCode", appendCode()).toBool());
@ -179,7 +178,7 @@ void AWScriptFormatter::writeConfiguration() const
{
AWAbstractFormatter::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWSCRIPTFORMATTER_H
#define AWSCRIPTFORMATTER_H
#include "awabstractformatter.h"
@ -55,3 +56,6 @@ private:
bool m_hasReturn = false;
QString m_program;
};
#endif /* AWSCRIPTFORMATTER_H */

View File

@ -53,7 +53,6 @@ AWStringFormatter *AWStringFormatter::copy(const QString &_fileName, const int _
auto item = new AWStringFormatter(parent(), _fileName);
AWAbstractFormatter::copyDefaults(item);
item->setCount(count());
item->setFillChar(fillChar());
item->setForceWidth(forceWidth());
@ -109,7 +108,7 @@ void AWStringFormatter::readConfiguration()
{
AWAbstractFormatter::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setCount(settings.value("X-AW-Width", count()).toInt());
@ -161,7 +160,7 @@ void AWStringFormatter::writeConfiguration() const
{
AWAbstractFormatter::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef AWSTRINGFORMATTER_H
#define AWSTRINGFORMATTER_H
#include "awabstractformatter.h"
@ -51,3 +52,6 @@ private:
QChar m_fillChar = QChar();
bool m_forceWidth = false;
};
#endif /* AWSTRINGFORMATTER_H */

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef EXTITEMAGGREGATOR_H
#define EXTITEMAGGREGATOR_H
#include <KI18n/KLocalizedString>
@ -23,8 +24,6 @@
#include <QSettings>
#include <QStandardPaths>
#include <ranges>
#include "abstractextitemaggregator.h"
#include "awdebug.h"
@ -50,12 +49,10 @@ public:
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
m_items.clear();
m_activeItems.clear();
};
auto activeItems()
{
return m_items | std::ranges::views::filter([](auto item) { return item->isActive(); });
};
QList<T *> activeItems() { return m_activeItems; };
void editItems()
{
@ -66,7 +63,14 @@ public:
void initItems() override
{
m_items.clear();
m_activeItems.clear();
m_items = getItems();
for (auto &item : m_items) {
if (!item->isActive())
continue;
m_activeItems.append(static_cast<T *>(item));
}
};
void initSockets()
@ -74,7 +78,7 @@ public:
// HACK as soon as per one widget instance we have two objects each of
// them will try to control socket, whereas actually only one of them
// should be owner of the socket
for (auto item : m_items)
for (auto &item : m_items)
item->initSocket();
}
@ -82,34 +86,41 @@ public:
{
qCDebug(LOG_LIB) << "Tag" << _tag << "with used type" << _type;
auto found = std::find_if(m_items.cbegin(), m_items.cend(),
[&_tag, &_type](auto item) { return item->tag(_type) == _tag; });
if (found == std::end(m_items)) {
qCWarning(LOG_LIB) << "Could not find item by tag" << _tag;
return nullptr;
T *found = nullptr;
for (auto &item : m_items) {
if (item->tag(_type) != _tag)
continue;
found = static_cast<T *>(item);
break;
}
return static_cast<T *>(*found);
if (found == nullptr)
qCWarning(LOG_LIB) << "Could not find item by tag" << _tag;
return found;
};
T *itemByTagNumber(const int _number) const
{
qCDebug(LOG_LIB) << "Number" << _number;
auto found = std::find_if(m_items.cbegin(), m_items.cend(),
[_number](auto item) { return item->number() == _number; });
if (found == std::end(m_items)) {
qCWarning(LOG_LIB) << "Could not find item by number" << _number;
return nullptr;
T *found = nullptr;
for (auto &item : m_items) {
if (item->number() != _number)
continue;
found = static_cast<T *>(item);
break;
}
return static_cast<T *>(*found);
if (found == nullptr)
qCWarning(LOG_LIB) << "Could not find item by number" << _number;
return found;
};
[[nodiscard]] QList<AbstractExtItem *> items() const override { return m_items; };
private:
QList<AbstractExtItem *> m_items;
QList<T *> m_activeItems;
void doCreateItem(QListWidget *_widget) override { return createItem<T>(_widget); }
@ -117,8 +128,9 @@ private:
{
QList<AbstractExtItem *> items;
for (auto &dir : directories()) {
auto files = QDir(dir).entryList(QDir::Files, QDir::Name);
auto dirs = directories();
for (auto &dir : dirs) {
QStringList files = QDir(dir).entryList(QDir::Files, QDir::Name);
for (auto &file : files) {
// check filename
if (!file.endsWith(".desktop"))
@ -126,14 +138,18 @@ private:
qCInfo(LOG_LIB) << "Found file" << file << "in" << dir;
auto filePath = QString("%1/%2").arg(dir, file);
// check if already exists
if (std::any_of(items.cbegin(), items.cend(), [&file](auto item) { return item->fileName() == file; }))
if (std::any_of(items.cbegin(), items.cend(),
[&filePath](AbstractExtItem *item) { return (item->fileName() == filePath); }))
continue;
items.append(new T(this, filePath));
}
}
// sort items
std::sort(items.begin(), items.end(), [](auto lhs, auto rhs) { return lhs->number() < rhs->number(); });
std::sort(items.begin(), items.end(), [](auto *lhs, auto *rhs) { return lhs->number() < rhs->number(); });
return items;
};
};
#endif /* EXTITEMAGGREGATOR_H */

View File

@ -40,8 +40,9 @@ ExtNetworkRequest::ExtNetworkRequest(QObject *_parent, const QString &_filePath)
// HACK declare as child of nullptr to avoid crash with plasmawindowed
// in the destructor
m_manager = new QNetworkAccessManager(nullptr);
connect(m_manager, &QNetworkAccessManager::finished, this, &ExtNetworkRequest::networkReplyReceived);
connect(this, &ExtNetworkRequest::requestDataUpdate, this, &ExtNetworkRequest::sendRequest);
connect(m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyReceived(QNetworkReply *)));
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
}
@ -49,6 +50,9 @@ ExtNetworkRequest::~ExtNetworkRequest()
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
disconnect(m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(networkReplyReceived(QNetworkReply *)));
disconnect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
m_manager->deleteLater();
}
@ -59,31 +63,31 @@ ExtNetworkRequest *ExtNetworkRequest::copy(const QString &_fileName, const int _
auto item = new ExtNetworkRequest(parent(), _fileName);
copyDefaults(item);
item->setNumber(_number);
item->setUrl(url());
item->setStringUrl(stringUrl());
return item;
}
QString ExtNetworkRequest::url() const
QString ExtNetworkRequest::stringUrl() const
{
return m_url.toString();
return m_stringUrl;
}
QString ExtNetworkRequest::uniq() const
{
return url();
return m_url.toString();
}
void ExtNetworkRequest::setUrl(const QString &_url)
void ExtNetworkRequest::setStringUrl(const QString &_url)
{
qCDebug(LOG_LIB) << "Url" << _url;
m_url = QUrl(_url);
m_stringUrl = _url;
initUrl();
}
@ -91,10 +95,10 @@ void ExtNetworkRequest::readConfiguration()
{
AbstractExtItem::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setUrl(settings.value("X-AW-Url", url()).toString());
setStringUrl(settings.value("X-AW-Url", stringUrl()).toString());
settings.endGroup();
bumpApi(AW_EXTNETREQUEST_API);
@ -123,7 +127,7 @@ int ExtNetworkRequest::showConfiguration(QWidget *_parent, const QVariant &_args
ui->lineEdit_name->setText(name());
ui->lineEdit_comment->setText(comment());
ui->label_numberValue->setText(QString("%1").arg(number()));
ui->lineEdit_url->setText(url());
ui->lineEdit_url->setText(stringUrl());
ui->checkBox_active->setCheckState(isActive() ? Qt::Checked : Qt::Unchecked);
ui->lineEdit_schedule->setText(cron());
ui->lineEdit_socket->setText(socket());
@ -135,7 +139,7 @@ int ExtNetworkRequest::showConfiguration(QWidget *_parent, const QVariant &_args
setComment(ui->lineEdit_comment->text());
setNumber(ui->label_numberValue->text().toInt());
setApiVersion(AW_EXTNETREQUEST_API);
setUrl(ui->lineEdit_url->text());
setStringUrl(ui->lineEdit_url->text());
setActive(ui->checkBox_active->checkState() == Qt::Checked);
setCron(ui->lineEdit_schedule->text());
setSocket(ui->lineEdit_socket->text());
@ -155,11 +159,11 @@ void ExtNetworkRequest::writeConfiguration() const
{
AbstractExtItem::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");
settings.setValue("X-AW-Url", url());
settings.setValue("X-AW-Url", stringUrl());
settings.endGroup();
settings.sync();
@ -187,6 +191,12 @@ void ExtNetworkRequest::sendRequest()
}
void ExtNetworkRequest::initUrl()
{
m_url = QUrl(m_stringUrl);
}
void ExtNetworkRequest::translate(void *_ui)
{
auto ui = reinterpret_cast<Ui::ExtNetworkRequest *>(_ui);

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef EXTNETWORKREQUEST_H
#define EXTNETWORKREQUEST_H
#include <QNetworkReply>
@ -25,17 +26,17 @@
class ExtNetworkRequest : public AbstractExtItem
{
Q_OBJECT
Q_PROPERTY(QString url READ url WRITE setUrl)
Q_PROPERTY(QString stringUrl READ stringUrl WRITE setStringUrl)
public:
explicit ExtNetworkRequest(QObject *_parent = nullptr, const QString &_filePath = "");
~ExtNetworkRequest() override;
ExtNetworkRequest *copy(const QString &_fileName, int _number) override;
// get methods
[[nodiscard]] QString url() const;
[[nodiscard]] QString stringUrl() const;
[[nodiscard]] QString uniq() const override;
// set methods
void setUrl(const QString &_url);
void setStringUrl(const QString &_url);
public slots:
void readConfiguration() override;
@ -51,9 +52,13 @@ private:
QNetworkAccessManager *m_manager = nullptr;
QUrl m_url;
bool m_isRunning = false;
void initUrl();
void translate(void *_ui) override;
// properties
QString m_stringUrl = "https://httpbin.org/get";
// values
QVariantHash m_values;
};
#endif /* EXTNETWORKREQUEST_H */

View File

@ -55,6 +55,9 @@ ExtQuotes::~ExtQuotes()
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
disconnect(m_manager, &QNetworkAccessManager::finished, this, &ExtQuotes::quotesReplyReceived);
disconnect(this, &ExtQuotes::requestDataUpdate, this, &ExtQuotes::sendRequest);
m_manager->deleteLater();
}
@ -65,7 +68,6 @@ ExtQuotes *ExtQuotes::copy(const QString &_fileName, const int _number)
auto item = new ExtQuotes(parent(), _fileName);
copyDefaults(item);
item->setNumber(_number);
item->setTicker(ticker());
@ -98,7 +100,7 @@ void ExtQuotes::readConfiguration()
{
AbstractExtItem::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setTicker(settings.value("X-AW-Ticker", ticker()).toString());
@ -162,7 +164,7 @@ void ExtQuotes::writeConfiguration() const
{
AbstractExtItem::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");
@ -183,10 +185,10 @@ void ExtQuotes::quotesReplyReceived(QNetworkReply *_reply)
auto text = _reply->readAll();
_reply->deleteLater();
auto data = m_providerObject->parse(text);
for (auto [key, value] : data.asKeyValueRange()) {
m_values[tag(key)] = value;
}
auto data = m_providerObject->parse(text, m_values);
if (data.isEmpty())
return;
m_values = data;
emit(dataReceived(m_values));
}
@ -202,8 +204,10 @@ void ExtQuotes::sendRequest()
void ExtQuotes::initProvider()
{
delete m_providerObject;
// in the future release it is possible to change provider here
m_providerObject = std::make_unique<StooqQuotesProvider>();
m_providerObject = new StooqQuotesProvider(this);
return m_providerObject->initUrl(ticker());
}

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef EXTQUOTES_H
#define EXTQUOTES_H
#include <QNetworkReply>
@ -50,7 +51,7 @@ private slots:
void sendRequest();
private:
std::unique_ptr<AbstractQuotesProvider> m_providerObject;
AbstractQuotesProvider *m_providerObject = nullptr;
QNetworkAccessManager *m_manager = nullptr;
bool m_isRunning = false;
void initProvider();
@ -60,3 +61,6 @@ private:
// values
QVariantHash m_values;
};
#endif /* EXTQUOTES_H */

View File

@ -40,10 +40,10 @@ ExtScript::ExtScript(QObject *_parent, const QString &_filePath)
m_values[tag("custom")] = "";
m_process = new QProcess(nullptr);
connect(m_process, &QProcess::finished, [this]() { return updateValue(); });
connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(updateValue()));
m_process->waitForFinished(0);
connect(this, &ExtScript::requestDataUpdate, this, &ExtScript::startProcess);
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(startProcess()));
}
@ -51,8 +51,10 @@ ExtScript::~ExtScript()
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
disconnect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(updateValue()));
m_process->kill();
m_process->deleteLater();
disconnect(this, SIGNAL(requestDataUpdate()), this, SLOT(startProcess()));
}
@ -62,7 +64,6 @@ ExtScript *ExtScript::copy(const QString &_fileName, const int _number)
auto item = new ExtScript(parent(), _fileName);
copyDefaults(item);
item->setExecutable(executable());
item->setNumber(_number);
item->setRedirect(redirect());
@ -179,8 +180,8 @@ QString ExtScript::applyFilters(QString _value) const
qCWarning(LOG_LIB) << "Could not find filter" << _value << "in the json";
continue;
}
for (auto [key, value] : filter.asKeyValueRange())
_value.replace(key, value.toString());
for (auto &f : filter.keys())
_value.replace(f, filter[f].toString());
}
return _value;
@ -205,7 +206,7 @@ void ExtScript::readConfiguration()
{
AbstractExtItem::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setExecutable(settings.value("Exec", executable()).toString());
@ -226,11 +227,11 @@ void ExtScript::readJsonFilters()
qCWarning(LOG_LIB) << "Could not open" << fileName;
return;
}
auto jsonText = jsonFile.readAll();
QString jsonText = jsonFile.readAll();
jsonFile.close();
QJsonParseError error{};
auto jsonDoc = QJsonDocument::fromJson(jsonText, &error);
auto jsonDoc = QJsonDocument::fromJson(jsonText.toUtf8(), &error);
if (error.error != QJsonParseError::NoError) {
qCWarning(LOG_LIB) << "Parse error" << error.errorString();
return;
@ -305,7 +306,7 @@ void ExtScript::writeConfiguration() const
{
AbstractExtItem::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");
@ -332,24 +333,24 @@ void ExtScript::updateValue()
qCInfo(LOG_LIB) << "Error" << qdebug;
auto qoutput = QString::fromUtf8(m_process->readAllStandardOutput()).trimmed();
qCInfo(LOG_LIB) << "Output" << qoutput;
QString strValue;
QString result;
switch (redirect()) {
case Redirect::stdout2stderr:
break;
case Redirect::stderr2stdout:
result = QString("%1\n%2").arg(qdebug, qoutput);
strValue = QString("%1\n%2").arg(qdebug).arg(qoutput);
break;
case Redirect::swap:
result = qdebug;
strValue = qdebug;
break;
case Redirect::nothing:
result = qoutput;
strValue = qoutput;
break;
}
// filters
m_values[tag("custom")] = applyFilters(result);
m_values[tag("custom")] = applyFilters(strValue);
emit(dataReceived(m_values));
}

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef EXTSCRIPT_H
#define EXTSCRIPT_H
#include <QProcess>
@ -75,3 +76,6 @@ private:
QVariantMap m_jsonFilters;
QVariantHash m_values;
};
#endif /* EXTSCRIPT_H */

View File

@ -36,10 +36,10 @@ ExtUpgrade::ExtUpgrade(QObject *_parent, const QString &_filePath)
m_values[tag("pkgcount")] = 0;
m_process = new QProcess(nullptr);
connect(m_process, &QProcess::finished, this, &ExtUpgrade::updateValue);
connect(m_process, SIGNAL(finished(int)), this, SLOT(updateValue()));
m_process->waitForFinished(0);
connect(this, &ExtUpgrade::requestDataUpdate, this, &ExtUpgrade::startProcess);
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(startProcess()));
}
@ -49,6 +49,7 @@ ExtUpgrade::~ExtUpgrade()
m_process->kill();
m_process->deleteLater();
disconnect(this, SIGNAL(requestDataUpdate()), this, SLOT(startProcess()));
}
@ -58,7 +59,6 @@ ExtUpgrade *ExtUpgrade::copy(const QString &_fileName, const int _number)
auto item = new ExtUpgrade(parent(), _fileName);
copyDefaults(item);
item->setExecutable(executable());
item->setFilter(filter());
item->setNumber(_number);
@ -122,7 +122,7 @@ void ExtUpgrade::readConfiguration()
{
AbstractExtItem::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setExecutable(settings.value("Exec", executable()).toString());
@ -193,7 +193,7 @@ void ExtUpgrade::writeConfiguration() const
{
AbstractExtItem::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef EXTUPGRADE_H
#define EXTUPGRADE_H
#include <QProcess>
@ -63,3 +64,6 @@ private:
// internal properties
QVariantHash m_values;
};
#endif /* EXTUPGRADE_H */

View File

@ -49,8 +49,9 @@ ExtWeather::ExtWeather(QObject *_parent, const QString &_filePath)
// HACK declare as child of nullptr to avoid crash with plasmawindowed
// in the destructor
m_manager = new QNetworkAccessManager(nullptr);
connect(m_manager, &QNetworkAccessManager::finished, this, &ExtWeather::weatherReplyReceived);
connect(this, &ExtWeather::requestDataUpdate, this, &ExtWeather::sendRequest);
connect(m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(weatherReplyReceived(QNetworkReply *)));
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
}
@ -58,6 +59,9 @@ ExtWeather::~ExtWeather()
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
disconnect(m_manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(weatherReplyReceived(QNetworkReply *)));
disconnect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
m_manager->deleteLater();
}
@ -68,7 +72,6 @@ ExtWeather *ExtWeather::copy(const QString &_fileName, const int _number)
auto item = new ExtWeather(parent(), _fileName);
copyDefaults(item);
item->setCity(city());
item->setCountry(country());
item->setImage(image());
@ -147,7 +150,7 @@ int ExtWeather::ts() const
QString ExtWeather::uniq() const
{
return QString("%1 (%2) at %3").arg(city(), country()).arg(ts());
return QString("%1 (%2) at %3").arg(city()).arg(country()).arg(ts());
}
@ -210,7 +213,7 @@ void ExtWeather::readConfiguration()
{
AbstractExtItem::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setCity(settings.value("X-AW-City", city()).toString());
@ -234,11 +237,11 @@ void ExtWeather::readJsonMap()
qCWarning(LOG_LIB) << "Could not open" << fileName;
return;
}
auto jsonText = jsonFile.readAll();
QString jsonText = jsonFile.readAll();
jsonFile.close();
QJsonParseError error{};
auto jsonDoc = QJsonDocument::fromJson(jsonText, &error);
auto jsonDoc = QJsonDocument::fromJson(jsonText.toUtf8(), &error);
if (error.error != QJsonParseError::NoError) {
qCWarning(LOG_LIB) << "Parse error" << error.errorString();
return;
@ -311,7 +314,7 @@ void ExtWeather::writeConfiguration() const
{
AbstractExtItem::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");
@ -351,8 +354,9 @@ void ExtWeather::weatherReplyReceived(QNetworkReply *_reply)
}
auto data = m_providerObject->parse(jsonDoc.toVariant().toMap());
for (auto [key, value] : data.asKeyValueRange())
m_values[tag(key)] = value;
if (data.isEmpty())
return;
m_values = data;
m_values[tag("weather")] = weatherFromInt(m_values[tag("weatherId")].toInt());
emit(dataReceived(m_values));
@ -361,8 +365,10 @@ void ExtWeather::weatherReplyReceived(QNetworkReply *_reply)
void ExtWeather::initProvider()
{
delete m_providerObject;
// in the future release it is possible to change provider here
m_providerObject = std::make_unique<OWMWeatherProvider>();
m_providerObject = new OWMWeatherProvider(this);
return m_providerObject->initUrl(city(), country(), ts());
}

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef EXTWEATHER_H
#define EXTWEATHER_H
#include <QNetworkReply>
@ -74,7 +75,7 @@ private slots:
void weatherReplyReceived(QNetworkReply *_reply);
private:
std::unique_ptr<AbstractWeatherProvider> m_providerObject;
AbstractWeatherProvider *m_providerObject = nullptr;
QNetworkAccessManager *m_manager = nullptr;
bool m_isRunning = false;
void initProvider();
@ -89,3 +90,6 @@ private:
// values
QVariantHash m_values;
};
#endif /* EXTWEATHER_H */

View File

@ -39,7 +39,7 @@ GraphicalItem::GraphicalItem(QObject *_parent, const QString &_filePath)
// init scene
m_scene = new QGraphicsScene();
m_scene->setBackgroundBrush({Qt::NoBrush});
m_scene->setBackgroundBrush(QBrush(Qt::NoBrush));
// init view
m_view = new QGraphicsView(m_scene);
m_view->setStyleSheet("background: transparent");
@ -55,22 +55,12 @@ GraphicalItem::GraphicalItem(QObject *_parent, const QString &_filePath)
}
GraphicalItem::~GraphicalItem()
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
m_view->deleteLater();
m_scene->deleteLater();
}
GraphicalItem *GraphicalItem::copy(const QString &_fileName, const int _number)
{
qCDebug(LOG_LIB) << "File" << _fileName << "with number" << _number;
auto item = new GraphicalItem(parent(), _fileName);
copyDefaults(item);
item->setActiveColor(activeColor());
item->setBar(bar());
item->setCount(count());
@ -93,41 +83,44 @@ QString GraphicalItem::image(const QVariant &value)
qCDebug(LOG_LIB) << "Value" << value;
m_scene->clear();
auto scaleX = 1, scaleY = 1;
auto converted = GraphicalItemHelper::getPercents(value.toDouble(), minValue(), maxValue());
int scale[2] = {1, 1};
auto converted = GraphicalItemHelper::getPercents(value.toFloat(), minValue(), maxValue());
// paint
switch (m_type) {
case Type::Vertical:
m_helper->paintVertical(converted);
scaleY = -2 * static_cast<int>(direction()) + 1;
// scale
scale[1] = -2 * static_cast<int>(direction()) + 1;
break;
case Type::Circle:
m_helper->paintCircle(converted);
scaleX = -2 * static_cast<int>(direction()) + 1;
// scale
scale[0] = -2 * static_cast<int>(direction()) + 1;
break;
case Type::Graph:
m_helper->paintGraph(converted);
scaleX = -2 * static_cast<int>(direction()) + 1;
scaleY = -1;
scale[0] = -2 * static_cast<int>(direction()) + 1;
scale[1] = -1;
break;
case Type::Bars:
m_helper->paintBars(converted);
scaleX = -2 * static_cast<int>(direction()) + 1;
scaleY = -1;
scale[0] = -2 * static_cast<int>(direction()) + 1;
scale[1] = -1;
break;
case Type::Horizontal:
m_helper->paintHorizontal(converted);
scaleX = -2 * static_cast<int>(direction()) + 1;
// scale
scale[0] = -2 * static_cast<int>(direction()) + 1;
break;
}
// convert
auto pixmap = m_view->grab().transformed(QTransform().scale(scaleX, scaleY));
auto pixmap = m_view->grab().transformed(QTransform().scale(scale[0], scale[1]));
QByteArray byteArray;
QBuffer buffer(&byteArray);
pixmap.save(&buffer, "PNG");
auto url = QString("<img src=\"data:image/png;base64,%1\"/>").arg(byteArray.toBase64());
auto url = QString("<img src=\"data:image/png;base64,%1\"/>").arg(QString(byteArray.toBase64()));
return url;
}
@ -182,13 +175,13 @@ int GraphicalItem::itemWidth() const
}
double GraphicalItem::maxValue() const
float GraphicalItem::maxValue() const
{
return m_maxValue;
}
double GraphicalItem::minValue() const
float GraphicalItem::minValue() const
{
return m_minValue;
}
@ -321,7 +314,7 @@ void GraphicalItem::setItemWidth(const int _width)
}
void GraphicalItem::setMaxValue(const double _value)
void GraphicalItem::setMaxValue(const float _value)
{
qCDebug(LOG_LIB) << "Max value" << _value;
@ -329,7 +322,7 @@ void GraphicalItem::setMaxValue(const double _value)
}
void GraphicalItem::setMinValue(const double _value)
void GraphicalItem::setMinValue(const float _value)
{
qCDebug(LOG_LIB) << "Min value" << _value;
@ -400,14 +393,14 @@ void GraphicalItem::readConfiguration()
{
AbstractExtItem::readConfiguration();
QSettings settings(filePath(), QSettings::IniFormat);
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup("Desktop Entry");
setCount(settings.value("X-AW-Count", count()).toInt());
setCustom(settings.value("X-AW-Custom", isCustom()).toBool());
setBar(settings.value("X-AW-Value", bar()).toString());
setMaxValue(settings.value("X-AW-Max", maxValue()).toDouble());
setMinValue(settings.value("X-AW-Min", minValue()).toDouble());
setMaxValue(settings.value("X-AW-Max", maxValue()).toFloat());
setMinValue(settings.value("X-AW-Min", minValue()).toFloat());
setActiveColor(settings.value("X-AW-ActiveColor", activeColor()).toString());
setInactiveColor(settings.value("X-AW-InactiveColor", inactiveColor()).toString());
setStrType(settings.value("X-AW-Type", strType()).toString());
@ -439,8 +432,9 @@ int GraphicalItem::showConfiguration(QWidget *_parent, const QVariant &_args)
ui->setupUi(dialog);
translate(ui);
connect(ui->checkBox_custom, &QCheckBox::stateChanged, [ui](const int state) { changeValue(ui, state); });
connect(ui->comboBox_type, &QComboBox::currentIndexChanged, [ui](const int state) { changeCountState(ui, state); });
connect(ui->checkBox_custom, &QCheckBox::stateChanged, [this, ui](const int state) { changeValue(ui, state); });
connect(ui->comboBox_type, &QComboBox::currentIndexChanged,
[this, ui](const int state) { changeCountState(ui, state); });
connect(ui->toolButton_activeColor, &QToolButton::clicked, [this, ui]() { changeColor(ui); });
connect(ui->toolButton_inactiveColor, &QToolButton::clicked, [this, ui]() { changeColor(ui); });
@ -508,7 +502,7 @@ void GraphicalItem::writeConfiguration() const
{
AbstractExtItem::writeConfiguration();
QSettings settings(writableConfig(), QSettings::IniFormat);
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup("Desktop Entry");

View File

@ -15,7 +15,8 @@
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#pragma once
#ifndef GRAPHICALITEM_H
#define GRAPHICALITEM_H
#include <QColor>
@ -52,7 +53,6 @@ public:
enum class Type { Horizontal = 0, Vertical = 1, Circle = 2, Graph = 3, Bars = 4 };
explicit GraphicalItem(QObject *_parent = nullptr, const QString &_filePath = "");
~GraphicalItem() override;
GraphicalItem *copy(const QString &_fileName, int _number) override;
QString image(const QVariant &value);
void initScene();
@ -64,8 +64,8 @@ public:
[[nodiscard]] bool isCustom() const;
[[nodiscard]] int itemHeight() const;
[[nodiscard]] int itemWidth() const;
[[nodiscard]] double minValue() const;
[[nodiscard]] double maxValue() const;
[[nodiscard]] float minValue() const;
[[nodiscard]] float maxValue() const;
[[nodiscard]] Type type() const;
[[nodiscard]] QString strType() const;
[[nodiscard]] Direction direction() const;
@ -80,8 +80,8 @@ public:
void setInactiveColor(const QString &_color);
void setItemHeight(int _height);
void setItemWidth(int _width);
void setMinValue(double _value);
void setMaxValue(double _value);
void setMinValue(float _value);
void setMaxValue(float _value);
void setType(Type _type);
void setStrType(const QString &_type);
void setDirection(Direction _direction);
@ -96,8 +96,8 @@ public slots:
private slots:
void changeColor(Ui::GraphicalItem *_ui);
static void changeCountState(Ui::GraphicalItem *_ui, int _state);
static void changeValue(Ui::GraphicalItem *_ui, int _state);
void changeCountState(Ui::GraphicalItem *_ui, int _state);
void changeValue(Ui::GraphicalItem *_ui, int _state);
private:
GraphicalItemHelper *m_helper = nullptr;
@ -110,11 +110,14 @@ private:
bool m_custom = false;
QString m_activeColor = "color://0,0,0,130";
QString m_inactiveColor = "color://255,255,255,130";
double m_minValue = 0.0;
double m_maxValue = 100.0;
float m_minValue = 0.0f;
float m_maxValue = 100.0f;
Type m_type = Type::Horizontal;
Direction m_direction = Direction::LeftToRight;
int m_height = 100;
QStringList m_usedKeys;
int m_width = 100;
};
#endif /* GRAPHICALITEM_H */

Some files were not shown because too many files have changed in this diff Show More