Merge pull request #121 from arcan1s/development

Master update
This commit is contained in:
Evgenii Alekseev 2017-05-03 14:38:23 +03:00 committed by GitHub
commit 4109f21bf6
162 changed files with 4800 additions and 2860 deletions

28
.travis.yml Normal file
View File

@ -0,0 +1,28 @@
sudo: required
arch:
packages:
- plasma-framework
# build deps
- cmake
- extra-cmake-modules
- python
# test
- xorg-server-xvfb
# additional targets
- clang
- cppcheck
script:
- export DISPLAY=:99.0
- git clone https://github.com/arcan1s/awesome-widgets/
- cd awesome-widgets; git submodule update --init --recursive
- mkdir awesome-widgets/build
- cd awesome-widgets/build; cmake -DKDE_INSTALL_USE_QT_SYS_PATHS=ON -DCMAKE_BUILD_TYPE=Optimization -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_FUTURE=ON -DBUILD_TESTING=ON ../sources
- cd awesome-widgets/build; make
- cd awesome-widgets/build; make cppcheck
- cd awesome-widgets/build; make clangformat && ( [ `git status -s | wc -l` -eq 0 ] || exit 1 )
- cd awesome-widgets/build; xvfb-run make test
- sleep 3
script:
- "curl -s https://raw.githubusercontent.com/mikkeloscar/arch-travis/master/arch-travis.sh | bash"

View File

@ -54,6 +54,7 @@ for more details. To avoid manual labor there is automatic cmake target named
``` ```
* C-like `NULL`, use `nullptr` instead. * C-like `NULL`, use `nullptr` instead.
* C-like constant definition, use `const vartype foo = bar` definition instead.
* It is highly recommended to avoid implicit casts. Exception `nullptr` casts to * It is highly recommended to avoid implicit casts. Exception `nullptr` casts to
boolean, e.g.: boolean, e.g.:

View File

@ -50,14 +50,14 @@ if (CMAKE_COMPILER_IS_GNUCXX)
# avoid newer gcc warnings # avoid newer gcc warnings
add_definitions(-D_DEFAULT_SOURCE) add_definitions(-D_DEFAULT_SOURCE)
elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang") elseif (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(CMAKE_CXX_FLAGS "-Wall -std=c++11 -stdlib=libc++") set(CMAKE_CXX_FLAGS "-Wall -std=c++11")
set(CMAKE_CXX_FLAGS_DEBUG "-g -O0") set(CMAKE_CXX_FLAGS_DEBUG "-g -O0")
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNDEBUG") set(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNDEBUG")
set(CMAKE_CXX_FLAGS_OPTIMIZATION "-Ofast -DNDEBUG") set(CMAKE_CXX_FLAGS_OPTIMIZATION "-Ofast -DNDEBUG")
# linker flags # linker flags
set(CMAKE_EXE_LINKER_FLAGS "-lc++abi") # set(CMAKE_EXE_LINKER_FLAGS "-lc++abi")
set(CMAKE_MODULE_LINKER_FLAGS "-lc++abi") # set(CMAKE_MODULE_LINKER_FLAGS "-lc++abi")
set(CMAKE_SHARED_LINKER_FLAGS "-lc++abi") # set(CMAKE_SHARED_LINKER_FLAGS "-lc++abi")
else () else ()
message(FATAL_ERROR "Unknown compiler") message(FATAL_ERROR "Unknown compiler")
endif () endif ()
@ -65,6 +65,9 @@ if (CMAKE_BUILD_TYPE MATCHES Debug)
set(CMAKE_VERBOSE_MAKEFILE ON) set(CMAKE_VERBOSE_MAKEFILE ON)
endif () endif ()
# required by successfully coverity and cppcheck build
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(PROJECT_TRDPARTY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/3rdparty) set(PROJECT_TRDPARTY_DIR ${CMAKE_CURRENT_SOURCE_DIR}/3rdparty)
set(PROJECT_LIBRARY awesomewidgets) set(PROJECT_LIBRARY awesomewidgets)
set(PROJECT_MONITORSOURCES extsysmonsources) set(PROJECT_MONITORSOURCES extsysmonsources)
@ -79,6 +82,7 @@ add_subdirectory(awesomewidgets)
add_subdirectory(extsysmonsources) add_subdirectory(extsysmonsources)
add_subdirectory(extsysmon) add_subdirectory(extsysmon)
if (BUILD_PLASMOIDS) if (BUILD_PLASMOIDS)
add_subdirectory(qml)
add_subdirectory(awesome-widget) add_subdirectory(awesome-widget)
add_subdirectory(desktop-panel) add_subdirectory(desktop-panel)
add_subdirectory(translations) add_subdirectory(translations)
@ -89,3 +93,4 @@ if (BUILD_TESTING)
endif () endif ()
include(packages-recipe.cmake) include(packages-recipe.cmake)

View File

@ -16,11 +16,14 @@
***************************************************************************/ ***************************************************************************/
#include <KI18n/KLocalizedString>
#include "awdebug.h" #include "awdebug.h"
Q_LOGGING_CATEGORY(LOG_AW, "org.kde.plasma.awesomewidget", Q_LOGGING_CATEGORY(LOG_AW, "org.kde.plasma.awesomewidget",
QtMsgType::QtWarningMsg) QtMsgType::QtWarningMsg)
Q_LOGGING_CATEGORY(LOG_DBUS, "org.kde.plasma.awdbus", QtMsgType::QtWarningMsg)
Q_LOGGING_CATEGORY(LOG_DP, "org.kde.plasma.desktoppanel", Q_LOGGING_CATEGORY(LOG_DP, "org.kde.plasma.desktoppanel",
QtMsgType::QtWarningMsg) QtMsgType::QtWarningMsg)
Q_LOGGING_CATEGORY(LOG_ESM, "org.kde.plasma.extsysmon", QtMsgType::QtWarningMsg) Q_LOGGING_CATEGORY(LOG_ESM, "org.kde.plasma.extsysmon", QtMsgType::QtWarningMsg)
@ -30,7 +33,80 @@ Q_LOGGING_CATEGORY(LOG_LIB, "org.kde.plasma.awesomewidgets",
QtMsgType::QtWarningMsg) QtMsgType::QtWarningMsg)
const QStringList getBuildData() QString AWDebug::getAboutText(const QString type)
{
QString text;
if (type == QString("header")) {
text = QString(NAME);
} else if (type == QString("version")) {
text = i18n("Version %1 (build date %2)", QString(VERSION),
QString(BUILD_DATE));
if (!QString(COMMIT_SHA).isEmpty())
text += QString(" (%1)").arg(QString(COMMIT_SHA));
} else if (type == QString("description")) {
text = i18n("A set of minimalistic plasmoid widgets");
} else if (type == QString("links")) {
text = i18n("Links:") + QString("<ul>")
+ QString("<li><a href=\"%1\">%2</a></li>")
.arg(QString(HOMEPAGE))
.arg(i18n("Homepage"))
+ QString("<li><a href=\"%1\">%2</a></li>")
.arg(QString(REPOSITORY))
.arg(i18n("Repository"))
+ QString("<li><a href=\"%1\">%2</a></li>")
.arg(QString(BUGTRACKER))
.arg(i18n("Bugtracker"))
+ QString("<li><a href=\"%1\">%2</a></li>")
.arg(QString(TRANSLATION))
.arg(i18n("Translation issue"))
+ QString("<li><a href=\"%1\">%2</a></li>")
.arg(QString(AUR_PACKAGES))
.arg(i18n("AUR packages"))
+ QString("<li><a href=\"%1\">%2</a></li>")
.arg(QString(OPENSUSE_PACKAGES))
.arg(i18n("openSUSE packages"))
+ QString("</ul>");
} else if (type == QString("copy")) {
text = QString("<small>&copy; %1 <a href=\"mailto:%2\">%3</a><br>")
.arg(QString(DATE))
.arg(QString(EMAIL))
.arg(QString(AUTHOR))
+ i18n("This software is licensed under %1", QString(LICENSE))
+ QString("</small>");
} else if (type == QString("translators")) {
QStringList translatorList = QString(TRANSLATORS).split(QChar(','));
for (auto &translator : translatorList)
translator = QString("<li>%1</li>").arg(translator);
text = i18n("Translators:") + QString("<ul>")
+ translatorList.join(QString("")) + QString("</ul>");
} else if (type == QString("3rdparty")) {
QStringList trdPartyList
= QString(TRDPARTY_LICENSE)
.split(QChar(';'), QString::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(QChar(','))[0])
.arg(trdPartyList.at(i).split(QChar(','))[1])
.arg(trdPartyList.at(i).split(QChar(','))[2]);
text = i18n("This software uses:") + QString("<ul>")
+ trdPartyList.join(QString("")) + QString("</ul>");
} else if (type == QString("thanks")) {
QStringList thanks = QString(SPECIAL_THANKS)
.split(QChar(';'), QString::SkipEmptyParts);
for (int i = 0; i < thanks.count(); i++)
thanks[i] = QString("<li><a href=\"%2\">%1</a></li>")
.arg(thanks.at(i).split(QChar(','))[0])
.arg(thanks.at(i).split(QChar(','))[1]);
text = i18n("Special thanks to:") + QString("<ul>")
+ thanks.join(QString("")) + QString("</ul>");
}
return text;
}
QStringList AWDebug::getBuildData()
{ {
QStringList metadata; QStringList metadata;
metadata.append(QString("=== Awesome Widgets configuration details ===")); metadata.append(QString("=== Awesome Widgets configuration details ==="));
@ -41,12 +117,14 @@ const QStringList getBuildData()
metadata.append(QString(" BUILD_DATE: %1").arg(BUILD_DATE)); metadata.append(QString(" BUILD_DATE: %1").arg(BUILD_DATE));
// configuration // configuration
metadata.append(QString("API details:")); metadata.append(QString("API details:"));
metadata.append(QString(" AWGIAPI: %1").arg(AWGIAPI)); metadata.append(QString(" AW_GRAPHITEM_API: %1").arg(AW_GRAPHITEM_API));
metadata.append(QString(" AWEQAPI: %1").arg(AWEQAPI)); metadata.append(QString(" AW_EXTQUOTES_API: %1").arg(AW_EXTQUOTES_API));
metadata.append(QString(" AWESAPI: %1").arg(AWESAPI)); metadata.append(QString(" AW_EXTSCRIPT_API: %1").arg(AW_EXTSCRIPT_API));
metadata.append(QString(" AWEUAPI: %1").arg(AWEUAPI)); metadata.append(
metadata.append(QString(" AWEWAPI: %1").arg(AWEWAPI)); QString(" AW_EXTUPGRADE_API: %1").arg(AW_EXTUPGRADE_API));
metadata.append(QString(" AWEFAPI: %1").arg(AWEFAPI)); metadata.append(
QString(" AW_EXTWEATHER_API: %1").arg(AW_EXTWEATHER_API));
metadata.append(QString(" AW_FORMATTER_API: %1").arg(AW_FORMATTER_API));
metadata.append(QString(" REQUEST_TIMEOUT: %1").arg(REQUEST_TIMEOUT)); metadata.append(QString(" REQUEST_TIMEOUT: %1").arg(REQUEST_TIMEOUT));
metadata.append(QString(" TIME_KEYS: %1").arg(TIME_KEYS)); metadata.append(QString(" TIME_KEYS: %1").arg(TIME_KEYS));
metadata.append(QString(" STATIC_KEYS: %1").arg(STATIC_KEYS)); metadata.append(QString(" STATIC_KEYS: %1").arg(STATIC_KEYS));

View File

@ -23,21 +23,25 @@
#include "version.h" #include "version.h"
#ifndef LOG_FORMAT namespace AWDebug
#define LOG_FORMAT \ {
"[%{time process}][%{if-debug}DD%{endif}%{if-info}II%{endif}%{if-" \ const char LOG_FORMAT[] = "[%{time "
"warning}WW%{endif}%{if-critical}CC%{endif}%{if-fatal}FF%{endif}][%{" \ "process}][%{if-debug}DD%{endif}%{if-info}II%{endif}%"
"category}][%{function}] %{message}" "{if-warning}WW%{endif}%{if-critical}CC%{endif}%{if-"
#endif /* LOG_FORMAT */ "fatal}FF%{endif}][%{category}][%{function}] "
"%{message}";
QString getAboutText(const QString type);
QStringList getBuildData();
}
Q_DECLARE_LOGGING_CATEGORY(LOG_AW) Q_DECLARE_LOGGING_CATEGORY(LOG_AW)
Q_DECLARE_LOGGING_CATEGORY(LOG_DBUS)
Q_DECLARE_LOGGING_CATEGORY(LOG_DP) Q_DECLARE_LOGGING_CATEGORY(LOG_DP)
Q_DECLARE_LOGGING_CATEGORY(LOG_ESM) Q_DECLARE_LOGGING_CATEGORY(LOG_ESM)
Q_DECLARE_LOGGING_CATEGORY(LOG_ESS) Q_DECLARE_LOGGING_CATEGORY(LOG_ESS)
Q_DECLARE_LOGGING_CATEGORY(LOG_LIB) Q_DECLARE_LOGGING_CATEGORY(LOG_LIB)
const QStringList getBuildData();
#endif /* AWDEBUG_H */ #endif /* AWDEBUG_H */

View File

@ -62,6 +62,15 @@
<entry name="acOffline" type="string"> <entry name="acOffline" type="string">
<default>( )</default> <default>( )</default>
</entry> </entry>
<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>
<group name="Tooltip"> <group name="Tooltip">
@ -138,6 +147,12 @@
<entry name="fontStyle" type="string"> <entry name="fontStyle" type="string">
<default>normal</default> <default>normal</default>
</entry> </entry>
<entry name="textStyle" type="string">
<default>normal</default>
</entry>
<entry name="textStyleColor" type="string">
<default>#000000</default>
</entry>
</group> </group>
</kcfg> </kcfg>

View File

@ -16,112 +16,24 @@
***************************************************************************/ ***************************************************************************/
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls
import QtQuick.Layouts 1.0 as QtLayouts
import org.kde.plasma.private.awesomewidget 1.0 import org.kde.plasma.private.awesomewidget 1.0
Item { Item {
id: aboutPage id: aboutPage
// backend
AWActions { AWActions {
id: awActions id: awActions
} }
width: childrenRect.width width: childrenRect.width
height: childrenRect.height height: childrenRect.height
implicitWidth: pageColumn.implicitWidth
implicitHeight: pageColumn.implicitHeight
property bool debug: awActions.isDebugEnabled() AboutTab {
textProvider: awActions
Column {
id: pageColumn
anchors.fill: parent
QtControls.TabView {
height: parent.height
width: parent.width
QtControls.Tab {
anchors.margins: 10.0
title: i18n("About")
QtLayouts.ColumnLayout {
QtControls.Label {
QtLayouts.Layout.fillWidth: true
horizontalAlignment: Text.AlignHCenter
text: awActions.getAboutText("header")
} }
QtControls.Label {
QtLayouts.Layout.fillWidth: true
horizontalAlignment: Text.AlignHCenter
text: awActions.getAboutText("version")
}
QtControls.Label {
QtLayouts.Layout.fillWidth: true
horizontalAlignment: Text.AlignJustify
text: awActions.getAboutText("description")
}
QtControls.Label {
QtLayouts.Layout.fillWidth: true
horizontalAlignment: Text.AlignLeft
textFormat: Text.RichText
text: awActions.getAboutText("links")
onLinkActivated: Qt.openUrlExternally(link)
}
QtControls.Label {
QtLayouts.Layout.fillHeight: true
QtLayouts.Layout.fillWidth: true
font.capitalization: Font.SmallCaps
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignBottom
textFormat: Text.RichText
text: awActions.getAboutText("copy")
}
}
}
QtControls.Tab {
anchors.margins: 10.0
title: i18n("Acknowledgment")
QtLayouts.ColumnLayout {
QtControls.Label {
QtLayouts.Layout.fillWidth: true
wrapMode: Text.WordWrap
horizontalAlignment: Text.AlignJustify
text: awActions.getAboutText("translators")
}
QtControls.Label {
QtLayouts.Layout.fillWidth: true
wrapMode: Text.WordWrap
horizontalAlignment: Text.AlignJustify
textFormat: Text.RichText
text: awActions.getAboutText("3rdparty")
onLinkActivated: Qt.openUrlExternally(link)
}
QtControls.Label {
QtLayouts.Layout.fillHeight: true
QtLayouts.Layout.fillWidth: true
wrapMode: Text.WordWrap
horizontalAlignment: Text.AlignJustify
verticalAlignment: Text.AlignTop
textFormat: Text.RichText
text: awActions.getAboutText("thanks")
onLinkActivated: Qt.openUrlExternally(link)
}
}
}
}
}
Component.onCompleted: { Component.onCompleted: {
if (debug) console.debug() if (debug) console.debug()
} }

View File

@ -17,7 +17,6 @@
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls import QtQuick.Controls 1.3 as QtControls
import QtQuick.Dialogs 1.2 as QtDialogs
import org.kde.plasma.private.awesomewidget 1.0 import org.kde.plasma.private.awesomewidget 1.0
@ -28,9 +27,6 @@ Item {
AWActions { AWActions {
id: awActions id: awActions
} }
AWConfigHelper {
id: awConfig
}
width: childrenRect.width width: childrenRect.width
height: childrenRect.height height: childrenRect.height
@ -50,208 +46,93 @@ Item {
property alias cfg_width: widgetWidth.value property alias cfg_width: widgetWidth.value
property alias cfg_interval: update.value property alias cfg_interval: update.value
property alias cfg_queueLimit: queueLimit.value property alias cfg_queueLimit: queueLimit.value
property string cfg_tempUnits: tempUnits.currentText property string cfg_tempUnits: tempUnits.value
property alias cfg_customTime: customTime.text property alias cfg_customTime: customTime.value
property alias cfg_customUptime: customUptime.text property alias cfg_customUptime: customUptime.value
property alias cfg_acOnline: acOnline.text property alias cfg_acOnline: acOnline.value
property alias cfg_acOffline: acOffline.text property alias cfg_acOffline: acOffline.value
property alias cfg_telemetryCount: telemetryCount.value
property alias cfg_telemetryRemote: telemetryRemote.checked
property alias cfg_telemetryId: telemetryId.value
Column { Column {
id: pageColumn id: pageColumn
anchors.fill: parent anchors.fill: parent
Row {
height: implicitHeight CheckBoxSelector {
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: background id: background
width: parent.width * 3 / 5
text: i18n("Enable background") text: i18n("Enable background")
} }
}
Row { CheckBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: translate id: translate
width: parent.width * 3 / 5
text: i18n("Translate strings") text: i18n("Translate strings")
} }
}
Row { CheckBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: wrapNewLines id: wrapNewLines
width: parent.width * 3 / 5
text: i18n("Wrap new lines") text: i18n("Wrap new lines")
} }
}
Row { CheckBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: wordWrap id: wordWrap
width: parent.width * 3 / 5
text: i18n("Enable word wrap") text: i18n("Enable word wrap")
} }
}
Row { CheckBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: notify id: notify
width: parent.width * 3 / 5
text: i18n("Enable notifications") text: i18n("Enable notifications")
} }
}
Row { CheckBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: updates id: updates
width: parent.width * 3 / 5
text: i18n("Check updates on startup") text: i18n("Check updates on startup")
} }
}
Row { CheckBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: optimize id: optimize
width: parent.width * 3 / 5
text: i18n("Optimize subscription") text: i18n("Optimize subscription")
} }
}
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Widget height, px")
}
QtControls.SpinBox {
id: widgetHeight id: widgetHeight
width: parent.width * 3 / 5
minimumValue: 0
maximumValue: 4096 maximumValue: 4096
minimumValue: 0
stepSize: 50 stepSize: 50
text: i18n("Widget height, px")
value: plasmoid.configuration.height value: plasmoid.configuration.height
} }
}
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Widget width, px")
}
QtControls.SpinBox {
id: widgetWidth id: widgetWidth
width: parent.width * 3 / 5
minimumValue: 0
maximumValue: 4096 maximumValue: 4096
minimumValue: 0
stepSize: 50 stepSize: 50
text: i18n("Widget width, px")
value: plasmoid.configuration.width value: plasmoid.configuration.width
} }
}
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Time interval")
}
QtControls.SpinBox {
id: update id: update
width: parent.width * 3 / 5
minimumValue: 1000
maximumValue: 10000 maximumValue: 10000
minimumValue: 1000
stepSize: 500 stepSize: 500
text: i18n("Time interval")
value: plasmoid.configuration.interval value: plasmoid.configuration.interval
} }
}
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Messages queue limit")
}
QtControls.SpinBox {
id: queueLimit id: queueLimit
width: parent.width * 3 / 5
minimumValue: 0
maximumValue: 99 maximumValue: 99
minimumValue: 0
stepSize: 1 stepSize: 1
text: i18n("Messages queue limit")
value: plasmoid.configuration.queueLimit value: plasmoid.configuration.queueLimit
} }
}
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Temperature units")
}
QtControls.ComboBox {
id: tempUnits id: tempUnits
width: parent.width * 3 / 5
textRole: "label"
model: [ model: [
{ {
'label': i18n("Celsius"), 'label': i18n("Celsius"),
@ -282,188 +163,93 @@ Item {
'name': "kcal/mol" 'name': "kcal/mol"
} }
] ]
onCurrentIndexChanged: cfg_tempUnits = model[currentIndex]["name"] text: i18n("Temperature units")
Component.onCompleted: { value: plasmoid.configuration.tempUnits
if (debug) console.debug() onValueEdited: cfg_tempUnits = newValue
for (var i = 0; i < model.length; i++) {
if (model[i]["name"] == plasmoid.configuration.tempUnits) {
if (debug) console.info("Found", model[i]["name"], "on", i)
tempUnits.currentIndex = i
}
}
}
}
} }
Row { LineSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Custom time format")
}
QtControls.TextField {
id: customTime id: customTime
width: parent.width * 3 / 5 text: i18n("Custom time format")
text: plasmoid.configuration.customTime value: plasmoid.configuration.customTime
}
} }
Row { LineSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Custom uptime format")
}
QtControls.TextField {
id: customUptime id: customUptime
width: parent.width * 3 / 5 text: i18n("Custom uptime format")
text: plasmoid.configuration.customUptime value: plasmoid.configuration.customUptime
}
} }
Row { LineSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("AC online tag")
}
QtControls.TextField {
id: acOnline id: acOnline
width: parent.width * 3 / 5 text: i18n("AC online tag")
text: plasmoid.configuration.acOnline value: plasmoid.configuration.acOnline
}
} }
Row { LineSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("AC offline tag")
}
QtControls.TextField {
id: acOffline id: acOffline
width: parent.width * 3 / 5 text: i18n("AC offline tag")
text: plasmoid.configuration.acOffline value: plasmoid.configuration.acOffline
}
} }
Row { QtControls.GroupBox {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
QtControls.Label { title: i18n("Actions")
height: parent.height
width: parent.width * 2 / 5
}
QtControls.Button {
width: parent.width * 3 / 5
text: i18n("Drop key cache")
onClicked: awActions.dropCache()
}
}
Row {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
}
QtControls.Button {
width: parent.width * 3 / 5
text: i18n("Export configuration")
onClicked: saveConfigAs.open()
}
QtDialogs.FileDialog {
id: saveConfigAs
selectExisting: false
title: i18n("Export")
folder: awConfig.configurationDirectory()
onAccepted: {
var status = awConfig.exportConfiguration(
plasmoid.configuration,
saveConfigAs.fileUrl.toString().replace("file://", ""))
if (status) {
messageDialog.title = i18n("Success")
messageDialog.text = i18n("Please note that binary files were not copied")
} else {
messageDialog.title = i18n("Ooops...")
messageDialog.text = i18n("Could not save configuration file")
}
messageDialog.open()
}
}
QtDialogs.MessageDialog {
id: messageDialog
standardButtons: QtDialogs.StandardButton.Ok
}
}
Row {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
}
QtControls.Button {
width: parent.width * 3 / 5
text: i18n("Import configuration")
onClicked: openConfig.open()
}
QtDialogs.FileDialog {
id: openConfig
title: i18n("Import")
folder: awConfig.configurationDirectory()
onAccepted: importSelection.open()
}
QtDialogs.Dialog {
id: importSelection
Column { Column {
QtControls.CheckBox { height: implicitHeight
id: importPlasmoid width: parent.width
text: i18n("Import plasmoid settings") ButtonSelector {
value: i18n("Drop key cache")
onButtonActivated: awActions.dropCache()
} }
ButtonSelector {
QtControls.CheckBox { ExportDialog {
id: importExtensions id: saveConfigAs
text: i18n("Import extensions") configuration: plasmoid.configuration
}
value: i18n("Export configuration")
onButtonActivated: saveConfigAs.open()
}
ButtonSelector {
ImportDialog {
id: loadConfigFrom
onConfigurationReceived: {
for (var key in configuration)
plasmoid.configuration[key] = configuration[key]
}
}
value: i18n("Import configuration")
onButtonActivated: loadConfigFrom.open()
} }
QtControls.CheckBox {
id: importAdds
text: i18n("Import additional files")
} }
} }
onAccepted: { QtControls.GroupBox {
if (debug) console.debug() height: implicitHeight
var importConfig = awConfig.importConfiguration( width: parent.width
openConfig.fileUrl.toString().replace("file://", ""), title: i18n("Telemetry")
importPlasmoid.checked, importExtensions.checked,
importAdds.checked) Column {
for (var key in importConfig) height: implicitHeight
plasmoid.configuration[key] = importConfig[key] width: parent.width
CheckBoxSelector {
id: telemetryRemote
text: i18n("Enable remote telemetry")
}
IntegerSelector {
id: telemetryCount
maximumValue: 10000
minimumValue: 0
stepSize: 50
text: i18n("History count")
value: plasmoid.configuration.telemetryCount
}
LineSelector {
id: telemetryId
text: i18n("Telemetry ID")
value: plasmoid.configuration.telemetryId
} }
} }
} }

View File

@ -16,11 +16,9 @@
***************************************************************************/ ***************************************************************************/
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls
import QtQuick.Controls.Styles 1.3 as QtStyles
import QtQuick.Dialogs 1.1 as QtDialogs
import org.kde.plasma.private.awesomewidget 1.0 import org.kde.plasma.private.awesomewidget 1.0
import "."
Item { Item {
@ -44,195 +42,68 @@ Item {
87: 5 87: 5
} }
property alias cfg_fontFamily: selectFont.text property alias cfg_fontFamily: font.value
property alias cfg_fontSize: fontSize.value property alias cfg_fontSize: fontSize.value
property string cfg_fontWeight: fontWeight.currentText property string cfg_fontWeight: fontWeight.value
property string cfg_fontStyle: fontStyle.currentText property string cfg_fontStyle: fontStyle.value
property alias cfg_fontColor: selectColor.text property alias cfg_fontColor: selectColor.value
property alias cfg_textStyleColor: selectStyleColor.value
property string cfg_textStyle: textStyle.value
Column { Column {
id: pageColumn id: pageColumn
anchors.fill: parent anchors.fill: parent
Row {
height: implicitHeight FontSelector {
width: parent.width id: font
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font") text: i18n("Font")
} value: plasmoid.configuration.fontFamily
QtControls.Button {
id: selectFont
width: parent.width * 2 / 3
text: plasmoid.configuration.fontFamily
onClicked: {
if (debug) console.debug()
fontDialog.setFont()
fontDialog.visible = true
}
}
} }
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font size")
}
QtControls.SpinBox {
id: fontSize id: fontSize
width: parent.width * 2 / 3
minimumValue: 8
maximumValue: 32 maximumValue: 32
minimumValue: 8
stepSize: 1 stepSize: 1
text: i18n("Font size")
value: plasmoid.configuration.fontSize value: plasmoid.configuration.fontSize
} }
}
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font weight")
}
QtControls.ComboBox {
id: fontWeight id: fontWeight
width: parent.width * 2 / 3 model: general.fontWeightModel
textRole: "label" text: i18n("Font weight")
model: [ value: plasmoid.configuration.fontWeight
{ onValueEdited: cfg_fontWeight = newValue
'label': i18n("light"),
'name': "light"
},
{
'label': i18n("normal"),
'name': "normal"
},
{
'label': i18n("demi bold"),
'name': "demibold"
},
{
'label': i18n("bold"),
'name': "bold"
},
{
'label': i18n("black"),
'name': "black"
}
]
onCurrentIndexChanged: cfg_fontWeight = model[currentIndex]["name"]
Component.onCompleted: {
if (debug) console.debug()
for (var i = 0; i < model.length; i++) {
if (model[i]["name"] == plasmoid.configuration.fontWeight) {
if (debug) console.info("Found", model[i]["name"], "on", i)
fontWeight.currentIndex = i
}
}
}
}
} }
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font style")
}
QtControls.ComboBox {
id: fontStyle id: fontStyle
width: parent.width * 2 / 3 model: general.fontStyleModel
textRole: "label" text: i18n("Font style")
model: [ value: plasmoid.configuration.fontStyle
{ onValueEdited: cfg_fontStyle = newValue
'label': i18n("normal"),
'name': "normal"
},
{
'label': i18n("italic"),
'name': "italic"
}
]
onCurrentIndexChanged: cfg_fontStyle = model[currentIndex]["name"]
Component.onCompleted: {
if (debug) console.debug()
for (var i = 0; i < model.length; i++) {
if (model[i]["name"] == plasmoid.configuration.fontStyle) {
if (debug) console.info("Found", model[i]["name"], "on", i)
fontStyle.currentIndex = i
}
}
}
}
} }
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font color")
}
QtControls.Button {
id: selectColor id: selectColor
width: parent.width * 2 / 3 text: i18n("Font color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.fontColor
background: Rectangle {
color: plasmoid.configuration.fontColor
}
}
text: plasmoid.configuration.fontColor
onClicked: colorDialog.visible = true
}
}
} }
QtDialogs.ColorDialog { ComboBoxSelector {
id: colorDialog id: textStyle
title: i18n("Select a color") model: general.textStyleModel
color: selectColor.text text: i18n("Style")
onAccepted: selectColor.text = colorDialog.color value: plasmoid.configuration.textStyle
onValueEdited: cfg_textStyle = newValue
} }
QtDialogs.FontDialog { ColorSelector {
id: fontDialog id: selectStyleColor
title: i18n("Select a font") text: i18n("Style color")
signal setFont value: plasmoid.configuration.textStyleColor
onAccepted: {
if (debug) console.debug()
selectFont.text = fontDialog.font.family
fontSize.value = fontDialog.font.pointSize
fontStyle.currentIndex = fontDialog.font.italic ? 1 : 0
fontWeight.currentIndex = weight[fontDialog.font.weight]
}
onSetFont: {
if (debug) console.debug()
fontDialog.font = Qt.font({
family: selectFont.text,
pointSize: fontSize.value > 0 ? fontSize.value : 12,
italic: fontStyle.currentIndex == 1,
weight: Font.Normal,
})
} }
} }

View File

@ -52,21 +52,10 @@ Item {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
title: i18n("ACPI") title: i18n("ACPI")
Row { LineSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("ACPI path") text: i18n("ACPI path")
} value: cfg_dataengine["ACPIPATH"]
QtControls.TextField { onValueEdited: cfg_dataengine["ACPIPATH"] = newValue
width: parent.width * 3 / 5
text: cfg_dataengine["ACPIPATH"]
onEditingFinished: cfg_dataengine["ACPIPATH"] = text
}
} }
} }
@ -74,30 +63,28 @@ Item {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
title: i18n("GPU") title: i18n("GPU")
Row { ComboBoxSelector {
height: implicitHeight model: [
width: parent.width {
QtControls.Label { 'label': "auto",
height: parent.height 'name': "auto"
width: parent.width * 2 / 5 },
horizontalAlignment: Text.AlignRight {
verticalAlignment: Text.AlignVCenter 'label': "disable",
'name': "disable"
},
{
'label': "ati",
'name': "ati"
},
{
'label': "nvidia",
'name': "nvidia"
}
]
text: i18n("GPU device") text: i18n("GPU device")
} value: cfg_dataengine["GPUDEV"]
QtControls.ComboBox { onValueEdited: cfg_dataengine["GPUDEV"] = newValue
id: gpuDev
width: parent.width * 3 / 5
model: ["auto", "disable", "ati", "nvidia"]
Component.onCompleted: {
if (debug) console.debug()
for (var i=0; i<model.length; i++) {
if (model[i] == cfg_dataengine["GPUDEV"]) {
if (debug) console.info("Found", model[i], "on", i)
currentIndex = i
}
}
}
}
} }
} }
@ -108,37 +95,17 @@ Item {
Column { Column {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("HDD")
}
QtControls.ComboBox {
id: hdd id: hdd
width: parent.width * 3 / 5 text: i18n("HDD")
} value: cfg_dataengine["HDDDEV"]
onValueEdited: cfg_dataengine["HDDDEV"] = newValue
} }
Row { LineSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("hddtemp cmd") text: i18n("hddtemp cmd")
} value: cfg_dataengine["HDDTEMPCMD"]
QtControls.TextField { onValueEdited: cfg_dataengine["HDDTEMPCMD"] = newValue
width: parent.width * 3 / 5
text: cfg_dataengine["HDDTEMPCMD"]
onEditingFinished: cfg_dataengine["HDDTEMPCMD"] = text
}
} }
} }
} }
@ -150,107 +117,93 @@ Item {
Column { Column {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Player data symbols")
}
QtControls.SpinBox {
width: parent.width * 3 / 5
minimumValue: 1
maximumValue: 100 maximumValue: 100
minimumValue: 1
stepSize: 1 stepSize: 1
text: i18n("Player data symbols")
value: cfg_dataengine["PLAYERSYMBOLS"] value: cfg_dataengine["PLAYERSYMBOLS"]
onEditingFinished: cfg_dataengine["PLAYERSYMBOLS"] = value onValueEdited: cfg_dataengine["PLAYERSYMBOLS"] = newValue
}
} }
Row { ComboBoxSelector {
height: implicitHeight model: [
width: parent.width {
QtControls.Label { 'label': "disable",
height: parent.height 'name': "disable"
width: parent.width * 2 / 5 },
horizontalAlignment: Text.AlignRight {
verticalAlignment: Text.AlignVCenter 'label': "mpris",
'name': "mpris"
},
{
'label': "mpd",
'name': "mpd"
}
]
text: i18n("Music player") text: i18n("Music player")
} value: cfg_dataengine["PLAYER"]
QtControls.ComboBox { onValueEdited: cfg_dataengine["PLAYER"] = newValue
id: player
width: parent.width * 3 / 5
model: ["disable", "mpris", "mpd"]
Component.onCompleted: {
if (debug) console.debug()
for (var i=0; i<model.length; i++) {
if (model[i] == cfg_dataengine["PLAYER"]) {
if (debug) console.info("Found", model[i], "on", i)
player.currentIndex = i
}
}
}
}
} }
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("MPRIS player name")
}
QtControls.ComboBox {
id: mpris id: mpris
width: parent.width * 3 / 5
editable: true editable: true
model: ["auto", "amarok", "audacious", "clementine", "deadbeef", model: [
"vlc", "qmmp", "xmms2", cfg_dataengine["MPRIS"]] {
'label': 'auto',
'name': 'auto'
},
{
'label': 'amarok',
'name': 'amarok'
},
{
'label': 'audacious',
'name': 'audacious'
},
{
'label': 'clementine',
'name': 'clementine'
},
{
'label': 'deadbeef',
'name': 'deadbeef'
},
{
'label': 'vlc',
'name': 'vlc'
},
{
'label': 'qmmp',
'name': 'qmmp'
},
{
'label': 'xmms2',
'name': 'xmms2'
},
{
'label': cfg_dataengine["MPRIS"],
'name': cfg_dataengine["MPRIS"]
}
]
text: i18n("MPRIS player name")
currentIndex: model.length - 1 currentIndex: model.length - 1
} }
}
Row { LineSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("MPD address") text: i18n("MPD address")
} value: cfg_dataengine["MPDADDRESS"]
QtControls.TextField { onValueEdited: cfg_dataengine["MPDADDRESS"] = newValue
width: parent.width * 3 / 5
text: cfg_dataengine["MPDADDRESS"]
onEditingFinished: cfg_dataengine["MPDADDRESS"] = text
}
} }
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("MPD port")
}
QtControls.SpinBox {
width: parent.width * 3 / 5
minimumValue: 1000
maximumValue: 65535 maximumValue: 65535
minimumValue: 1000
stepSize: 1 stepSize: 1
text: i18n("MPD port")
value: cfg_dataengine["MPDPORT"] value: cfg_dataengine["MPDPORT"]
onEditingFinished: cfg_dataengine["MPDPORT"] = value onValueEdited: cfg_dataengine["MPDPORT"] = newValue
}
} }
} }
} }
@ -262,72 +215,29 @@ Item {
Column { Column {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
Row { ButtonSelector {
height: implicitHeight value: i18n("Custom scripts")
width: parent.width onButtonActivated: awKeys.editItem("extscript")
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Custom scripts")
}
QtControls.Button {
width: parent.width * 3 / 5
text: i18n("Edit scripts")
onClicked: awKeys.editItem("extscript")
}
} }
Row { ButtonSelector {
height: implicitHeight value: i18n("Network requests")
width: parent.width onButtonActivated: awKeys.editItem("extnetworkrequest")
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Quotes monitor")
}
QtControls.Button {
width: parent.width * 3 / 5
text: i18n("Edit tickers")
onClicked: awKeys.editItem("extquotes")
}
} }
Row { ButtonSelector {
height: implicitHeight value: i18n("Package manager")
width: parent.width onButtonActivated: awKeys.editItem("extupgrade")
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Package manager")
}
QtControls.Button {
width: parent.width * 3 / 5
text: i18n("Edit command")
onClicked: awKeys.editItem("extupgrade")
}
} }
Row { ButtonSelector {
height: implicitHeight value: i18n("Quotes monitor")
width: parent.width onButtonActivated: awKeys.editItem("extquotes")
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Weather")
}
QtControls.Button {
width: parent.width * 3 / 5
text: i18n("Edit weather")
onClicked: awKeys.editItem("extweather")
} }
ButtonSelector {
value: i18n("Weather")
onButtonActivated: awKeys.editItem("extweather")
} }
} }
} }
@ -342,21 +252,13 @@ Item {
// update hdd model // update hdd model
hdd.model = awKeys.getHddDevices() hdd.model = awKeys.getHddDevices()
for (var i=0; i<hdd.model.length; i++) { hdd.onCompleted
if (hdd.model[i] == cfg_dataengine["HDDDEV"]) {
if (debug) console.info("Found", hdd.model[i], "on", i)
hdd.currentIndex = i
}
}
} }
Component.onDestruction: { Component.onDestruction: {
if (debug) console.debug() if (debug) console.debug()
cfg_dataengine["GPUDEV"] = gpuDev.currentText cfg_dataengine["MPRIS"] = mpris.editText
cfg_dataengine["HDDDEV"] = hdd.currentText
cfg_dataengine["PLAYER"] = player.currentText
cfg_dataengine["MPRIS"] = mpris.currentText
awConfig.writeDataEngineConfiguration(cfg_dataengine) awConfig.writeDataEngineConfiguration(cfg_dataengine)
} }
} }

View File

@ -104,6 +104,9 @@ Item {
font.pointSize: plasmoid.configuration.fontSize font.pointSize: plasmoid.configuration.fontSize
font.weight: general.fontWeight[plasmoid.configuration.fontWeight] font.weight: general.fontWeight[plasmoid.configuration.fontWeight]
style: general.textStyle[plasmoid.configuration.textStyle]
styleColor: plasmoid.configuration.textStyleColor
PlasmaCore.ToolTipArea { PlasmaCore.ToolTipArea {
height: tooltip.height height: tooltip.height
width: tooltip.width width: tooltip.width
@ -207,7 +210,13 @@ Item {
awKeys.setAggregatorProperty("customUptime", plasmoid.configuration.customUptime) awKeys.setAggregatorProperty("customUptime", plasmoid.configuration.customUptime)
awKeys.setAggregatorProperty("tempUnits", plasmoid.configuration.tempUnits) awKeys.setAggregatorProperty("tempUnits", plasmoid.configuration.tempUnits)
awKeys.setAggregatorProperty("translate", plasmoid.configuration.translateStrings) awKeys.setAggregatorProperty("translate", plasmoid.configuration.translateStrings)
// update telemetry ID
if (plasmoid.configuration.telemetryId.length == 0)
plasmoid.configuration.telemetryId = generateUuid()
// save telemetry // save telemetry
awTelemetryHandler.init(plasmoid.configuration.telemetryCount,
plasmoid.configuration.telemetryRemote,
plasmoid.configuration.telemetryId)
if (awTelemetryHandler.put("awwidgetconfig", plasmoid.configuration.text)) if (awTelemetryHandler.put("awwidgetconfig", plasmoid.configuration.text))
awTelemetryHandler.uploadTelemetry("awwidgetconfig", plasmoid.configuration.text) awTelemetryHandler.uploadTelemetry("awwidgetconfig", plasmoid.configuration.text)
} }
@ -238,4 +247,12 @@ Item {
tagSelectorBox.model = awKeys.dictKeys(true) tagSelectorBox.model = awKeys.dictKeys(true)
return tagSelector.open() return tagSelector.open()
} }
// 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) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
} }

View File

@ -1,2 +1,27 @@
singleton general 1.0 general.qml # Do not edit qmldir directly it will be overrided during compilation,
BugReport ./BugReport.qml # 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

@ -17,8 +17,6 @@
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls import QtQuick.Controls 1.3 as QtControls
import QtQuick.Controls.Styles 1.3 as QtStyles
import QtQuick.Dialogs 1.1 as QtDialogs
import org.kde.plasma.private.awesomewidget 1.0 import org.kde.plasma.private.awesomewidget 1.0
@ -39,21 +37,21 @@ Item {
property alias cfg_tooltipNumber: tooltipNumber.value property alias cfg_tooltipNumber: tooltipNumber.value
property alias cfg_useTooltipBackground: useTooltipBackground.checked property alias cfg_useTooltipBackground: useTooltipBackground.checked
property alias cfg_tooltipBackground: tooltipBackground.text property alias cfg_tooltipBackground: tooltipBackground.value
property alias cfg_cpuTooltip: cpuTooltip.checked property alias cfg_cpuTooltip: cpuTooltip.checked
property alias cfg_cpuTooltipColor: cpuTooltipColor.text property alias cfg_cpuTooltipColor: cpuTooltipColor.value
property alias cfg_cpuclTooltip: cpuclTooltip.checked property alias cfg_cpuclTooltip: cpuclTooltip.checked
property alias cfg_cpuclTooltipColor: cpuclTooltipColor.text property alias cfg_cpuclTooltipColor: cpuclTooltipColor.value
property alias cfg_memTooltip: memTooltip.checked property alias cfg_memTooltip: memTooltip.checked
property alias cfg_memTooltipColor: memTooltipColor.text property alias cfg_memTooltipColor: memTooltipColor.value
property alias cfg_swapTooltip: swapTooltip.checked property alias cfg_swapTooltip: swapTooltip.checked
property alias cfg_swapTooltipColor: swapTooltipColor.text property alias cfg_swapTooltipColor: swapTooltipColor.value
property alias cfg_downkbTooltip: downkbTooltip.checked property alias cfg_downkbTooltip: downkbTooltip.checked
property alias cfg_downkbTooltipColor: downkbTooltipColor.text property alias cfg_downkbTooltipColor: downkbTooltipColor.value
property alias cfg_upkbTooltipColor: upkbTooltipColor.text property alias cfg_upkbTooltipColor: upkbTooltipColor.value
property alias cfg_batTooltip: batTooltip.checked property alias cfg_batTooltip: batTooltip.checked
property alias cfg_batTooltipColor: batTooltipColor.text property alias cfg_batTooltipColor: batTooltipColor.value
property alias cfg_batInTooltipColor: batInTooltipColor.text property alias cfg_batInTooltipColor: batInTooltipColor.value
Column { Column {
@ -67,25 +65,14 @@ Item {
text: i18n("CPU, CPU clock, memory, swap and network labels support graphical tooltip. To enable them just make needed checkbox checked.") text: i18n("CPU, CPU clock, memory, swap and network labels support graphical tooltip. To enable them just make needed checkbox checked.")
} }
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Number of values for tooltips")
}
QtControls.SpinBox {
id: tooltipNumber id: tooltipNumber
width: parent.width * 3 / 5
minimumValue: 50
maximumValue: 1000 maximumValue: 1000
minimumValue: 50
stepSize: 25 stepSize: 25
text: i18n("Number of values for tooltips")
value: plasmoid.configuration.tooltipNumber value: plasmoid.configuration.tooltipNumber
} }
}
QtControls.GroupBox { QtControls.GroupBox {
id: useTooltipBackground id: useTooltipBackground
@ -93,34 +80,10 @@ Item {
width: parent.width width: parent.width
checkable: true checkable: true
title: i18n("Background") title: i18n("Background")
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Background color")
}
QtControls.Button {
id: tooltipBackground id: tooltipBackground
width: parent.width * 3 / 5 text: i18n("Background color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.tooltipBackground
background: Rectangle {
color: plasmoid.configuration.tooltipBackground
}
}
text: plasmoid.configuration.tooltipBackground
onClicked: tooltipBackgroundDialog.visible = true
}
QtDialogs.ColorDialog {
id: tooltipBackgroundDialog
title: i18n("Select a color")
color: tooltipBackground.text
onAccepted: tooltipBackground.text = tooltipBackgroundDialog.color
}
} }
} }
@ -130,34 +93,10 @@ Item {
width: parent.width width: parent.width
checkable: true checkable: true
title: i18n("CPU") title: i18n("CPU")
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("CPU color")
}
QtControls.Button {
id: cpuTooltipColor id: cpuTooltipColor
width: parent.width * 3 / 5 text: i18n("CPU color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.cpuTooltipColor
background: Rectangle {
color: plasmoid.configuration.cpuTooltipColor
}
}
text: plasmoid.configuration.cpuTooltipColor
onClicked: cpuTooltipColorDialog.visible = true
}
QtDialogs.ColorDialog {
id: cpuTooltipColorDialog
title: i18n("Select a color")
color: cpuTooltipColor.text
onAccepted: cpuTooltipColor.text = cpuTooltipColorDialog.color
}
} }
} }
@ -167,34 +106,10 @@ Item {
width: parent.width width: parent.width
checkable: true checkable: true
title: i18n("CPU clock") title: i18n("CPU clock")
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("CPU clock color")
}
QtControls.Button {
id: cpuclTooltipColor id: cpuclTooltipColor
width: parent.width * 3 / 5 text: i18n("CPU clock color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.cpuclTooltipColor
background: Rectangle {
color: plasmoid.configuration.cpuclTooltipColor
}
}
text: plasmoid.configuration.cpuclTooltipColor
onClicked: cpuclTooltipColorDialog.visible = true
}
QtDialogs.ColorDialog {
id: cpuclTooltipColorDialog
title: i18n("Select a color")
color: cpuclTooltipColor.text
onAccepted: cpuclTooltipColor.text = cpuclTooltipColorDialog.color
}
} }
} }
@ -204,34 +119,10 @@ Item {
width: parent.width width: parent.width
checkable: true checkable: true
title: i18n("Memory") title: i18n("Memory")
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Memory color")
}
QtControls.Button {
id: memTooltipColor id: memTooltipColor
width: parent.width * 3 / 5 text: i18n("Memory color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.memTooltipColor
background: Rectangle {
color: plasmoid.configuration.memTooltipColor
}
}
text: plasmoid.configuration.memTooltipColor
onClicked: memTooltipColorDialog.visible = true
}
QtDialogs.ColorDialog {
id: memTooltipColorDialog
title: i18n("Select a color")
color: memTooltipColor.text
onAccepted: memTooltipColor.text = memTooltipColorDialog.color
}
} }
} }
@ -241,34 +132,10 @@ Item {
width: parent.width width: parent.width
checkable: true checkable: true
title: i18n("Swap") title: i18n("Swap")
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Swap color")
}
QtControls.Button {
id: swapTooltipColor id: swapTooltipColor
width: parent.width * 3 / 5 text: i18n("Swap color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.swapTooltipColor
background: Rectangle {
color: plasmoid.configuration.swapTooltipColor
}
}
text: plasmoid.configuration.swapTooltipColor
onClicked: swapTooltipColorDialog.visible = true
}
QtDialogs.ColorDialog {
id: swapTooltipColorDialog
title: i18n("Select a color")
color: swapTooltipColor.text
onAccepted: swapTooltipColor.text = swapTooltipColorDialog.color
}
} }
} }
@ -281,63 +148,15 @@ Item {
Column { Column {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Download speed color")
}
QtControls.Button {
id: downkbTooltipColor id: downkbTooltipColor
width: parent.width * 3 / 5 text: i18n("Download speed color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.downkbTooltipColor
background: Rectangle {
color: plasmoid.configuration.downkbTooltipColor
} }
} ColorSelector {
text: plasmoid.configuration.downkbTooltipColor
onClicked: downkbTooltipColorDialog.visible = true
}
QtDialogs.ColorDialog {
id: downkbTooltipColorDialog
title: i18n("Select a color")
color: downkbTooltipColor.text
onAccepted: downkbTooltipColor.text = downkbTooltipColorDialog.color
}
}
Row {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Upload speed color")
}
QtControls.Button {
id: upkbTooltipColor id: upkbTooltipColor
width: parent.width * 3 / 5 text: i18n("Upload speed color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.upkbTooltipColor
background: Rectangle {
color: plasmoid.configuration.upkbTooltipColor
}
}
text: plasmoid.configuration.upkbTooltipColor
onClicked: upkbTooltipColorDialog.visible = true
}
QtDialogs.ColorDialog {
id: upkbTooltipColorDialog
title: i18n("Select a color")
color: upkbTooltipColor.text
onAccepted: upkbTooltipColor.text = upkbTooltipColorDialog.color
}
} }
} }
} }
@ -351,63 +170,15 @@ Item {
Column { Column {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Battery active color")
}
QtControls.Button {
id: batTooltipColor id: batTooltipColor
width: parent.width * 3 / 5 text: i18n("Battery active color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.batTooltipColor
background: Rectangle {
color: plasmoid.configuration.batTooltipColor
} }
} ColorSelector {
text: plasmoid.configuration.batTooltipColor
onClicked: batTooltipColorDialog.visible = true
}
QtDialogs.ColorDialog {
id: batTooltipColorDialog
title: i18n("Select a color")
color: batTooltipColor.text
onAccepted: batTooltipColor.text = batTooltipColorDialog.color
}
}
Row {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Battery inactive color")
}
QtControls.Button {
id: batInTooltipColor id: batInTooltipColor
width: parent.width * 3 / 5 text: i18n("Battery inactive color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.batInTooltipColor
background: Rectangle {
color: plasmoid.configuration.batInTooltipColor
}
}
text: plasmoid.configuration.batInTooltipColor
onClicked: batInTooltipColorDialog.visible = true
}
QtDialogs.ColorDialog {
id: batInTooltipColorDialog
title: i18n("Select a color")
color: batInTooltipColor.text
onAccepted: batInTooltipColor.text = batInTooltipColorDialog.color
}
} }
} }
} }

View File

@ -16,10 +16,9 @@
***************************************************************************/ ***************************************************************************/
import QtQuick 2.2 import QtQuick 2.2
import QtQuick.Controls 1.3 as QtControls
import QtQuick.Dialogs 1.2 as QtDialogs
import org.kde.plasma.private.awesomewidget 1.0 import org.kde.plasma.private.awesomewidget 1.0
import "."
Item { Item {
@ -31,12 +30,6 @@ Item {
AWActions { AWActions {
id: awActions id: awActions
} }
AWFormatterConfigFactory {
id: awFormatter
}
AWTelemetryHandler {
id: awTelemetryHandler
}
width: childrenRect.width width: childrenRect.width
height: childrenRect.height height: childrenRect.height
@ -54,329 +47,33 @@ Item {
Column { Column {
id: pageColumn id: pageColumn
anchors.fill: parent anchors.fill: parent
QtControls.Label {
width: parent.width AWInfoLabel {}
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter HtmlDefaultFunctionsBar {
wrapMode: Text.WordWrap textArea: textPattern
text: i18n("Detailed information may be found on <a href=\"https://arcanis.me/projects/awesome-widgets/\">project homepage</a>")
onLinkActivated: Qt.openUrlExternally(link)
} }
Row { AWTagSelector {
height: implicitHeight backend: awKeys
width: parent.width notifyBackend: awActions
QtControls.Button { textArea: textPattern
width: parent.width * 3 / 15 groups: general.awTagRegexp
text: i18n("Bgcolor")
onClicked: backgroundDialog.visible = true
QtDialogs.ColorDialog {
id: backgroundDialog
title: i18n("Select a color")
onAccepted: {
var text = textPattern.text
textPattern.text = "<body bgcolor=\"" +
backgroundDialog.color + "\">" +
text + "</body>"
}
}
}
QtControls.Button {
width: parent.width * 3 / 15
text: i18n("Font")
iconName: "font"
onClicked: {
if (debug) console.debug("Font button")
var defaultFont = {
"color": plasmoid.configuration.fontColor,
"family": plasmoid.configuration.fontFamily,
"size": plasmoid.configuration.fontSize
}
var font = awActions.getFont(defaultFont)
if (font.applied != 1) {
if (debug) console.debug("No font selected")
return
} }
var selected = textPattern.selectedText AWExtensions {
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd) id: extensions
textPattern.insert(textPattern.cursorPosition, backend: awKeys
"<span style=\"color:" + font.color + textArea: textPattern
"; font-family:'" + font.family + onUnlock: lock = false
"'; font-size:" + font.size + "pt;\">" +
selected + "</span>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-indent-more"
onClicked: {
if (debug) console.debug("Indent button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, selected + "<br>\n")
}
} }
QtControls.Button { AWTextEditor {
width: parent.width / 15
iconName: "format-text-bold"
onClicked: {
if (debug) console.debug("Bold button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<b>" + selected + "</b>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-text-italic"
onClicked: {
if (debug) console.debug("Italic button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<i>" + selected + "</i>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-text-underline"
onClicked: {
if (debug) console.debug("Underline button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<u>" + selected + "</u>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-text-strikethrough"
onClicked: {
if (debug) console.debug("Strike button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<s>" + selected + "</s>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-justify-left"
onClicked: {
if (debug) console.debug("Left button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<p align=\"left\">" + selected + "</p>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-justify-center"
onClicked: {
if (debug) console.debug("Center button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<p align=\"center\">" + selected + "</p>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-justify-right"
onClicked: {
if (debug) console.debug("Right button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<p align=\"right\">" + selected + "</p>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-justify-fill"
onClicked: {
if (debug) console.debug("Justify button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<p align=\"justify\">" + selected + "</p>")
}
}
}
Row {
height: implicitHeight
width: parent.width
QtControls.ComboBox {
width: parent.width * 2 / 5
textRole: "label"
model: [
{
'label': i18n("AC"),
'regexp': "^(ac|bat).*"
},
{
'label': i18n("Bars"),
'regexp': "^bar.*"
},
{
'label': i18n("CPU"),
'regexp': "^(cpu|gpu|la|ps|temp(?!erature)).*"
},
{
'label': i18n("Desktops"),
'regexp': "^(n|t)?desktop(s)?"
},
{
'label': i18n("HDD"),
'regexp': "^hdd.*"
},
{
'label': i18n("Memory"),
'regexp': "^(mem|swap).*"
},
{
'label': i18n("Network"),
'regexp': "^(netdev|(down|up(?!time)).*)"
},
{
'label': i18n("Music player"),
'regexp': "(^|d|s)(album|artist|duration|progress|title)"
},
{
'label': i18n("Scripts"),
'regexp': "^custom.*"
},
{
'label': i18n("Time"),
'regexp': ".*time$"
},
{
'label': i18n("Quotes"),
'regexp': "^(perc)?(ask|bid|price)(chg)?.*"
},
{
'label': i18n("Upgrades"),
'regexp': "^pkgcount.*"
},
{
'label': i18n("Weathers"),
'regexp': "^(weather(Id)?|humidity|pressure|temperature|timestamp)"
},
{
'label': i18n("Functions"),
'regexp': "functions"
}
]
onCurrentIndexChanged: {
if (debug) console.debug()
if (model[currentIndex]["regexp"] == "functions")
tags.model = ["{{\n\n}}", "template{{\n\n}}",
"aw_all<>{{}}", "aw_count<>{{}}", "aw_keys<>{{}}",
"aw_macro<>{{}}", "aw_names<>{{}}"]
else
tags.model = awKeys.dictKeys(true, model[currentIndex]["regexp"])
if (debug) console.info("Init model", tags.model, "for", model[currentIndex]["label"])
tags.currentIndex = -1
}
}
QtControls.ComboBox {
id: tags
width: parent.width * 1 / 5
}
QtControls.Button {
width: parent.width * 1 / 5
text: i18n("Add")
onClicked: {
if (!tags.currentText) return
if (debug) console.debug("Add tag button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, selected + "$" + tags.currentText)
}
}
QtControls.Button {
width: parent.width * 1 / 5
text: i18n("Show value")
onClicked: {
if (!tags.currentText) return
if (debug) console.debug("Show tag button")
var message = i18n("Tag: %1", tags.currentText)
message += "<br>"
message += i18n("Value: %1", awKeys.valueByKey(tags.currentText))
message += "<br>"
message += i18n("Info: %1", awKeys.infoByKey(tags.currentText))
awActions.sendNotification("tag", message)
}
}
}
Row {
height: implicitHeight
width: parent.width
QtControls.Button {
width: parent.width * 3 / 10
text: i18n("Edit bars")
onClicked: awKeys.editItem("graphicalitem")
}
QtControls.Button {
width: parent.width * 3 / 10
text: i18n("Formatters")
onClicked: awFormatter.showDialog(awKeys.dictKeys(true))
}
QtControls.Button {
width: parent.width * 5 / 15
text: i18n("Preview")
onClicked: {
lock = false
awKeys.initKeys(textPattern.text, plasmoid.configuration.interval,
plasmoid.configuration.queueLimit, false)
}
}
QtControls.Button {
width: parent.width / 15
iconName: "view-history"
menu: QtControls.Menu {
id: historyConfig
Instantiator {
model: awTelemetryHandler.get("awwidgetconfig")
QtControls.MenuItem {
text: modelData
onTriggered: textPattern.text = modelData
}
onObjectAdded: historyConfig.insertItem(index, object)
onObjectRemoved: historyConfig.removeItem(object)
}
}
}
}
QtControls.TextArea {
id: textPattern id: textPattern
width: parent.width backend: awKeys
height: parent.height * 4 / 5
textFormat: TextEdit.PlainText
text: plasmoid.configuration.text
} }
} }
QtDialogs.MessageDialog {
id: compiledText
modality: Qt.NonModal
title: i18n("Preview")
}
Component.onCompleted: { Component.onCompleted: {
if (debug) console.debug() if (debug) console.debug()
@ -397,8 +94,7 @@ Item {
if (lock) return if (lock) return
if (debug) console.debug() if (debug) console.debug()
compiledText.text = newText.replace(/&nbsp;/g, " ") extensions.showMessage(newText)
compiledText.open()
lock = true lock = true
} }
} }

View File

@ -21,13 +21,16 @@
#include "awdebug.h" #include "awdebug.h"
AWAbstractSelector::AWAbstractSelector(QWidget *parent) AWAbstractSelector::AWAbstractSelector(QWidget *parent,
const QPair<bool, bool> editable)
: QWidget(parent) : QWidget(parent)
, ui(new Ui::AWAbstractSelector) , ui(new Ui::AWAbstractSelector)
{ {
qCDebug(LOG_AW) << __PRETTY_FUNCTION__; qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
ui->setupUi(this); ui->setupUi(this);
ui->comboBox_key->setEditable(editable.first);
ui->comboBox_value->setEditable(editable.second);
connect(ui->comboBox_key, SIGNAL(currentIndexChanged(int)), this, connect(ui->comboBox_key, SIGNAL(currentIndexChanged(int)), this,
SIGNAL(selectionChanged())); SIGNAL(selectionChanged()));

View File

@ -32,7 +32,9 @@ class AWAbstractSelector : public QWidget
Q_OBJECT Q_OBJECT
public: public:
explicit AWAbstractSelector(QWidget *parent = nullptr); explicit AWAbstractSelector(QWidget *parent = nullptr,
const QPair<bool, bool> editable
= {false, false});
virtual ~AWAbstractSelector(); virtual ~AWAbstractSelector();
QPair<QString, QString> current() const; QPair<QString, QString> current() const;
void init(const QStringList keys, const QStringList values, void init(const QStringList keys, const QStringList values,

View File

@ -118,66 +118,7 @@ QString AWActions::getAboutText(const QString type) const
{ {
qCDebug(LOG_AW) << "Type" << type; qCDebug(LOG_AW) << "Type" << type;
QString text; return AWDebug::getAboutText(type);
if (type == QString("header")) {
text = QString(NAME);
} else if (type == QString("version")) {
text = i18n("Version %1 (build date %2)", QString(VERSION),
QString(BUILD_DATE));
if (!QString(COMMIT_SHA).isEmpty())
text += QString(" (%1)").arg(QString(COMMIT_SHA));
} else if (type == QString("description")) {
text = i18n("A set of minimalistic plasmoid widgets");
} else if (type == QString("links")) {
text = i18n("Links:") + QString("<br>")
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(HOMEPAGE))
.arg(i18n("Homepage"))
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(REPOSITORY))
.arg(i18n("Repository"))
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(BUGTRACKER))
.arg(i18n("Bugtracker"))
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(TRANSLATION))
.arg(i18n("Translation issue"))
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(AUR_PACKAGES))
.arg(i18n("AUR packages"))
+ QString("<a href=\"%1\">%2</a>")
.arg(QString(OPENSUSE_PACKAGES))
.arg(i18n("openSUSE packages"));
} else if (type == QString("copy")) {
text = QString("<small>&copy; %1 <a href=\"mailto:%2\">%3</a><br>")
.arg(QString(DATE))
.arg(QString(EMAIL))
.arg(QString(AUTHOR))
+ i18n("This software is licensed under %1", QString(LICENSE))
+ QString("</small>");
} else if (type == QString("translators")) {
text = i18n("Translators: %1", QString(TRANSLATORS));
} else if (type == QString("3rdparty")) {
QStringList trdPartyList
= QString(TRDPARTY_LICENSE)
.split(QChar(';'), QString::SkipEmptyParts);
for (int i = 0; i < trdPartyList.count(); i++)
trdPartyList[i] = QString("<a href=\"%3\">%1</a> (%2 license)")
.arg(trdPartyList.at(i).split(QChar(','))[0])
.arg(trdPartyList.at(i).split(QChar(','))[1])
.arg(trdPartyList.at(i).split(QChar(','))[2]);
text = i18n("This software uses: %1", trdPartyList.join(QString(", ")));
} else if (type == QString("thanks")) {
QStringList thanks = QString(SPECIAL_THANKS)
.split(QChar(';'), QString::SkipEmptyParts);
for (int i = 0; i < thanks.count(); i++)
thanks[i] = QString("<a href=\"%2\">%1</a>")
.arg(thanks.at(i).split(QChar(','))[0])
.arg(thanks.at(i).split(QChar(','))[1]);
text = i18n("Special thanks to %1", thanks.join(QString(", ")));
}
return text;
} }

View File

@ -66,7 +66,7 @@ QString AWBugReporter::generateText(const QString description,
output += QString("**Step to reproduce**\n\n%1\n\n").arg(reproduce); output += QString("**Step to reproduce**\n\n%1\n\n").arg(reproduce);
output += QString("**Expected result**\n\n%1\n\n").arg(expected); output += QString("**Expected result**\n\n%1\n\n").arg(expected);
output += QString("**Version**\n\n%1\n\n") output += QString("**Version**\n\n%1\n\n")
.arg(getBuildData().join(QString("\n"))); .arg(AWDebug::getBuildData().join(QString("\n")));
// append logs // append logs
output += QString("**Logs**\n\n%1").arg(logs); output += QString("**Logs**\n\n%1").arg(logs);
@ -83,7 +83,7 @@ void AWBugReporter::sendBugReport(const QString title, const QString body)
connect(manager, SIGNAL(finished(QNetworkReply *)), this, connect(manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(issueReplyRecieved(QNetworkReply *))); SLOT(issueReplyRecieved(QNetworkReply *)));
QNetworkRequest request(QUrl(BUGTRACKER_API)); QNetworkRequest request = QNetworkRequest(QUrl(BUGTRACKER_API));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// generate payload // generate payload

View File

@ -69,13 +69,12 @@ bool AWConfigHelper::dropCache() const
} }
bool AWConfigHelper::exportConfiguration(const QObject *nativeConfig, bool AWConfigHelper::exportConfiguration(QObject *nativeConfig,
const QString fileName) const const QString fileName) const
{ {
qCDebug(LOG_AW) << "Selected filename" << fileName; qCDebug(LOG_AW) << "Selected filename" << fileName;
QSettings settings(fileName, QSettings::IniFormat); QSettings settings(fileName, QSettings::IniFormat);
// plasmoid configuration // plasmoid configuration
const QQmlPropertyMap *configuration const QQmlPropertyMap *configuration
= static_cast<const QQmlPropertyMap *>(nativeConfig); = static_cast<const QQmlPropertyMap *>(nativeConfig);

View File

@ -35,7 +35,7 @@ public:
virtual ~AWConfigHelper(); virtual ~AWConfigHelper();
Q_INVOKABLE QString configurationDirectory() const; Q_INVOKABLE QString configurationDirectory() const;
Q_INVOKABLE bool dropCache() const; Q_INVOKABLE bool dropCache() const;
Q_INVOKABLE bool exportConfiguration(const QObject *nativeConfig, Q_INVOKABLE bool exportConfiguration(QObject *nativeConfig,
const QString fileName) const; const QString fileName) const;
Q_INVOKABLE QVariantMap importConfiguration(const QString fileName, Q_INVOKABLE QVariantMap importConfiguration(const QString fileName,
const bool importPlasmoid, const bool importPlasmoid,

View File

@ -143,9 +143,9 @@ QPixmap AWDataAggregator::tooltipImage()
for (int j = 0; j < m_values[key].count() - 1; j++) { for (int j = 0; j < m_values[key].count() - 1; j++) {
// some magic here // some magic here
float x1 = j * normX + shift; float x1 = j * normX + shift;
float y1 = -fabs(m_values[key].at(j)) * normY + 5.0f; float y1 = -std::fabs(m_values[key].at(j)) * normY + 5.0f;
float x2 = (j + 1) * normX + shift; float x2 = (j + 1) * normX + shift;
float y2 = -fabs(m_values[key].at(j + 1)) * normY + 5.0f; float y2 = -std::fabs(m_values[key].at(j + 1)) * normY + 5.0f;
if (key == QString("batTooltip")) { if (key == QString("batTooltip")) {
if (m_values[key].at(j + 1) > 0) if (m_values[key].at(j + 1) > 0)
pen.setColor( pen.setColor(

View File

@ -0,0 +1,92 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#include "awdbusadaptor.h"
#include "awdebug.h"
#include "awkeys.h"
AWDBusAdaptor::AWDBusAdaptor(AWKeys *parent)
: QDBusAbstractAdaptor(parent)
, m_plugin(parent)
{
qCDebug(LOG_DBUS) << __PRETTY_FUNCTION__;
}
AWDBusAdaptor::~AWDBusAdaptor()
{
qCDebug(LOG_DBUS) << __PRETTY_FUNCTION__;
}
QString AWDBusAdaptor::Info(const QString key) const
{
return m_plugin->infoByKey(key);
}
QStringList AWDBusAdaptor::Keys(const QString regexp) const
{
return m_plugin->dictKeys(true, regexp);
}
QString AWDBusAdaptor::Value(const QString key) const
{
return m_plugin->valueByKey(key);
}
qlonglong AWDBusAdaptor::WhoAmI() const
{
return reinterpret_cast<qlonglong>(m_plugin);
}
void AWDBusAdaptor::SetLogLevel(const QString what, const int level)
{
qCDebug(LOG_DBUS) << "Set log level" << level << "for" << what;
if (level >= m_logLevels.count()) {
qCDebug(LOG_DBUS) << "Invalid logging level" << level
<< "should be less than" << m_logLevels.count();
return;
}
for (auto lev : m_logLevels)
SetLogLevel(what, lev, m_logLevels.indexOf(lev) >= level);
}
void AWDBusAdaptor::SetLogLevel(const QString what, const QString level,
const bool enabled)
{
qCDebug(LOG_DBUS) << "Set log level" << level << "enabled" << enabled
<< "for" << what;
if (!m_logLevels.contains(level)) {
qCDebug(LOG_DBUS) << "Invalid logging level" << level << "should be in"
<< m_logLevels;
return;
}
QString state = enabled ? QString("true") : QString("false");
QLoggingCategory::setFilterRules(
QString("%1.%2=%3").arg(what).arg(level).arg(state));
}

View File

@ -0,0 +1,57 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#ifndef AWDBUSADAPTOR_H
#define AWDBUSADAPTOR_H
#include <QDBusAbstractAdaptor>
#include "version.h"
class AWKeys;
class AWDBusAdaptor : public QDBusAbstractAdaptor
{
Q_OBJECT
Q_CLASSINFO("D-Bus Interface", AWDBUS_SERVICE_NAME)
public:
explicit AWDBusAdaptor(AWKeys *parent = nullptr);
virtual ~AWDBusAdaptor();
public slots:
// get methods
QString Info(const QString key) const;
QStringList Keys(const QString regexp) const;
QString Value(const QString key) const;
qlonglong WhoAmI() const;
// set methods
void SetLogLevel(const QString what, const int level);
void SetLogLevel(const QString what, const QString level,
const bool enabled);
private:
AWKeys *m_plugin = nullptr;
QStringList m_logLevels = QStringList()
<< QString("debug") << QString("info")
<< QString("warning") << QString("critical");
};
#endif /* AWDBUSADAPTOR_H */

View File

@ -80,12 +80,14 @@ void AWFormatterConfig::updateUi()
= m_selectors.indexOf(static_cast<AWAbstractSelector *>(sender())); = m_selectors.indexOf(static_cast<AWAbstractSelector *>(sender()));
if ((current.first.isEmpty()) && (current.second.isEmpty())) { if ((current.first.isEmpty()) && (current.second.isEmpty())) {
// remove current selector if it is empty and does not last
if (sender() == m_selectors.last()) if (sender() == m_selectors.last())
return; return;
AWAbstractSelector *selector = m_selectors.takeAt(index); AWAbstractSelector *selector = m_selectors.takeAt(index);
ui->verticalLayout->removeWidget(selector); ui->verticalLayout->removeWidget(selector);
selector->deleteLater(); selector->deleteLater();
} else { } else {
// add new selector if something changed
if (sender() != m_selectors.last()) if (sender() != m_selectors.last())
return; return;
auto keys = initKeys(); auto keys = initKeys();
@ -140,7 +142,7 @@ void AWFormatterConfig::execDialog()
case 1: case 1:
default: default:
m_helper->writeFormatters(data); m_helper->writeFormatters(data);
m_helper->writeFormatters(data.keys()); m_helper->removeUnusedFormatters(data.keys());
break; break;
} }
} }

View File

@ -26,6 +26,7 @@
#include "awdatetimeformatter.h" #include "awdatetimeformatter.h"
#include "awdebug.h" #include "awdebug.h"
#include "awfloatformatter.h" #include "awfloatformatter.h"
#include "awjsonformatter.h"
#include "awlistformatter.h" #include "awlistformatter.h"
#include "awnoformatter.h" #include "awnoformatter.h"
#include "awscriptformatter.h" #include "awscriptformatter.h"
@ -37,6 +38,7 @@ AWFormatterHelper::AWFormatterHelper(QWidget *parent)
{ {
qCDebug(LOG_AW) << __PRETTY_FUNCTION__; qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_filePath = QString("awesomewidgets/formatters/formatters.ini");
initItems(); initItems();
} }
@ -92,13 +94,14 @@ QStringList AWFormatterHelper::knownFormatters() const
} }
bool AWFormatterHelper::writeFormatters(const QStringList keys) const bool AWFormatterHelper::removeUnusedFormatters(const QStringList keys) const
{ {
qCDebug(LOG_AW) << "Remove formatters" << keys; qCDebug(LOG_AW) << "Remove formatters" << keys;
QString fileName = QString("%1/awesomewidgets/formatters/formatters.ini") QString fileName = QString("%1/%2")
.arg(QStandardPaths::writableLocation( .arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation)); QStandardPaths::GenericDataLocation))
.arg(m_filePath);
QSettings settings(fileName, QSettings::IniFormat); QSettings settings(fileName, QSettings::IniFormat);
qCInfo(LOG_AW) << "Configuration file" << fileName; qCInfo(LOG_AW) << "Configuration file" << fileName;
@ -122,9 +125,10 @@ bool AWFormatterHelper::writeFormatters(
{ {
qCDebug(LOG_AW) << "Write configuration" << configuration; qCDebug(LOG_AW) << "Write configuration" << configuration;
QString fileName = QString("%1/awesomewidgets/formatters/formatters.ini") QString fileName = QString("%1/%2")
.arg(QStandardPaths::writableLocation( .arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation)); QStandardPaths::GenericDataLocation))
.arg(m_filePath);
QSettings settings(fileName, QSettings::IniFormat); QSettings settings(fileName, QSettings::IniFormat);
qCInfo(LOG_AW) << "Configuration file" << fileName; qCInfo(LOG_AW) << "Configuration file" << fileName;
@ -166,6 +170,8 @@ AWFormatterHelper::defineFormatterClass(const QString stringType) const
formatter = AWAbstractFormatter::FormatterClass::Script; formatter = AWAbstractFormatter::FormatterClass::Script;
else if (stringType == QString("String")) else if (stringType == QString("String"))
formatter = AWAbstractFormatter::FormatterClass::String; formatter = AWAbstractFormatter::FormatterClass::String;
else if (stringType == QString("Json"))
formatter = AWAbstractFormatter::FormatterClass::Json;
else else
qCWarning(LOG_AW) << "Unknown formatter" << stringType; qCWarning(LOG_AW) << "Unknown formatter" << stringType;
@ -213,6 +219,9 @@ void AWFormatterHelper::initFormatters()
m_formattersClasses[name] m_formattersClasses[name]
= new AWStringFormatter(this, filePath); = new AWStringFormatter(this, filePath);
break; break;
case AWAbstractFormatter::FormatterClass::Json:
m_formattersClasses[name] = new AWJsonFormatter(this, filePath);
break;
case AWAbstractFormatter::FormatterClass::NoFormat: case AWAbstractFormatter::FormatterClass::NoFormat:
m_formattersClasses[name] = new AWNoFormatter(this, filePath); m_formattersClasses[name] = new AWNoFormatter(this, filePath);
break; break;
@ -227,8 +236,7 @@ void AWFormatterHelper::initKeys()
m_formatters.clear(); m_formatters.clear();
QStringList configs = QStandardPaths::locateAll( QStringList configs = QStandardPaths::locateAll(
QStandardPaths::GenericDataLocation, QStandardPaths::GenericDataLocation, m_filePath);
QString("awesomewidgets/formatters/formatters.ini"));
for (auto fileName : configs) { for (auto fileName : configs) {
QSettings settings(fileName, QSettings::IniFormat); QSettings settings(fileName, QSettings::IniFormat);
@ -245,8 +253,8 @@ void AWFormatterHelper::initKeys()
continue; continue;
} }
if (!m_formattersClasses.contains(name)) { if (!m_formattersClasses.contains(name)) {
qCWarning(LOG_AW) << "Invalid formatter" << name << "found in" qCWarning(LOG_AW)
<< key; << "Invalid formatter" << name << "found in" << key;
continue; continue;
} }
m_formatters[key] = m_formattersClasses[name]; m_formatters[key] = m_formattersClasses[name];
@ -294,7 +302,8 @@ void AWFormatterHelper::doCreateItem()
QStringList selection = QStringList() QStringList selection = QStringList()
<< QString("NoFormat") << QString("DateTime") << QString("NoFormat") << QString("DateTime")
<< QString("Float") << QString("List") << QString("Float") << QString("List")
<< QString("Script") << QString("String"); << QString("Script") << QString("String")
<< QString("Json");
bool ok; bool ok;
QString select = QInputDialog::getItem( QString select = QInputDialog::getItem(
this, i18n("Select type"), i18n("Type:"), selection, 0, false, &ok); this, i18n("Select type"), i18n("Type:"), selection, 0, false, &ok);
@ -317,6 +326,8 @@ void AWFormatterHelper::doCreateItem()
return createItem<AWScriptFormatter>(); return createItem<AWScriptFormatter>();
case AWAbstractFormatter::FormatterClass::String: case AWAbstractFormatter::FormatterClass::String:
return createItem<AWStringFormatter>(); return createItem<AWStringFormatter>();
case AWAbstractFormatter::FormatterClass::Json:
return createItem<AWJsonFormatter>();
case AWAbstractFormatter::FormatterClass::NoFormat: case AWAbstractFormatter::FormatterClass::NoFormat:
return createItem<AWNoFormatter>(); return createItem<AWNoFormatter>();
} }

View File

@ -38,7 +38,7 @@ public:
QHash<QString, QString> getFormatters() const; QHash<QString, QString> getFormatters() const;
QList<AbstractExtItem *> items() const; QList<AbstractExtItem *> items() const;
QStringList knownFormatters() const; QStringList knownFormatters() const;
bool writeFormatters(const QStringList keys) const; bool removeUnusedFormatters(const QStringList keys) const;
bool writeFormatters(const QHash<QString, QString> configuration) const; bool writeFormatters(const QHash<QString, QString> configuration) const;
public slots: public slots:
@ -58,6 +58,7 @@ private:
void initItems(); void initItems();
// properties // properties
QStringList m_directories; QStringList m_directories;
QString m_filePath;
QHash<QString, AWAbstractFormatter *> m_formatters; QHash<QString, AWAbstractFormatter *> m_formatters;
QHash<QString, AWAbstractFormatter *> m_formattersClasses; QHash<QString, AWAbstractFormatter *> m_formattersClasses;
}; };

View File

@ -26,6 +26,7 @@
#include "awkeycache.h" #include "awkeycache.h"
#include "awpatternfunctions.h" #include "awpatternfunctions.h"
// extensions // extensions
#include "extnetworkrequest.h"
#include "extquotes.h" #include "extquotes.h"
#include "extscript.h" #include "extscript.h"
#include "extupgrade.h" #include "extupgrade.h"
@ -46,6 +47,7 @@ AWKeyOperations::~AWKeyOperations()
// extensions // extensions
delete m_graphicalItems; delete m_graphicalItems;
delete m_extNetRequest;
delete m_extQuotes; delete m_extQuotes;
delete m_extScripts; delete m_extScripts;
delete m_extUpgrade; delete m_extUpgrade;
@ -151,13 +153,14 @@ QStringList AWKeyOperations::dictKeys() const
// custom // custom
for (auto item : m_extScripts->activeItems()) for (auto item : m_extScripts->activeItems())
allKeys.append(item->tag(QString("custom"))); allKeys.append(item->tag(QString("custom")));
// network requests
for (auto item : m_extNetRequest->activeItems())
allKeys.append(item->tag(QString("response")));
// bars // bars
for (auto item : m_graphicalItems->activeItems()) for (auto item : m_graphicalItems->activeItems())
allKeys.append(item->tag(QString("bar"))); allKeys.append(item->tag(QString("bar")));
// static keys // static keys
QStringList staticKeys = QString(STATIC_KEYS).split(QChar(',')); allKeys.append(QString(STATIC_KEYS).split(QChar(',')));
std::for_each(staticKeys.cbegin(), staticKeys.cend(),
[&allKeys](const QString &key) { allKeys.append(key); });
// sort in valid order // sort in valid order
allKeys.sort(); allKeys.sort();
@ -227,6 +230,10 @@ QString AWKeyOperations::infoByKey(QString key) const
} else if (key.startsWith(QString("temp"))) { } else if (key.startsWith(QString("temp"))) {
output output
= m_devices[QString("temp")][key.remove(QString("temp")).toInt()]; = m_devices[QString("temp")][key.remove(QString("temp")).toInt()];
} else if (key.startsWith(QString("response"))) {
AbstractExtItem *item = m_extNetRequest->itemByTag(key, stripped);
if (item)
output = item->uniq();
} else { } else {
output = QString("(none)"); output = QString("(none)");
} }
@ -259,6 +266,8 @@ void AWKeyOperations::editItem(const QString type)
keys.sort(); keys.sort();
m_graphicalItems->setConfigArgs(keys); m_graphicalItems->setConfigArgs(keys);
return m_graphicalItems->editItems(); return m_graphicalItems->editItems();
} else if (type == QString("extnetworkrequest")) {
return m_extNetRequest->editItems();
} else if (type == QString("extquotes")) { } else if (type == QString("extquotes")) {
return m_extQuotes->editItems(); return m_extQuotes->editItems();
} else if (type == QString("extscript")) { } else if (type == QString("extscript")) {
@ -310,6 +319,8 @@ void AWKeyOperations::reinitKeys()
// delete them if any // delete them if any
delete m_graphicalItems; delete m_graphicalItems;
m_graphicalItems = nullptr; m_graphicalItems = nullptr;
delete m_extNetRequest;
m_extNetRequest = nullptr;
delete m_extQuotes; delete m_extQuotes;
m_extQuotes = nullptr; m_extQuotes = nullptr;
delete m_extScripts; delete m_extScripts;
@ -321,6 +332,8 @@ void AWKeyOperations::reinitKeys()
// create // create
m_graphicalItems m_graphicalItems
= new ExtItemAggregator<GraphicalItem>(nullptr, QString("desktops")); = new ExtItemAggregator<GraphicalItem>(nullptr, QString("desktops"));
m_extNetRequest = new ExtItemAggregator<ExtNetworkRequest>(
nullptr, QString("requests"));
m_extQuotes = new ExtItemAggregator<ExtQuotes>(nullptr, QString("quotes")); m_extQuotes = new ExtItemAggregator<ExtQuotes>(nullptr, QString("quotes"));
m_extScripts m_extScripts
= new ExtItemAggregator<ExtScript>(nullptr, QString("scripts")); = new ExtItemAggregator<ExtScript>(nullptr, QString("scripts"));

View File

@ -30,6 +30,7 @@
class AWDataAggregator; class AWDataAggregator;
class AWDataEngineAggregator; class AWDataEngineAggregator;
class AWKeysAggregator; class AWKeysAggregator;
class ExtNetworkRequest;
class ExtQuotes; class ExtQuotes;
class ExtScript; class ExtScript;
class ExtUpgrade; class ExtUpgrade;
@ -70,6 +71,7 @@ private:
void reinitKeys(); void reinitKeys();
// objects // objects
ExtItemAggregator<GraphicalItem> *m_graphicalItems = nullptr; ExtItemAggregator<GraphicalItem> *m_graphicalItems = nullptr;
ExtItemAggregator<ExtNetworkRequest> *m_extNetRequest = nullptr;
ExtItemAggregator<ExtQuotes> *m_extQuotes = nullptr; ExtItemAggregator<ExtQuotes> *m_extQuotes = nullptr;
ExtItemAggregator<ExtScript> *m_extScripts = nullptr; ExtItemAggregator<ExtScript> *m_extScripts = nullptr;
ExtItemAggregator<ExtUpgrade> *m_extUpgrade = nullptr; ExtItemAggregator<ExtUpgrade> *m_extUpgrade = nullptr;

View File

@ -17,7 +17,8 @@
#include "awkeys.h" #include "awkeys.h"
#include <QJSEngine> #include <QDBusConnection>
#include <QDBusError>
#include <QRegExp> #include <QRegExp>
#include <QThread> #include <QThread>
#include <QTimer> #include <QTimer>
@ -25,6 +26,7 @@
#include "awdataaggregator.h" #include "awdataaggregator.h"
#include "awdataengineaggregator.h" #include "awdataengineaggregator.h"
#include "awdbusadaptor.h"
#include "awdebug.h" #include "awdebug.h"
#include "awkeycache.h" #include "awkeycache.h"
#include "awkeyoperations.h" #include "awkeyoperations.h"
@ -36,9 +38,9 @@
AWKeys::AWKeys(QObject *parent) AWKeys::AWKeys(QObject *parent)
: QObject(parent) : QObject(parent)
{ {
qSetMessagePattern(LOG_FORMAT); qSetMessagePattern(AWDebug::LOG_FORMAT);
qCDebug(LOG_AW) << __PRETTY_FUNCTION__; qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
for (auto metadata : getBuildData()) for (auto &metadata : AWDebug::getBuildData())
qCDebug(LOG_AW) << metadata; qCDebug(LOG_AW) << metadata;
// thread pool // thread pool
@ -52,6 +54,8 @@ AWKeys::AWKeys(QObject *parent)
m_timer = new QTimer(this); m_timer = new QTimer(this);
m_timer->setSingleShot(false); m_timer->setSingleShot(false);
createDBusInterface();
// update key data if required // update key data if required
connect(m_keyOperator, SIGNAL(updateKeys(QStringList)), this, connect(m_keyOperator, SIGNAL(updateKeys(QStringList)), this,
SLOT(reinitKeys(QStringList))); SLOT(reinitKeys(QStringList)));
@ -74,6 +78,10 @@ AWKeys::~AWKeys()
m_timer->stop(); m_timer->stop();
delete m_timer; delete m_timer;
// delete dbus session
qlonglong id = reinterpret_cast<qlonglong>(this);
QDBusConnection::sessionBus().unregisterObject(QString("/%1").arg(id));
// core // core
delete m_dataEngineAggregator; delete m_dataEngineAggregator;
delete m_threadPool; delete m_threadPool;
@ -83,6 +91,12 @@ AWKeys::~AWKeys()
} }
bool AWKeys::isDBusActive() const
{
return m_dbusActive;
}
void AWKeys::initDataAggregator(const QVariantMap tooltipParams) void AWKeys::initDataAggregator(const QVariantMap tooltipParams)
{ {
qCDebug(LOG_AW) << "Tooltip parameters" << tooltipParams; qCDebug(LOG_AW) << "Tooltip parameters" << tooltipParams;
@ -144,6 +158,10 @@ QStringList AWKeys::dictKeys(const bool sorted, const QString regexp) const
qCDebug(LOG_AW) << "Should be sorted" << sorted << "and filter applied" qCDebug(LOG_AW) << "Should be sorted" << sorted << "and filter applied"
<< regexp; << regexp;
// check if functions asked
if (regexp == QString("functions"))
return QString(STATIC_FUNCTIONS).split(QChar(','));
QStringList allKeys = m_keyOperator->dictKeys(); QStringList allKeys = m_keyOperator->dictKeys();
// sort if required // sort if required
if (sorted) if (sorted)
@ -153,12 +171,21 @@ QStringList AWKeys::dictKeys(const bool sorted, const QString regexp) const
} }
QStringList AWKeys::getHddDevices() const QVariantList AWKeys::getHddDevices() const
{ {
QStringList devices = m_keyOperator->devices(QString("hdd")); QStringList hddDevices = m_keyOperator->devices(QString("hdd"));
// required by selector in the UI // required by selector in the UI
devices.insert(0, QString("disable")); hddDevices.insert(0, QString("disable"));
devices.insert(0, QString("auto")); hddDevices.insert(0, QString("auto"));
// build model
QVariantList devices;
for (auto device : hddDevices) {
QVariantMap model;
model[QString("label")] = device;
model[QString("name")] = device;
devices.append(model);
}
return devices; return devices;
} }
@ -306,6 +333,27 @@ void AWKeys::calculateValues()
} }
void AWKeys::createDBusInterface()
{
// get this object id
qlonglong id = reinterpret_cast<qlonglong>(this);
// create session
QDBusConnection bus = QDBusConnection::sessionBus();
if (!bus.registerService(AWDBUS_SERVICE))
qCWarning(LOG_AW) << "Could not register DBus service, last error"
<< bus.lastError().message();
if (!bus.registerObject(QString("/%1").arg(id), new AWDBusAdaptor(this),
QDBusConnection::ExportAllContents)) {
qCWarning(LOG_AW) << "Could not register DBus object, last error"
<< bus.lastError().message();
m_dbusActive = false;
} else {
m_dbusActive = true;
}
}
QString AWKeys::parsePattern(QString pattern) const QString AWKeys::parsePattern(QString pattern) const
{ {
// screen sign // screen sign

View File

@ -39,6 +39,7 @@ class AWKeys : public QObject
public: public:
explicit AWKeys(QObject *parent = nullptr); explicit AWKeys(QObject *parent = nullptr);
virtual ~AWKeys(); virtual ~AWKeys();
bool isDBusActive() const;
Q_INVOKABLE void initDataAggregator(const QVariantMap tooltipParams); Q_INVOKABLE void initDataAggregator(const QVariantMap tooltipParams);
Q_INVOKABLE void initKeys(const QString currentPattern, const int interval, Q_INVOKABLE void initKeys(const QString currentPattern, const int interval,
const int limit, const bool optimize); const int limit, const bool optimize);
@ -51,7 +52,7 @@ public:
// keys // keys
Q_INVOKABLE QStringList dictKeys(const bool sorted = false, Q_INVOKABLE QStringList dictKeys(const bool sorted = false,
const QString regexp = QString()) const; const QString regexp = QString()) const;
Q_INVOKABLE QStringList getHddDevices() const; Q_INVOKABLE QVariantList getHddDevices() const;
// values // values
Q_INVOKABLE QString infoByKey(QString key) const; Q_INVOKABLE QString infoByKey(QString key) const;
Q_INVOKABLE QString valueByKey(QString key) const; Q_INVOKABLE QString valueByKey(QString key) const;
@ -76,6 +77,7 @@ private slots:
private: private:
// methods // methods
void calculateValues(); void calculateValues();
void createDBusInterface();
QString parsePattern(QString pattern) const; QString parsePattern(QString pattern) const;
void setDataBySource(const QString &sourceName, const QVariantMap &data); void setDataBySource(const QString &sourceName, const QVariantMap &data);
// objects // objects
@ -85,6 +87,7 @@ private:
AWKeyOperations *m_keyOperator = nullptr; AWKeyOperations *m_keyOperator = nullptr;
QTimer *m_timer = nullptr; QTimer *m_timer = nullptr;
// variables // variables
bool m_dbusActive = false;
QVariantMap m_tooltipParams; QVariantMap m_tooltipParams;
QStringList m_foundBars, m_foundKeys, m_foundLambdas, m_requiredKeys; QStringList m_foundBars, m_foundKeys, m_foundLambdas, m_requiredKeys;
QVariantHash m_values; QVariantHash m_values;

View File

@ -441,6 +441,12 @@ QStringList AWKeysAggregator::registerSource(const QString &source,
// network device // network device
m_map[source] = QString("netdev"); m_map[source] = QString("netdev");
m_formatter[QString("netdev")] = FormatterType::NoFormat; m_formatter[QString("netdev")] = FormatterType::NoFormat;
} else if (source.startsWith(QString("network/response"))) {
// network response
QString key = source;
key.remove(QString("network/"));
m_map[source] = key;
m_formatter[key] = FormatterType::NoFormat;
} else if (source.contains(netRegExp)) { } else if (source.contains(netRegExp)) {
// network speed // network speed
QString type = source.contains(QString("receiver")) ? QString("down") QString type = source.contains(QString("receiver")) ? QString("down")

View File

@ -234,9 +234,9 @@ QString AWPatternFunctions::insertMacros(QString code)
QString("aw_macro_%1").arg(name), code); QString("aw_macro_%1").arg(name), code);
for (auto function : macroUsage) { for (auto function : macroUsage) {
if (function.args.count() != macro.args.count()) { if (function.args.count() != macro.args.count()) {
qCWarning(LOG_AW) << "Invalid args count found for call" qCWarning(LOG_AW)
<< function.what << "with macro" << "Invalid args count found for call" << function.what
<< macro.what; << "with macro" << macro.what;
continue; continue;
} }
// generate body to replace // generate body to replace
@ -267,12 +267,14 @@ QStringList AWPatternFunctions::findKeys(const QString code,
<< keys; << keys;
QStringList selectedKeys; QStringList selectedKeys;
QString replacedCode = code;
for (auto key : keys) for (auto key : keys)
if ((key.startsWith(QString("bar")) == isBars) if ((key.startsWith(QString("bar")) == isBars)
&& (code.contains(QString("$%1").arg(key)))) { && (replacedCode.contains(QString("$%1").arg(key)))) {
qCInfo(LOG_AW) << "Found key" << key << "with bar enabled" qCInfo(LOG_AW) << "Found key" << key << "with bar enabled"
<< isBars; << isBars;
selectedKeys.append(key); selectedKeys.append(key);
replacedCode.replace(QString("$%1").arg(key), "");
} }
if (selectedKeys.isEmpty()) if (selectedKeys.isEmpty())
qCWarning(LOG_AW) << "No keys found"; qCWarning(LOG_AW) << "No keys found";

View File

@ -34,14 +34,10 @@ AWTelemetryHandler::AWTelemetryHandler(QObject *parent, const QString clientId)
{ {
qCDebug(LOG_AW) << __PRETTY_FUNCTION__; qCDebug(LOG_AW) << __PRETTY_FUNCTION__;
m_genericConfig = QString("%1/awesomewidgets/general.ini")
.arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation));
m_localFile = QString("%1/awesomewidgets/telemetry.ini") m_localFile = QString("%1/awesomewidgets/telemetry.ini")
.arg(QStandardPaths::writableLocation( .arg(QStandardPaths::writableLocation(
QStandardPaths::GenericDataLocation)); QStandardPaths::GenericDataLocation));
init();
// override client id if any // override client id if any
if (!clientId.isEmpty()) if (!clientId.isEmpty())
m_clientId = clientId; m_clientId = clientId;
@ -78,6 +74,18 @@ QString AWTelemetryHandler::getLast(const QString group) const
} }
void AWTelemetryHandler::init(const int count, const bool enableRemote,
const QString clientId)
{
qCDebug(LOG_AW) << "Init telemetry with count" << count << "enable remote"
<< enableRemote << "client ID" << clientId;
m_storeCount = count;
m_uploadEnabled = enableRemote;
m_clientId = clientId;
}
bool AWTelemetryHandler::put(const QString group, const QString value) const bool AWTelemetryHandler::put(const QString group, const QString value) const
{ {
qCDebug(LOG_AW) << "Store data with group" << group << "and value" << value; qCDebug(LOG_AW) << "Store data with group" << group << "and value" << value;
@ -130,13 +138,12 @@ void AWTelemetryHandler::uploadTelemetry(const QString group,
SLOT(telemetryReplyRecieved(QNetworkReply *))); SLOT(telemetryReplyRecieved(QNetworkReply *)));
QUrl url(REMOTE_TELEMETRY_URL); QUrl url(REMOTE_TELEMETRY_URL);
url.setPort(REMOTE_TELEMETRY_PORT);
QNetworkRequest request(url); QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
// generate payload // generate payload
QVariantMap payload; QVariantMap payload;
payload[QString("api")] = AWTEAPI; payload[QString("api")] = AW_TELEMETRY_API;
payload[QString("client_id")] = m_clientId; payload[QString("client_id")] = m_clientId;
payload[QString("metadata")] = value; payload[QString("metadata")] = value;
payload[QString("type")] = group; payload[QString("type")] = group;
@ -181,44 +188,3 @@ QString AWTelemetryHandler::getKey(const int count) const
return QString("%1").arg(count, 3, 10, QChar('0')); return QString("%1").arg(count, 3, 10, QChar('0'));
} }
void AWTelemetryHandler::init()
{
QSettings settings(m_genericConfig, QSettings::IniFormat);
settings.beginGroup(QString("Telemetry"));
// unique client id
m_clientId
= settings.value(QString("ClientID"), QUuid::createUuid().toString())
.toString();
setConfiguration(QString("ClientID"), m_clientId, false);
// count items to store
m_storeCount = settings.value(QString("StoreHistory"), 100).toInt();
setConfiguration(QString("StoreHistory"), m_storeCount, false);
// check if upload enabled
m_uploadEnabled = settings.value(QString("Upload"), false).toBool();
setConfiguration(QString("Upload"), m_uploadEnabled, false);
settings.endGroup();
}
bool AWTelemetryHandler::setConfiguration(const QString key,
const QVariant value,
const bool override) const
{
qCDebug(LOG_AW) << "Set configuration key" << key << "to value" << value
<< "force override enabled" << override;
QSettings settings(m_genericConfig, QSettings::IniFormat);
settings.beginGroup(QString("Telemetry"));
if (settings.childKeys().contains(key) && !override)
return true;
settings.setValue(key, value);
settings.endGroup();
settings.sync();
return (settings.status() == QSettings::NoError);
}

View File

@ -31,14 +31,15 @@ class AWTelemetryHandler : public QObject
Q_OBJECT Q_OBJECT
public: public:
const char *REMOTE_TELEMETRY_URL = "http://arcanis.me/telemetry"; const char *REMOTE_TELEMETRY_URL = "https://arcanis.me/telemetry";
const int REMOTE_TELEMETRY_PORT = 8080;
explicit AWTelemetryHandler(QObject *parent = nullptr, explicit AWTelemetryHandler(QObject *parent = nullptr,
const QString clientId = QString()); const QString clientId = QString());
virtual ~AWTelemetryHandler(); virtual ~AWTelemetryHandler();
Q_INVOKABLE QStringList get(const QString group) const; Q_INVOKABLE QStringList get(const QString group) const;
Q_INVOKABLE QString getLast(const QString group) const; Q_INVOKABLE QString getLast(const QString group) const;
Q_INVOKABLE void init(const int count, const bool enableRemote,
const QString clientId);
Q_INVOKABLE bool put(const QString group, const QString value) const; Q_INVOKABLE bool put(const QString group, const QString value) const;
Q_INVOKABLE void uploadTelemetry(const QString group, const QString value); Q_INVOKABLE void uploadTelemetry(const QString group, const QString value);
@ -50,11 +51,7 @@ private slots:
private: private:
QString getKey(const int count) const; QString getKey(const int count) const;
void init();
bool setConfiguration(const QString key, const QVariant value,
const bool override) const;
QString m_clientId; QString m_clientId;
QString m_genericConfig;
QString m_localFile; QString m_localFile;
int m_storeCount = 0; int m_storeCount = 0;
bool m_uploadEnabled = false; bool m_uploadEnabled = false;

View File

@ -19,6 +19,7 @@ set(SUBPROJECT_FORMATTERS ${CMAKE_CURRENT_SOURCE_DIR}/formatters)
set(SUBPROJECT_GRAPHITEMS ${CMAKE_CURRENT_SOURCE_DIR}/desktops) set(SUBPROJECT_GRAPHITEMS ${CMAKE_CURRENT_SOURCE_DIR}/desktops)
set(SUBPROJECT_QUOTES ${CMAKE_CURRENT_SOURCE_DIR}/quotes) set(SUBPROJECT_QUOTES ${CMAKE_CURRENT_SOURCE_DIR}/quotes)
set(SUBPROJECT_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/scripts) set(SUBPROJECT_SCRIPTS ${CMAKE_CURRENT_SOURCE_DIR}/scripts)
set(SUBPROJECT_REQUESTS ${CMAKE_CURRENT_SOURCE_DIR}/requests)
set(SUBPROJECT_UPGRADE ${CMAKE_CURRENT_SOURCE_DIR}/upgrade) set(SUBPROJECT_UPGRADE ${CMAKE_CURRENT_SOURCE_DIR}/upgrade)
set(SUBPROJECT_WEATHER ${CMAKE_CURRENT_SOURCE_DIR}/weather) set(SUBPROJECT_WEATHER ${CMAKE_CURRENT_SOURCE_DIR}/weather)
file(GLOB SUBPROJECT_WEATHER_JSON_IN *.json) file(GLOB SUBPROJECT_WEATHER_JSON_IN *.json)
@ -37,6 +38,7 @@ install(DIRECTORY ${SUBPROJECT_FORMATTERS} DESTINATION ${DATA_INSTALL_DIR}/${PRO
install(DIRECTORY ${SUBPROJECT_GRAPHITEMS} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME}) install(DIRECTORY ${SUBPROJECT_GRAPHITEMS} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME})
install(DIRECTORY ${SUBPROJECT_QUOTES} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME}) install(DIRECTORY ${SUBPROJECT_QUOTES} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME})
install(DIRECTORY ${SUBPROJECT_SCRIPTS} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME}) install(DIRECTORY ${SUBPROJECT_SCRIPTS} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME})
install(DIRECTORY ${SUBPROJECT_REQUESTS} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME})
install(DIRECTORY ${SUBPROJECT_UPGRADE} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME}) install(DIRECTORY ${SUBPROJECT_UPGRADE} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME})
install(DIRECTORY ${SUBPROJECT_WEATHER} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME}) install(DIRECTORY ${SUBPROJECT_WEATHER} DESTINATION ${DATA_INSTALL_DIR}/${PROJECT_NAME})
install(FILES ${SUBPROJECT_INI} DESTINATION ${CONFIG_INSTALL_DIR}) install(FILES ${SUBPROJECT_INI} DESTINATION ${CONFIG_INSTALL_DIR})

View File

@ -18,12 +18,14 @@
#include "abstractextitem.h" #include "abstractextitem.h"
#include <QDir> #include <QDir>
#include <QLocalServer>
#include <QSettings> #include <QSettings>
#include <QStandardPaths> #include <QStandardPaths>
#include <QTime> #include <QTime>
#include "abstractextitemaggregator.h" #include "abstractextitemaggregator.h"
#include "awdebug.h" #include "awdebug.h"
#include "qcronscheduler.h"
AbstractExtItem::AbstractExtItem(QWidget *parent, const QString filePath) AbstractExtItem::AbstractExtItem(QWidget *parent, const QString filePath)
@ -41,6 +43,12 @@ AbstractExtItem::AbstractExtItem(QWidget *parent, const QString filePath)
AbstractExtItem::~AbstractExtItem() AbstractExtItem::~AbstractExtItem()
{ {
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
if (m_socket) {
m_socket->close();
m_socket->removeServer(socket());
delete m_socket;
}
} }
@ -63,8 +71,29 @@ void AbstractExtItem::copyDefaults(AbstractExtItem *_other) const
_other->setActive(isActive()); _other->setActive(isActive());
_other->setApiVersion(apiVersion()); _other->setApiVersion(apiVersion());
_other->setComment(comment()); _other->setComment(comment());
_other->setCron(cron());
_other->setInterval(interval()); _other->setInterval(interval());
_other->setName(name()); _other->setName(name());
_other->setSocket(socket());
}
void AbstractExtItem::startTimer()
{
if (!socket().isEmpty())
// check if there is active socket setup
return;
else if (!cron().isEmpty())
// check if there is active scheduler
return;
else if (m_times == 1)
// check if it is time to update
emit(requestDataUpdate());
// update counter value
if (m_times >= interval())
m_times = 0;
m_times++;
} }
@ -95,6 +124,12 @@ QString AbstractExtItem::comment() const
} }
QString AbstractExtItem::cron() const
{
return m_cron;
}
QString AbstractExtItem::fileName() const QString AbstractExtItem::fileName() const
{ {
return m_fileName; return m_fileName;
@ -125,6 +160,12 @@ int AbstractExtItem::number() const
} }
QString AbstractExtItem::socket() const
{
return m_socketFile;
}
QString AbstractExtItem::tag(const QString _type) const QString AbstractExtItem::tag(const QString _type) const
{ {
qCDebug(LOG_LIB) << "Tag type" << _type; qCDebug(LOG_LIB) << "Tag type" << _type;
@ -157,6 +198,28 @@ 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 (cron().isEmpty())
return;
// init scheduler
m_scheduler = new QCronScheduler(this);
m_scheduler->parse(cron());
connect(m_scheduler, SIGNAL(activated()), this,
SIGNAL(requestDataUpdate()));
}
void AbstractExtItem::setInterval(const int _interval) void AbstractExtItem::setInterval(const int _interval)
{ {
qCDebug(LOG_LIB) << "Interval" << _interval; qCDebug(LOG_LIB) << "Interval" << _interval;
@ -196,6 +259,42 @@ 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();
m_socket->removeServer(socket());
delete m_socket;
disconnect(m_socket, SIGNAL(newConnection()), this,
SLOT(newConnectionReceived()));
}
void AbstractExtItem::initSocket()
{
// remove old socket first
deinitSocket();
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() void AbstractExtItem::readConfiguration()
{ {
QSettings settings(m_fileName, QSettings::IniFormat); QSettings settings(m_fileName, QSettings::IniFormat);
@ -210,6 +309,8 @@ void AbstractExtItem::readConfiguration()
== QString("true")); == QString("true"));
setInterval(settings.value(QString("X-AW-Interval"), interval()).toInt()); setInterval(settings.value(QString("X-AW-Interval"), interval()).toInt());
setNumber(settings.value(QString("X-AW-Number"), number()).toInt()); setNumber(settings.value(QString("X-AW-Number"), number()).toInt());
setCron(settings.value(QString("X-AW-Schedule"), cron()).toString());
setSocket(settings.value(QString("X-AW-Socket"), socket()).toString());
settings.endGroup(); settings.endGroup();
} }
@ -234,9 +335,19 @@ void AbstractExtItem::writeConfiguration() const
settings.setValue(QString("Comment"), comment()); settings.setValue(QString("Comment"), comment());
settings.setValue(QString("X-AW-ApiVersion"), apiVersion()); settings.setValue(QString("X-AW-ApiVersion"), apiVersion());
settings.setValue(QString("X-AW-Active"), QVariant(isActive()).toString()); settings.setValue(QString("X-AW-Active"), QVariant(isActive()).toString());
settings.setValue(QString("X-AW-Interval"), interval()); settings.setValue(QString("X-AW-Interval"),
cron().isEmpty() ? QVariant(interval())
: QVariant(cron()));
settings.setValue(QString("X-AW-Number"), number()); settings.setValue(QString("X-AW-Number"), number());
settings.setValue(QString("X-AW-Schedule"), cron());
settings.setValue(QString("X-AW-Socket"), socket());
settings.endGroup(); settings.endGroup();
settings.sync(); settings.sync();
} }
void AbstractExtItem::newConnectionReceived()
{
emit(requestDataUpdate());
}

View File

@ -22,16 +22,21 @@
#include <QVariant> #include <QVariant>
class QCronScheduler;
class QLocalServer;
class AbstractExtItem : public QDialog class AbstractExtItem : public QDialog
{ {
Q_OBJECT Q_OBJECT
Q_PROPERTY(bool active READ isActive WRITE setActive) Q_PROPERTY(bool active READ isActive WRITE setActive)
Q_PROPERTY(int apiVersion READ apiVersion WRITE setApiVersion) Q_PROPERTY(int apiVersion READ apiVersion WRITE setApiVersion)
Q_PROPERTY(QString comment READ comment WRITE setComment) 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 fileName READ fileName)
Q_PROPERTY(int interval READ interval WRITE setInterval) Q_PROPERTY(int interval READ interval WRITE setInterval)
Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(int number READ number WRITE setNumber) Q_PROPERTY(int number READ number WRITE setNumber)
Q_PROPERTY(QString socket READ socket WRITE setSocket)
Q_PROPERTY(QString uniq READ uniq) Q_PROPERTY(QString uniq READ uniq)
public: public:
@ -42,45 +47,61 @@ public:
virtual AbstractExtItem *copy(const QString _fileName, const int _number) virtual AbstractExtItem *copy(const QString _fileName, const int _number)
= 0; = 0;
virtual void copyDefaults(AbstractExtItem *_other) const; virtual void copyDefaults(AbstractExtItem *_other) const;
virtual void startTimer();
QString writtableConfig() const; QString writtableConfig() const;
// get methods // get methods
int apiVersion() const; int apiVersion() const;
QString comment() const; QString comment() const;
QString cron() const;
QString fileName() const; QString fileName() const;
int interval() const; int interval() const;
bool isActive() const; bool isActive() const;
QString name() const; QString name() const;
int number() const; int number() const;
QString socket() const;
QString tag(const QString _type) const; QString tag(const QString _type) const;
virtual QString uniq() const = 0; virtual QString uniq() const = 0;
// set methods // set methods
void setApiVersion(const int _apiVersion = 0); void setApiVersion(const int _apiVersion = 0);
void setActive(const bool _state = true); void setActive(const bool _state = true);
void setComment(const QString _comment = QString("empty")); void setComment(const QString _comment = QString("empty"));
void setCron(const QString _cron = "");
void setInterval(const int _interval = 1); void setInterval(const int _interval = 1);
void setName(const QString _name = QString("none")); void setName(const QString _name = QString("none"));
void setNumber(int _number = -1); void setNumber(int _number = -1);
void setSocket(const QString _socket = QString(""));
signals: signals:
void dataReceived(const QVariantHash &data); void dataReceived(const QVariantHash &data);
void requestDataUpdate();
public slots: public slots:
virtual void deinitSocket();
virtual void initSocket();
virtual void readConfiguration(); virtual void readConfiguration();
virtual QVariantHash run() = 0; virtual QVariantHash run() = 0;
virtual int showConfiguration(const QVariant args = QVariant()) = 0; virtual int showConfiguration(const QVariant args = QVariant()) = 0;
bool tryDelete() const; virtual bool tryDelete() const;
virtual void writeConfiguration() const; virtual void writeConfiguration() const;
private slots:
void newConnectionReceived();
private: private:
QCronScheduler *m_scheduler = nullptr;
QString m_fileName = QString("/dev/null"); QString m_fileName = QString("/dev/null");
int m_times = 0;
virtual void translate() = 0; virtual void translate() = 0;
// properties // properties
int m_apiVersion = 0; int m_apiVersion = 0;
bool m_active = true; bool m_active = true;
QString m_comment = QString("empty"); QString m_comment = QString("empty");
QString m_cron = "";
int m_interval = 1; int m_interval = 1;
QString m_name = QString("none"); QString m_name = QString("none");
int m_number = -1; int m_number = -1;
QLocalServer *m_socket = nullptr;
QString m_socketFile = QString("");
}; };

View File

@ -69,6 +69,9 @@ QString AWAbstractFormatter::strType() const
case FormatterClass::String: case FormatterClass::String:
value = QString("String"); value = QString("String");
break; break;
case FormatterClass::Json:
value = QString("Json");
break;
case FormatterClass::NoFormat: case FormatterClass::NoFormat:
value = QString("NoFormat"); value = QString("NoFormat");
break; break;
@ -98,6 +101,8 @@ void AWAbstractFormatter::setStrType(const QString _type)
m_type = FormatterClass::Script; m_type = FormatterClass::Script;
else if (_type == QString("String")) else if (_type == QString("String"))
m_type = FormatterClass::String; m_type = FormatterClass::String;
else if (_type == QString("Json"))
m_type = FormatterClass::Json;
else else
m_type = FormatterClass::NoFormat; m_type = FormatterClass::NoFormat;
} }

View File

@ -34,7 +34,8 @@ public:
List, List,
Script, Script,
String, String,
NoFormat NoFormat,
Json
}; };
explicit AWAbstractFormatter(QWidget *parent, explicit AWAbstractFormatter(QWidget *parent,

View File

@ -115,7 +115,7 @@ void AWDateTimeFormatter::readConfiguration()
settings.value(QString("X-AW-Translate"), translateString()).toBool()); settings.value(QString("X-AW-Translate"), translateString()).toBool());
settings.endGroup(); settings.endGroup();
bumpApi(AWEFAPI); bumpApi(AW_FORMATTER_API);
} }
@ -135,7 +135,7 @@ int AWDateTimeFormatter::showConfiguration(const QVariant args)
return ret; return ret;
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setApiVersion(AWEFAPI); setApiVersion(AW_FORMATTER_API);
setStrType(ui->label_typeValue->text()); setStrType(ui->label_typeValue->text());
setFormat(ui->lineEdit_format->text()); setFormat(ui->lineEdit_format->text());
setTranslateString(ui->checkBox_translate->checkState() == Qt::Checked); setTranslateString(ui->checkBox_translate->checkState() == Qt::Checked);

View File

@ -210,7 +210,7 @@ void AWFloatFormatter::readConfiguration()
setSummand(settings.value(QString("X-AW-Summand"), summand()).toDouble()); setSummand(settings.value(QString("X-AW-Summand"), summand()).toDouble());
settings.endGroup(); settings.endGroup();
bumpApi(AWEFAPI); bumpApi(AW_FORMATTER_API);
} }
@ -236,7 +236,7 @@ int AWFloatFormatter::showConfiguration(const QVariant args)
return ret; return ret;
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setApiVersion(AWEFAPI); setApiVersion(AW_FORMATTER_API);
setStrType(ui->label_typeValue->text()); setStrType(ui->label_typeValue->text());
setFormat(ui->comboBox_format->currentText().at(0).toLatin1()); setFormat(ui->comboBox_format->currentText().at(0).toLatin1());
setPrecision(ui->spinBox_precision->value()); setPrecision(ui->spinBox_precision->value());

View File

@ -0,0 +1,207 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#include "awjsonformatter.h"
#include "ui_awjsonformatter.h"
#include <KI18n/KLocalizedString>
#include <QJsonDocument>
#include <QSettings>
#include "awdebug.h"
AWJsonFormatter::AWJsonFormatter(QWidget *parent, const QString filePath)
: AWAbstractFormatter(parent, filePath)
, ui(new Ui::AWJsonFormatter)
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
if (!filePath.isEmpty())
readConfiguration();
ui->setupUi(this);
translate();
}
AWJsonFormatter::~AWJsonFormatter()
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
delete ui;
}
QString AWJsonFormatter::convert(const QVariant &_value) const
{
qCDebug(LOG_LIB) << "Convert value" << _value;
// check if _value is string and parse first if required
QJsonDocument json
= _value.type() == QVariant::String
? QJsonDocument::fromJson(_value.toString().toUtf8())
: QJsonDocument::fromVariant(_value);
QVariant converted = json.toVariant();
for (auto &element : m_splittedPath)
converted = getFromJson(converted, element);
return converted.toString();
}
AWJsonFormatter *AWJsonFormatter::copy(const QString _fileName,
const int _number)
{
qCDebug(LOG_LIB) << "File" << _fileName << "with number" << _number;
AWJsonFormatter *item
= new AWJsonFormatter(static_cast<QWidget *>(parent()), _fileName);
AWAbstractFormatter::copyDefaults(item);
item->setNumber(_number);
item->setPath(path());
return item;
}
QString AWJsonFormatter::path() const
{
return m_path;
}
void AWJsonFormatter::setPath(const QString _path)
{
qCDebug(LOG_LIB) << "Path" << _path;
m_path = _path;
initPath();
}
void AWJsonFormatter::readConfiguration()
{
AWAbstractFormatter::readConfiguration();
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup(QString("Desktop Entry"));
setPath(settings.value(QString("X-AW-Path"), path()).toString());
settings.endGroup();
bumpApi(AW_FORMATTER_API);
}
int AWJsonFormatter::showConfiguration(const QVariant args)
{
Q_UNUSED(args)
ui->lineEdit_name->setText(name());
ui->lineEdit_comment->setText(comment());
ui->label_typeValue->setText(QString("Json"));
ui->lineEdit_path->setText(path());
int ret = exec();
if (ret != 1)
return ret;
setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text());
setApiVersion(AW_FORMATTER_API);
setStrType(ui->label_typeValue->text());
setPath(ui->lineEdit_path->text());
writeConfiguration();
return ret;
}
void AWJsonFormatter::writeConfiguration() const
{
AWAbstractFormatter::writeConfiguration();
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup(QString("Desktop Entry"));
settings.setValue(QString("X-AW-Path"), path());
settings.endGroup();
settings.sync();
}
QVariant AWJsonFormatter::getFromJson(const QVariant &value,
const QVariant &element) const
{
qCDebug(LOG_LIB) << "Looking for element" << element << "in" << value;
if (element.type() == QVariant::String) {
return getFromMap(value, element.toString());
} else if (element.type() == QVariant::Int) {
return getFromList(value, element.toInt());
} else {
qCWarning(LOG_LIB) << "Unknown type" << element.typeName();
return value;
}
}
QVariant AWJsonFormatter::getFromList(const QVariant &value,
const int index) const
{
qCDebug(LOG_LIB) << "Looking for index" << index << "in" << value;
return value.toList()[index];
}
QVariant AWJsonFormatter::getFromMap(const QVariant &value,
const QString &key) const
{
qCDebug(LOG_LIB) << "Looking for key" << key << "in" << value;
return value.toMap()[key];
}
void AWJsonFormatter::initPath()
{
m_splittedPath.clear();
QStringList splittedByDot
= m_path.split(QChar('.'), QString::SkipEmptyParts);
for (auto &element : splittedByDot) {
bool ok;
int number = element.toInt(&ok);
if (ok)
m_splittedPath.append(number);
else
m_splittedPath.append(element);
}
}
void AWJsonFormatter::translate()
{
ui->label_name->setText(i18n("Name"));
ui->label_comment->setText(i18n("Comment"));
ui->label_type->setText(i18n("Type"));
ui->label_path->setText(i18n("Path"));
}

View File

@ -0,0 +1,62 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#ifndef AWJSONFORMATTER_H
#define AWJSONFORMATTER_H
#include "awabstractformatter.h"
namespace Ui
{
class AWJsonFormatter;
}
class AWJsonFormatter : public AWAbstractFormatter
{
Q_OBJECT
Q_PROPERTY(QString path READ path WRITE setPath)
public:
explicit AWJsonFormatter(QWidget *parent,
const QString filePath = QString());
virtual ~AWJsonFormatter();
QString convert(const QVariant &_value) const;
AWJsonFormatter *copy(const QString _fileName, const int _number);
// properties
QString path() const;
void setPath(const QString _path);
public slots:
void readConfiguration();
int showConfiguration(const QVariant args = QVariant());
void writeConfiguration() const;
private:
Ui::AWJsonFormatter *ui = nullptr;
QVariant getFromJson(const QVariant &value, const QVariant &element) const;
QVariant getFromList(const QVariant &value, const int index) const;
QVariant getFromMap(const QVariant &value, const QString &key) const;
void initPath();
void translate();
// properties
QString m_path;
QVariantList m_splittedPath;
};
#endif /* AWJSONFORMATTER_H */

View File

@ -0,0 +1,167 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AWJsonFormatter</class>
<widget class="QDialog" name="AWJsonFormatter">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>420</width>
<height>128</height>
</rect>
</property>
<property name="windowTitle">
<string>Configuration</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="layout_name">
<item>
<widget class="QLabel" name="label_name">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Name</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_name"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_comment">
<item>
<widget class="QLabel" name="label_comment">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Comment</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_comment"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_type">
<item>
<widget class="QLabel" name="label_type">
<property name="text">
<string>Type</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_typeValue">
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_path">
<item>
<widget class="QLabel" name="label_path">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Path</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_path"/>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>AWJsonFormatter</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>AWJsonFormatter</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -132,7 +132,7 @@ void AWListFormatter::readConfiguration()
setSorted(settings.value(QString("X-AW-Sort"), isSorted()).toBool()); setSorted(settings.value(QString("X-AW-Sort"), isSorted()).toBool());
settings.endGroup(); settings.endGroup();
bumpApi(AWEFAPI); bumpApi(AW_FORMATTER_API);
} }
@ -153,7 +153,7 @@ int AWListFormatter::showConfiguration(const QVariant args)
return ret; return ret;
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setApiVersion(AWEFAPI); setApiVersion(AW_FORMATTER_API);
setStrType(ui->label_typeValue->text()); setStrType(ui->label_typeValue->text());
setFilter(ui->lineEdit_filter->text()); setFilter(ui->lineEdit_filter->text());
setSeparator(ui->lineEdit_separator->text()); setSeparator(ui->lineEdit_separator->text());

View File

@ -79,7 +79,7 @@ int AWNoFormatter::showConfiguration(const QVariant args)
return ret; return ret;
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setApiVersion(AWEFAPI); setApiVersion(AW_FORMATTER_API);
setStrType(ui->label_typeValue->text()); setStrType(ui->label_typeValue->text());
writeConfiguration(); writeConfiguration();

View File

@ -152,7 +152,7 @@ void AWScriptFormatter::readConfiguration()
settings.value(QString("X-AW-HasReturn"), hasReturn()).toBool()); settings.value(QString("X-AW-HasReturn"), hasReturn()).toBool());
settings.endGroup(); settings.endGroup();
bumpApi(AWEFAPI); bumpApi(AW_FORMATTER_API);
} }
@ -174,7 +174,7 @@ int AWScriptFormatter::showConfiguration(const QVariant args)
return ret; return ret;
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setApiVersion(AWEFAPI); setApiVersion(AW_FORMATTER_API);
setStrType(ui->label_typeValue->text()); setStrType(ui->label_typeValue->text());
setAppendCode(ui->checkBox_appendCode->checkState() == Qt::Checked); setAppendCode(ui->checkBox_appendCode->checkState() == Qt::Checked);
setHasReturn(ui->checkBox_hasReturn->checkState() == Qt::Checked); setHasReturn(ui->checkBox_hasReturn->checkState() == Qt::Checked);

View File

@ -133,7 +133,7 @@ void AWStringFormatter::readConfiguration()
settings.value(QString("X-AW-ForceWidth"), forceWidth()).toBool()); settings.value(QString("X-AW-ForceWidth"), forceWidth()).toBool());
settings.endGroup(); settings.endGroup();
bumpApi(AWEFAPI); bumpApi(AW_FORMATTER_API);
} }
@ -154,7 +154,7 @@ int AWStringFormatter::showConfiguration(const QVariant args)
return ret; return ret;
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setApiVersion(AWEFAPI); setApiVersion(AW_FORMATTER_API);
setStrType(ui->label_typeValue->text()); setStrType(ui->label_typeValue->text());
setCount(ui->spinBox_width->value()); setCount(ui->spinBox_width->value());
setFillChar(ui->lineEdit_fill->text().at(0)); setFillChar(ui->lineEdit_fill->text().at(0));

View File

@ -34,9 +34,9 @@ public:
explicit ExtItemAggregator(QWidget *parent, const QString type) explicit ExtItemAggregator(QWidget *parent, const QString type)
: AbstractExtItemAggregator(parent, type) : AbstractExtItemAggregator(parent, type)
{ {
qSetMessagePattern(LOG_FORMAT); qSetMessagePattern(AWDebug::LOG_FORMAT);
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
for (auto metadata : getBuildData()) for (auto &metadata : AWDebug::getBuildData())
qCDebug(LOG_LIB) << metadata; qCDebug(LOG_LIB) << metadata;
qCDebug(LOG_LIB) << "Type" << type; qCDebug(LOG_LIB) << "Type" << type;
@ -61,6 +61,15 @@ public:
qCInfo(LOG_LIB) << "Dialog returns" << ret; qCInfo(LOG_LIB) << "Dialog returns" << ret;
}; };
void initSockets()
{
// 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)
item->initSocket();
}
T *itemByTag(const QString _tag, const QString _type) const T *itemByTag(const QString _tag, const QString _type) const
{ {
qCDebug(LOG_LIB) << "Tag" << _tag << "with used type" << _type; qCDebug(LOG_LIB) << "Tag" << _tag << "with used type" << _type;

View File

@ -0,0 +1,216 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#include "extnetworkrequest.h"
#include "ui_extnetworkrequest.h"
#include <KI18n/KLocalizedString>
#include <QDir>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QSettings>
#include <QTextCodec>
#include <qreplytimeout/qreplytimeout.h>
#include "awdebug.h"
ExtNetworkRequest::ExtNetworkRequest(QWidget *parent, const QString filePath)
: AbstractExtItem(parent, filePath)
, ui(new Ui::ExtNetworkRequest)
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
if (!filePath.isEmpty())
readConfiguration();
ui->setupUi(this);
translate();
m_values[tag(QString("response"))] = QString();
// HACK declare as child of nullptr to avoid crash with plasmawindowed
// in the destructor
m_manager = new QNetworkAccessManager(nullptr);
connect(m_manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(networkReplyReceived(QNetworkReply *)));
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
}
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();
delete ui;
}
ExtNetworkRequest *ExtNetworkRequest::copy(const QString _fileName,
const int _number)
{
qCDebug(LOG_LIB) << "File" << _fileName << "with number" << _number;
ExtNetworkRequest *item
= new ExtNetworkRequest(static_cast<QWidget *>(parent()), _fileName);
copyDefaults(item);
item->setNumber(_number);
item->setStringUrl(stringUrl());
return item;
}
QString ExtNetworkRequest::stringUrl() const
{
return m_stringUrl;
}
QString ExtNetworkRequest::uniq() const
{
return m_url.toString();
}
void ExtNetworkRequest::setStringUrl(const QString _url)
{
qCDebug(LOG_LIB) << "Url" << _url;
m_stringUrl = _url;
initUrl();
}
void ExtNetworkRequest::readConfiguration()
{
AbstractExtItem::readConfiguration();
QSettings settings(fileName(), QSettings::IniFormat);
settings.beginGroup(QString("Desktop Entry"));
setStringUrl(settings.value(QString("X-AW-Url"), stringUrl()).toString());
settings.endGroup();
bumpApi(AW_EXTNETREQUEST_API);
}
QVariantHash ExtNetworkRequest::run()
{
if (m_isRunning)
return m_values;
startTimer();
return m_values;
}
int ExtNetworkRequest::showConfiguration(const QVariant args)
{
Q_UNUSED(args)
ui->lineEdit_name->setText(name());
ui->lineEdit_comment->setText(comment());
ui->label_numberValue->setText(QString("%1").arg(number()));
ui->lineEdit_url->setText(stringUrl());
ui->checkBox_active->setCheckState(isActive() ? Qt::Checked
: Qt::Unchecked);
ui->lineEdit_schedule->setText(cron());
ui->lineEdit_socket->setText(socket());
ui->spinBox_interval->setValue(interval());
int ret = exec();
if (ret != 1)
return ret;
setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text());
setNumber(ui->label_numberValue->text().toInt());
setApiVersion(AW_EXTNETREQUEST_API);
setStringUrl(ui->lineEdit_url->text());
setActive(ui->checkBox_active->checkState() == Qt::Checked);
setCron(ui->lineEdit_schedule->text());
setSocket(ui->lineEdit_socket->text());
setInterval(ui->spinBox_interval->value());
writeConfiguration();
return ret;
}
void ExtNetworkRequest::writeConfiguration() const
{
AbstractExtItem::writeConfiguration();
QSettings settings(writtableConfig(), QSettings::IniFormat);
qCInfo(LOG_LIB) << "Configuration file" << settings.fileName();
settings.beginGroup(QString("Desktop Entry"));
settings.setValue(QString("X-AW-Url"), stringUrl());
settings.endGroup();
settings.sync();
}
void ExtNetworkRequest::networkReplyReceived(QNetworkReply *reply)
{
if (reply->error() != QNetworkReply::NoError) {
qCWarning(LOG_AW) << "An error occurs" << reply->error()
<< "with message" << reply->errorString();
return;
}
m_isRunning = false;
m_values[tag(QString("response"))]
= QTextCodec::codecForMib(106)->toUnicode(reply->readAll()).trimmed();
emit(dataReceived(m_values));
}
void ExtNetworkRequest::sendRequest()
{
m_isRunning = true;
QNetworkReply *reply = m_manager->get(QNetworkRequest(m_url));
new QReplyTimeout(reply, REQUEST_TIMEOUT);
}
void ExtNetworkRequest::initUrl()
{
m_url = QUrl(m_stringUrl);
}
void ExtNetworkRequest::translate()
{
ui->label_name->setText(i18n("Name"));
ui->label_comment->setText(i18n("Comment"));
ui->label_number->setText(i18n("Tag"));
ui->label_url->setText(i18n("URL"));
ui->checkBox_active->setText(i18n("Active"));
ui->label_schedule->setText(i18n("Schedule"));
ui->label_socket->setText(i18n("Socket"));
ui->label_interval->setText(i18n("Interval"));
}

View File

@ -0,0 +1,72 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#ifndef EXTNETWORKREQUEST_H
#define EXTNETWORKREQUEST_H
#include <QNetworkReply>
#include "abstractextitem.h"
namespace Ui
{
class ExtNetworkRequest;
}
class ExtNetworkRequest : public AbstractExtItem
{
Q_OBJECT
Q_PROPERTY(QString stringUrl READ stringUrl WRITE setStringUrl)
public:
explicit ExtNetworkRequest(QWidget *parent,
const QString filePath = QString());
virtual ~ExtNetworkRequest();
ExtNetworkRequest *copy(const QString _fileName, const int _number);
// get methods
QString stringUrl() const;
QString uniq() const;
// set methods
void setStringUrl(const QString _url = QString("https://httpbin.org/get"));
public slots:
void readConfiguration();
QVariantHash run();
int showConfiguration(const QVariant args = QVariant());
void writeConfiguration() const;
private slots:
void networkReplyReceived(QNetworkReply *reply);
void sendRequest();
private:
QNetworkAccessManager *m_manager = nullptr;
QUrl m_url;
bool m_isRunning = false;
Ui::ExtNetworkRequest *ui = nullptr;
void initUrl();
void translate();
// properties
QString m_stringUrl = QString("https://httpbin.org/get");
// values
int m_times = 0;
QVariantHash m_values;
};
#endif /* EXTNETWORKREQUEST_H */

View File

@ -0,0 +1,273 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>ExtNetworkRequest</class>
<widget class="QDialog" name="ExtNetworkRequest">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>420</width>
<height>301</height>
</rect>
</property>
<property name="windowTitle">
<string>Configuration</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="layout_name">
<item>
<widget class="QLabel" name="label_name">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Name</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_name"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_comment">
<item>
<widget class="QLabel" name="label_comment">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Comment</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_comment"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_number">
<item>
<widget class="QLabel" name="label_number">
<property name="text">
<string>Tag</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_numberValue">
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_url">
<item>
<widget class="QLabel" name="label_url">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>URL</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_url"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_active">
<item>
<spacer name="spacer_active">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QCheckBox" name="checkBox_active">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Active</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_schedule">
<item>
<widget class="QLabel" name="label_schedule">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Schedule</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_schedule"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_socket">
<item>
<widget class="QLabel" name="label_socket">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Socket</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_socket"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_interval">
<item>
<widget class="QLabel" name="label_interval">
<property name="text">
<string>Interval</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinBox_interval">
<property name="minimum">
<number>1</number>
</property>
<property name="maximum">
<number>10000</number>
</property>
<property name="singleStep">
<number>10</number>
</property>
<property name="value">
<number>60</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>ExtNetworkRequest</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>ExtNetworkRequest</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -59,6 +59,8 @@ ExtQuotes::ExtQuotes(QWidget *parent, const QString filePath)
m_manager = new QNetworkAccessManager(nullptr); m_manager = new QNetworkAccessManager(nullptr);
connect(m_manager, SIGNAL(finished(QNetworkReply *)), this, connect(m_manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(quotesReplyReceived(QNetworkReply *))); SLOT(quotesReplyReceived(QNetworkReply *)));
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
} }
@ -68,6 +70,7 @@ ExtQuotes::~ExtQuotes()
disconnect(m_manager, SIGNAL(finished(QNetworkReply *)), this, disconnect(m_manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(quotesReplyReceived(QNetworkReply *))); SLOT(quotesReplyReceived(QNetworkReply *)));
disconnect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
m_manager->deleteLater(); m_manager->deleteLater();
delete ui; delete ui;
@ -119,26 +122,15 @@ void ExtQuotes::readConfiguration()
setTicker(settings.value(QString("X-AW-Ticker"), ticker()).toString()); setTicker(settings.value(QString("X-AW-Ticker"), ticker()).toString());
settings.endGroup(); settings.endGroup();
bumpApi(AWEQAPI); bumpApi(AW_EXTQUOTES_API);
} }
QVariantHash ExtQuotes::run() QVariantHash ExtQuotes::run()
{ {
if ((!isActive()) || (m_isRunning)) if (m_isRunning)
return m_values; return m_values;
startTimer();
if (m_times == 1) {
qCInfo(LOG_LIB) << "Send request";
m_isRunning = true;
QNetworkReply *reply = m_manager->get(QNetworkRequest(m_url));
new QReplyTimeout(reply, REQUEST_TIMEOUT);
}
// update value
if (m_times >= interval())
m_times = 0;
m_times++;
return m_values; return m_values;
} }
@ -154,6 +146,8 @@ int ExtQuotes::showConfiguration(const QVariant args)
ui->lineEdit_ticker->setText(ticker()); ui->lineEdit_ticker->setText(ticker());
ui->checkBox_active->setCheckState(isActive() ? Qt::Checked ui->checkBox_active->setCheckState(isActive() ? Qt::Checked
: Qt::Unchecked); : Qt::Unchecked);
ui->lineEdit_schedule->setText(cron());
ui->lineEdit_socket->setText(socket());
ui->spinBox_interval->setValue(interval()); ui->spinBox_interval->setValue(interval());
int ret = exec(); int ret = exec();
@ -162,9 +156,11 @@ int ExtQuotes::showConfiguration(const QVariant args)
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setNumber(ui->label_numberValue->text().toInt()); setNumber(ui->label_numberValue->text().toInt());
setApiVersion(AWEQAPI); setApiVersion(AW_EXTQUOTES_API);
setTicker(ui->lineEdit_ticker->text()); setTicker(ui->lineEdit_ticker->text());
setActive(ui->checkBox_active->checkState() == Qt::Checked); setActive(ui->checkBox_active->checkState() == Qt::Checked);
setCron(ui->lineEdit_schedule->text());
setSocket(ui->lineEdit_socket->text());
setInterval(ui->spinBox_interval->value()); setInterval(ui->spinBox_interval->value());
writeConfiguration(); writeConfiguration();
@ -245,6 +241,14 @@ void ExtQuotes::quotesReplyReceived(QNetworkReply *reply)
} }
void ExtQuotes::sendRequest()
{
m_isRunning = true;
QNetworkReply *reply = m_manager->get(QNetworkRequest(m_url));
new QReplyTimeout(reply, REQUEST_TIMEOUT);
}
void ExtQuotes::initUrl() void ExtQuotes::initUrl()
{ {
// init query // init query
@ -271,5 +275,7 @@ get quotes for the instrument. Refer to <a href=\"http://finance.yahoo.com/\">\
</span></a></p></body></html>")); </span></a></p></body></html>"));
ui->label_ticker->setText(i18n("Ticker")); ui->label_ticker->setText(i18n("Ticker"));
ui->checkBox_active->setText(i18n("Active")); ui->checkBox_active->setText(i18n("Active"));
ui->label_schedule->setText(i18n("Schedule"));
ui->label_socket->setText(i18n("Socket"));
ui->label_interval->setText(i18n("Interval")); ui->label_interval->setText(i18n("Interval"));
} }

View File

@ -22,10 +22,6 @@
#include "abstractextitem.h" #include "abstractextitem.h"
#define YAHOO_QUOTES_URL "https://query.yahooapis.com/v1/public/yql"
#define YAHOO_QUOTES_QUERY \
"select * from yahoo.finance.quotes where symbol='%1'"
namespace Ui namespace Ui
{ {
@ -38,6 +34,10 @@ class ExtQuotes : public AbstractExtItem
Q_PROPERTY(QString ticker READ ticker WRITE setTicker) Q_PROPERTY(QString ticker READ ticker WRITE setTicker)
public: public:
const char *YAHOO_QUOTES_URL = "https://query.yahooapis.com/v1/public/yql";
const char *YAHOO_QUOTES_QUERY
= "select * from yahoo.finance.quotes where symbol='%1'";
explicit ExtQuotes(QWidget *parent, const QString filePath = QString()); explicit ExtQuotes(QWidget *parent, const QString filePath = QString());
virtual ~ExtQuotes(); virtual ~ExtQuotes();
ExtQuotes *copy(const QString _fileName, const int _number); ExtQuotes *copy(const QString _fileName, const int _number);
@ -55,6 +55,7 @@ public slots:
private slots: private slots:
void quotesReplyReceived(QNetworkReply *reply); void quotesReplyReceived(QNetworkReply *reply);
void sendRequest();
private: private:
QNetworkAccessManager *m_manager = nullptr; QNetworkAccessManager *m_manager = nullptr;

View File

@ -7,7 +7,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>420</width> <width>420</width>
<height>301</height> <height>339</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -150,6 +150,52 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<layout class="QHBoxLayout" name="layout_schedule">
<item>
<widget class="QLabel" name="label_schedule">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Schedule</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_schedule"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_socket">
<item>
<widget class="QLabel" name="label_socket">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Socket</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_socket"/>
</item>
</layout>
</item>
<item> <item>
<layout class="QHBoxLayout" name="layout_interval"> <layout class="QHBoxLayout" name="layout_interval">
<item> <item>

View File

@ -48,6 +48,8 @@ ExtScript::ExtScript(QWidget *parent, const QString filePath)
connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(updateValue())); SLOT(updateValue()));
m_process->waitForFinished(0); m_process->waitForFinished(0);
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(startProcess()));
} }
@ -55,8 +57,11 @@ ExtScript::~ExtScript()
{ {
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__; qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
disconnect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this,
SLOT(updateValue()));
m_process->kill(); m_process->kill();
m_process->deleteLater(); m_process->deleteLater();
disconnect(this, SIGNAL(requestDataUpdate()), this, SLOT(startProcess()));
delete ui; delete ui;
} }
@ -78,6 +83,18 @@ ExtScript *ExtScript::copy(const QString _fileName, const int _number)
} }
QString ExtScript::jsonFiltersFile() const
{
QString fileName = QStandardPaths::locate(
QStandardPaths::GenericDataLocation,
QString(
"awesomewidgets/scripts/awesomewidgets-extscripts-filters.json"));
qCInfo(LOG_LIB) << "Filters file" << fileName;
return fileName;
}
QString ExtScript::executable() const QString ExtScript::executable() const
{ {
return m_executable; return m_executable;
@ -186,8 +203,8 @@ QString ExtScript::applyFilters(QString _value) const
qCInfo(LOG_LIB) << "Found filter" << filt; qCInfo(LOG_LIB) << "Found filter" << filt;
QVariantMap filter = m_jsonFilters[filt].toMap(); QVariantMap filter = m_jsonFilters[filt].toMap();
if (filter.isEmpty()) { if (filter.isEmpty()) {
qCWarning(LOG_LIB) << "Could not find filter" << _value qCWarning(LOG_LIB)
<< "in the json"; << "Could not find filter" << _value << "in the json";
continue; continue;
} }
for (auto f : filter.keys()) for (auto f : filter.keys())
@ -229,17 +246,13 @@ void ExtScript::readConfiguration()
.split(QChar(','), QString::SkipEmptyParts)); .split(QChar(','), QString::SkipEmptyParts));
settings.endGroup(); settings.endGroup();
bumpApi(AWESAPI); bumpApi(AW_EXTSCRIPT_API);
} }
void ExtScript::readJsonFilters() void ExtScript::readJsonFilters()
{ {
QString fileName = QStandardPaths::locate( QString fileName = jsonFiltersFile();
QStandardPaths::GenericDataLocation,
QString(
"awesomewidgets/scripts/awesomewidgets-extscripts-filters.json"));
qCInfo(LOG_LIB) << "Filters file" << fileName;
QFile jsonFile(fileName); QFile jsonFile(fileName);
if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) { if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qCWarning(LOG_LIB) << "Could not open" << fileName; qCWarning(LOG_LIB) << "Could not open" << fileName;
@ -262,25 +275,9 @@ void ExtScript::readJsonFilters()
QVariantHash ExtScript::run() QVariantHash ExtScript::run()
{ {
if (!isActive())
return m_values;
if (m_process->state() != QProcess::NotRunning) if (m_process->state() != QProcess::NotRunning)
qCWarning(LOG_LIB) << "Another process is already running" return m_values;
<< m_process->state(); startTimer();
if ((m_times == 1) && (m_process->state() == QProcess::NotRunning)) {
QStringList cmdList;
if (!prefix().isEmpty())
cmdList.append(prefix());
cmdList.append(executable());
qCInfo(LOG_LIB) << "Run cmd" << cmdList.join(QChar(' '));
m_process->start(cmdList.join(QChar(' ')));
}
// update value
if (m_times >= interval())
m_times = 0;
m_times++;
return m_values; return m_values;
} }
@ -298,6 +295,8 @@ int ExtScript::showConfiguration(const QVariant args)
ui->checkBox_active->setCheckState(isActive() ? Qt::Checked ui->checkBox_active->setCheckState(isActive() ? Qt::Checked
: Qt::Unchecked); : Qt::Unchecked);
ui->comboBox_redirect->setCurrentIndex(static_cast<int>(redirect())); ui->comboBox_redirect->setCurrentIndex(static_cast<int>(redirect()));
ui->lineEdit_schedule->setText(cron());
ui->lineEdit_socket->setText(socket());
ui->spinBox_interval->setValue(interval()); ui->spinBox_interval->setValue(interval());
// filters // filters
ui->checkBox_colorFilter->setCheckState( ui->checkBox_colorFilter->setCheckState(
@ -313,11 +312,13 @@ int ExtScript::showConfiguration(const QVariant args)
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setNumber(ui->label_numberValue->text().toInt()); setNumber(ui->label_numberValue->text().toInt());
setApiVersion(AWESAPI); setApiVersion(AW_EXTSCRIPT_API);
setExecutable(ui->lineEdit_command->text()); setExecutable(ui->lineEdit_command->text());
setPrefix(ui->lineEdit_prefix->text()); setPrefix(ui->lineEdit_prefix->text());
setActive(ui->checkBox_active->checkState() == Qt::Checked); setActive(ui->checkBox_active->checkState() == Qt::Checked);
setRedirect(static_cast<Redirect>(ui->comboBox_redirect->currentIndex())); setRedirect(static_cast<Redirect>(ui->comboBox_redirect->currentIndex()));
setCron(ui->lineEdit_schedule->text());
setSocket(ui->lineEdit_socket->text());
setInterval(ui->spinBox_interval->value()); setInterval(ui->spinBox_interval->value());
// filters // filters
updateFilter(QString("color"), updateFilter(QString("color"),
@ -350,6 +351,17 @@ void ExtScript::writeConfiguration() const
} }
void ExtScript::startProcess()
{
QStringList cmdList;
if (!prefix().isEmpty())
cmdList.append(prefix());
cmdList.append(executable());
qCInfo(LOG_LIB) << "Run cmd" << cmdList.join(QChar(' '));
m_process->start(cmdList.join(QChar(' ')));
}
void ExtScript::updateValue() void ExtScript::updateValue()
{ {
qCInfo(LOG_LIB) << "Cmd returns" << m_process->exitCode(); qCInfo(LOG_LIB) << "Cmd returns" << m_process->exitCode();
@ -392,6 +404,8 @@ void ExtScript::translate()
ui->label_prefix->setText(i18n("Prefix")); ui->label_prefix->setText(i18n("Prefix"));
ui->checkBox_active->setText(i18n("Active")); ui->checkBox_active->setText(i18n("Active"));
ui->label_redirect->setText(i18n("Redirect")); ui->label_redirect->setText(i18n("Redirect"));
ui->label_schedule->setText(i18n("Schedule"));
ui->label_socket->setText(i18n("Socket"));
ui->label_interval->setText(i18n("Interval")); ui->label_interval->setText(i18n("Interval"));
ui->groupBox_filters->setTitle(i18n("Additional filters")); ui->groupBox_filters->setTitle(i18n("Additional filters"));
ui->checkBox_colorFilter->setText(i18n("Wrap colors")); ui->checkBox_colorFilter->setText(i18n("Wrap colors"));

View File

@ -47,6 +47,7 @@ public:
explicit ExtScript(QWidget *parent, const QString filePath = QString()); explicit ExtScript(QWidget *parent, const QString filePath = QString());
virtual ~ExtScript(); virtual ~ExtScript();
ExtScript *copy(const QString _fileName, const int _number); ExtScript *copy(const QString _fileName, const int _number);
QString jsonFiltersFile() const;
// get methods // get methods
QString executable() const; QString executable() const;
QStringList filters() const; QStringList filters() const;
@ -73,6 +74,7 @@ public slots:
void writeConfiguration() const; void writeConfiguration() const;
private slots: private slots:
void startProcess();
void updateValue(); void updateValue();
private: private:

View File

@ -7,7 +7,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>420</width> <width>420</width>
<height>424</height> <height>473</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -195,6 +195,52 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<layout class="QHBoxLayout" name="layout_schedule">
<item>
<widget class="QLabel" name="label_schedule">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Schedule</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_schedule"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_socket">
<item>
<widget class="QLabel" name="label_socket">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Socket</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_socket"/>
</item>
</layout>
</item>
<item> <item>
<layout class="QHBoxLayout" name="layout_interval"> <layout class="QHBoxLayout" name="layout_interval">
<item> <item>

View File

@ -44,6 +44,8 @@ ExtUpgrade::ExtUpgrade(QWidget *parent, const QString filePath)
m_process = new QProcess(nullptr); m_process = new QProcess(nullptr);
connect(m_process, SIGNAL(finished(int)), this, SLOT(updateValue())); connect(m_process, SIGNAL(finished(int)), this, SLOT(updateValue()));
m_process->waitForFinished(0); m_process->waitForFinished(0);
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(startProcess()));
} }
@ -53,6 +55,7 @@ ExtUpgrade::~ExtUpgrade()
m_process->kill(); m_process->kill();
m_process->deleteLater(); m_process->deleteLater();
disconnect(this, SIGNAL(requestDataUpdate()), this, SLOT(startProcess()));
delete ui; delete ui;
} }
@ -136,25 +139,15 @@ void ExtUpgrade::readConfiguration()
setFilter(settings.value(QString("X-AW-Filter"), filter()).toString()); setFilter(settings.value(QString("X-AW-Filter"), filter()).toString());
settings.endGroup(); settings.endGroup();
bumpApi(AWEUAPI); bumpApi(AW_EXTUPGRADE_API);
} }
QVariantHash ExtUpgrade::run() QVariantHash ExtUpgrade::run()
{ {
if (!isActive()) if (m_process->state() != QProcess::NotRunning)
return m_values; return m_values;
startTimer();
if ((m_times == 1) && (m_process->state() == QProcess::NotRunning)) {
QString cmd = QString("sh -c \"%1\"").arg(executable());
qCInfo(LOG_LIB) << "Run cmd" << cmd;
m_process->start(cmd);
}
// update value
if (m_times >= interval())
m_times = 0;
m_times++;
return m_values; return m_values;
} }
@ -172,6 +165,8 @@ int ExtUpgrade::showConfiguration(const QVariant args)
ui->checkBox_active->setCheckState(isActive() ? Qt::Checked ui->checkBox_active->setCheckState(isActive() ? Qt::Checked
: Qt::Unchecked); : Qt::Unchecked);
ui->spinBox_null->setValue(null()); ui->spinBox_null->setValue(null());
ui->lineEdit_schedule->setText(cron());
ui->lineEdit_socket->setText(socket());
ui->spinBox_interval->setValue(interval()); ui->spinBox_interval->setValue(interval());
int ret = exec(); int ret = exec();
@ -180,11 +175,13 @@ int ExtUpgrade::showConfiguration(const QVariant args)
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setNumber(ui->label_numberValue->text().toInt()); setNumber(ui->label_numberValue->text().toInt());
setApiVersion(AWEUAPI); setApiVersion(AW_EXTUPGRADE_API);
setExecutable(ui->lineEdit_command->text()); setExecutable(ui->lineEdit_command->text());
setFilter(ui->lineEdit_filter->text()); setFilter(ui->lineEdit_filter->text());
setActive(ui->checkBox_active->checkState() == Qt::Checked); setActive(ui->checkBox_active->checkState() == Qt::Checked);
setNull(ui->spinBox_null->value()); setNull(ui->spinBox_null->value());
setCron(ui->lineEdit_schedule->text());
setSocket(ui->lineEdit_socket->text());
setInterval(ui->spinBox_interval->value()); setInterval(ui->spinBox_interval->value());
writeConfiguration(); writeConfiguration();
@ -209,6 +206,14 @@ void ExtUpgrade::writeConfiguration() const
} }
void ExtUpgrade::startProcess()
{
QString cmd = QString("sh -c \"%1\"").arg(executable());
qCInfo(LOG_LIB) << "Run cmd" << cmd;
m_process->start(cmd);
}
void ExtUpgrade::updateValue() void ExtUpgrade::updateValue()
{ {
qCInfo(LOG_LIB) << "Cmd returns" << m_process->exitCode(); qCInfo(LOG_LIB) << "Cmd returns" << m_process->exitCode();
@ -239,5 +244,7 @@ void ExtUpgrade::translate()
ui->label_filter->setText(i18n("Filter")); ui->label_filter->setText(i18n("Filter"));
ui->checkBox_active->setText(i18n("Active")); ui->checkBox_active->setText(i18n("Active"));
ui->label_null->setText(i18n("Null")); ui->label_null->setText(i18n("Null"));
ui->label_socket->setText(i18n("Socket"));
ui->label_schedule->setText(i18n("Schedule"));
ui->label_interval->setText(i18n("Interval")); ui->label_interval->setText(i18n("Interval"));
} }

View File

@ -56,6 +56,7 @@ public slots:
void writeConfiguration() const; void writeConfiguration() const;
private slots: private slots:
void startProcess();
void updateValue(); void updateValue();
private: private:

View File

@ -7,7 +7,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>420</width> <width>420</width>
<height>301</height> <height>349</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -181,6 +181,52 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<layout class="QHBoxLayout" name="layout_schedule">
<item>
<widget class="QLabel" name="label_schedule">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Schedule</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_schedule"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_socket">
<item>
<widget class="QLabel" name="label_socket">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Socket</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_socket"/>
</item>
</layout>
</item>
<item> <item>
<layout class="QHBoxLayout" name="layout_interval"> <layout class="QHBoxLayout" name="layout_interval">
<item> <item>

View File

@ -58,6 +58,8 @@ ExtWeather::ExtWeather(QWidget *parent, const QString filePath)
m_manager = new QNetworkAccessManager(nullptr); m_manager = new QNetworkAccessManager(nullptr);
connect(m_manager, SIGNAL(finished(QNetworkReply *)), this, connect(m_manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(weatherReplyReceived(QNetworkReply *))); SLOT(weatherReplyReceived(QNetworkReply *)));
connect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
} }
@ -67,6 +69,7 @@ ExtWeather::~ExtWeather()
disconnect(m_manager, SIGNAL(finished(QNetworkReply *)), this, disconnect(m_manager, SIGNAL(finished(QNetworkReply *)), this,
SLOT(weatherReplyReceived(QNetworkReply *))); SLOT(weatherReplyReceived(QNetworkReply *)));
disconnect(this, SIGNAL(requestDataUpdate()), this, SLOT(sendRequest()));
m_manager->deleteLater(); m_manager->deleteLater();
delete m_providerObject; delete m_providerObject;
@ -92,6 +95,17 @@ ExtWeather *ExtWeather::copy(const QString _fileName, const int _number)
} }
QString ExtWeather::jsonMapFile() const
{
QString fileName = QStandardPaths::locate(
QStandardPaths::GenericDataLocation,
QString("awesomewidgets/weather/awesomewidgets-extweather-ids.json"));
qCInfo(LOG_LIB) << "Map file" << fileName;
return fileName;
}
QString ExtWeather::weatherFromInt(const int _id) const QString ExtWeather::weatherFromInt(const int _id) const
{ {
qCDebug(LOG_LIB) << "Weather ID" << _id; qCDebug(LOG_LIB) << "Weather ID" << _id;
@ -227,16 +241,13 @@ void ExtWeather::readConfiguration()
settings.value(QString("X-AW-Provider"), strProvider()).toString()); settings.value(QString("X-AW-Provider"), strProvider()).toString());
settings.endGroup(); settings.endGroup();
bumpApi(AWEWAPI); bumpApi(AW_EXTWEATHER_API);
} }
void ExtWeather::readJsonMap() void ExtWeather::readJsonMap()
{ {
QString fileName = QStandardPaths::locate( QString fileName = jsonMapFile();
QStandardPaths::GenericDataLocation,
QString("awesomewidgets/weather/awesomewidgets-extweather-ids.json"));
qCInfo(LOG_LIB) << "Map file" << fileName;
QFile jsonFile(fileName); QFile jsonFile(fileName);
if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) { if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
qCWarning(LOG_LIB) << "Could not open" << fileName; qCWarning(LOG_LIB) << "Could not open" << fileName;
@ -259,21 +270,9 @@ void ExtWeather::readJsonMap()
QVariantHash ExtWeather::run() QVariantHash ExtWeather::run()
{ {
if ((!isActive()) || (m_isRunning)) if (m_isRunning)
return m_values; return m_values;
startTimer();
if (m_times == 1) {
qCInfo(LOG_LIB) << "Send request";
m_isRunning = true;
QNetworkReply *reply
= m_manager->get(QNetworkRequest(m_providerObject->url()));
new QReplyTimeout(reply, REQUEST_TIMEOUT);
}
// update value
if (m_times >= interval())
m_times = 0;
m_times++;
return m_values; return m_values;
} }
@ -293,6 +292,8 @@ int ExtWeather::showConfiguration(const QVariant args)
ui->checkBox_image->setCheckState(image() ? Qt::Checked : Qt::Unchecked); ui->checkBox_image->setCheckState(image() ? Qt::Checked : Qt::Unchecked);
ui->checkBox_active->setCheckState(isActive() ? Qt::Checked ui->checkBox_active->setCheckState(isActive() ? Qt::Checked
: Qt::Unchecked); : Qt::Unchecked);
ui->lineEdit_schedule->setText(cron());
ui->lineEdit_socket->setText(socket());
ui->spinBox_interval->setValue(interval()); ui->spinBox_interval->setValue(interval());
int ret = exec(); int ret = exec();
@ -301,13 +302,15 @@ int ExtWeather::showConfiguration(const QVariant args)
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setNumber(ui->label_numberValue->text().toInt()); setNumber(ui->label_numberValue->text().toInt());
setApiVersion(AWEWAPI); setApiVersion(AW_EXTWEATHER_API);
setCity(ui->lineEdit_city->text()); setCity(ui->lineEdit_city->text());
setCountry(ui->lineEdit_country->text()); setCountry(ui->lineEdit_country->text());
setProvider(static_cast<Provider>(ui->comboBox_provider->currentIndex())); setProvider(static_cast<Provider>(ui->comboBox_provider->currentIndex()));
setTs(ui->spinBox_timestamp->value()); setTs(ui->spinBox_timestamp->value());
setImage(ui->checkBox_image->checkState() == Qt::Checked); setImage(ui->checkBox_image->checkState() == Qt::Checked);
setActive(ui->checkBox_active->checkState() == Qt::Checked); setActive(ui->checkBox_active->checkState() == Qt::Checked);
setCron(ui->lineEdit_schedule->text());
setSocket(ui->lineEdit_socket->text());
setInterval(ui->spinBox_interval->value()); setInterval(ui->spinBox_interval->value());
writeConfiguration(); writeConfiguration();
@ -334,6 +337,15 @@ void ExtWeather::writeConfiguration() const
} }
void ExtWeather::sendRequest()
{
m_isRunning = true;
QNetworkReply *reply
= m_manager->get(QNetworkRequest(m_providerObject->url()));
new QReplyTimeout(reply, REQUEST_TIMEOUT);
}
void ExtWeather::weatherReplyReceived(QNetworkReply *reply) void ExtWeather::weatherReplyReceived(QNetworkReply *reply)
{ {
if (reply->error() != QNetworkReply::NoError) { if (reply->error() != QNetworkReply::NoError) {
@ -390,5 +402,7 @@ void ExtWeather::translate()
ui->label_timestamp->setText(i18n("Timestamp")); ui->label_timestamp->setText(i18n("Timestamp"));
ui->checkBox_image->setText(i18n("Use images")); ui->checkBox_image->setText(i18n("Use images"));
ui->checkBox_active->setText(i18n("Active")); ui->checkBox_active->setText(i18n("Active"));
ui->label_schedule->setText(i18n("Schedule"));
ui->label_socket->setText(i18n("Socket"));
ui->label_interval->setText(i18n("Interval")); ui->label_interval->setText(i18n("Interval"));
} }

View File

@ -45,6 +45,7 @@ public:
explicit ExtWeather(QWidget *parent, const QString filePath = QString()); explicit ExtWeather(QWidget *parent, const QString filePath = QString());
virtual ~ExtWeather(); virtual ~ExtWeather();
ExtWeather *copy(const QString _fileName, const int _number); ExtWeather *copy(const QString _fileName, const int _number);
QString jsonMapFile() const;
QString weatherFromInt(const int _id) const; QString weatherFromInt(const int _id) const;
// get methods // get methods
QString city() const; QString city() const;
@ -70,6 +71,7 @@ public slots:
void writeConfiguration() const; void writeConfiguration() const;
private slots: private slots:
void sendRequest();
void weatherReplyReceived(QNetworkReply *reply); void weatherReplyReceived(QNetworkReply *reply);
private: private:

View File

@ -7,7 +7,7 @@
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>420</width> <width>420</width>
<height>333</height> <height>413</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
@ -248,6 +248,52 @@
</item> </item>
</layout> </layout>
</item> </item>
<item>
<layout class="QHBoxLayout" name="layout_schedule">
<item>
<widget class="QLabel" name="label_schedule">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Schedule</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_schedule"/>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_socket">
<item>
<widget class="QLabel" name="label_socket">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Socket</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_socket"/>
</item>
</layout>
</item>
<item> <item>
<layout class="QHBoxLayout" name="layout_interval"> <layout class="QHBoxLayout" name="layout_interval">
<item> <item>

View File

@ -3,7 +3,7 @@ Comment=Default float formatter
Encoding=UTF-8 Encoding=UTF-8
Name=Float Name=Float
X-AW-Active=true X-AW-Active=true
X-AW-ApiVersion=2 X-AW-ApiVersion=3
X-AW-FillChar=@Variant(\0\0\0\a\0\0) X-AW-FillChar=@Variant(\0\0\0\a\0\0)
X-AW-ForceWidth=false X-AW-ForceWidth=false
X-AW-Format=f X-AW-Format=f

View File

@ -3,7 +3,7 @@ Comment=Default integer formatter
Encoding=UTF-8 Encoding=UTF-8
Name=Integer Name=Integer
X-AW-Active=true X-AW-Active=true
X-AW-ApiVersion=2 X-AW-ApiVersion=3
X-AW-FillChar=@Variant(\0\0\0\a\0\0) X-AW-FillChar=@Variant(\0\0\0\a\0\0)
X-AW-ForceWidth=false X-AW-ForceWidth=false
X-AW-Format=f X-AW-Format=f

View File

@ -3,7 +3,7 @@ Comment=Default list formatter
Encoding=UTF-8 Encoding=UTF-8
Name=List Name=List
X-AW-Active=true X-AW-Active=true
X-AW-ApiVersion=2 X-AW-ApiVersion=3
X-AW-Filter= X-AW-Filter=
X-AW-Interval=1 X-AW-Interval=1
X-AW-Number=5 X-AW-Number=5

View File

@ -3,7 +3,7 @@ Comment=Float formatter with two symbols
Encoding=UTF-8 Encoding=UTF-8
Name=FloatTwoSymbols Name=FloatTwoSymbols
X-AW-Active=true X-AW-Active=true
X-AW-ApiVersion=2 X-AW-ApiVersion=3
X-AW-FillChar=@Variant(\0\0\0\a\0\0) X-AW-FillChar=@Variant(\0\0\0\a\0\0)
X-AW-ForceWidth=false X-AW-ForceWidth=false
X-AW-Format=f X-AW-Format=f

View File

@ -3,7 +3,7 @@ Comment=Long integer formatter
Encoding=UTF-8 Encoding=UTF-8
Name=LongInteger Name=LongInteger
X-AW-Active=true X-AW-Active=true
X-AW-ApiVersion=2 X-AW-ApiVersion=3
X-AW-FillChar=@Variant(\0\0\0\a\0\0) X-AW-FillChar=@Variant(\0\0\0\a\0\0)
X-AW-ForceWidth=false X-AW-ForceWidth=false
X-AW-Format=f X-AW-Format=f

View File

@ -3,7 +3,7 @@ Comment=Memory in GB formatter
Encoding=UTF-8 Encoding=UTF-8
Name=MemGB Name=MemGB
X-AW-Active=true X-AW-Active=true
X-AW-ApiVersion=2 X-AW-ApiVersion=3
X-AW-FillChar=@Variant(\0\0\0\a\0\0) X-AW-FillChar=@Variant(\0\0\0\a\0\0)
X-AW-ForceWidth=false X-AW-ForceWidth=false
X-AW-Format=f X-AW-Format=f

View File

@ -3,7 +3,7 @@ Comment=Memory in MB formatter
Encoding=UTF-8 Encoding=UTF-8
Name=MemMB Name=MemMB
X-AW-Active=true X-AW-Active=true
X-AW-ApiVersion=2 X-AW-ApiVersion=3
X-AW-FillChar=@Variant(\0\0\0\a\0\0) X-AW-FillChar=@Variant(\0\0\0\a\0\0)
X-AW-ForceWidth=false X-AW-ForceWidth=false
X-AW-Format=f X-AW-Format=f

View File

@ -3,7 +3,7 @@ Comment=Short integer formatter
Encoding=UTF-8 Encoding=UTF-8
Name=ShortInteger Name=ShortInteger
X-AW-Active=true X-AW-Active=true
X-AW-ApiVersion=2 X-AW-ApiVersion=3
X-AW-FillChar=@Variant(\0\0\0\a\0\0) X-AW-FillChar=@Variant(\0\0\0\a\0\0)
X-AW-ForceWidth=false X-AW-ForceWidth=false
X-AW-Format=f X-AW-Format=f

View File

@ -455,7 +455,7 @@ void GraphicalItem::readConfiguration()
} }
settings.endGroup(); settings.endGroup();
bumpApi(AWGIAPI); bumpApi(AW_GRAPHITEM_API);
initScene(); initScene();
} }
@ -504,7 +504,7 @@ int GraphicalItem::showConfiguration(const QVariant args)
return ret; return ret;
setName(ui->lineEdit_name->text()); setName(ui->lineEdit_name->text());
setComment(ui->lineEdit_comment->text()); setComment(ui->lineEdit_comment->text());
setApiVersion(AWGIAPI); setApiVersion(AW_GRAPHITEM_API);
setCount(ui->spinBox_count->value()); setCount(ui->spinBox_count->value());
setCustom(ui->checkBox_custom->isChecked()); setCustom(ui->checkBox_custom->isChecked());
setBar(m_custom ? ui->lineEdit_customValue->text() setBar(m_custom ? ui->lineEdit_customValue->text()

View File

@ -20,17 +20,17 @@
#include "abstractweatherprovider.h" #include "abstractweatherprovider.h"
// we are using own server to pass requests to OpenWeatherMap because it
// requires specific APPID which belongs to developer not user
#define OWM_WEATHER_URL "http://arcanis.me/weather"
#define OWM_FORECAST_URL "http://arcanis.me/forecast"
class OWMWeatherProvider : public AbstractWeatherProvider class OWMWeatherProvider : public AbstractWeatherProvider
{ {
Q_OBJECT Q_OBJECT
public: public:
// we are using own server to pass requests to OpenWeatherMap because it
// requires specific APPID which belongs to developer not user
const char *OWM_WEATHER_URL = "https://arcanis.me/weather";
const char *OWM_FORECAST_URL = "https://arcanis.me/forecast";
explicit OWMWeatherProvider(QObject *parent, const int number); explicit OWMWeatherProvider(QObject *parent, const int number);
virtual ~OWMWeatherProvider(); virtual ~OWMWeatherProvider();
void initUrl(const QString city, const QString country, const int); void initUrl(const QString city, const QString country, const int);

View File

@ -0,0 +1,158 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#include "qcronscheduler.h"
#include <QDateTime>
#include <QTimer>
#include "awdebug.h"
QCronScheduler::QCronScheduler(QObject *parent)
: QObject(parent)
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
m_timer = new QTimer(this);
m_timer->setSingleShot(false);
m_timer->setInterval(60 * 1000);
connect(m_timer, SIGNAL(timeout()), this, SLOT(expired()));
m_timer->start();
}
QCronScheduler::~QCronScheduler()
{
qCDebug(LOG_LIB) << __PRETTY_FUNCTION__;
m_timer->stop();
delete m_timer;
}
void QCronScheduler::parse(const QString &timer)
{
qCDebug(LOG_LIB) << "Parse timer string" << timer;
QStringList fields = timer.split(' ');
if (fields.count() != 5)
return;
m_schedule.minutes = parseField(fields.at(0), 0, 59);
m_schedule.hours = parseField(fields.at(1), 0, 23);
m_schedule.days = parseField(fields.at(2), 1, 31);
m_schedule.months = parseField(fields.at(3), 1, 12);
m_schedule.weekdays = parseField(fields.at(4), 1, 7);
}
void QCronScheduler::expired()
{
QDateTime now = QDateTime::currentDateTime();
if (m_schedule.minutes.contains(now.time().minute())
&& m_schedule.hours.contains(now.time().hour())
&& m_schedule.days.contains(now.date().day())
&& m_schedule.months.contains(now.date().month())
&& m_schedule.weekdays.contains(now.date().dayOfWeek()))
emit(activated());
}
QList<int> QCronScheduler::parseField(const QString &value, const int min,
const int max) const
{
qCDebug(LOG_LIB) << "Parse field" << value << "with corner values" << min
<< max;
QList<int> parsed;
auto fields = value.split(',');
for (auto &field : fields) {
QCronField parsedField;
parsedField.fromRange(field.split('/').first(), min, max);
if (field.contains('/')) {
bool status;
parsedField.div = field.split('/', QString::SkipEmptyParts)
.at(1)
.toInt(&status);
if (!status)
parsedField.div = 1;
}
// append
parsed.append(parsedField.toList());
}
return parsed;
}
void QCronScheduler::QCronField::fromRange(const QString &range, const int min,
const int max)
{
qCDebug(LOG_LIB) << "Parse field from range" << range
<< "with corner values" << min << max;
if (range == '*') {
minValue = min;
maxValue = max;
} else if (range.contains('-')) {
auto interval = range.split('-', QString::SkipEmptyParts);
if (interval.count() != 2)
return;
bool status;
// minimal value
minValue = std::max(min, interval.at(0).toInt(&status));
if (!status)
minValue = -1;
// maximal value
maxValue = std::min(max, interval.at(1).toInt(&status));
if (!status)
maxValue = -1;
// error check
if (minValue > maxValue)
std::swap(minValue, maxValue);
} else {
bool status;
int value = range.toInt(&status);
if (!status || (value < min) || (value > max))
value = -1;
minValue = value;
maxValue = value;
}
}
QList<int> QCronScheduler::QCronField::toList()
{
// error checking
if ((minValue == -1) || (maxValue == -1))
return QList<int>();
QList<int> output;
for (auto i = minValue; i <= maxValue; ++i) {
if (i % div != 0)
continue;
output.append(i);
}
std::sort(output.begin(), output.end());
return output;
}

View File

@ -0,0 +1,64 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#ifndef QCRONSCHEDULER_H
#define QCRONSCHEDULER_H
#include "QObject"
class QTimer;
class QCronScheduler : public QObject
{
Q_OBJECT
public:
typedef struct {
QList<int> minutes;
QList<int> hours;
QList<int> days;
QList<int> months;
QList<int> weekdays;
} QCronRunSchedule;
typedef struct {
int minValue = -1;
int maxValue = -1;
int div = 1;
void fromRange(const QString &range, const int min, const int max);
QList<int> toList();
} QCronField;
explicit QCronScheduler(QObject *parent);
virtual ~QCronScheduler();
void parse(const QString &timer);
signals:
void activated();
private slots:
void expired();
private:
QCronRunSchedule m_schedule;
QTimer *m_timer = nullptr;
QList<int> parseField(const QString &value, const int min,
const int max) const;
};
#endif /* QCRONSCHEDULER_H */

View File

@ -0,0 +1,9 @@
[Desktop Entry]
Encoding=UTF-8
Name=httpbin
Comment=httpbin example
X-AW-Ticker=https://httpbin.org/get
X-AW-Active=false
X-AW-ApiVersion=1
X-AW-Interval=10
X-AW-Number=0

View File

@ -93,8 +93,9 @@ YahooWeatherProvider::parseCurrent(const QVariantMap &json,
= json[QString("condition")].toMap()[QString("date")].toString(); = json[QString("condition")].toMap()[QString("date")].toString();
values[QString("humidity%1").arg(number())] values[QString("humidity%1").arg(number())]
= atmosphere[QString("humidity")].toInt(); = atmosphere[QString("humidity")].toInt();
values[QString("pressure%1").arg(number())] // HACK temporary fix of invalid values on Yahoo! side
= static_cast<int>(atmosphere[QString("pressure")].toFloat()); values[QString("pressure%1").arg(number())] = static_cast<int>(
atmosphere[QString("pressure")].toFloat() / 33.863753);
return values; return values;
} }

View File

@ -20,17 +20,17 @@
#include "abstractweatherprovider.h" #include "abstractweatherprovider.h"
#define YAHOO_WEATHER_URL "https://query.yahooapis.com/v1/public/yql"
#define YAHOO_WEATHER_QUERY \
"select * from weather.forecast where u='c' and woeid in (select woeid " \
"from geo.places(1) where text='%1, %2')"
class YahooWeatherProvider : public AbstractWeatherProvider class YahooWeatherProvider : public AbstractWeatherProvider
{ {
Q_OBJECT Q_OBJECT
public: public:
const char *YAHOO_WEATHER_URL = "https://query.yahooapis.com/v1/public/yql";
const char *YAHOO_WEATHER_QUERY = "select * from weather.forecast where "
"u='c' and woeid in (select woeid from "
"geo.places(1) where text='%1, %2')";
explicit YahooWeatherProvider(QObject *parent, const int number); explicit YahooWeatherProvider(QObject *parent, const int number);
virtual ~YahooWeatherProvider(); virtual ~YahooWeatherProvider();
void initUrl(const QString city, const QString country, const int); void initUrl(const QString city, const QString country, const int);

View File

@ -14,7 +14,8 @@ endforeach ()
add_custom_target( add_custom_target(
cppcheck cppcheck
COMMAND ${CPPCHECK_EXECUTABLE} COMMAND ${CPPCHECK_EXECUTABLE}
--enable=warning,performance,portability,information,missingInclude --enable=warning,performance,portability
--error-exitcode=1
--std=c++11 --std=c++11
--language=c++ --language=c++
--library=qt.cfg --library=qt.cfg

View File

@ -60,6 +60,12 @@
<entry name="fontStyle" type="string"> <entry name="fontStyle" type="string">
<default>normal</default> <default>normal</default>
</entry> </entry>
<entry name="textStyle" type="string">
<default>normal</default>
</entry>
<entry name="textStyleColor" type="string">
<default>#000000</default>
</entry>
<!-- current --> <!-- current -->
<entry name="currentTextAlign" type="string"> <entry name="currentTextAlign" type="string">
<default>center</default> <default>center</default>
@ -79,6 +85,12 @@
<entry name="currentFontStyle" type="string"> <entry name="currentFontStyle" type="string">
<default>normal</default> <default>normal</default>
</entry> </entry>
<entry name="currentTextStyle" type="string">
<default>normal</default>
</entry>
<entry name="currentTextStyleColor" type="string">
<default>#000000</default>
</entry>
</group> </group>
</kcfg> </kcfg>

View File

@ -16,8 +16,6 @@
***************************************************************************/ ***************************************************************************/
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls
import QtQuick.Layouts 1.0 as QtLayouts
import org.kde.plasma.private.desktoppanel 1.0 import org.kde.plasma.private.desktoppanel 1.0
@ -31,98 +29,11 @@ Item {
width: childrenRect.width width: childrenRect.width
height: childrenRect.height height: childrenRect.height
implicitWidth: pageColumn.implicitWidth
implicitHeight: pageColumn.implicitHeight
property bool debug: dpAdds.isDebugEnabled() AboutTab {
textProvider: dpAdds
Column {
id: pageColumn
anchors.fill: parent
QtControls.TabView {
height: parent.height
width: parent.width
QtControls.Tab {
anchors.margins: 10.0
title: i18n("About")
QtLayouts.ColumnLayout {
QtControls.Label {
QtLayouts.Layout.fillWidth: true
horizontalAlignment: Text.AlignHCenter
text: dpAdds.getAboutText("header")
} }
QtControls.Label {
QtLayouts.Layout.fillWidth: true
horizontalAlignment: Text.AlignHCenter
text: dpAdds.getAboutText("version")
}
QtControls.Label {
QtLayouts.Layout.fillWidth: true
horizontalAlignment: Text.AlignJustify
text: dpAdds.getAboutText("description")
}
QtControls.Label {
QtLayouts.Layout.fillWidth: true
horizontalAlignment: Text.AlignLeft
textFormat: Text.RichText
text: dpAdds.getAboutText("links")
onLinkActivated: Qt.openUrlExternally(link)
}
QtControls.Label {
QtLayouts.Layout.fillHeight: true
QtLayouts.Layout.fillWidth: true
font.capitalization: Font.SmallCaps
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignBottom
textFormat: Text.RichText
text: dpAdds.getAboutText("copy")
}
}
}
QtControls.Tab {
anchors.margins: 10.0
title: i18n("Acknowledgment")
QtLayouts.ColumnLayout {
QtControls.Label {
QtLayouts.Layout.fillWidth: true
wrapMode: Text.WordWrap
horizontalAlignment: Text.AlignJustify
text: dpAdds.getAboutText("translators")
}
QtControls.Label {
QtLayouts.Layout.fillWidth: true
wrapMode: Text.WordWrap
horizontalAlignment: Text.AlignJustify
textFormat: Text.RichText
text: dpAdds.getAboutText("3rdparty")
onLinkActivated: Qt.openUrlExternally(link)
}
QtControls.Label {
QtLayouts.Layout.fillHeight: true
QtLayouts.Layout.fillWidth: true
wrapMode: Text.WordWrap
horizontalAlignment: Text.AlignJustify
verticalAlignment: Text.AlignTop
textFormat: Text.RichText
text: dpAdds.getAboutText("thanks")
onLinkActivated: Qt.openUrlExternally(link)
}
}
}
}
}
Component.onCompleted: { Component.onCompleted: {
if (debug) console.debug() if (debug) console.debug()
} }

View File

@ -16,11 +16,9 @@
***************************************************************************/ ***************************************************************************/
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls
import QtQuick.Controls.Styles 1.3 as QtStyles
import QtQuick.Dialogs 1.1 as QtDialogs
import org.kde.plasma.private.desktoppanel 1.0 import org.kde.plasma.private.desktoppanel 1.0
import "."
Item { Item {
@ -36,203 +34,69 @@ Item {
implicitHeight: pageColumn.implicitHeight implicitHeight: pageColumn.implicitHeight
property bool debug: dpAdds.isDebugEnabled() property bool debug: dpAdds.isDebugEnabled()
property variant weight: {
25: 0,
50: 1,
63: 3,
75: 4,
87: 5
}
property alias cfg_currentFontFamily: selectFont.text property alias cfg_currentFontFamily: font.value
property alias cfg_currentFontSize: fontSize.value property alias cfg_currentFontSize: fontSize.value
property string cfg_currentFontWeight: fontWeight.currentText property string cfg_currentFontWeight: fontWeight.value
property string cfg_currentFontStyle: fontStyle.currentText property string cfg_currentFontStyle: fontStyle.value
property alias cfg_currentFontColor: selectColor.text property alias cfg_currentFontColor: selectColor.text
property alias cfg_currentTextStyleColor: selectStyleColor.text
property string cfg_currentTextStyle: textStyle.value
Column { Column {
id: pageColumn id: pageColumn
anchors.fill: parent anchors.fill: parent
Row {
height: implicitHeight FontSelector {
width: parent.width id: font
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font") text: i18n("Font")
} value: plasmoid.configuration.currentFontFamily
QtControls.Button {
id: selectFont
width: parent.width * 2 / 3
text: plasmoid.configuration.currentFontFamily
onClicked: {
if (debug) console.debug()
fontDialog.setFont()
fontDialog.visible = true
}
}
} }
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font size")
}
QtControls.SpinBox {
id: fontSize id: fontSize
width: parent.width * 2 / 3
minimumValue: 8
maximumValue: 32 maximumValue: 32
minimumValue: 8
stepSize: 1 stepSize: 1
text: i18n("Font size")
value: plasmoid.configuration.currentFontSize value: plasmoid.configuration.currentFontSize
} }
}
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font weight")
}
QtControls.ComboBox {
id: fontWeight id: fontWeight
width: parent.width * 2 / 3 model: general.fontWeightModel
textRole: "label" text: i18n("Font weight")
model: [ value: plasmoid.configuration.currentFontWeight
{ onValueEdited: cfg_currentFontWeight = newValue
'label': i18n("light"),
'name': "light"
},
{
'label': i18n("normal"),
'name': "normal"
},
{
'label': i18n("demi bold"),
'name': "demibold"
},
{
'label': i18n("bold"),
'name': "bold"
},
{
'label': i18n("black"),
'name': "black"
}
]
onCurrentIndexChanged: cfg_currentFontWeight = model[currentIndex]["name"]
Component.onCompleted: {
if (debug) console.debug()
for (var i = 0; i < model.length; i++) {
if (model[i]["name"] == plasmoid.configuration.currentFontWeight) {
if (debug) console.info("Found", model[i]["name"], "on", i)
fontWeight.currentIndex = i
}
}
}
}
} }
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font style")
}
QtControls.ComboBox {
id: fontStyle id: fontStyle
width: parent.width * 2 / 3 model: general.fontStyleModel
textRole: "label" text: i18n("Font style")
model: [ value: plasmoid.configuration.currentFontStyle
{ onValueEdited: cfg_currentFontStyle = newValue
'label': i18n("normal"),
'name': "normal"
},
{
'label': i18n("italic"),
'name': "italic"
}
]
onCurrentIndexChanged: cfg_currentFontStyle = model[currentIndex]["name"]
Component.onCompleted: {
if (debug) console.debug()
for (var i = 0; i < model.length; i++) {
if (model[i]["name"] == plasmoid.configuration.currentFontStyle) {
if (debug) console.info("Found", model[i]["name"], "on", i)
fontStyle.currentIndex = i
}
}
}
}
} }
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font color")
}
QtControls.Button {
id: selectColor id: selectColor
width: parent.width * 2 / 3 text: i18n("Font color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.currentFontColor
background: Rectangle {
color: plasmoid.configuration.currentFontColor
}
}
text: plasmoid.configuration.currentFontColor
onClicked: colorDialog.visible = true
}
}
} }
QtDialogs.ColorDialog { ComboBoxSelector {
id: colorDialog id: textStyle
title: i18n("Select a color") model: general.textStyleModel
color: selectColor.text text: i18n("Style")
onAccepted: selectColor.text = colorDialog.color value: plasmoid.configuration.currentTextStyle
onValueEdited: cfg_currentTextStyle = newValue
} }
QtDialogs.FontDialog { ColorSelector {
id: fontDialog id: selectStyleColor
title: i18n("Select a font") text: i18n("Style color")
signal setFont value: plasmoid.configuration.currentTextStyleColor
onAccepted: {
if (debug) console.debug()
selectFont.text = fontDialog.font.family
fontSize.value = fontDialog.font.pointSize
fontStyle.currentIndex = fontDialog.font.italic ? 1 : 0
fontWeight.currentIndex = weight[fontDialog.font.weight]
}
onSetFont: {
if (debug) console.debug()
fontDialog.font = Qt.font({
family: selectFont.text,
pointSize: fontSize.value > 0 ? fontSize.value : 12,
italic: fontStyle.currentIndex == 1,
weight: Font.Normal,
})
} }
} }

View File

@ -17,8 +17,6 @@
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls import QtQuick.Controls 1.3 as QtControls
import QtQuick.Controls.Styles 1.3 as QtStyles
import QtQuick.Dialogs 1.1 as QtDialogs
import org.kde.plasma.private.desktoppanel 1.0 import org.kde.plasma.private.desktoppanel 1.0
@ -41,125 +39,109 @@ Item {
property alias cfg_verticalLayout: verticalLayout.checked property alias cfg_verticalLayout: verticalLayout.checked
property alias cfg_height: widgetHeight.value property alias cfg_height: widgetHeight.value
property alias cfg_width: widgetWidth.value property alias cfg_width: widgetWidth.value
property string cfg_mark: mark.currentText property string cfg_mark: mark.value
property string cfg_tooltipType: tooltipType.currentText property string cfg_tooltipType: tooltipType.value
property alias cfg_tooltipWidth: tooltipWidth.value property alias cfg_tooltipWidth: tooltipWidth.value
property alias cfg_tooltipColor: tooltipColor.text property alias cfg_tooltipColor: tooltipColor.value
Column { Column {
id: pageColumn id: pageColumn
anchors.fill: parent anchors.fill: parent
Row {
height: implicitHeight CheckBoxSelector {
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: background id: background
width: parent.width * 3 / 5
text: i18n("Enable background") text: i18n("Enable background")
} }
}
Row { CheckBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.heigth
width: parent.width * 2 / 5
}
QtControls.CheckBox {
id: verticalLayout id: verticalLayout
width: parent.width * 3 / 5
text: i18n("Vertical layout") text: i18n("Vertical layout")
} }
}
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Widget height, px")
}
QtControls.SpinBox {
id: widgetHeight id: widgetHeight
width: parent.width * 3 / 5
minimumValue: 0
maximumValue: 4096 maximumValue: 4096
minimumValue: 0
stepSize: 50 stepSize: 50
text: i18n("Widget height, px")
value: plasmoid.configuration.height value: plasmoid.configuration.height
} }
}
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Widget width, px")
}
QtControls.SpinBox {
id: widgetWidth id: widgetWidth
width: parent.width * 3 / 5
minimumValue: 0
maximumValue: 4096 maximumValue: 4096
minimumValue: 0
stepSize: 50 stepSize: 50
text: i18n("Widget width, px")
value: plasmoid.configuration.width value: plasmoid.configuration.width
} }
}
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Mark")
}
QtControls.ComboBox {
id: mark id: mark
width: parent.width * 3 / 5
editable: true editable: true
model: ["#", "$", "%", "&", "*", "@", "¤", "¶", "·", "º", model: [
plasmoid.configuration.mark] {
currentIndex: model.length - 1 'label': '#',
onCurrentIndexChanged: cfg_mark = currentText 'name': '#'
},
{
'label': '$',
'name': '$'
},
{
'label': '%',
'name': '%'
},
{
'label': '&',
'name': '&'
},
{
'label': '*',
'name': '*'
},
{
'label': '@',
'name': '@'
},
{
'label': '¤',
'name': '¤'
},
{
'label': '¶',
'name': '¶'
},
{
'label': '·',
'name': '·'
},
{
'label': 'º',
'name': 'º'
},
{
'label': plasmoid.configuration.mark,
'name': plasmoid.configuration.mark
} }
]
text: i18n("Mark")
currentIndex: model.length - 1
onValueEdited: cfg_mark = newValue
} }
QtControls.GroupBox { QtControls.GroupBox {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
title: i18n("Tooltip") title: i18n("Tooltip")
Column { Column {
height: implicitHeight height: implicitHeight
width: parent.width width: parent.width
Row {
height: implicitHeight ComboBoxSelector {
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Tooltip type")
}
QtControls.ComboBox {
id: tooltipType id: tooltipType
width: parent.width * 3 / 5
textRole: "label"
model: [ model: [
{ {
'label': i18n("contours"), 'label': i18n("contours"),
@ -182,71 +164,28 @@ Item {
'name': "none" 'name': "none"
} }
] ]
onCurrentIndexChanged: cfg_tooltipType = model[currentIndex]["name"] text: i18n("Tooltip type")
Component.onCompleted: { value: plasmoid.configuration.tooltipType
if (debug) console.debug() onValueEdited: cfg_tooltipType = newValue
for (var i = 0; i < model.length; i++) {
if (model[i]["name"] == plasmoid.configuration.tooltipType) {
if (debug) console.info("Found", model[i]["name"], "on", i)
tooltipType.currentIndex = i
}
}
}
}
} }
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Tooltip width")
}
QtControls.SpinBox {
id: tooltipWidth id: tooltipWidth
width: parent.width * 3 / 5
minimumValue: 100
maximumValue: 1000 maximumValue: 1000
minimumValue: 100
stepSize: 50 stepSize: 50
text: i18n("Tooltip width")
value: plasmoid.configuration.tooltipWidth value: plasmoid.configuration.tooltipWidth
} }
}
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width * 2 / 5
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font color")
}
QtControls.Button {
id: tooltipColor id: tooltipColor
width: parent.width * 3 / 5 text: i18n("Font color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.tooltipColor
background: Rectangle {
color: plasmoid.configuration.tooltipColor
}
}
text: plasmoid.configuration.tooltipColor
onClicked: colorDialog.visible = true
} }
} }
} }
} }
}
QtDialogs.ColorDialog {
id: colorDialog
title: i18n("Select a color")
color: tooltipColor.text
onAccepted: tooltipColor.text = colorDialog.color
}
Component.onCompleted: { Component.onCompleted: {
if (debug) console.debug() if (debug) console.debug()

View File

@ -16,11 +16,9 @@
***************************************************************************/ ***************************************************************************/
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls
import QtQuick.Controls.Styles 1.3 as QtStyles
import QtQuick.Dialogs 1.1 as QtDialogs
import org.kde.plasma.private.desktoppanel 1.0 import org.kde.plasma.private.desktoppanel 1.0
import "."
Item { Item {
@ -36,203 +34,69 @@ Item {
implicitHeight: pageColumn.implicitHeight implicitHeight: pageColumn.implicitHeight
property bool debug: dpAdds.isDebugEnabled() property bool debug: dpAdds.isDebugEnabled()
property variant weight: {
25: 0,
50: 1,
63: 3,
75: 4,
87: 5
}
property alias cfg_fontFamily: selectFont.text property alias cfg_fontFamily: font.value
property alias cfg_fontSize: fontSize.value property alias cfg_fontSize: fontSize.value
property string cfg_fontWeight: fontWeight.currentText property string cfg_fontWeight: fontWeight.value
property string cfg_fontStyle: fontStyle.currentText property string cfg_fontStyle: fontStyle.value
property alias cfg_fontColor: selectColor.text property alias cfg_fontColor: selectColor.value
property alias cfg_textStyleColor: selectStyleColor.value
property string cfg_textStyle: textStyle.value
Column { Column {
id: pageColumn id: pageColumn
anchors.fill: parent anchors.fill: parent
Row {
height: implicitHeight FontSelector {
width: parent.width id: font
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font") text: i18n("Font")
} value: plasmoid.configuration.fontFamily
QtControls.Button {
id: selectFont
width: parent.width * 2 / 3
text: plasmoid.configuration.fontFamily
onClicked: {
if (debug) console.debug()
fontDialog.setFont()
fontDialog.visible = true
}
}
} }
Row { IntegerSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font size")
}
QtControls.SpinBox {
id: fontSize id: fontSize
width: parent.width * 2 / 3
minimumValue: 8
maximumValue: 32 maximumValue: 32
minimumValue: 8
stepSize: 1 stepSize: 1
text: i18n("Font size")
value: plasmoid.configuration.fontSize value: plasmoid.configuration.fontSize
} }
}
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font weight")
}
QtControls.ComboBox {
id: fontWeight id: fontWeight
width: parent.width * 2 / 3 model: general.fontWeightModel
textRole: "label" text: i18n("Font weight")
model: [ value: plasmoid.configuration.fontWeight
{ onValueEdited: cfg_fontWeight = newValue
'label': i18n("light"),
'name': "light"
},
{
'label': i18n("normal"),
'name': "normal"
},
{
'label': i18n("demi bold"),
'name': "demibold"
},
{
'label': i18n("bold"),
'name': "bold"
},
{
'label': i18n("black"),
'name': "black"
}
]
onCurrentIndexChanged: cfg_fontWeight = model[currentIndex]["name"]
Component.onCompleted: {
if (debug) console.debug()
for (var i = 0; i < model.length; i++) {
if (model[i]["name"] == plasmoid.configuration.fontWeight) {
if (debug) console.info("Found", model[i]["name"], "on", i)
fontWeight.currentIndex = i
}
}
}
}
} }
Row { ComboBoxSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font style")
}
QtControls.ComboBox {
id: fontStyle id: fontStyle
width: parent.width * 2 / 3 model: general.fontStyleModel
textRole: "label" text: i18n("Font style")
model: [ value: plasmoid.configuration.fontStyle
{ onValueEdited: cfg_fontStyle = newValue
'label': i18n("normal"),
'name': "normal"
},
{
'label': i18n("italic"),
'name': "italic"
}
]
onCurrentIndexChanged: cfg_fontStyle = model[currentIndex]["name"]
Component.onCompleted: {
if (debug) console.debug()
for (var i = 0; i < model.length; i++) {
if (model[i]["name"] == plasmoid.configuration.fontStyle) {
if (debug) console.info("Found", model[i]["name"], "on", i)
fontStyle.currentIndex = i
}
}
}
}
} }
Row { ColorSelector {
height: implicitHeight
width: parent.width
QtControls.Label {
height: parent.height
width: parent.width / 3
horizontalAlignment: Text.AlignRight
verticalAlignment: Text.AlignVCenter
text: i18n("Font color")
}
QtControls.Button {
id: selectColor id: selectColor
width: parent.width * 2 / 3 text: i18n("Font color")
style: QtStyles.ButtonStyle { value: plasmoid.configuration.fontColor
background: Rectangle {
color: plasmoid.configuration.fontColor
}
}
text: plasmoid.configuration.fontColor
onClicked: colorDialog.visible = true
}
}
} }
QtDialogs.ColorDialog { ComboBoxSelector {
id: colorDialog id: textStyle
title: i18n("Select a color") model: general.textStyleModel
color: selectColor.text text: i18n("Style")
onAccepted: selectColor.text = colorDialog.color value: plasmoid.configuration.textStyle
onValueEdited: cfg_textStyle = newValue
} }
QtDialogs.FontDialog { ColorSelector {
id: fontDialog id: selectStyleColor
title: i18n("Select a font") text: i18n("Style color")
signal setFont value: plasmoid.configuration.textStyleColor
onAccepted: {
if (debug) console.debug()
selectFont.text = fontDialog.font.family
fontSize.value = fontDialog.font.pointSize
fontStyle.currentIndex = fontDialog.font.italic ? 1 : 0
fontWeight.currentIndex = weight[fontDialog.font.weight]
}
onSetFont: {
if (debug) console.debug()
fontDialog.font = Qt.font({
family: selectFont.text,
pointSize: fontSize.value > 0 ? fontSize.value : 12,
italic: fontStyle.currentIndex == 1,
weight: Font.Normal,
})
} }
} }

View File

@ -124,12 +124,16 @@ Item {
repeater.itemAt(i).font.italic = plasmoid.configuration.currentFontStyle == "italic" ? true : false repeater.itemAt(i).font.italic = plasmoid.configuration.currentFontStyle == "italic" ? true : false
repeater.itemAt(i).font.pointSize = plasmoid.configuration.currentFontSize repeater.itemAt(i).font.pointSize = plasmoid.configuration.currentFontSize
repeater.itemAt(i).font.weight = general.fontWeight[plasmoid.configuration.currentFontWeight] repeater.itemAt(i).font.weight = general.fontWeight[plasmoid.configuration.currentFontWeight]
repeater.itemAt(i).style = general.textStyle[plasmoid.configuration.currentTextStyle]
repeater.itemAt(i).styleColor = plasmoid.configuration.currentTextStyleColor
} else { } else {
repeater.itemAt(i).color = plasmoid.configuration.fontColor repeater.itemAt(i).color = plasmoid.configuration.fontColor
repeater.itemAt(i).font.family = plasmoid.configuration.fontFamily repeater.itemAt(i).font.family = plasmoid.configuration.fontFamily
repeater.itemAt(i).font.italic = plasmoid.configuration.fontStyle == "italic" ? true : false repeater.itemAt(i).font.italic = plasmoid.configuration.fontStyle == "italic" ? true : false
repeater.itemAt(i).font.pointSize = plasmoid.configuration.fontSize repeater.itemAt(i).font.pointSize = plasmoid.configuration.fontSize
repeater.itemAt(i).font.weight = general.fontWeight[plasmoid.configuration.fontWeight] repeater.itemAt(i).font.weight = general.fontWeight[plasmoid.configuration.fontWeight]
repeater.itemAt(i).style = general.textStyle[plasmoid.configuration.textStyle]
repeater.itemAt(i).styleColor = plasmoid.configuration.textStyleColor
} }
repeater.itemAt(i).update() repeater.itemAt(i).update()
} }

View File

@ -1 +1,27 @@
singleton general 1.0 general.qml # 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

@ -16,10 +16,9 @@
***************************************************************************/ ***************************************************************************/
import QtQuick 2.0 import QtQuick 2.0
import QtQuick.Controls 1.3 as QtControls
import QtQuick.Dialogs 1.2 as QtDialogs
import org.kde.plasma.private.desktoppanel 1.0 import org.kde.plasma.private.desktoppanel 1.0
import "."
Item { Item {
@ -42,204 +41,23 @@ Item {
Column { Column {
id: pageColumn id: pageColumn
anchors.fill: parent anchors.fill: parent
QtControls.Label {
width: parent.width AWInfoLabel {}
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter HtmlDefaultFunctionsBar {
wrapMode: Text.WordWrap textArea: textPattern
text: i18n("Detailed information may be found on <a href=\"https://arcanis.me/projects/awesome-widgets/\">project homepage</a>")
onLinkActivated: Qt.openUrlExternally(link)
} }
Row { AWTagSelector {
height: implicitHeight backend: dpAdds
width: parent.width notifyBackend: dpAdds
QtControls.Button { textArea: textPattern
width: parent.width * 3 / 15 groups: general.dpTagRegexp
text: i18n("Bgcolor")
onClicked: backgroundDialog.visible = true
QtDialogs.ColorDialog {
id: backgroundDialog
title: i18n("Select a color")
onAccepted: {
var text = textPattern.text
textPattern.text = "<body bgcolor=\"" +
backgroundDialog.color + "\">" +
text + "</body>"
}
}
}
QtControls.Button {
width: parent.width * 3 / 15
text: i18n("Font")
iconName: "font"
onClicked: {
if (debug) console.debug("Font button")
var defaultFont = {
"color": plasmoid.configuration.fontColor,
"family": plasmoid.configuration.fontFamily,
"size": plasmoid.configuration.fontSize
}
var font = dpAdds.getFont(defaultFont)
if (font.applied != 1) {
if (debug) console.debug("No font selected")
return
} }
var selected = textPattern.selectedText AWTextEditor {
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition,
"<span style=\"color:" + font.color +
"; font-family:'" + font.family +
"'; font-size:" + font.size + "pt;\">" +
selected + "</span>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-indent-more"
onClicked: {
if (debug) console.debug("Indent button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, selected + "<br>\n")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-text-bold"
onClicked: {
if (debug) console.debug("Bold button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<b>" + selected + "</b>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-text-italic"
onClicked: {
if (debug) console.debug("Italic button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<i>" + selected + "</i>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-text-underline"
onClicked: {
if (debug) console.debug("Underline button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<u>" + selected + "</u>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-text-strikethrough"
onClicked: {
if (debug) console.debug("Strike button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<s>" + selected + "</s>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-justify-left"
onClicked: {
if (debug) console.debug("Left button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<p align=\"left\">" + selected + "</p>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-justify-center"
onClicked: {
if (debug) console.debug("Center button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<p align=\"center\">" + selected + "</p>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-justify-right"
onClicked: {
if (debug) console.debug("Right button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<p align=\"right\">" + selected + "</p>")
}
}
QtControls.Button {
width: parent.width / 15
iconName: "format-justify-fill"
onClicked: {
if (debug) console.debug("Justify button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, "<p align=\"justify\">" + selected + "</p>")
}
}
}
Row {
height: implicitHeight
width: parent.width
QtControls.ComboBox {
id: tags
width: parent.width - addTagButton.width - showValueButton.width
model: dpAdds.dictKeys()
}
QtControls.Button {
id: addTagButton
text: i18n("Add")
onClicked: {
if (debug) console.debug("Add tag button")
var selected = textPattern.selectedText
textPattern.remove(textPattern.selectionStart, textPattern.selectionEnd)
textPattern.insert(textPattern.cursorPosition, selected + "$" + tags.currentText)
}
}
QtControls.Button {
id: showValueButton
text: i18n("Show value")
onClicked: {
if (debug) console.debug("Show tag button")
var message = i18n("Tag: %1", tags.currentText)
message += "<br>"
message += i18n("Value: %1", dpAdds.valueByKey(tags.currentText))
dpAdds.sendNotification("tag", message)
}
}
}
QtControls.TextArea {
id: textPattern id: textPattern
width: parent.width backend: dpAdds
height: parent.height * 4 / 5
textFormat: TextEdit.PlainText
text: plasmoid.configuration.text
} }
} }

View File

@ -39,9 +39,9 @@
DPAdds::DPAdds(QObject *parent) DPAdds::DPAdds(QObject *parent)
: QObject(parent) : QObject(parent)
{ {
qSetMessagePattern(LOG_FORMAT); qSetMessagePattern(AWDebug::LOG_FORMAT);
qCDebug(LOG_DP) << __PRETTY_FUNCTION__; qCDebug(LOG_DP) << __PRETTY_FUNCTION__;
for (auto metadata : getBuildData()) for (auto &metadata : AWDebug::getBuildData())
qCDebug(LOG_DP) << metadata; qCDebug(LOG_DP) << metadata;
connect(KWindowSystem::self(), SIGNAL(currentDesktopChanged(int)), this, connect(KWindowSystem::self(), SIGNAL(currentDesktopChanged(int)), this,
@ -72,15 +72,21 @@ int DPAdds::currentDesktop() const
} }
QStringList DPAdds::dictKeys() const QStringList DPAdds::dictKeys(const bool sorted, const QString regexp) const
{ {
qCDebug(LOG_DP) << "Should be sorted" << sorted << "and filter applied"
<< regexp;
QStringList allKeys; QStringList allKeys;
allKeys.append(QString("mark")); allKeys.append(QString("mark"));
allKeys.append(QString("name")); allKeys.append(QString("name"));
allKeys.append(QString("number")); allKeys.append(QString("number"));
allKeys.append(QString("total")); allKeys.append(QString("total"));
return allKeys; if (sorted)
allKeys.sort();
return allKeys.filter(QRegExp(regexp));
} }
@ -220,6 +226,14 @@ void DPAdds::setToolTipData(const QVariantMap tooltipData)
} }
QString DPAdds::infoByKey(QString key) const
{
qCDebug(LOG_AW) << "Requested info for key" << key;
return QString("(none)");
}
QString DPAdds::valueByKey(const QString key, int desktop) const QString DPAdds::valueByKey(const QString key, int desktop) const
{ {
qCDebug(LOG_DP) << "Requested key" << key << "for desktop" << desktop; qCDebug(LOG_DP) << "Requested key" << key << "for desktop" << desktop;
@ -248,67 +262,7 @@ QString DPAdds::getAboutText(const QString type) const
{ {
qCDebug(LOG_DP) << "Type" << type; qCDebug(LOG_DP) << "Type" << type;
QString text; return AWDebug::getAboutText(type);
if (type == QString("header")) {
text = QString(NAME);
} else if (type == QString("version")) {
text = i18n("Version %1 (build date %2)", QString(VERSION),
QString(BUILD_DATE));
if (!QString(COMMIT_SHA).isEmpty())
text += QString(" (%1)").arg(QString(COMMIT_SHA));
} else if (type == QString("description")) {
text = i18n("A set of minimalistic plasmoid widgets");
} else if (type == QString("links")) {
text = i18n("Links:") + QString("<br>")
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(HOMEPAGE))
.arg(i18n("Homepage"))
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(REPOSITORY))
.arg(i18n("Repository"))
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(BUGTRACKER))
.arg(i18n("Bugtracker"))
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(TRANSLATION))
.arg(i18n("Translation issue"))
+ QString("<a href=\"%1\">%2</a><br>")
.arg(QString(AUR_PACKAGES))
.arg(i18n("AUR packages"))
+ QString("<a href=\"%1\">%2</a>")
.arg(QString(OPENSUSE_PACKAGES))
.arg(i18n("openSUSE packages"));
} else if (type == QString("copy")) {
text = QString("<small>&copy; %1 <a href=\"mailto:%2\">%3</a><br>")
.arg(QString(DATE))
.arg(QString(EMAIL))
.arg(QString(AUTHOR))
+ i18n("This software is licensed under %1", QString(LICENSE))
+ QString("</small>");
} else if (type == QString("translators")) {
text = i18n("Translators: %1", QString(TRANSLATORS));
} else if (type == QString("3rdparty")) {
QStringList trdPartyList
= QString(TRDPARTY_LICENSE)
.split(QChar(';'), QString::SkipEmptyParts);
for (int i = 0; i < trdPartyList.count(); i++)
trdPartyList[i]
= QString("<a href=\"%3\">%1</a> (%2 license)")
.arg(trdPartyList.at(i).split(QChar(',')).at(0))
.arg(trdPartyList.at(i).split(QChar(',')).at(1))
.arg(trdPartyList.at(i).split(QChar(',')).at(2));
text = i18n("This software uses: %1", trdPartyList.join(QString(", ")));
} else if (type == QString("thanks")) {
QStringList thanks = QString(SPECIAL_THANKS)
.split(QChar(';'), QString::SkipEmptyParts);
for (int i = 0; i < thanks.count(); i++)
thanks[i] = QString("<a href=\"%2\">%1</a>")
.arg(thanks.at(i).split(QChar(','))[0])
.arg(thanks.at(i).split(QChar(','))[1]);
text = i18n("Special thanks to %1", thanks.join(QString(", ")));
}
return text;
} }
@ -364,7 +318,8 @@ DPAdds::DesktopWindowsInfo DPAdds::getInfoByDesktop(const int desktop) const
for (auto id : KWindowSystem::windows()) { for (auto id : KWindowSystem::windows()) {
KWindowInfo winInfo = KWindowInfo( KWindowInfo winInfo = KWindowInfo(
id, NET::Property::WMDesktop | NET::Property::WMGeometry id,
NET::Property::WMDesktop | NET::Property::WMGeometry
| NET::Property::WMState | NET::Property::WMWindowType | NET::Property::WMState | NET::Property::WMWindowType
| NET::Property::WMVisibleName); | NET::Property::WMVisibleName);
if (!winInfo.isOnDesktop(desktop)) if (!winInfo.isOnDesktop(desktop))

View File

@ -45,7 +45,8 @@ public:
virtual ~DPAdds(); virtual ~DPAdds();
Q_INVOKABLE bool isDebugEnabled() const; Q_INVOKABLE bool isDebugEnabled() const;
Q_INVOKABLE int currentDesktop() const; Q_INVOKABLE int currentDesktop() const;
Q_INVOKABLE QStringList dictKeys() const; Q_INVOKABLE QStringList dictKeys(const bool sorted = true,
const QString regexp = QString()) const;
Q_INVOKABLE int numberOfDesktops() const; Q_INVOKABLE int numberOfDesktops() const;
Q_INVOKABLE QString toolTipImage(const int desktop) const; Q_INVOKABLE QString toolTipImage(const int desktop) const;
Q_INVOKABLE QString parsePattern(const QString pattern, Q_INVOKABLE QString parsePattern(const QString pattern,
@ -53,6 +54,7 @@ public:
// values // values
Q_INVOKABLE void setMark(const QString newMark); Q_INVOKABLE void setMark(const QString newMark);
Q_INVOKABLE void setToolTipData(const QVariantMap tooltipData); Q_INVOKABLE void setToolTipData(const QVariantMap tooltipData);
Q_INVOKABLE QString infoByKey(QString key) const;
Q_INVOKABLE QString valueByKey(const QString key, int desktop = -1) const; Q_INVOKABLE QString valueByKey(const QString key, int desktop = -1) const;
// configuration slots // configuration slots
Q_INVOKABLE QString getAboutText(const QString type = "header") const; Q_INVOKABLE QString getAboutText(const QString type = "header") const;

View File

@ -32,9 +32,9 @@ ExtendedSysMon::ExtendedSysMon(QObject *parent, const QVariantList &args)
: Plasma::DataEngine(parent, args) : Plasma::DataEngine(parent, args)
{ {
Q_UNUSED(args) Q_UNUSED(args)
qSetMessagePattern(LOG_FORMAT); qSetMessagePattern(AWDebug::LOG_FORMAT);
qCDebug(LOG_ESM) << __PRETTY_FUNCTION__; qCDebug(LOG_ESM) << __PRETTY_FUNCTION__;
for (auto metadata : getBuildData()) for (auto &metadata : AWDebug::getBuildData())
qCDebug(LOG_ESM) << metadata; qCDebug(LOG_ESM) << metadata;
setMinimumPollingInterval(333); setMinimumPollingInterval(333);

View File

@ -29,6 +29,7 @@
#include "playersource.h" #include "playersource.h"
#include "processessource.h" #include "processessource.h"
#include "quotessource.h" #include "quotessource.h"
#include "requestsource.h"
#include "upgradesource.h" #include "upgradesource.h"
#include "weathersource.h" #include "weathersource.h"
@ -112,7 +113,8 @@ void ExtSysMonAggregator::init(const QHash<QString, QString> config)
m_map[source] = gpuTempItem; m_map[source] = gpuTempItem;
// hdd temperature // hdd temperature
AbstractExtSysMonSource *hddTempItem = new HDDTemperatureSource( AbstractExtSysMonSource *hddTempItem = new HDDTemperatureSource(
this, QStringList() << config[QString("HDDDEV")] this,
QStringList() << config[QString("HDDDEV")]
<< config[QString("HDDTEMPCMD")]); << config[QString("HDDTEMPCMD")]);
for (auto source : hddTempItem->sources()) for (auto source : hddTempItem->sources())
m_map[source] = hddTempItem; m_map[source] = hddTempItem;
@ -123,8 +125,9 @@ void ExtSysMonAggregator::init(const QHash<QString, QString> config)
m_map[source] = networkItem; m_map[source] = networkItem;
// player // player
AbstractExtSysMonSource *playerItem = new PlayerSource( AbstractExtSysMonSource *playerItem = new PlayerSource(
this, QStringList() this,
<< config[QString("PLAYER")] << config[QString("MPDADDRESS")] QStringList() << config[QString("PLAYER")]
<< config[QString("MPDADDRESS")]
<< config[QString("MPDPORT")] << config[QString("MPRIS")] << config[QString("MPDPORT")] << config[QString("MPRIS")]
<< config[QString("PLAYERSYMBOLS")]); << config[QString("PLAYERSYMBOLS")]);
for (auto source : playerItem->sources()) for (auto source : playerItem->sources())
@ -134,6 +137,11 @@ void ExtSysMonAggregator::init(const QHash<QString, QString> config)
= new ProcessesSource(this, QStringList()); = new ProcessesSource(this, QStringList());
for (auto source : processesItem->sources()) for (auto source : processesItem->sources())
m_map[source] = processesItem; m_map[source] = processesItem;
// network request
AbstractExtSysMonSource *requestItem
= new RequestSource(this, QStringList());
for (auto source : requestItem->sources())
m_map[source] = requestItem;
// quotes // quotes
AbstractExtSysMonSource *quotesItem = new QuotesSource(this, QStringList()); AbstractExtSysMonSource *quotesItem = new QuotesSource(this, QStringList());
for (auto source : quotesItem->sources()) for (auto source : quotesItem->sources())

View File

@ -30,6 +30,7 @@ CustomSource::CustomSource(QObject *parent, const QStringList args)
m_extScripts m_extScripts
= new ExtItemAggregator<ExtScript>(nullptr, QString("scripts")); = new ExtItemAggregator<ExtScript>(nullptr, QString("scripts"));
m_extScripts->initSockets();
m_sources = getSources(); m_sources = getSources();
} }

View File

@ -240,9 +240,9 @@ QString PlayerSource::buildString(const QString &current, const QString &value,
int index = value.indexOf(current); int index = value.indexOf(current);
if ((current.isEmpty()) || ((index + s + 1) > value.count())) if ((current.isEmpty()) || ((index + s + 1) > value.count()))
return QString("%1").arg(value.left(s), s, QLatin1Char(' ')); return QString("%1").arg(value.left(s), -s, QLatin1Char(' '));
else else
return QString("%1").arg(value.mid(index + 1, s), s, QLatin1Char(' ')); return QString("%1").arg(value.mid(index + 1, s), -s, QLatin1Char(' '));
} }
@ -255,6 +255,12 @@ QString PlayerSource::stripString(const QString &value, const int s)
} }
bool PlayerSource::isMpdSocketConnected() const
{
return (m_mpdSocket.state() == QAbstractSocket::ConnectedState);
}
void PlayerSource::mpdSocketConnected() void PlayerSource::mpdSocketConnected()
{ {
qCDebug(LOG_ESS) << "MPD socket connected to" << m_mpdSocket.peerName() qCDebug(LOG_ESS) << "MPD socket connected to" << m_mpdSocket.peerName()
@ -323,8 +329,8 @@ QVariantHash PlayerSource::getPlayerMpdInfo()
} else if (m_mpdSocket.state() == QAbstractSocket::ConnectedState) { } else if (m_mpdSocket.state() == QAbstractSocket::ConnectedState) {
// send request // send request
if (m_mpdSocket.write(MPD_STATUS_REQUEST) == -1) if (m_mpdSocket.write(MPD_STATUS_REQUEST) == -1)
qCWarning(LOG_ESS) << "Could not write request to" qCWarning(LOG_ESS)
<< m_mpdSocket.peerName(); << "Could not write request to" << m_mpdSocket.peerName();
} }
return m_mpdCached; return m_mpdCached;

View File

@ -24,8 +24,6 @@
#include "abstractextsysmonsource.h" #include "abstractextsysmonsource.h"
#define MPD_STATUS_REQUEST "currentsong\nstatus\n"
class QProcess; class QProcess;
@ -34,6 +32,8 @@ class PlayerSource : public AbstractExtSysMonSource
Q_OBJECT Q_OBJECT
public: public:
const char *MPD_STATUS_REQUEST = "currentsong\nstatus\n";
explicit PlayerSource(QObject *parent, const QStringList args); explicit PlayerSource(QObject *parent, const QStringList args);
virtual ~PlayerSource(); virtual ~PlayerSource();
QVariant data(QString source); QVariant data(QString source);
@ -45,6 +45,8 @@ public:
static QString buildString(const QString &current, const QString &value, static QString buildString(const QString &current, const QString &value,
const int s); const int s);
static QString stripString(const QString &value, const int s); static QString stripString(const QString &value, const int s);
// additional test method
bool isMpdSocketConnected() const;
private slots: private slots:
void mpdSocketConnected(); void mpdSocketConnected();
@ -64,8 +66,8 @@ private:
QMutex m_dbusMutex; QMutex m_dbusMutex;
QString m_player; QString m_player;
int m_symbols; int m_symbols;
QStringList m_metadata = QStringList() << QString("album") QStringList m_metadata = QStringList()
<< QString("artist") << QString("album") << QString("artist")
<< QString("title"); << QString("title");
QVariantHash m_values; QVariantHash m_values;
}; };

View File

@ -29,6 +29,7 @@ QuotesSource::QuotesSource(QObject *parent, const QStringList args)
qCDebug(LOG_ESS) << __PRETTY_FUNCTION__; qCDebug(LOG_ESS) << __PRETTY_FUNCTION__;
m_extQuotes = new ExtItemAggregator<ExtQuotes>(nullptr, QString("quotes")); m_extQuotes = new ExtItemAggregator<ExtQuotes>(nullptr, QString("quotes"));
m_extQuotes->initSockets();
m_sources = getSources(); m_sources = getSources();
} }

View File

@ -0,0 +1,96 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#include "requestsource.h"
#include "awdebug.h"
#include "extnetworkrequest.h"
RequestSource::RequestSource(QObject *parent, const QStringList args)
: AbstractExtSysMonSource(parent, args)
{
Q_ASSERT(args.count() == 0);
qCDebug(LOG_ESS) << __PRETTY_FUNCTION__;
m_extNetRequest = new ExtItemAggregator<ExtNetworkRequest>(
nullptr, QString("requests"));
m_extNetRequest->initSockets();
m_sources = getSources();
}
RequestSource::~RequestSource()
{
qCDebug(LOG_ESS) << __PRETTY_FUNCTION__;
delete m_extNetRequest;
}
QVariant RequestSource::data(QString source)
{
qCDebug(LOG_ESS) << "Source" << source;
int ind = index(source);
source.remove(QString("network/"));
if (!m_values.contains(source)) {
QVariantHash data = m_extNetRequest->itemByTagNumber(ind)->run();
for (auto key : data.keys())
m_values[key] = data[key];
}
QVariant value = m_values.take(source);
return value;
}
QVariantMap RequestSource::initialData(QString source) const
{
qCDebug(LOG_ESS) << "Source" << source;
int ind = index(source);
QVariantMap data;
if (source.startsWith(QString("network/response"))) {
data[QString("min")] = QString("");
data[QString("max")] = QString("");
data[QString("name")]
= QString("Network response for %1")
.arg(m_extNetRequest->itemByTagNumber(ind)->uniq());
data[QString("type")] = QString("QString");
data[QString("units")] = QString("");
}
return data;
}
QStringList RequestSource::sources() const
{
return m_sources;
}
QStringList RequestSource::getSources()
{
QStringList sources;
for (auto item : m_extNetRequest->activeItems())
sources.append(
QString("network/%1").arg(item->tag(QString("response"))));
return sources;
}

View File

@ -0,0 +1,50 @@
/***************************************************************************
* This file is part of awesome-widgets *
* *
* awesome-widgets is free software: you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* awesome-widgets is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with awesome-widgets. If not, see http://www.gnu.org/licenses/ *
***************************************************************************/
#ifndef REQUESTSOURCE_H
#define REQUESTSOURCE_H
#include <QObject>
#include "abstractextsysmonsource.h"
#include "extitemaggregator.h"
class ExtNetworkRequest;
class RequestSource : public AbstractExtSysMonSource
{
Q_OBJECT
public:
explicit RequestSource(QObject *parent, const QStringList args);
virtual ~RequestSource();
QVariant data(QString source);
QVariantMap initialData(QString source) const;
void run(){};
QStringList sources() const;
private:
QStringList getSources();
// configuration and values
ExtItemAggregator<ExtNetworkRequest> *m_extNetRequest = nullptr;
QStringList m_sources;
QVariantHash m_values;
};
#endif /* REQUESTSOURCE_H */

View File

@ -30,6 +30,7 @@ UpgradeSource::UpgradeSource(QObject *parent, const QStringList args)
m_extUpgrade m_extUpgrade
= new ExtItemAggregator<ExtUpgrade>(nullptr, QString("upgrade")); = new ExtItemAggregator<ExtUpgrade>(nullptr, QString("upgrade"));
m_extUpgrade->initSockets();
m_sources = getSources(); m_sources = getSources();
} }

View File

@ -30,6 +30,7 @@ WeatherSource::WeatherSource(QObject *parent, const QStringList args)
m_extWeather m_extWeather
= new ExtItemAggregator<ExtWeather>(nullptr, QString("weather")); = new ExtItemAggregator<ExtWeather>(nullptr, QString("weather"));
m_extWeather->initSockets();
m_sources = getSources(); m_sources = getSources();
} }

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