diff --git a/.github/workflows/kcm.yml b/.github/workflows/kcm.yml new file mode 100644 index 00000000..1806f9b1 --- /dev/null +++ b/.github/workflows/kcm.yml @@ -0,0 +1,66 @@ +name: kcm + +# The System Settings module (kcm/): build it warning-free, run its tests (the staging model, the +# controller against tools/mock_plasmaard.py on a private bus, qmllint) and check the translations. + +on: + push: + paths: + - "kcm/**" + - "tools/mock_plasmaard*" + - ".github/workflows/kcm.yml" + pull_request: + paths: + - "kcm/**" + - "tools/mock_plasmaard*" + - ".github/workflows/kcm.yml" + +jobs: + build: + name: build and test (${{ matrix.image }}) + runs-on: ubuntu-latest + container: ${{ matrix.image }} + strategy: + fail-fast: false + matrix: + image: ["ubuntu:26.04", "fedora:latest"] + + steps: + - name: Install dependencies (Ubuntu) + if: startsWith(matrix.image, 'ubuntu') + env: + DEBIAN_FRONTEND: noninteractive + run: | + apt-get update + apt-get install -y --no-install-recommends \ + ca-certificates cmake ninja-build g++ extra-cmake-modules gettext \ + qt6-base-dev qt6-declarative-dev qt6-declarative-dev-tools qt6-tools-dev \ + libkf6kcmutils-dev libkf6i18n-dev libkf6coreaddons-dev libkirigami-dev \ + qml6-module-org-kde-kirigami qml6-module-org-kde-kcmutils \ + qml6-module-qtquick-controls qml6-module-qtquick-layouts \ + dbus-daemon python3 python3-gi gir1.2-glib-2.0 + + - name: Install dependencies (Fedora) + if: startsWith(matrix.image, 'fedora') + run: | + dnf install -y \ + cmake ninja-build gcc-c++ extra-cmake-modules gettext \ + qt6-qtbase-devel qt6-qtdeclarative-devel qt6-qttools-devel \ + kf6-kcmutils-devel kf6-ki18n-devel kf6-kcoreaddons-devel kf6-kirigami-devel \ + dbus-daemon dbus-tools python3 python3-gobject-base + + - name: Checkout + uses: actions/checkout@v4 + + - name: Configure + run: cmake -S kcm -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_COMPILE_WARNING_AS_ERROR=ON + + - name: Build + run: cmake --build build + + - name: Test + run: ctest --test-dir build --output-on-failure + + - name: Check translations + run: | + for po in kcm/po/*/*.po; do msgfmt --check --statistics -o /dev/null "$po"; done diff --git a/Makefile b/Makefile index ce9a3dd7..734c96f7 100644 --- a/Makefile +++ b/Makefile @@ -123,3 +123,37 @@ lint: test: @echo "Running Solaar tests" pytest -rs --cov --cov-report=xml + +# --- System Settings module (kcm/, see docs/kcm.md) --------------------------------------------------- +# A user install: the plugin, its translations and desktop entry under KCM_PREFIX, plus a Plasma session +# environment script that adds the plugin directory to QT_PLUGIN_PATH (effective at the next login). + +KCM_BUILD_DIR ?= kcm/build +KCM_PREFIX ?= $(HOME)/.local +PLASMA_ENV_DIR := $(HOME)/.config/plasma-workspace/env +KCM_ENV_SCRIPT := $(PLASMA_ENV_DIR)/plasmaar-kcm.sh + +.PHONY: build_kcm test_kcm install_kcm uninstall_kcm + +build_kcm: + cmake -S kcm -B $(KCM_BUILD_DIR) -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX=$(KCM_PREFIX) + cmake --build $(KCM_BUILD_DIR) --parallel + +test_kcm: build_kcm + ctest --test-dir $(KCM_BUILD_DIR) --output-on-failure + +install_kcm: build_kcm + cmake --install $(KCM_BUILD_DIR) + install -D -m 644 $(KCM_BUILD_DIR)/plasmaar-kcm.sh $(KCM_ENV_SCRIPT) + @echo + @echo "Installed. System Settings lists it under Input Devices after you log out and back in." + @echo "To try it right away:" + @echo " sh -c '. $(KCM_ENV_SCRIPT) && exec kcmshell6 kcm_plasmaar'" + +uninstall_kcm: + @if [ -f $(KCM_BUILD_DIR)/install_manifest.txt ]; then \ + cmake --build $(KCM_BUILD_DIR) --target uninstall; \ + else \ + echo "$(KCM_BUILD_DIR)/install_manifest.txt not found: nothing installed from this build directory"; \ + fi + rm -f $(KCM_ENV_SCRIPT) diff --git a/docs/kcm.md b/docs/kcm.md new file mode 100644 index 00000000..e06001ca --- /dev/null +++ b/docs/kcm.md @@ -0,0 +1,164 @@ +# The System Settings module (KCM) + +"Logitech Devices" ("Périphériques Logitech") under System Settings → Input Devices: the settings page of +[Assessment B](ROADMAP.md#assessment-b-the-settings-page-system-settings-module). It is a thin C++ plugin +plus a QML page that talks to `plasmaard` over its [D-Bus API](dbus-api.md); all device work stays in the +service. + +| Settings | Buttons | Haptic feedback | +|---|---|---| +| ![Settings](../kcm/screenshots/mx-master-4-settings.png) | ![Buttons](../kcm/screenshots/mx-master-4-buttons.png) | ![Haptics](../kcm/screenshots/mx-master-4-haptics.png) | + +More in [`kcm/screenshots/`](../kcm/screenshots): the KDE action picker (`mx-master-4-action-picker`), +the K850 (`k850-settings`), an offline device, write errors, an older plasmaard, plasmaard not running, +and the buttons of the real MX Master 4 read from the running service. They are rendered headless (see +the end of this page), in French. + +## What it shows + +- **Device header**: picker (switching is locked while there are unapplied changes), name, connection, + battery, model/unit ids and HID++ version. +- **Settings**: every setting of the schema, grouped in sections (scroll wheel, thumb wheel, pointer, …). + `TOGGLE` → switch, `CHOICE` → combo box (long numeric lists such as DPI → stepped slider + spin box, + long named lists → searchable list), `RANGE` → slider + spin box, other kinds read-only, `display: false` + hidden. Descriptions are behind the ⓘ buttons. Per-key settings (`reprogrammable-keys`, `divert-keys`, + `persistent-remappable-keys`, …) form one table: a row per key, a column per setting. +- **Buttons** (Keys for a keyboard): each divertable button's behavior (normal, an action when pressed, + gestures; only the modes it offers) and the KDE actions, chosen from a searchable list of + `ListKdeActions` grouped by component, for the press or each gesture direction including a click. +- **Haptic feedback**: intensity (`haptic-level`), a test button per waveform (`PlayHaptic`, immediate), + and which waveform desktop events play (`GetHapticEvents`/`SetHapticEvent`). +- **plasmaard not running**: a placeholder with a "Start plasmaard" button (systemd `StartUnit`) and the + `systemctl --user start plasmaard` hint. The page comes back by itself when the service appears. + +## Build, test, install + +Build dependencies (Kubuntu/Debian names): `cmake extra-cmake-modules qt6-base-dev qt6-declarative-dev +libkf6kcmutils-dev libkf6i18n-dev libkf6coreaddons-dev libkirigami-dev gettext`; the tests also use +`qt6-declarative-dev-tools` (qmllint), `dbus-daemon` and `python3-gi`. + +```sh +make test_kcm # configure kcm/build, build, run the tests +make install_kcm # install for your user, see below +make uninstall_kcm +``` + +`make install_kcm` installs into `~/.local` (`KCM_PREFIX=…` to change it): the plugin in +`~/.local/lib//plugins/plasma/kcms/systemsettings/`, the French translation and a desktop entry. +Plasma only looks for plugins on `QT_PLUGIN_PATH`, so it also writes +`~/.config/plasma-workspace/env/plasmaar-kcm.sh`, which Plasma sources at login. Until you log in again: + +```sh +sh -c '. ~/.config/plasma-workspace/env/plasmaar-kcm.sh && exec kcmshell6 kcm_plasmaar' +``` + +Without make: `cmake -S kcm -B kcm/build && cmake --build kcm/build && ctest --test-dir kcm/build`. +A plain `cmake --install` to `/usr` needs no environment script. + +## Architecture + +``` +plasmaard ──D-Bus (JSON payloads)── PlasmaarClient ── Controller ── StagedModel ×3 ── QML pages + (async calls, (devices, (settings, + signals, load/save/ buttons, + service watch) defaults) haptic events) + │ + PlasmaarKcm (KQuickConfigModule): Apply/Reset/Defaults +``` + +C++ (`kcm/src/`): + +- **`PlasmaarClient`**: every call is a `QDBusPendingCallWatcher` (never blocking the UI; 30 s timeout for + sleeping Bluetooth devices) whose JSON reply is parsed into a `QVariant` and handed to a callback. + It relays `DeviceAdded/Changed/Removed`, `SettingChanged` and `ButtonActionsChanged` with parsed + payloads, and follows the service with a `QDBusServiceWatcher` (Checking → Running ↔ Missing). +- **`StagedModel`**: a list model of entries (settings, buttons or haptic events) with a live value and an + optional staged value per row. QML reads `pending` (staged, else live) and stages edits, also per key of + a map (`stageKey`) or along a path (`stagePath`, for gesture directions). Staging the live value again + unstages the row, so "needs save" really means something would change. Live updates keep the user's + edits: for maps, only the edited keys are kept and the others follow the device. A refresh with the same + entries updates the rows in place (views keep their delegates). It also knows the `default` of each + entry and the write error of each row. +- **`Controller`**: the devices, the selected one, its three models, the KDE actions and waveforms, and + the KCM operations. `load()` drops edits and reloads; `save()` writes the changed rows one after the + other (settings first, with `SetSetting`, or `SetSettingKey` per changed key; then `SetButtonAction`; + then `SetHapticEvent`) and takes each reply as the new live value; a failed write keeps its edit staged + and shows its error inline and in a summary. `defaults()` stages every setting's `default`. Each + optional part has a state: Available, Unavailable (the device has none), NeedsNewerService (the method + is unknown: an older plasmaard), Failed. +- **`PlasmaarKcm`**: the plugin. `needsSave` follows the staged edits; `representsDefaults` is true when + the pending values are the defaults, or when no default is known, which disables the Defaults button. + +The C++ types form a static QML module, `io.github.fredaime.plasmaar`, so the QML is typed and qmllint +checks it against the generated `.qmltypes`. + +QML (`kcm/ui/`, loaded by `kcmutils_add_qml_kcm`): `main.qml` (header with the device and tabs, service +placeholders, the shared pickers), `DeviceHeader`, `SettingsPage` (sections of `SettingRow`) and +`KeyMapTable`/`KeyCell`, `ButtonsPage`/`ActionField`, `HapticsPage`, `PickerDialog` (a +`Kirigami.SearchDialog`), `SnapshotRunner`. The pages are rebuilt when another device is selected rather +than having all their rows replaced under the form layouts. + +### With an older plasmaard + +Each addition is optional: an `org.freedesktop.DBus.Error.UnknownMethod` answer hides or explains the part +that needs it. Without `GetButtonActions` the Buttons tab says that a newer plasmaard is needed (if the +device has divertable buttons); without `GetHapticEvents` the haptics page keeps intensity and the test +buttons (waveforms from the `haptic-play` setting); without `"default"` the Defaults button stays off. + +## Translations + +All strings go through `i18n()`; the domain is `kcm_plasmaar`. `kcm/Messages.sh` extracts them into +`kcm/po/kcm_plasmaar.pot` and merges them into the translations; `kcm/po/fr/kcm_plasmaar.po` is the French +one, installed by `ki18n_install`. Setting labels and descriptions come translated from the service. + +## Tests and checks + +`ctest` in the build directory runs: + +- `stagedmodeltest`: the staging rules (unstaging, per-key edits and live merges, nested paths, defaults, + in-place refresh, errors) and the JSON conversions. +- `controllertest`: the `Controller` against `tools/mock_plasmaard.py` on a private bus + (`dbus-run-session` with `kcm/autotests/isolated-bus.conf`, which has no service activation): loading, + apply, per-key apply, live updates, defaults, write errors, button actions, haptic events, the service + quitting and coming back, and an older service. It refuses to run if a plasmaard already owns the name. +- `qmllint`: `kcm/autotests/qmllint.py` fails on any warning except unqualified access to `kcm` and the + i18n functions, which KCMUtils and KI18n inject as context properties that qmllint cannot see. + +`.github/workflows/kcm.yml` builds with warnings as errors and runs these tests in Ubuntu 26.04 and Fedora +containers. + +## The mock service and headless snapshots + +`tools/mock_plasmaard.py` implements the whole API with data captured from a real MX Master 4, K850 and +MX Anywhere 3S (`tools/mock_plasmaard_data.json`), in memory, with the same signals. Run it only on a +private bus; it refuses to start next to a running plasmaard. `--legacy` emulates a v1-only service, +`--fail NAME` makes writes of a setting fail (`button:`, `haptic:` too), `--delay MS` +slows every answer, `-v` logs calls. Its `io.github.fredaime.PlasmaarMock` interface simulates the +device: `SetDeviceValue`, `SetOnline`, `SetBattery`, and `Quit`. + +```sh +dbus-run-session --config-file=kcm/autotests/isolated-bus.conf -- \ + sh -c 'python3 tools/mock_plasmaard.py -v & sleep 1; \ + QT_PLUGIN_PATH=$PWD/kcm/build/bin kcmshell6 kcm_plasmaar' +``` + +With `PLASMAAR_KCM_SNAPSHOT=/path/prefix` the module renders each page of each device once the data has +loaded, grows the window to fit, saves `/path/prefix--.png` and quits. `kcm/run-snapshots.sh` +does it all offscreen (`QT_QPA_PLATFORM=offscreen`, French by default): + +```sh +kcm/run-snapshots.sh /tmp/shots/mock # against the mock, private bus +kcm/run-snapshots.sh --legacy /tmp/shots/legacy # an older plasmaard +kcm/run-snapshots.sh --fail smart-shift --scenario apply-errors /tmp/shots/errors +kcm/run-snapshots.sh --no-service /tmp/shots/none # plasmaard not running +kcm/run-snapshots.sh --real /tmp/shots/real # your plasmaard, read-only +``` + +Snapshot mode never writes to the service; the `apply-errors` scenario, which stages and applies a few +edits, is refused with `--real`. + +## Not covered yet + +- B8: the advanced kinds (`MULTIPLE_TOGGLE`, `MULTIPLE_RANGE`, `PACKED_RANGE`, …) are shown read-only. +- B9: pairing with Bolt/Unifying receivers. +- Edits are per device: switching devices requires applying or resetting first. diff --git a/kcm/.gitignore b/kcm/.gitignore new file mode 100644 index 00000000..75ea648c --- /dev/null +++ b/kcm/.gitignore @@ -0,0 +1,2 @@ +/build/ +/po/*.pot diff --git a/kcm/CMakeLists.txt b/kcm/CMakeLists.txt new file mode 100644 index 00000000..72a7ba4c --- /dev/null +++ b/kcm/CMakeLists.txt @@ -0,0 +1,64 @@ +# SPDX-FileCopyrightText: 2026 plasmaar contributors +# SPDX-License-Identifier: GPL-2.0-or-later + +cmake_minimum_required(VERSION 3.22) +project(kcm_plasmaar VERSION 0.1.0 LANGUAGES CXX) + +set(QT_MIN_VERSION "6.6.0") +set(KF_MIN_VERSION "6.3.0") # Kirigami.SearchDialog + +find_package(ECM ${KF_MIN_VERSION} REQUIRED NO_MODULE) +set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH}) + +include(KDEInstallDirs) +include(KDECMakeSettings) +include(KDECompilerSettings NO_POLICY_SCOPE) +include(ECMQmlModule) +include(FeatureSummary) + +find_package(Qt6 ${QT_MIN_VERSION} REQUIRED COMPONENTS Core DBus Gui Qml Quick) +find_package(KF6 ${KF_MIN_VERSION} REQUIRED COMPONENTS CoreAddons I18n KCMUtils) + +option(BUILD_TESTING "Build the tests" ON) + +add_compile_definitions(TRANSLATION_DOMAIN="kcm_plasmaar") +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +# The plugin is a shared object that links the static core library and the object libraries Qt +# generates for its QML module (resources, type registrations): all of them must be PIC. Some +# toolchains (Ubuntu) default to it, others (Fedora) do not. +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +# The D-Bus client, the staging model and the controller: a static QML module, so that the QML is typed +# (qmllint checks it against the generated .qmltypes) and the tests can use it without KCMUtils. +qt_add_library(plasmaar_kcm_core STATIC) +qt_add_qml_module(plasmaar_kcm_core + URI io.github.fredaime.plasmaar + VERSION 1.0 + NO_PLUGIN + SOURCES + src/controller.cpp src/controller.h + src/json.cpp src/json.h + src/plasmaarclient.cpp src/plasmaarclient.h + src/stagedmodel.cpp src/stagedmodel.h +) +target_include_directories(plasmaar_kcm_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src) +# The module's resource objects share the include directories, and may compile before AUTOMOC has created +# its include directory: create it up front for -Wmissing-include-dirs (set by KDECompilerSettings). +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/plasmaar_kcm_core_autogen/include) +target_link_libraries(plasmaar_kcm_core PUBLIC Qt6::Core Qt6::DBus Qt6::Gui Qt6::Qml KF6::I18n) + +kcmutils_add_qml_kcm(kcm_plasmaar SOURCES src/plasmaarkcm.cpp src/plasmaarkcm.h) +target_link_libraries(kcm_plasmaar PRIVATE plasmaar_kcm_core KF6::CoreAddons KF6::I18n KF6::KCMUtilsQuick Qt6::Quick) + +ki18n_install(po) + +# For installs outside the system prefix (make install_kcm): the Plasma session environment script that +# adds the plugin directory to QT_PLUGIN_PATH. +configure_file(plasmaar-kcm.sh.in ${CMAKE_CURRENT_BINARY_DIR}/plasmaar-kcm.sh @ONLY) + +if(BUILD_TESTING) + add_subdirectory(autotests) +endif() + +feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/kcm/Messages.sh b/kcm/Messages.sh new file mode 100755 index 00000000..c0e17d65 --- /dev/null +++ b/kcm/Messages.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 plasmaar contributors +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Extracts the module's messages into po/kcm_plasmaar.pot and merges them into the translations: +# kcm/Messages.sh +# (Same keywords as KDE's scripty; QML is read as JavaScript.) +set -e +cd "$(dirname "$0")" +KEYWORDS="-ki18n:1 -ki18nc:1c,2 -ki18np:1,2 -ki18ncp:1c,2,3 -kxi18n:1 -kxi18nc:1c,2 -kxi18np:1,2 -kxi18ncp:1c,2,3 -kkli18n:1 -kkli18nc:1c,2" +COMMON="--from-code=UTF-8 --add-comments=i18n --package-name=kcm_plasmaar --msgid-bugs-address=https://github.com/fredaime/plasmaar/issues" +xgettext $COMMON -C $KEYWORDS -o po/cpp.pot src/*.cpp +xgettext $COMMON -L JavaScript $KEYWORDS -o po/qml.pot ui/*.qml +msgcat --use-first po/cpp.pot po/qml.pot -o po/kcm_plasmaar.pot +rm -f po/cpp.pot po/qml.pot +for po in po/*/kcm_plasmaar.po; do + [ -e "$po" ] || continue + msgmerge --quiet --update --backup=none --no-fuzzy-matching "$po" po/kcm_plasmaar.pot +done diff --git a/kcm/autotests/CMakeLists.txt b/kcm/autotests/CMakeLists.txt new file mode 100644 index 00000000..76bbea5b --- /dev/null +++ b/kcm/autotests/CMakeLists.txt @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2026 plasmaar contributors +# SPDX-License-Identifier: GPL-2.0-or-later + +find_package(Qt6 ${QT_MIN_VERSION} REQUIRED COMPONENTS Test) +include(ECMAddTests) + +ecm_add_test(stagedmodeltest.cpp TEST_NAME stagedmodeltest LINK_LIBRARIES plasmaar_kcm_core Qt6::Test) + +# The controller against the mock service, on a private session bus without service activation. +find_program(DBUS_RUN_SESSION dbus-run-session) +find_program(PYTHON3 python3) +if(DBUS_RUN_SESSION AND PYTHON3) + add_executable(controllertest controllertest.cpp) + target_link_libraries(controllertest plasmaar_kcm_core Qt6::Test) + add_test(NAME controllertest + COMMAND ${DBUS_RUN_SESSION} --config-file=${CMAKE_CURRENT_SOURCE_DIR}/isolated-bus.conf -- $) + set_tests_properties(controllertest PROPERTIES + ENVIRONMENT "PLASMAAR_MOCK=${CMAKE_CURRENT_SOURCE_DIR}/../../tools/mock_plasmaard.py;PLASMAAR_PYTHON=${PYTHON3}" + TIMEOUT 300) +else() + message(STATUS "dbus-run-session or python3 missing: controllertest is not built") +endif() + +# QML: lint the module's pages against the generated types of the C++ module (also run in CI). +find_program(QMLLINT qmllint PATHS ${QT6_INSTALL_PREFIX}/${QT6_INSTALL_BINS} /usr/lib/qt6/bin /usr/lib64/qt6/bin) +if(QMLLINT AND PYTHON3) + file(GLOB qml_files ${CMAKE_CURRENT_SOURCE_DIR}/../ui/*.qml) + add_test(NAME qmllint COMMAND ${PYTHON3} ${CMAKE_CURRENT_SOURCE_DIR}/qmllint.py ${QMLLINT} ${CMAKE_BINARY_DIR}/bin ${qml_files}) +endif() diff --git a/kcm/autotests/controllertest.cpp b/kcm/autotests/controllertest.cpp new file mode 100644 index 00000000..48011cac --- /dev/null +++ b/kcm/autotests/controllertest.cpp @@ -0,0 +1,406 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +// The Controller (and its D-Bus client) against tools/mock_plasmaard.py on a private session bus. +// Run through ctest, which wraps it in dbus-run-session; it refuses to run next to a real plasmaard. + +#include "controller.h" +#include "json.h" + +#include +#include +#include +#include +#include +#include +#include + +using namespace Qt::StringLiterals; + +namespace +{ +const QString MX4 = u"B04200000000-BD2BC136"_s; +const QString K850 = u"B34D40620000-FF883310"_s; +const QString MockInterface = u"io.github.fredaime.PlasmaarMock"_s; +constexpr int Timeout = 10000; + +QVariantMap action(const QString &component, const QString &name) +{ + return {{u"component"_s, component}, {u"action"_s, name}}; +} +} + +class ControllerTest : public QObject +{ + Q_OBJECT + +private: + QProcess *m_mock = nullptr; + + void startMock(const QStringList &extraArgs = {}) + { + m_mock = new QProcess(this); + m_mock->setProcessChannelMode(QProcess::ForwardedChannels); + QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); + env.insert(u"LANGUAGE"_s, u"fr"_s); + m_mock->setProcessEnvironment(env); + m_mock->start(qEnvironmentVariable("PLASMAAR_PYTHON", u"python3"_s), QStringList{qEnvironmentVariable("PLASMAAR_MOCK")} + extraArgs); + QVERIFY2(m_mock->waitForStarted(), "cannot start the mock service"); + QTRY_VERIFY_WITH_TIMEOUT(QDBusConnection::sessionBus().interface()->isServiceRegistered(PlasmaarClient::Service), Timeout); + // make sure that this is the mock, never a real plasmaard + QDBusInterface introspect(PlasmaarClient::Service, PlasmaarClient::Path, u"org.freedesktop.DBus.Introspectable"_s); + const QDBusReply xml = introspect.call(u"Introspect"_s); + QVERIFY2(xml.isValid() && xml.value().contains(MockInterface), "the service on this bus is not the mock"); + } + + void stopMock() + { + if (!m_mock) { + return; + } + if (m_mock->state() != QProcess::NotRunning) { + m_mock->terminate(); + if (!m_mock->waitForFinished(5000)) { + m_mock->kill(); + m_mock->waitForFinished(); + } + } + delete m_mock; + m_mock = nullptr; + QTRY_VERIFY_WITH_TIMEOUT(!QDBusConnection::sessionBus().interface()->isServiceRegistered(PlasmaarClient::Service), Timeout); + } + + // synchronous calls are fine in a test + QVariant api(const QString &method, const QVariantList &args) + { + QDBusInterface iface(PlasmaarClient::Service, PlasmaarClient::Path, PlasmaarClient::Interface); + const QDBusMessage reply = iface.callWithArgumentList(QDBus::Block, method, args); + if (reply.type() != QDBusMessage::ReplyMessage || reply.arguments().isEmpty()) { + return {}; + } + return Json::parse(reply.arguments().constFirst().toString()); + } + + void mock(const QString &method, const QVariantList &args) + { + QDBusInterface iface(PlasmaarClient::Service, PlasmaarClient::Path, MockInterface); + const QDBusMessage reply = iface.callWithArgumentList(QDBus::Block, method, args); + QVERIFY2(reply.type() == QDBusMessage::ReplyMessage, qPrintable(reply.errorMessage())); + } + + QVariant deviceSetting(const QString &deviceId, const QString &name) + { + const QVariantList settings = api(u"ListSettings"_s, {deviceId}).toList(); + for (const QVariant &setting : settings) { + if (setting.toMap().value(u"name"_s) == name) { + return setting.toMap().value(u"value"_s); + } + } + return {}; + } + + QVariantMap deviceButton(const QString &deviceId, int control) + { + const QVariantList buttons = api(u"GetButtonActions"_s, {deviceId}).toMap().value(u"buttons"_s).toList(); + for (const QVariant &button : buttons) { + if (button.toMap().value(u"control"_s).toInt() == control) { + return button.toMap(); + } + } + return {}; + } + + static bool save(Controller &controller, bool expected = true) + { + QSignalSpy saved(&controller, &Controller::saved); + controller.save(); + if (!saved.wait(Timeout)) { + return false; + } + return saved.first().first().toBool() == expected; + } + +private Q_SLOTS: + void initTestCase() + { + QVERIFY2(!qEnvironmentVariableIsEmpty("PLASMAAR_MOCK"), "PLASMAAR_MOCK must point to tools/mock_plasmaard.py (run through ctest)"); + QVERIFY2(!QDBusConnection::sessionBus().interface()->isServiceRegistered(PlasmaarClient::Service), + "a plasmaard already runs on this bus: refusing to test against it (run through ctest, which uses a private bus)"); + } + + void init() + { + const QString test = QString::fromLatin1(QTest::currentTestFunction()); + if (test == u"degradesWithAnOlderService"_s) { + startMock({u"--legacy"_s}); + } else if (test == u"reportsWriteErrors"_s) { + startMock({u"--fail"_s, u"smart-shift"_s, u"--fail"_s, u"button:416"_s}); + } else { + startMock(); + } + } + + void cleanup() + { + stopMock(); + } + + void loadsDevicesAndSettings() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + QCOMPARE(controller.serviceState(), Controller::ServiceState::Running); + QCOMPARE(controller.devices().size(), 3); + QCOMPARE(controller.currentDeviceId(), MX4); // the first online device + QCOMPARE(controller.currentDevice().value(u"name"_s).toString(), u"MX Master 4"_s); + QCOMPARE(controller.settings()->count(), 15); + QCOMPARE(controller.settingsState(), Controller::FeatureState::Available); + QCOMPARE(controller.buttonsState(), Controller::FeatureState::Available); + QCOMPARE(controller.buttons()->count(), 6); + QCOMPARE(controller.hapticEventsState(), Controller::FeatureState::Available); + QCOMPARE(controller.hapticEvents()->count(), 3); + QCOMPARE(controller.kdeActionsState(), Controller::FeatureState::Available); + QCOMPARE(controller.waveforms().size(), 16); + QVERIFY(controller.hasDefaults()); + QVERIFY(!controller.atDefaults()); + QVERIFY(!controller.needsSave()); + // localized labels come from the service; unknown actions get a readable fallback + QCOMPARE(controller.actionLabel(action(u"kwin"_s, u"Overview"_s)), u"Basculer vers l'aperçu"_s); + QVERIFY(controller.actionLabel(action(u"kwin"_s, u"Nope"_s)).contains(u"Nope"_s)); + QVERIFY(controller.actionLabel(QVariant::fromValue(nullptr)).isEmpty()); + + // another device: its own settings, no haptics + controller.setCurrentDeviceId(K850); + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady() && !controller.isLoading(), Timeout); + QCOMPARE(controller.settings()->count(), 6); + QCOMPARE(controller.hapticEventsState(), Controller::FeatureState::Unavailable); + QCOMPARE(controller.buttons()->count(), 19); + } + + void stagesAndAppliesSetting() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + StagedModel *settings = controller.settings(); + const int dpi = settings->indexOf(u"dpi"_s); + + settings->stage(dpi, 2000.0); + QVERIFY(controller.needsSave()); + settings->stage(dpi, 1600.0); + QVERIFY(!controller.needsSave()); + settings->stage(dpi, 2000.0); + QCOMPARE(deviceSetting(MX4, u"dpi"_s).toInt(), 1600); // nothing written before Apply + + QVERIFY(save(controller)); + QCOMPARE(settings->liveValue(dpi).toInt(), 2000); + QVERIFY(!controller.needsSave()); + QCOMPARE(deviceSetting(MX4, u"dpi"_s).toInt(), 2000); + + // Reset drops edits and reloads + settings->stage(settings->indexOf(u"smart-shift"_s), 30.0); + QVERIFY(controller.needsSave()); + controller.load(); + QVERIFY(!controller.needsSave()); + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + QCOMPARE(settings->pendingValue(settings->indexOf(u"smart-shift"_s)).toInt(), 12); + } + + void appliesPerKeyEdits() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + StagedModel *settings = controller.settings(); + const int divert = settings->indexOf(u"divert-keys"_s); + settings->stageKey(divert, u"82"_s, 1); + QVERIFY(save(controller)); + QCOMPARE(deviceSetting(MX4, u"divert-keys"_s).toMap().value(u"82"_s).toInt(), 1); + QCOMPARE(settings->liveValue(divert).toMap().value(u"195"_s).toInt(), 2); // the other keys untouched + // the service re-announces the buttons, whose mode follows the diversion + const int middle = controller.buttons()->indexOf(u"82"_s); + QTRY_COMPARE_WITH_TIMEOUT(controller.buttons()->liveValue(middle).toMap().value(u"mode"_s).toString(), u"press"_s, Timeout); + } + + void followsTheDevice() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + StagedModel *settings = controller.settings(); + const int divert = settings->indexOf(u"divert-keys"_s); + settings->stageKey(divert, u"83"_s, 1); + + // changed on the device meanwhile: another key, and a value that equals an edit + QVariantMap onDevice = settings->liveValue(divert).toMap(); + onDevice.insert(u"86"_s, 2); + mock(u"SetDeviceValue"_s, {MX4, u"divert-keys"_s, Json::serialize(onDevice)}); + QTRY_COMPARE_WITH_TIMEOUT(settings->liveValue(divert).toMap().value(u"86"_s).toInt(), 2, Timeout); + QCOMPARE(settings->pendingValue(divert).toMap().value(u"83"_s).toInt(), 1); + QCOMPARE(settings->pendingValue(divert).toMap().value(u"86"_s).toInt(), 2); + + const int smartShift = settings->indexOf(u"smart-shift"_s); + settings->stage(smartShift, 20.0); + mock(u"SetDeviceValue"_s, {MX4, u"smart-shift"_s, u"20"_s}); + QTRY_COMPARE_WITH_TIMEOUT(settings->liveValue(smartShift).toInt(), 20, Timeout); + QVERIFY(!settings->data(settings->index(smartShift), StagedModel::ChangedRole).toBool()); + + mock(u"SetOnline"_s, {MX4, false}); + QTRY_VERIFY_WITH_TIMEOUT(!controller.currentDevice().value(u"online"_s).toBool(), Timeout); + mock(u"SetBattery"_s, {MX4, 12}); + QTRY_COMPARE_WITH_TIMEOUT(controller.currentDevice().value(u"battery"_s).toMap().value(u"level"_s).toInt(), 12, Timeout); + QVERIFY(controller.needsSave()); // the edit of key 83 is still there + } + + void stagesDefaults() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + StagedModel *settings = controller.settings(); + controller.defaults(); + QVERIFY(controller.atDefaults()); + QVERIFY(controller.needsSave()); + QCOMPARE(settings->pendingValue(settings->indexOf(u"dpi"_s)).toInt(), 1000); + QVERIFY(save(controller)); + QVERIFY(controller.atDefaults()); + QVERIFY(!controller.needsSave()); + QCOMPARE(deviceSetting(MX4, u"dpi"_s).toInt(), 1000); + QCOMPARE(deviceSetting(MX4, u"divert-keys"_s).toMap().value(u"195"_s).toInt(), 0); + } + + void reportsWriteErrors() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + StagedModel *settings = controller.settings(); + const int smartShift = settings->indexOf(u"smart-shift"_s); + settings->stage(smartShift, 30.0); + settings->stage(settings->indexOf(u"dpi"_s), 2400.0); + const int haptic = controller.buttons()->indexOf(u"416"_s); + controller.buttons()->stageKey(haptic, u"mode"_s, u"off"_s); + + QVERIFY(save(controller, false)); + QVERIFY(controller.needsSave()); // the failed edits stay staged + QVERIFY(!settings->writeError(smartShift).isEmpty()); + QVERIFY(!controller.buttons()->writeError(haptic).isEmpty()); + QVERIFY(controller.saveError().contains(settings->get(smartShift).value(u"label"_s).toString())); + QCOMPARE(deviceSetting(MX4, u"dpi"_s).toInt(), 2400); // the others were applied + QCOMPARE(deviceSetting(MX4, u"smart-shift"_s).toInt(), 12); + + // writing to an offline device fails cleanly too + controller.setCurrentDeviceId(u"B03700000000-3F51C045"_s); + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady() && !controller.isLoading(), Timeout); + QVERIFY(!controller.needsSave()); // edits do not follow to another device + controller.settings()->stage(controller.settings()->indexOf(u"dpi"_s), 1200.0); + QVERIFY(save(controller, false)); + QVERIFY(!controller.saveError().isEmpty()); + QVERIFY(!controller.settings()->writeError(controller.settings()->indexOf(u"dpi"_s)).isEmpty()); + } + + void appliesButtonActions() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + StagedModel *buttons = controller.buttons(); + const int haptic = buttons->indexOf(u"416"_s); + QCOMPARE(buttons->liveValue(haptic).toMap().value(u"press"_s).toMap(), action(u"kwin"_s, u"Overview"_s)); + + buttons->stageKey(haptic, u"mode"_s, u"gesture"_s); + buttons->stagePath(haptic, {u"gestures"_s, u"up"_s}, action(u"kwin"_s, u"Grid View"_s)); + buttons->stagePath(haptic, {u"gestures"_s, u"click"_s}, action(u"mediacontrol"_s, u"playpausemedia"_s)); + QVERIFY(save(controller)); + QVERIFY(!controller.needsSave()); + + const QVariantMap onService = deviceButton(MX4, 416); + QCOMPARE(onService.value(u"mode"_s).toString(), u"gesture"_s); + QCOMPARE(onService.value(u"gestures"_s).toMap().value(u"up"_s).toMap(), action(u"kwin"_s, u"Grid View"_s)); + QCOMPARE(onService.value(u"gestures"_s).toMap().value(u"click"_s).toMap(), action(u"mediacontrol"_s, u"playpausemedia"_s)); + // the service diverts the button for gestures, and says so + const int divert = controller.settings()->indexOf(u"divert-keys"_s); + QTRY_COMPARE_WITH_TIMEOUT(controller.settings()->liveValue(divert).toMap().value(u"416"_s).toInt(), 2, Timeout); + + // clearing an action + buttons->stagePath(haptic, {u"gestures"_s, u"click"_s}, QVariant::fromValue(nullptr)); + QVERIFY(save(controller)); + QVERIFY(deviceButton(MX4, 416).value(u"gestures"_s).toMap().value(u"click"_s).isNull()); + } + + void appliesHapticEvents() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + StagedModel *events = controller.hapticEvents(); + events->stage(events->indexOf(u"battery_low"_s), u"WAVE"_s); + events->stage(events->indexOf(u"notification"_s), QVariant::fromValue(nullptr)); + QVERIFY(save(controller)); + const QVariantList onService = api(u"GetHapticEvents"_s, {MX4}).toMap().value(u"events"_s).toList(); + for (const QVariant &event : onService) { + const QVariantMap map = event.toMap(); + if (map.value(u"event"_s) == u"battery_low"_s) { + QCOMPARE(map.value(u"waveform"_s).toString(), u"WAVE"_s); + } else if (map.value(u"event"_s) == u"notification"_s) { + QVERIFY(map.value(u"waveform"_s).isNull()); + } + } + QVERIFY(!controller.needsSave()); + + // playing a waveform is immediate and has no visible effect besides errors + controller.playHaptic(u"NOT A WAVEFORM"_s); + QTRY_VERIFY_WITH_TIMEOUT(!controller.notice().isEmpty(), Timeout); + controller.clearNotice(); + controller.playHaptic(u"WAVE"_s); + QTest::qWait(300); + QVERIFY(controller.notice().isEmpty()); + } + + void tracksServiceAvailability() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + controller.settings()->stage(controller.settings()->indexOf(u"dpi"_s), 2000.0); + + mock(u"Quit"_s, {}); + QTRY_COMPARE_WITH_TIMEOUT(controller.serviceState(), Controller::ServiceState::Missing, Timeout); + QVERIFY(controller.devices().isEmpty()); + QCOMPARE(controller.settings()->count(), 0); + QVERIFY(!controller.needsSave()); + m_mock->waitForFinished(5000); + delete m_mock; + m_mock = nullptr; + + // no systemd on the private bus: starting the service reports why it failed + controller.startService(); + QTRY_VERIFY_WITH_TIMEOUT(!controller.notice().isEmpty(), Timeout); + + startMock(); + QTRY_COMPARE_WITH_TIMEOUT(controller.serviceState(), Controller::ServiceState::Running, Timeout); + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + QCOMPARE(controller.devices().size(), 3); + QCOMPARE(controller.settings()->count(), 15); + } + + void degradesWithAnOlderService() + { + Controller controller; + controller.load(); // as the KCM host does + QTRY_VERIFY_WITH_TIMEOUT(controller.isReady(), Timeout); + QCOMPARE(controller.settings()->count(), 15); + QCOMPARE(controller.buttonsState(), Controller::FeatureState::NeedsNewerService); + QCOMPARE(controller.hapticEventsState(), Controller::FeatureState::NeedsNewerService); + QCOMPARE(controller.kdeActionsState(), Controller::FeatureState::NeedsNewerService); + QVERIFY(!controller.hasDefaults()); // no "default" in the settings: the Defaults button stays off + QCOMPARE(controller.waveforms().size(), 16); // from the haptic-play setting + controller.settings()->stage(controller.settings()->indexOf(u"dpi"_s), 2000.0); + QVERIFY(save(controller)); + } +}; + +QTEST_GUILESS_MAIN(ControllerTest) + +#include "controllertest.moc" diff --git a/kcm/autotests/isolated-bus.conf b/kcm/autotests/isolated-bus.conf new file mode 100644 index 00000000..ae460873 --- /dev/null +++ b/kcm/autotests/isolated-bus.conf @@ -0,0 +1,19 @@ + + + + session + + unix:tmpdir=/tmp + EXTERNAL + + + + + + diff --git a/kcm/autotests/qmllint.py b/kcm/autotests/qmllint.py new file mode 100644 index 00000000..17ecd634 --- /dev/null +++ b/kcm/autotests/qmllint.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 plasmaar contributors +# SPDX-License-Identifier: GPL-2.0-or-later +"""Run qmllint on the module's QML and fail on any warning, except unqualified access to the names that +KCMUtils and KI18n put into the QML context (the `kcm` object, i18n() and friends): qmllint cannot know +about context properties, and these are the documented way to reach them in a KCM. + + kcm/autotests/qmllint.py QMLLINT BUILD_BIN_DIR FILE.qml... +""" + +import json +import re +import subprocess +import sys + +CONTEXT_NAMES = {"kcm", "i18n", "i18nc", "i18np", "i18ncp", "xi18n", "xi18nc", "xi18np", "xi18ncp"} + + +def main(qmllint, import_dir, files): + result = subprocess.run([qmllint, "--json", "-", "-I", import_dir, *files], capture_output=True, text=True) + try: + report = json.loads(result.stdout) + except ValueError: + print(result.stdout, result.stderr, sep="\n") + return 1 + problems = 0 + for entry in report.get("files", []): + filename = entry["filename"] + lines = open(filename, encoding="utf-8").read().splitlines() + for warning in entry.get("warnings", []): + if warning.get("type") == "info": + continue + line, column = warning.get("line", 0), warning.get("column", 0) + source = lines[line - 1] if 0 < line <= len(lines) else "" + name = re.match(r"[A-Za-z_][A-Za-z0-9_]*", source[column - 1 :] if column else "") + if warning.get("id") in ("unqualified", "context-properties") and name and name.group(0) in CONTEXT_NAMES: + continue + problems += 1 + print(f"{filename}:{line}:{column}: {warning.get('type')}: {warning.get('message')} [{warning.get('id')}]") + if source: + print(" " + source.strip()) + if not entry.get("success", True) and not entry.get("warnings"): + problems += 1 + print(f"{filename}: qmllint failed") + print(f"qmllint: {len(report.get('files', []))} files, {problems} problem(s)") + return 1 if problems else 0 + + +if __name__ == "__main__": + if len(sys.argv) < 4: + print(__doc__) + sys.exit(2) + sys.exit(main(sys.argv[1], sys.argv[2], sys.argv[3:])) diff --git a/kcm/autotests/stagedmodeltest.cpp b/kcm/autotests/stagedmodeltest.cpp new file mode 100644 index 00000000..93234271 --- /dev/null +++ b/kcm/autotests/stagedmodeltest.cpp @@ -0,0 +1,211 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +// The staging rules behind the KCM's Apply/Reset/Defaults, without D-Bus. + +#include "json.h" +#include "stagedmodel.h" + +#include +#include + +using namespace Qt::StringLiterals; + +namespace +{ +QVariantMap setting(const QString &name, const QVariant &value, const QVariant &defaultValue = {}) +{ + QVariantMap entry{{u"name"_s, name}, {u"label"_s, name.toUpper()}, {u"value"_s, value}}; + if (defaultValue.isValid()) { + entry.insert(u"default"_s, defaultValue); + } + return entry; +} + +QVariantMap map(std::initializer_list> items) +{ + QVariantMap result; + for (const auto &[key, value] : items) { + result.insert(key, value); + } + return result; +} +} + +class StagedModelTest : public QObject +{ + Q_OBJECT + +private: + StagedModel *settings(QObject *parent) + { + auto *model = new StagedModel(u"name"_s, {u"value"_s}, {u"name"_s, u"label"_s}, parent); + model->setEntries({ + setting(u"dpi"_s, 1600, 1000), + setting(u"smart-shift"_s, 12, 12), + setting(u"change-host"_s, 2), + setting(u"divert-keys"_s, map({{u"82"_s, 0}, {u"195"_s, 2}}), map({{u"82"_s, 0}, {u"195"_s, 0}})), + }); + return model; + } + +private Q_SLOTS: + void jsonRoundTrip() + { + QCOMPARE(Json::serialize(QVariant(2000.0)), u"2000"_s); // QML numbers are doubles + QCOMPARE(Json::serialize(QVariant(true)), u"true"_s); + QCOMPARE(Json::serialize(QVariant::fromValue(nullptr)), u"null"_s); + QCOMPARE(Json::serialize(map({{u"mode"_s, u"press"_s}})), uR"({"mode":"press"})"_s); + QCOMPARE(Json::parse(u"1200"_s).toInt(), 1200); + QVERIFY(Json::parse(u"null"_s).isNull()); + bool ok = true; + Json::parse(u"{oops"_s, &ok); + QVERIFY(!ok); + QVERIFY(Json::equal(QVariant(qlonglong(5)), QVariant(5.0))); + QVERIFY(!Json::equal(QVariant(true), QVariant(1))); + QVERIFY(Json::equal(map({{u"a"_s, 1}, {u"b"_s, 2}}), map({{u"b"_s, 2.0}, {u"a"_s, 1}}))); + } + + void stagingTheLiveValueUnstages() + { + QObject parent; + StagedModel *model = settings(&parent); + const int dpi = model->indexOf(u"dpi"_s); + QVERIFY(!model->hasChanges()); + + model->stage(dpi, 2000.0); + QVERIFY(model->hasChanges()); + QCOMPARE(model->pendingValue(dpi).toInt(), 2000); + QCOMPARE(model->liveValue(dpi).toInt(), 1600); + QCOMPARE(model->data(model->index(dpi), StagedModel::ChangedRole).toBool(), true); + + model->stage(dpi, 1600.0); // back to what the device has: nothing to apply + QVERIFY(!model->hasChanges()); + QCOMPARE(model->changes().size(), 0); + } + + void perKeyEditsOnlyTouchTheirKey() + { + QObject parent; + StagedModel *model = settings(&parent); + const int row = model->indexOf(u"divert-keys"_s); + + model->stageKey(row, u"82"_s, 1); + const auto changes = model->changes(); + QCOMPARE(changes.size(), 1); + QCOMPARE(changes.first().changedKeys, QStringList{u"82"_s}); + QCOMPARE(changes.first().pending.toMap().value(u"195"_s).toInt(), 2); + + // the device changes another key meanwhile: the edit survives, the other key follows the device + QVERIFY(model->setLiveValue(u"divert-keys"_s, map({{u"82"_s, 0}, {u"195"_s, 0}}))); + const QVariantMap pending = model->pendingValue(row).toMap(); + QCOMPARE(pending.value(u"82"_s).toInt(), 1); + QCOMPARE(pending.value(u"195"_s).toInt(), 0); + QCOMPARE(model->changes().first().changedKeys, QStringList{u"82"_s}); + + // and once the device has the edited value, nothing is left to apply + QVERIFY(model->setLiveValue(u"divert-keys"_s, map({{u"82"_s, 1}, {u"195"_s, 0}}))); + QVERIFY(!model->hasChanges()); + } + + void nestedPaths() + { + QObject parent; + StagedModel model(u"control"_s, {u"mode"_s, u"press"_s, u"gestures"_s}, {u"name"_s}, &parent); + model.setEntries({QVariantMap{ + {u"control"_s, 195}, + {u"name"_s, u"Gesture"_s}, + {u"mode"_s, u"off"_s}, + {u"press"_s, QVariant::fromValue(nullptr)}, + {u"gestures"_s, map({{u"up"_s, QVariant::fromValue(nullptr)}, {u"down"_s, QVariant::fromValue(nullptr)}})}, + }}); + const QVariantMap overview = map({{u"component"_s, u"kwin"_s}, {u"action"_s, u"Overview"_s}}); + model.stageKey(0, u"mode"_s, u"gesture"_s); + model.stagePath(0, {u"gestures"_s, u"up"_s}, overview); + const QVariantMap pending = model.pendingValue(0).toMap(); + QCOMPARE(pending.value(u"mode"_s).toString(), u"gesture"_s); + QCOMPARE(pending.value(u"gestures"_s).toMap().value(u"up"_s).toMap(), overview); + QVERIFY(pending.value(u"gestures"_s).toMap().value(u"down"_s).isNull()); + QCOMPARE(Json::serialize(pending.value(u"press"_s)), u"null"_s); + + // the service answers with the whole button: it becomes the live value + QVariantMap reply = model.get(0); + reply.insert(u"mode"_s, u"gesture"_s); + reply.insert(u"gestures"_s, pending.value(u"gestures"_s)); + QVERIFY(model.setLiveEntry(reply)); + QVERIFY(!model.hasChanges()); + } + + void defaults() + { + QObject parent; + StagedModel *model = settings(&parent); + QVERIFY(model->hasDefaults()); + QVERIFY(!model->atDefaults()); // dpi and divert-keys differ + + model->stageDefaults(); + QVERIFY(model->atDefaults()); + QCOMPARE(model->pendingValue(model->indexOf(u"dpi"_s)).toInt(), 1000); + QCOMPARE(model->pendingValue(model->indexOf(u"change-host"_s)).toInt(), 2); // no default: untouched + QCOMPARE(model->changes().size(), 2); + + model->discard(); + QVERIFY(!model->hasChanges()); + QVERIFY(!model->atDefaults()); + + StagedModel none(u"name"_s, {u"value"_s}, {}, &parent); + none.setEntries({setting(u"change-host"_s, 2)}); + QVERIFY(!none.hasDefaults()); + QVERIFY(none.atDefaults()); + } + + void refreshKeepsRowsAndOptionallyEdits() + { + QObject parent; + StagedModel *model = settings(&parent); + const QVariantList entries = model->entries(); + QSignalSpy resets(model, &QAbstractItemModel::modelReset); + QSignalSpy changes(model, &QAbstractItemModel::dataChanged); + + model->stage(model->indexOf(u"dpi"_s), 2000); + model->setEntries(entries, true); // same keys: updated in place, edits kept + QCOMPARE(resets.count(), 0); + QVERIFY(changes.count() > 0); + QVERIFY(model->hasChanges()); + + model->setEntries(entries, false); // Reset + QCOMPARE(resets.count(), 0); + QVERIFY(!model->hasChanges()); + + model->setEntries(entries.mid(1)); // other entries (another device): a real reset + QCOMPARE(resets.count(), 1); + QCOMPARE(model->count(), 3); + } + + void errorsAndReadErrors() + { + QObject parent; + StagedModel model(u"name"_s, {u"value"_s}, {u"readError=error"_s}, &parent); + QVariantMap broken = setting(u"dpi"_s, QVariant::fromValue(nullptr)); + broken.insert(u"error"_s, u"device asleep"_s); + model.setEntries({broken}); + const int readErrorRole = StagedModel::FirstFieldRole; + QCOMPARE(model.roleNames().value(readErrorRole), QByteArray("readError")); + QCOMPARE(model.data(model.index(0), readErrorRole).toString(), u"device asleep"_s); + + model.stage(0, 1000); + model.setError(0, u"refused"_s); + QVERIFY(model.hasErrors()); + QCOMPARE(model.writeError(0), u"refused"_s); + model.stage(0, 1200); // editing again clears the error + QVERIFY(!model.hasErrors()); + + model.setLiveValue(u"dpi"_s, 1200); // a value arrived: readable now, and nothing left to apply + QVERIFY(model.data(model.index(0), readErrorRole).isNull()); + QVERIFY(!model.hasChanges()); + } +}; + +QTEST_GUILESS_MAIN(StagedModelTest) + +#include "stagedmodeltest.moc" diff --git a/kcm/kcm_plasmaar.json b/kcm/kcm_plasmaar.json new file mode 100644 index 00000000..e5d065f8 --- /dev/null +++ b/kcm/kcm_plasmaar.json @@ -0,0 +1,19 @@ +{ + "KPlugin": { + "Authors": [ + { + "Name": "plasmaar contributors" + } + ], + "Description": "Buttons, gestures, haptics, scrolling and sensitivity of Logitech mice and keyboards", + "Description[fr]": "Boutons, gestes, retour haptique, défilement et sensibilité des souris et claviers Logitech", + "Icon": "input-mouse", + "License": "GPL-2.0-or-later", + "Name": "Logitech Devices", + "Name[fr]": "Périphériques Logitech", + "Website": "https://github.com/fredaime/plasmaar" + }, + "X-KDE-Keywords": "Logitech,mouse,keyboard,MX Master,buttons,gestures,haptic,haptics,DPI,sensitivity,scroll wheel,Smart Shift,HID++,plasmaar,Solaar", + "X-KDE-Keywords[fr]": "Logitech,souris,clavier,MX Master,boutons,gestes,haptique,retour haptique,DPI,sensibilité,molette,défilement,Smart Shift,HID++,plasmaar,Solaar", + "X-KDE-System-Settings-Parent-Category": "inputdevices" +} diff --git a/kcm/plasmaar-kcm.sh.in b/kcm/plasmaar-kcm.sh.in new file mode 100644 index 00000000..6987113c --- /dev/null +++ b/kcm/plasmaar-kcm.sh.in @@ -0,0 +1,3 @@ +# Installed by `make install_kcm` into ~/.config/plasma-workspace/env/, which Plasma sources at login: +# lets System Settings find the plasmaar module installed under @CMAKE_INSTALL_PREFIX@. +export QT_PLUGIN_PATH="@KDE_INSTALL_FULL_PLUGINDIR@${QT_PLUGIN_PATH:+:$QT_PLUGIN_PATH}" diff --git a/kcm/po/fr/kcm_plasmaar.po b/kcm/po/fr/kcm_plasmaar.po new file mode 100644 index 00000000..8e4145b3 --- /dev/null +++ b/kcm/po/fr/kcm_plasmaar.po @@ -0,0 +1,564 @@ +# French translation of kcm_plasmaar, the plasmaar System Settings module. +# SPDX-FileCopyrightText: 2026 plasmaar contributors +# SPDX-License-Identifier: GPL-2.0-or-later +# +msgid "" +msgstr "" +"Project-Id-Version: kcm_plasmaar\n" +"Report-Msgid-Bugs-To: https://github.com/fredaime/plasmaar/issues\n" +"POT-Creation-Date: 2026-10-03 00:00+0200\n" +"PO-Revision-Date: 2026-10-03 00:00+0200\n" +"Last-Translator: plasmaar contributors\n" +"Language-Team: French\n" +"Language: fr\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=2; plural=(n > 1);\n" + +#: src/controller.cpp:525 +msgid "The device is switched off, asleep or out of range." +msgstr "Le périphérique est éteint, en veille ou hors de portée." + +#: src/controller.cpp:528 +msgid "The device is no longer connected." +msgstr "Le périphérique n'est plus connecté." + +#: src/controller.cpp:531 +msgid "The device no longer has this setting." +msgstr "Le périphérique n'a plus ce réglage." + +#: src/controller.cpp:534 +msgid "The value was refused: %1" +msgstr "La valeur a été refusée : %1" + +#: src/controller.cpp:537 +msgid "The device does not support this." +msgstr "Le périphérique ne prend pas cela en charge." + +#: src/controller.cpp:540 +msgid "The plasmaard service is not running." +msgstr "Le service plasmaard n'est pas lancé." + +#: src/controller.cpp:543 +msgid "The plasmaard service did not answer in time." +msgstr "Le service plasmaard n'a pas répondu à temps." + +#: src/controller.cpp:598 +msgid "One change could not be applied:" +msgid_plural "%1 changes could not be applied:" +msgstr[0] "Une modification n'a pas pu être appliquée :" +msgstr[1] "%1 modifications n'ont pas pu être appliquées :" + +#: src/controller.cpp:616 +msgctxt "@info failed write: setting label, error message" +msgid "%1: %2" +msgstr "%1 : %2" + +#: src/controller.cpp:683 +msgid "Could not play the effect: %1" +msgstr "Impossible de jouer l'effet : %1" + +#: src/controller.cpp:693 +msgid "Could not start plasmaard: %1" +msgstr "Impossible de démarrer plasmaard : %1" + +#: src/controller.cpp:710 +msgctxt "@label a KDE action that is not in the list: action name, component" +msgid "%1 (%2)" +msgstr "%1 (%2)" + +#: ui/ActionField.qml:35 +msgctxt "@action:button" +msgid "Choose an Action…" +msgstr "Choisir une action…" + +#: ui/ActionField.qml:41 +msgctxt "@info:tooltip KDE action: component, action id" +msgid "%1 › %2" +msgstr "%1 › %2" + +#: ui/ActionField.qml:49 +msgctxt "@action:button" +msgid "Remove Action" +msgstr "Retirer l'action" + +#: ui/ButtonsPage.qml:37 +msgctxt "@label:chooser gesture direction" +msgid "Swipe up:" +msgstr "Glisser vers le haut :" + +#: ui/ButtonsPage.qml:38 +msgctxt "@label:chooser gesture direction" +msgid "Swipe down:" +msgstr "Glisser vers le bas :" + +#: ui/ButtonsPage.qml:39 +msgctxt "@label:chooser gesture direction" +msgid "Swipe left:" +msgstr "Glisser vers la gauche :" + +#: ui/ButtonsPage.qml:40 +msgctxt "@label:chooser gesture direction" +msgid "Swipe right:" +msgstr "Glisser vers la droite :" + +#: ui/ButtonsPage.qml:41 +msgctxt "@label:chooser gesture button pressed and released without moving" +msgid "Click without swiping:" +msgstr "Clic sans glisser :" + +#: ui/ButtonsPage.qml:47 +msgctxt "@item:inlistbox button mode" +msgid "Normal (its usual function)" +msgstr "Normal (sa fonction habituelle)" + +#: ui/ButtonsPage.qml:49 +msgctxt "@item:inlistbox button mode" +msgid "Run an action when pressed" +msgstr "Lancer une action à l'appui" + +#: ui/ButtonsPage.qml:51 +msgctxt "@item:inlistbox button mode" +msgid "Gestures: hold, swipe and release" +msgstr "Gestes : maintenir, glisser, relâcher" + +#: ui/ButtonsPage.qml:68 +msgctxt "@info:placeholder" +msgid "Button actions need a newer plasmaard" +msgstr "Les actions des boutons nécessitent un plasmaard plus récent" + +#: ui/ButtonsPage.qml:70 +msgctxt "@info:placeholder" +msgid "The running plasmaard service cannot configure button actions yet. Update it, or map the buttons in ~/.config/plasmaar/rules.yaml for now." +msgstr "Le service plasmaard lancé ne sait pas encore configurer les actions des boutons. Mettez-le à jour, ou en attendant associez les boutons dans ~/.config/plasmaar/rules.yaml." + +#: ui/ButtonsPage.qml:77 +msgctxt "@info" +msgid "The button actions could not be read." +msgstr "Les actions des boutons n'ont pas pu être lues." + +#: ui/ButtonsPage.qml:86 +msgctxt "@info" +msgid "The list of KDE actions is not available, so actions cannot be chosen right now." +msgstr "La liste des actions de KDE n'est pas disponible : impossible de choisir une action pour l'instant." + +#: ui/ButtonsPage.qml:98 +msgctxt "@info" +msgid "Buttons set to an action or to gestures run KDE Plasma actions instead of their usual function. For a gesture, hold the button, move the mouse in one direction and release it." +msgstr "Les boutons réglés sur une action ou sur des gestes lancent des actions de KDE Plasma à la place de leur fonction habituelle. Pour un geste, maintenez le bouton, déplacez la souris dans une direction et relâchez-le." + +#: ui/ButtonsPage.qml:99 +msgctxt "@info" +msgid "Keys set to an action run a KDE Plasma action instead of their usual function." +msgstr "Les touches réglées sur une action lancent une action de KDE Plasma à la place de leur fonction habituelle." + +#: ui/ButtonsPage.qml:133 +msgctxt "@label:listbox" +msgid "Behavior:" +msgstr "Comportement :" + +#: ui/ButtonsPage.qml:158 +msgctxt "@label:chooser" +msgid "Action:" +msgstr "Action :" + +#: ui/ButtonsPage.qml:180 +msgctxt "@info:placeholder button, gesture direction" +msgid "%1, %2" +msgstr "%1, %2" + +#: ui/DeviceHeader.qml:49 +msgctxt "@info battery state" +msgid "discharging" +msgstr "en décharge" + +#: ui/DeviceHeader.qml:52 +msgctxt "@info battery state" +msgid "charging" +msgstr "en charge" + +#: ui/DeviceHeader.qml:54 +msgctxt "@info battery state" +msgid "fully charged" +msgstr "chargée" + +#: ui/DeviceHeader.qml:56 +msgctxt "@info battery state" +msgid "almost full" +msgstr "presque pleine" + +#: ui/DeviceHeader.qml:60 +msgctxt "@info battery state" +msgid "battery error" +msgstr "erreur de batterie" + +#: ui/DeviceHeader.qml:67 +msgctxt "@item:inlistbox device that is switched off" +msgid "%1 (offline)" +msgstr "%1 (hors ligne)" + +#: ui/DeviceHeader.qml:101 +msgctxt "@info device state" +msgid "Connected" +msgstr "Connecté" + +#: ui/DeviceHeader.qml:101 +msgctxt "@info device state" +msgid "Offline: switched off, asleep or out of range" +msgstr "Hors ligne : éteint, en veille ou hors de portée" + +#: ui/DeviceHeader.qml:117 +msgctxt "@info battery level" +msgid "%1%" +msgstr "%1 %" + +#: ui/DeviceHeader.qml:119 +msgctxt "@info battery level, state" +msgid "%1 (%2)" +msgstr "%1 (%2)" + +#: ui/DeviceHeader.qml:136 +msgctxt "@info device id" +msgid "Model %1" +msgstr "Modèle %1" + +#: ui/DeviceHeader.qml:139 +msgctxt "@info device id" +msgid "Unit %1" +msgstr "Unité %1" + +#: ui/DeviceHeader.qml:142 +msgctxt "@info device id" +msgid "Serial %1" +msgstr "N° de série %1" + +#: ui/DeviceHeader.qml:145 +msgctxt "@info protocol version" +msgid "HID++ %1" +msgstr "HID++ %1" + +#: ui/DeviceHeader.qml:170 +msgctxt "@info:tooltip" +msgid "Choose the device to configure" +msgstr "Choisir le périphérique à configurer" + +#: ui/DeviceHeader.qml:171 +msgctxt "@info:tooltip" +msgid "Apply or reset your changes before switching to another device" +msgstr "Appliquez ou annulez vos modifications avant de passer à un autre périphérique" + +#: ui/HapticsPage.qml:28 +msgctxt "@item haptic waveform" +msgid "Sharp state change" +msgstr "Changement d'état net" + +#: ui/HapticsPage.qml:30 +msgctxt "@item haptic waveform" +msgid "Damped state change" +msgstr "Changement d'état amorti" + +#: ui/HapticsPage.qml:32 +msgctxt "@item haptic waveform" +msgid "Sharp collision" +msgstr "Choc net" + +#: ui/HapticsPage.qml:34 +msgctxt "@item haptic waveform" +msgid "Damped collision" +msgstr "Choc amorti" + +#: ui/HapticsPage.qml:36 +msgctxt "@item haptic waveform" +msgid "Subtle collision" +msgstr "Choc léger" + +#: ui/HapticsPage.qml:38 +msgctxt "@item haptic waveform" +msgid "Whisper collision" +msgstr "Choc murmuré" + +#: ui/HapticsPage.qml:40 +msgctxt "@item haptic waveform" +msgid "Happy alert" +msgstr "Alerte joyeuse" + +#: ui/HapticsPage.qml:42 +msgctxt "@item haptic waveform" +msgid "Angry alert" +msgstr "Alerte agacée" + +#: ui/HapticsPage.qml:44 +msgctxt "@item haptic waveform" +msgid "Completed" +msgstr "Terminé" + +#: ui/HapticsPage.qml:46 +msgctxt "@item haptic waveform" +msgid "Square" +msgstr "Carré" + +#: ui/HapticsPage.qml:48 +msgctxt "@item haptic waveform" +msgid "Wave" +msgstr "Vague" + +#: ui/HapticsPage.qml:50 +msgctxt "@item haptic waveform" +msgid "Firework" +msgstr "Feu d'artifice" + +#: ui/HapticsPage.qml:52 +msgctxt "@item haptic waveform" +msgid "Mad" +msgstr "Colère" + +#: ui/HapticsPage.qml:54 +msgctxt "@item haptic waveform" +msgid "Knock" +msgstr "Toc-toc" + +#: ui/HapticsPage.qml:56 +msgctxt "@item haptic waveform" +msgid "Jingle" +msgstr "Ritournelle" + +#: ui/HapticsPage.qml:58 +msgctxt "@item haptic waveform" +msgid "Ringing" +msgstr "Sonnerie" + +#: ui/HapticsPage.qml:79 +msgctxt "@info" +msgid "The device is offline. Switch it on or wake it up to feel the effects." +msgstr "Le périphérique est hors ligne. Allumez-le ou réveillez-le pour ressentir les effets." + +#: ui/HapticsPage.qml:93 +msgctxt "@label:slider" +msgid "Intensity:" +msgstr "Intensité :" + +#: ui/HapticsPage.qml:99 +msgctxt "@title:group" +msgid "Try the Effects" +msgstr "Essayer les effets" + +#: ui/HapticsPage.qml:104 +msgctxt "@label" +msgid "Play:" +msgstr "Jouer :" + +#: ui/HapticsPage.qml:127 +msgctxt "@title:group" +msgid "Desktop Events" +msgstr "Événements du bureau" + +#: ui/HapticsPage.qml:144 +msgctxt "@label:listbox desktop event" +msgid "%1:" +msgstr "%1 :" + +#: ui/HapticsPage.qml:152 +msgctxt "@item:inlistbox no haptic effect" +msgid "None" +msgstr "Aucun" + +#: ui/HapticsPage.qml:167 +msgctxt "@action:button" +msgid "Try It" +msgstr "Essayer" + +#: ui/HapticsPage.qml:194 +msgctxt "@info" +msgid "Haptic feedback for desktop events needs a newer plasmaard." +msgstr "Le retour haptique pour les événements du bureau nécessite un plasmaard plus récent." + +#: ui/KeyCell.qml:49 ui/KeyCell.qml:68 ui/KeyCell.qml:84 +msgctxt "@label accessible name: setting, key" +msgid "%1, %2" +msgstr "%1, %2" + +#: ui/KeyCell.qml:62 +msgctxt "@title:window setting, key" +msgid "%1: %2" +msgstr "%1 : %2" + +#: ui/KeyMapTable.qml:98 +msgctxt "@title:group" +msgid "Keys and Buttons" +msgstr "Touches et boutons" + +#: ui/KeyMapTable.qml:163 +msgctxt "@label:key name in the key table" +msgid "%1:" +msgstr "%1 :" + +#: ui/PickerDialog.qml:21 +msgctxt "@info:placeholder search field: what is being chosen" +msgid "Search: %1" +msgstr "Rechercher : %1" + +#: ui/PickerDialog.qml:64 +msgctxt "@info:placeholder" +msgid "No match" +msgstr "Aucun résultat" + +#: ui/SettingRow.qml:55 +msgctxt "@info setting value" +msgid "On" +msgstr "Activé" + +#: ui/SettingRow.qml:55 +msgctxt "@info setting value" +msgid "Off" +msgstr "Désactivé" + +#: ui/SettingRow.qml:62 +msgctxt "@info no flag is set" +msgid "None" +msgstr "Aucune" + +#: ui/SettingRow.qml:70 +msgctxt "@label:setting form label" +msgid "%1:" +msgstr "%1 :" + +#: ui/SettingRow.qml:236 +msgctxt "@info setting value that cannot be changed here" +msgid "%1 (read-only)" +msgstr "%1 (lecture seule)" + +#: ui/SettingRow.qml:236 +msgctxt "@info" +msgid "Read-only" +msgstr "Lecture seule" + +#: ui/SettingRow.qml:247 +msgctxt "@info" +msgid "Could not be read: %1" +msgstr "Lecture impossible : %1" + +#: ui/SettingRow.qml:248 +msgctxt "@info" +msgid "Unknown while the device is offline" +msgstr "Inconnu tant que le périphérique est hors ligne" + +#: ui/SettingsPage.qml:26 +msgctxt "@title:group" +msgid "Scroll Wheel" +msgstr "Molette" + +#: ui/SettingsPage.qml:27 +msgctxt "@title:group" +msgid "Thumb Wheel" +msgstr "Molette de pouce" + +#: ui/SettingsPage.qml:28 +msgctxt "@title:group" +msgid "Pointer" +msgstr "Pointeur" + +#: ui/SettingsPage.qml:29 +msgctxt "@title:group" +msgid "Buttons" +msgstr "Boutons" + +#: ui/SettingsPage.qml:30 +msgctxt "@title:group" +msgid "Keyboard" +msgstr "Clavier" + +#: ui/SettingsPage.qml:31 +msgctxt "@title:group" +msgid "Lighting" +msgstr "Éclairage" + +#: ui/SettingsPage.qml:32 +msgctxt "@title:group" +msgid "Audio" +msgstr "Audio" + +#: ui/SettingsPage.qml:33 +msgctxt "@title:group" +msgid "Connection" +msgstr "Connexion" + +#: ui/SettingsPage.qml:34 +msgctxt "@title:group" +msgid "Other Settings" +msgstr "Autres réglages" + +#: ui/SettingsPage.qml:88 +msgctxt "@info" +msgid "The device is offline. These are the last known values; switch it on or wake it up to change them." +msgstr "Le périphérique est hors ligne. Voici les dernières valeurs connues ; allumez-le ou réveillez-le pour les modifier." + +#: ui/SettingsPage.qml:95 +msgctxt "@info" +msgid "The settings could not be read: %1" +msgstr "Les réglages n'ont pas pu être lus : %1" + +#: ui/SettingsPage.qml:103 +msgctxt "@info:placeholder" +msgid "This device has no settings" +msgstr "Ce périphérique n'a aucun réglage" + +#: ui/main.qml:26 +msgctxt "@title:tab" +msgid "Settings" +msgstr "Réglages" + +#: ui/main.qml:34 +msgctxt "@title:tab keyboard keys" +msgid "Keys" +msgstr "Touches" + +#: ui/main.qml:34 +msgctxt "@title:tab" +msgid "Buttons" +msgstr "Boutons" + +#: ui/main.qml:42 +msgctxt "@title:tab" +msgid "Haptic Feedback" +msgstr "Retour haptique" + +#: ui/main.qml:190 +msgctxt "@info:placeholder" +msgid "Connecting to plasmaard…" +msgstr "Connexion à plasmaard…" + +#: ui/main.qml:198 +msgctxt "@info:placeholder" +msgid "The plasmaard service is not running" +msgstr "Le service plasmaard n'est pas lancé" + +#: ui/main.qml:200 +msgctxt "@info:placeholder" +msgid "Logitech devices are managed by the plasmaard user service. Start it here, or in a terminal with systemctl --user start plasmaard.It starts with your Plasma session once it is installed with make install_user_service." +msgstr "Les périphériques Logitech sont gérés par le service utilisateur plasmaard. Démarrez-le ici, ou dans un terminal avec systemctl --user start plasmaard.Il démarre avec votre session Plasma une fois installé avec make install_user_service." + +#: ui/main.qml:203 +msgctxt "@action:button" +msgid "Start plasmaard" +msgstr "Démarrer plasmaard" + +#: ui/main.qml:213 +msgctxt "@info:placeholder" +msgid "No Logitech device found" +msgstr "Aucun périphérique Logitech trouvé" + +#: ui/main.qml:214 +msgctxt "@info:placeholder" +msgid "Switch your mouse or keyboard on, or pair it with this computer over Bluetooth or a Logitech receiver." +msgstr "Allumez votre souris ou votre clavier, ou appairez-le avec cet ordinateur en Bluetooth ou via un récepteur Logitech." + +#: ui/main.qml:222 +msgctxt "@info:placeholder" +msgid "Search KDE actions…" +msgstr "Rechercher une action de KDE…" + +#: ui/main.qml:227 +msgctxt "@info:placeholder" +msgid "Search…" +msgstr "Rechercher…" diff --git a/kcm/run-snapshots.sh b/kcm/run-snapshots.sh new file mode 100755 index 00000000..80e93b2e --- /dev/null +++ b/kcm/run-snapshots.sh @@ -0,0 +1,91 @@ +#!/bin/bash +# SPDX-FileCopyrightText: 2026 plasmaar contributors +# SPDX-License-Identifier: GPL-2.0-or-later +# +# Render the module headless and save PNG snapshots of every page (see docs/kcm.md): +# +# kcm/run-snapshots.sh [options] PREFIX -> PREFIX--.png +# +# --build DIR build directory of kcm/ (default: kcm/build) +# --lang LANG UI language (default: fr) +# --legacy mock: v1 API only, like a plasmaard without the additions +# --fail NAME mock: make writes of this setting fail (repeatable) +# --scenario apply-errors +# mock: stage and apply a few edits first (use with --fail smart-shift) +# --no-service no service at all (the "plasmaard is not running" page) +# --real the plasmaard on your session bus instead of the mock (read-only: snapshot +# mode never writes, and --scenario is refused) +# +# The mock runs on a private D-Bus session without service activation, so nothing touches your devices or +# desktop services. The window is offscreen either way and never shows on screen. +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +repo=$(dirname "$here") +build="$here/build" +lang=fr +real=0 +service=1 +scenario="" +mock_args=() +while [ $# -gt 1 ]; do + case "$1" in + --build) build=$(cd "$2" && pwd); shift ;; + --lang) lang=$2; shift ;; + --legacy) mock_args+=(--legacy) ;; + --fail) mock_args+=(--fail "$2"); shift ;; + --scenario) scenario=$2; shift ;; + --no-service) service=0 ;; + --real) real=1 ;; + --inner) ;; + *) echo "unknown option $1" >&2; exit 2 ;; + esac + shift +done +prefix=${1:?"usage: $0 [options] PREFIX (see the top of this script)"} +mkdir -p "$(dirname "$prefix")" +prefix=$(cd "$(dirname "$prefix")" && pwd)/$(basename "$prefix") + +if [ ! -e "$build/bin/plasma/kcms/systemsettings/kcm_plasmaar.so" ]; then + echo "build the module first: cmake -S kcm -B $build && cmake --build $build" >&2 + exit 1 +fi + +run_module() { + export QT_QPA_PLATFORM=offscreen + export QT_PLUGIN_PATH="$build/bin${QT_PLUGIN_PATH:+:$QT_PLUGIN_PATH}" + export XDG_DATA_DIRS="$build:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}" # translations + export QT_QUICK_CONTROLS_STYLE=${QT_QUICK_CONTROLS_STYLE:-org.kde.desktop} + export QT_QPA_PLATFORMTHEME=${QT_QPA_PLATFORMTHEME:-kde} + export LANGUAGE=$lang + export PLASMAAR_KCM_SNAPSHOT=$prefix + export PLASMAAR_KCM_SNAPSHOT_SCENARIO=$scenario + timeout 180 kcmshell6 kcm_plasmaar +} + +if [ "$real" = 1 ]; then + if [ -n "$scenario" ]; then + echo "--scenario writes settings: only against the mock" >&2 + exit 2 + fi + run_module +elif [ -z "${PLASMAAR_SNAPSHOT_BUS:-}" ]; then + # re-run inside a private session bus + export QT_QPA_PLATFORM=offscreen + args=(--inner --build "$build" --lang "$lang") + [ -n "$scenario" ] && args+=(--scenario "$scenario") + [ "$service" = 0 ] && args+=(--no-service) + PLASMAAR_SNAPSHOT_BUS=1 exec dbus-run-session --config-file="$here/autotests/isolated-bus.conf" -- \ + "$0" "${args[@]}" "${mock_args[@]}" "$prefix" +else + if [ "$service" = 1 ]; then + LANGUAGE=$lang python3 "$repo/tools/mock_plasmaard.py" "${mock_args[@]}" & + mock=$! + trap 'kill $mock 2>/dev/null || true' EXIT + for _ in $(seq 50); do + busctl --user status io.github.fredaime.Plasmaar >/dev/null 2>&1 && break + sleep 0.1 + done + fi + run_module +fi diff --git a/kcm/screenshots/k850-settings.png b/kcm/screenshots/k850-settings.png new file mode 100644 index 00000000..ed9da37d Binary files /dev/null and b/kcm/screenshots/k850-settings.png differ diff --git a/kcm/screenshots/mx-master-4-action-picker.png b/kcm/screenshots/mx-master-4-action-picker.png new file mode 100644 index 00000000..daffd0c6 Binary files /dev/null and b/kcm/screenshots/mx-master-4-action-picker.png differ diff --git a/kcm/screenshots/mx-master-4-buttons.png b/kcm/screenshots/mx-master-4-buttons.png new file mode 100644 index 00000000..ad347c03 Binary files /dev/null and b/kcm/screenshots/mx-master-4-buttons.png differ diff --git a/kcm/screenshots/mx-master-4-haptics.png b/kcm/screenshots/mx-master-4-haptics.png new file mode 100644 index 00000000..57cf0a20 Binary files /dev/null and b/kcm/screenshots/mx-master-4-haptics.png differ diff --git a/kcm/screenshots/mx-master-4-settings.png b/kcm/screenshots/mx-master-4-settings.png new file mode 100644 index 00000000..8127ddd3 Binary files /dev/null and b/kcm/screenshots/mx-master-4-settings.png differ diff --git a/kcm/screenshots/offline-device.png b/kcm/screenshots/offline-device.png new file mode 100644 index 00000000..06bbd5fc Binary files /dev/null and b/kcm/screenshots/offline-device.png differ diff --git a/kcm/screenshots/older-plasmaard.png b/kcm/screenshots/older-plasmaard.png new file mode 100644 index 00000000..c0339f19 Binary files /dev/null and b/kcm/screenshots/older-plasmaard.png differ diff --git a/kcm/screenshots/plasmaard-not-running.png b/kcm/screenshots/plasmaard-not-running.png new file mode 100644 index 00000000..7df45348 Binary files /dev/null and b/kcm/screenshots/plasmaard-not-running.png differ diff --git a/kcm/screenshots/real-service-mx-master-4-buttons.png b/kcm/screenshots/real-service-mx-master-4-buttons.png new file mode 100644 index 00000000..5ae437ec Binary files /dev/null and b/kcm/screenshots/real-service-mx-master-4-buttons.png differ diff --git a/kcm/screenshots/write-errors.png b/kcm/screenshots/write-errors.png new file mode 100644 index 00000000..b7cc4e39 Binary files /dev/null and b/kcm/screenshots/write-errors.png differ diff --git a/kcm/src/controller.cpp b/kcm/src/controller.cpp new file mode 100644 index 00000000..c54be506 --- /dev/null +++ b/kcm/src/controller.cpp @@ -0,0 +1,758 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "controller.h" + +#include "json.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ +const QString MapChoice = QStringLiteral("MAP_CHOICE"); + +QVariantMap toMap(const QVariant &value) +{ + if (value.metaType() == QMetaType::fromType()) { + return value.value().toVariant().toMap(); + } + return value.toMap(); +} +} + +Controller::Controller(const QDBusConnection &bus, QObject *parent) + : QObject(parent) + , m_client(new PlasmaarClient(bus, this)) + , m_settings(new StagedModel(QStringLiteral("name"), + {QStringLiteral("value")}, + {QStringLiteral("name"), + QStringLiteral("label"), + QStringLiteral("description"), + QStringLiteral("kind"), + QStringLiteral("display"), + QStringLiteral("writable"), + QStringLiteral("choices"), + QStringLiteral("min"), + QStringLiteral("max"), + QStringLiteral("keys"), + QStringLiteral("readError=error")}, + this)) + , m_buttons(new StagedModel(QStringLiteral("control"), + {QStringLiteral("mode"), QStringLiteral("press"), QStringLiteral("gestures")}, + {QStringLiteral("control"), QStringLiteral("name"), QStringLiteral("modes")}, + this)) + , m_hapticEvents(new StagedModel(QStringLiteral("event"), {QStringLiteral("waveform")}, {QStringLiteral("event"), QStringLiteral("label")}, this)) + , m_snapshotPrefix(qEnvironmentVariable("PLASMAAR_KCM_SNAPSHOT")) + , m_snapshotScenario(qEnvironmentVariable("PLASMAAR_KCM_SNAPSHOT_SCENARIO")) +{ + for (StagedModel *model : {m_settings, m_buttons, m_hapticEvents}) { + connect(model, &StagedModel::stateChanged, this, &Controller::stagingChanged); + } + connect(m_settings, &StagedModel::stateChanged, this, [this] { + if (m_eventWaveforms.isEmpty()) { + Q_EMIT waveformsChanged(); // they come from the haptic-play setting then + } + }); + connect(m_client, &PlasmaarClient::serviceStateChanged, this, &Controller::onServiceStateChanged); + connect(m_client, &PlasmaarClient::deviceAdded, this, &Controller::upsertDevice); + connect(m_client, &PlasmaarClient::deviceChanged, this, &Controller::upsertDevice); + connect(m_client, &PlasmaarClient::deviceRemoved, this, &Controller::removeDevice); + connect(m_client, &PlasmaarClient::settingChanged, this, [this](const QString &deviceId, const QString &name, const QVariant &value) { + if (deviceId == m_currentDeviceId) { + m_settings->setLiveValue(name, value); + } + }); + connect(m_client, &PlasmaarClient::buttonActionsChanged, this, [this](const QString &deviceId) { + if (deviceId == m_currentDeviceId && m_buttonsState == FeatureState::Available) { + loadButtons(true); + } + }); +} + +QString Controller::snapshotScenario() const +{ + return m_snapshotScenario; +} + +PlasmaarClient *Controller::client() const +{ + return m_client; +} + +Controller::ServiceState Controller::serviceState() const +{ + switch (m_client->serviceState()) { + case PlasmaarClient::ServiceState::Running: + return ServiceState::Running; + case PlasmaarClient::ServiceState::Missing: + return ServiceState::Missing; + case PlasmaarClient::ServiceState::Checking: + break; + } + return ServiceState::Checking; +} + +bool Controller::isReady() const +{ + return m_ready; +} + +void Controller::updateReady() +{ + const ServiceState state = serviceState(); + const bool ready = state == ServiceState::Missing + || (state == ServiceState::Running && m_devicesLoaded && m_pending == 0 && m_kdeActionsState != FeatureState::Loading); + if (ready != m_ready) { + m_ready = ready; + Q_EMIT readyChanged(); + } +} + +QVariantList Controller::devices() const +{ + return m_devices; +} + +QString Controller::currentDeviceId() const +{ + return m_currentDeviceId; +} + +void Controller::setCurrentDeviceId(const QString &deviceId) +{ + if (deviceId == m_currentDeviceId) { + return; + } + m_currentDeviceId = deviceId; + Q_EMIT currentDeviceChanged(); + loadDevice(false); +} + +QVariantMap Controller::currentDevice() const +{ + for (const QVariant &device : m_devices) { + if (device.toMap().value(QStringLiteral("id")).toString() == m_currentDeviceId) { + return device.toMap(); + } + } + return {}; +} + +bool Controller::isLoading() const +{ + return m_loading; +} + +void Controller::setLoading(bool loading) +{ + if (m_loading != loading) { + m_loading = loading; + Q_EMIT loadingChanged(); + } +} + +bool Controller::isSaving() const +{ + return m_saving; +} + +StagedModel *Controller::settings() const +{ + return m_settings; +} + +StagedModel *Controller::buttons() const +{ + return m_buttons; +} + +StagedModel *Controller::hapticEvents() const +{ + return m_hapticEvents; +} + +Controller::FeatureState Controller::settingsState() const +{ + return m_settingsState; +} + +Controller::FeatureState Controller::buttonsState() const +{ + return m_buttonsState; +} + +Controller::FeatureState Controller::hapticEventsState() const +{ + return m_hapticEventsState; +} + +Controller::FeatureState Controller::kdeActionsState() const +{ + return m_kdeActionsState; +} + +QString Controller::settingsError() const +{ + return m_settingsError; +} + +QVariantList Controller::kdeActions() const +{ + return m_kdeActions; +} + +QStringList Controller::waveforms() const +{ + if (!m_eventWaveforms.isEmpty()) { + return m_eventWaveforms; + } + QStringList names; + const QVariantMap play = m_settings->get(m_settings->indexOf(QStringLiteral("haptic-play"))); + const QVariantList choices = play.value(QStringLiteral("choices")).toList(); + for (const QVariant &choice : choices) { + names.append(choice.toMap().value(QStringLiteral("name")).toString()); + } + return names; +} + +QString Controller::saveError() const +{ + return m_saveError; +} + +QString Controller::notice() const +{ + return m_notice; +} + +bool Controller::needsSave() const +{ + return m_settings->hasChanges() || m_buttons->hasChanges() || m_hapticEvents->hasChanges(); +} + +bool Controller::hasDefaults() const +{ + return m_settings->hasDefaults(); +} + +bool Controller::atDefaults() const +{ + return m_settings->atDefaults(); +} + +QString Controller::snapshotPrefix() const +{ + return m_snapshotPrefix; +} + +// --- loading --- + +void Controller::onServiceStateChanged() +{ + Q_EMIT serviceStateChanged(); // first: the page drops its views before the models are emptied + if (m_client->serviceState() == PlasmaarClient::ServiceState::Running) { + loadDevices(); + loadKdeActions(); + } else { + ++m_generation; + m_pending = 0; + m_loadedDeviceId.clear(); + setLoading(false); + m_devicesLoaded = false; + m_devices.clear(); + Q_EMIT devicesChanged(); + m_settings->setEntries({}); + m_buttons->setEntries({}); + m_hapticEvents->setEntries({}); + m_eventWaveforms.clear(); + Q_EMIT waveformsChanged(); + } + updateReady(); +} + +void Controller::load() +{ + m_settings->discard(); + m_buttons->discard(); + m_hapticEvents->discard(); + setSaveError(QString()); + setNotice(QString()); + if (m_client->serviceState() == PlasmaarClient::ServiceState::Running) { + loadDevices(); + } else { + m_client->checkService(); + } +} + +void Controller::loadDevices() +{ + m_client->call(QStringLiteral("ListDevices"), {}, this, [this](const QVariant &result, const PlasmaarClient::Error &error) { + m_devicesLoaded = true; + if (error.isError()) { + m_settingsError = describe(error); + setDevices({}); + } else { + setDevices(result.toList()); + } + updateReady(); + }); +} + +void Controller::setDevices(const QVariantList &devices) +{ + m_devices = devices; + Q_EMIT devicesChanged(); + if (currentDevice().isEmpty()) { + pickDevice(); + } else { + Q_EMIT currentDeviceChanged(); + loadDevice(false); + } +} + +void Controller::pickDevice() +{ + // the first online device, else the first one + QString first; + QString firstOnline; + for (const QVariant &device : std::as_const(m_devices)) { + const QVariantMap map = device.toMap(); + const QString id = map.value(QStringLiteral("id")).toString(); + if (first.isEmpty()) { + first = id; + } + if (firstOnline.isEmpty() && map.value(QStringLiteral("online")).toBool()) { + firstOnline = id; + } + } + m_currentDeviceId = firstOnline.isEmpty() ? first : firstOnline; + Q_EMIT currentDeviceChanged(); + loadDevice(false); +} + +void Controller::upsertDevice(const QVariantMap &device) +{ + const QString id = device.value(QStringLiteral("id")).toString(); + if (id.isEmpty()) { + return; + } + bool cameOnline = false; + bool found = false; + for (QVariant &existing : m_devices) { + if (existing.toMap().value(QStringLiteral("id")).toString() == id) { + cameOnline = !existing.toMap().value(QStringLiteral("online")).toBool() && device.value(QStringLiteral("online")).toBool(); + existing = device; + found = true; + break; + } + } + if (!found) { + m_devices.append(device); + } + Q_EMIT devicesChanged(); + if (m_currentDeviceId.isEmpty()) { + pickDevice(); + } else if (id == m_currentDeviceId) { + Q_EMIT currentDeviceChanged(); + if (cameOnline) { + loadDevice(true); // values that could not be read while it was away + } + } +} + +void Controller::removeDevice(const QString &deviceId) +{ + for (qsizetype i = 0; i < m_devices.size(); ++i) { + if (m_devices.at(i).toMap().value(QStringLiteral("id")).toString() == deviceId) { + m_devices.removeAt(i); + Q_EMIT devicesChanged(); + break; + } + } + if (deviceId == m_currentDeviceId) { + pickDevice(); + } +} + +void Controller::loadDevice(bool keepStaged) +{ + const quint64 generation = ++m_generation; + const QString id = m_currentDeviceId; + // Another device: the page drops its views first (loading), then the models are emptied. The same + // device again (Reset, reconnection): the models are updated in place when the data arrives. + const bool switching = id != m_loadedDeviceId; + m_loadedDeviceId = id; + if (switching) { + setLoading(true); + m_settings->setEntries({}); + m_buttons->setEntries({}); + m_hapticEvents->setEntries({}); + m_eventWaveforms.clear(); + Q_EMIT waveformsChanged(); + m_settingsState = m_buttonsState = m_hapticEventsState = FeatureState::Loading; + m_settingsError.clear(); + Q_EMIT featuresChanged(); + } + if (id.isEmpty()) { + m_pending = 0; + m_settingsState = m_buttonsState = m_hapticEventsState = FeatureState::Unavailable; + Q_EMIT featuresChanged(); + setLoading(false); + updateReady(); + return; + } + m_pending = 3; + updateReady(); + + auto done = [this, generation] { + if (generation == m_generation && m_pending > 0 && --m_pending == 0) { + setLoading(false); + updateReady(); + } + }; + + m_client->call(QStringLiteral("ListSettings"), {id}, this, [=, this](const QVariant &result, const PlasmaarClient::Error &error) { + if (generation != m_generation) { + return; + } + if (error.isError()) { + m_settings->setEntries({}); + m_settingsState = stateFor(error) == FeatureState::Unavailable ? FeatureState::Unavailable : FeatureState::Failed; + m_settingsError = describe(error); + } else { + m_settings->setEntries(result.toList(), keepStaged); + m_settingsState = m_settings->count() > 0 ? FeatureState::Available : FeatureState::Unavailable; + m_settingsError.clear(); + } + Q_EMIT featuresChanged(); + Q_EMIT waveformsChanged(); + done(); + }); + + m_client->call(QStringLiteral("GetButtonActions"), {id}, this, [=, this](const QVariant &result, const PlasmaarClient::Error &error) { + if (generation != m_generation) { + return; + } + if (error.isError()) { + m_buttons->setEntries({}); + m_buttonsState = stateFor(error); + } else { + m_buttons->setEntries(result.toMap().value(QStringLiteral("buttons")).toList(), keepStaged); + m_buttonsState = m_buttons->count() > 0 ? FeatureState::Available : FeatureState::Unavailable; + } + Q_EMIT featuresChanged(); + done(); + }); + + m_client->call(QStringLiteral("GetHapticEvents"), {id}, this, [=, this](const QVariant &result, const PlasmaarClient::Error &error) { + if (generation != m_generation) { + return; + } + if (error.isError()) { + m_hapticEvents->setEntries({}); + m_eventWaveforms.clear(); + m_hapticEventsState = stateFor(error); + } else { + const QVariantMap map = result.toMap(); + m_eventWaveforms = map.value(QStringLiteral("waveforms")).toStringList(); + m_hapticEvents->setEntries(map.value(QStringLiteral("events")).toList(), keepStaged); + m_hapticEventsState = m_hapticEvents->count() > 0 ? FeatureState::Available : FeatureState::Unavailable; + } + Q_EMIT featuresChanged(); + Q_EMIT waveformsChanged(); + done(); + }); +} + +void Controller::loadButtons(bool keepStaged) +{ + const quint64 generation = m_generation; + m_client->call(QStringLiteral("GetButtonActions"), {m_currentDeviceId}, this, [=, this](const QVariant &result, const PlasmaarClient::Error &error) { + if (generation != m_generation || error.isError()) { + return; + } + m_buttons->setEntries(result.toMap().value(QStringLiteral("buttons")).toList(), keepStaged); + }); +} + +void Controller::loadKdeActions() +{ + m_kdeActionsState = FeatureState::Loading; + Q_EMIT featuresChanged(); + m_client->call(QStringLiteral("ListKdeActions"), {}, this, [this](const QVariant &result, const PlasmaarClient::Error &error) { + m_kdeActions = error.isError() ? QVariantList() : result.toList(); + m_actionLabels.clear(); + for (const QVariant &component : std::as_const(m_kdeActions)) { + const QVariantMap map = component.toMap(); + const QString name = map.value(QStringLiteral("component")).toString(); + const QVariantList actions = map.value(QStringLiteral("actions")).toList(); + for (const QVariant &action : actions) { + const QVariantMap actionMap = action.toMap(); + m_actionLabels.insert(name + QLatin1Char('/') + actionMap.value(QStringLiteral("name")).toString(), + actionMap.value(QStringLiteral("label")).toString()); + } + } + m_kdeActionsState = error.isError() ? stateFor(error) : FeatureState::Available; + Q_EMIT kdeActionsChanged(); + Q_EMIT featuresChanged(); + updateReady(); + }); +} + +Controller::FeatureState Controller::stateFor(const PlasmaarClient::Error &error) const +{ + if (error.isUnknownMethod()) { + return FeatureState::NeedsNewerService; + } + const QString name = error.shortName(); + if (name == QLatin1String("NotSupported") || name == QLatin1String("NoSuchDevice")) { + return FeatureState::Unavailable; + } + return FeatureState::Failed; +} + +QString Controller::describe(const PlasmaarClient::Error &error) const +{ + const QString name = error.shortName(); + if (name == QLatin1String("DeviceOffline")) { + return i18n("The device is switched off, asleep or out of range."); + } + if (name == QLatin1String("NoSuchDevice")) { + return i18n("The device is no longer connected."); + } + if (name == QLatin1String("NoSuchSetting")) { + return i18n("The device no longer has this setting."); + } + if (name == QLatin1String("InvalidValue")) { + return i18n("The value was refused: %1", error.message); + } + if (name == QLatin1String("NotSupported")) { + return i18n("The device does not support this."); + } + if (error.isServiceGone()) { + return i18n("The plasmaard service is not running."); + } + if (error.name == QLatin1String("org.freedesktop.DBus.Error.NoReply") || error.name == QLatin1String("org.freedesktop.DBus.Error.Timeout")) { + return i18n("The plasmaard service did not answer in time."); + } + return error.message.isEmpty() ? error.name : error.message; +} + +// --- saving --- + +void Controller::save() +{ + if (m_saving) { + return; + } + const QString id = m_currentDeviceId; + QList writes; + // Settings first: a button action written afterwards decides the button's final diversion. + const auto settingChanges = m_settings->changes(); + for (const StagedModel::Change &change : settingChanges) { + if (change.entry.value(QStringLiteral("kind")).toString() == MapChoice) { + const QVariantMap pending = change.pending.toMap(); + for (const QString &key : change.changedKeys) { + writes.append({m_settings, change.key, QStringLiteral("SetSettingKey"), {id, change.key, key, Json::serialize(pending.value(key))}}); + } + } else { + writes.append({m_settings, change.key, QStringLiteral("SetSetting"), {id, change.key, Json::serialize(change.pending)}}); + } + } + const auto buttonChanges = m_buttons->changes(); + for (const StagedModel::Change &change : buttonChanges) { + writes.append({m_buttons, + change.key, + QStringLiteral("SetButtonAction"), + {id, change.entry.value(QStringLiteral("control")).toInt(), Json::serialize(change.pending)}}); + } + const auto eventChanges = m_hapticEvents->changes(); + for (const StagedModel::Change &change : eventChanges) { + const QString waveform = change.pending.isNull() ? QString() : change.pending.toString(); + writes.append({m_hapticEvents, change.key, QStringLiteral("SetHapticEvent"), {id, change.key, waveform}}); + } + m_settings->clearErrors(); + m_buttons->clearErrors(); + m_hapticEvents->clearErrors(); + setSaveError(QString()); + if (writes.isEmpty()) { + Q_EMIT saved(true); + return; + } + setSaving(true); + runWrites(writes, {}); +} + +void Controller::runWrites(QList writes, QStringList failures) +{ + if (writes.isEmpty()) { + setSaving(false); + if (!failures.isEmpty()) { + setSaveError(i18np("One change could not be applied:", "%1 changes could not be applied:", failures.size()) + QLatin1Char('\n') + + failures.join(QLatin1Char('\n'))); + } + Q_EMIT saved(failures.isEmpty()); + return; + } + const Write write = writes.takeFirst(); + const quint64 generation = m_generation; + write.model->setBusy(write.model->indexOf(write.key), true); + m_client->call(write.method, write.args, this, [=, this](const QVariant &result, const PlasmaarClient::Error &error) mutable { + if (generation == m_generation) { + const int row = write.model->indexOf(write.key); + write.model->setBusy(row, false); + if (error.isError()) { + const QString message = describe(error); + write.model->setError(row, message); + const QVariantMap entry = write.model->get(row); + const QString label = entry.value(QStringLiteral("label"), entry.value(QStringLiteral("name"), write.key)).toString(); + failures.append(i18nc("@info failed write: setting label, error message", "%1: %2", label, message)); + } else { + applyWriteResult(write, result); + } + } + runWrites(writes, failures); + }); +} + +void Controller::applyWriteResult(const Write &write, const QVariant &result) +{ + if (write.model == m_settings) { + m_settings->setLiveValue(write.key, result); + return; + } + const QVariantMap map = result.toMap(); + const int row = write.model->indexOf(write.key); + if (write.model == m_hapticEvents && map.contains(QStringLiteral("events"))) { + m_hapticEvents->setEntries(map.value(QStringLiteral("events")).toList(), true); + } else if (!map.isEmpty() && map.contains(write.model == m_buttons ? QStringLiteral("control") : QStringLiteral("event"))) { + write.model->setLiveEntry(map); + } else { + // no description in the reply: what was written is now the live value + write.model->setLiveValue(write.key, write.model->pendingValue(row)); + } +} + +void Controller::defaults() +{ + m_settings->stageDefaults(); +} + +void Controller::setSaving(bool saving) +{ + if (m_saving != saving) { + m_saving = saving; + Q_EMIT savingChanged(); + } +} + +void Controller::setSaveError(const QString &error) +{ + if (m_saveError != error) { + m_saveError = error; + Q_EMIT saveErrorChanged(); + } +} + +void Controller::setNotice(const QString ¬ice) +{ + if (m_notice != notice) { + m_notice = notice; + Q_EMIT noticeChanged(); + } +} + +void Controller::clearNotice() +{ + setNotice(QString()); +} + +// --- immediate actions --- + +void Controller::playHaptic(const QString &waveform) +{ + m_client->call(QStringLiteral("PlayHaptic"), {m_currentDeviceId, waveform}, this, [this](const QVariant &, const PlasmaarClient::Error &error) { + if (error.isError()) { + setNotice(i18n("Could not play the effect: %1", describe(error))); + } + }); +} + +void Controller::startService() +{ + setNotice(QString()); + m_client->startService(this, [this](const QVariant &, const PlasmaarClient::Error &error) { + if (error.isError()) { + setNotice(i18n("Could not start plasmaard: %1", error.message.isEmpty() ? error.name : error.message)); + } + }); +} + +QString Controller::actionLabel(const QVariant &action) const +{ + const QVariantMap map = toMap(action); + const QString component = map.value(QStringLiteral("component")).toString(); + const QString name = map.value(QStringLiteral("action")).toString(); + if (component.isEmpty() || name.isEmpty()) { + return QString(); + } + const QString label = m_actionLabels.value(component + QLatin1Char('/') + name); + if (!label.isEmpty()) { + return label; + } + return i18nc("@label a KDE action that is not in the list: action name, component", "%1 (%2)", name, component); +} + +// --- snapshot mode --- + +void Controller::resizeTopLevelWindows(int width, int height) const +{ + const auto windows = QGuiApplication::topLevelWindows(); + for (QWindow *window : windows) { + if (window->isVisible() && (window->type() == Qt::Window || window->type() == Qt::Dialog)) { + window->resize(width, height); + } + } +} + +static QWindow *largestTopLevelWindow() +{ + QWindow *largest = nullptr; + const auto windows = QGuiApplication::topLevelWindows(); + for (QWindow *window : windows) { + if (window->isVisible() && (!largest || window->width() * window->height() > largest->width() * largest->height())) { + largest = window; + } + } + return largest; +} + +int Controller::topLevelWindowHeight() const +{ + QWindow *window = largestTopLevelWindow(); + return window ? window->height() : 0; +} + +bool Controller::grabTopLevelWindow(const QString &path) const +{ + QWindow *largest = largestTopLevelWindow(); + if (!largest || !largest->screen()) { + return false; + } + const QPixmap pixmap = largest->screen()->grabWindow(largest->winId()); + return !pixmap.isNull() && pixmap.save(path); +} + +void Controller::quitApplication() const +{ + QMetaObject::invokeMethod(QCoreApplication::instance(), &QCoreApplication::quit, Qt::QueuedConnection); +} + +#include "moc_controller.cpp" diff --git a/kcm/src/controller.h b/kcm/src/controller.h new file mode 100644 index 00000000..9f159618 --- /dev/null +++ b/kcm/src/controller.h @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include + +#include "plasmaarclient.h" +#include "stagedmodel.h" + +/* + * What the settings page shows and edits: the devices, the selected device's settings, button actions and + * haptic events (each a StagedModel), the KDE actions to pick from, plus load/save/defaults with KCM + * semantics. Independent of KCMUtils so that it can be tested against the mock service. + */ +class Controller : public QObject +{ + Q_OBJECT + QML_ELEMENT + QML_UNCREATABLE("Provided by the KCM") + + Q_PROPERTY(ServiceState serviceState READ serviceState NOTIFY serviceStateChanged) + Q_PROPERTY(bool ready READ isReady NOTIFY readyChanged) + Q_PROPERTY(QVariantList devices READ devices NOTIFY devicesChanged) + Q_PROPERTY(QString currentDeviceId READ currentDeviceId WRITE setCurrentDeviceId NOTIFY currentDeviceChanged) + Q_PROPERTY(QVariantMap currentDevice READ currentDevice NOTIFY currentDeviceChanged) + Q_PROPERTY(bool loading READ isLoading NOTIFY loadingChanged) // a newly selected device is loading + Q_PROPERTY(bool saving READ isSaving NOTIFY savingChanged) + Q_PROPERTY(StagedModel *settings READ settings CONSTANT) + Q_PROPERTY(StagedModel *buttons READ buttons CONSTANT) + Q_PROPERTY(StagedModel *hapticEvents READ hapticEvents CONSTANT) + Q_PROPERTY(FeatureState settingsState READ settingsState NOTIFY featuresChanged) + Q_PROPERTY(FeatureState buttonsState READ buttonsState NOTIFY featuresChanged) + Q_PROPERTY(FeatureState hapticEventsState READ hapticEventsState NOTIFY featuresChanged) + Q_PROPERTY(FeatureState kdeActionsState READ kdeActionsState NOTIFY featuresChanged) + Q_PROPERTY(QString settingsError READ settingsError NOTIFY featuresChanged) + Q_PROPERTY(QVariantList kdeActions READ kdeActions NOTIFY kdeActionsChanged) + Q_PROPERTY(QStringList waveforms READ waveforms NOTIFY waveformsChanged) + Q_PROPERTY(QString saveError READ saveError NOTIFY saveErrorChanged) + Q_PROPERTY(QString notice READ notice NOTIFY noticeChanged) + Q_PROPERTY(bool needsSave READ needsSave NOTIFY stagingChanged) + Q_PROPERTY(bool hasDefaults READ hasDefaults NOTIFY stagingChanged) + Q_PROPERTY(bool atDefaults READ atDefaults NOTIFY stagingChanged) + Q_PROPERTY(QString snapshotPrefix READ snapshotPrefix CONSTANT) + Q_PROPERTY(QString snapshotScenario READ snapshotScenario CONSTANT) + +public: + enum class ServiceState { + Checking, + Running, + Missing, + }; + Q_ENUM(ServiceState) + + enum class FeatureState { + Loading, + Available, + Unavailable, // the device has nothing of the kind + NeedsNewerService, // plasmaard does not have the method yet + Failed, + }; + Q_ENUM(FeatureState) + + explicit Controller(const QDBusConnection &bus = QDBusConnection::sessionBus(), QObject *parent = nullptr); + + ServiceState serviceState() const; + bool isReady() const; + QVariantList devices() const; + QString currentDeviceId() const; + void setCurrentDeviceId(const QString &deviceId); + QVariantMap currentDevice() const; + bool isLoading() const; + bool isSaving() const; + StagedModel *settings() const; + StagedModel *buttons() const; + StagedModel *hapticEvents() const; + FeatureState settingsState() const; + FeatureState buttonsState() const; + FeatureState hapticEventsState() const; + FeatureState kdeActionsState() const; + QString settingsError() const; + QVariantList kdeActions() const; + QStringList waveforms() const; + QString saveError() const; + QString notice() const; + bool needsSave() const; + bool hasDefaults() const; + bool atDefaults() const; + QString snapshotPrefix() const; + QString snapshotScenario() const; + + PlasmaarClient *client() const; + +public Q_SLOTS: + // KCM semantics: reload everything and drop staged edits (also the first load, which looks for the + // service) / write staged edits / stage the defaults. + void load(); + void save(); + void defaults(); + + void playHaptic(const QString &waveform); + void startService(); + void clearNotice(); + +public: + // The localized label of a KDE action {component, action}, or a readable fallback. + Q_INVOKABLE QString actionLabel(const QVariant &action) const; + + // Snapshot mode (PLASMAAR_KCM_SNAPSHOT): size and grab the top-level windows, then quit. + Q_INVOKABLE void resizeTopLevelWindows(int width, int height) const; + Q_INVOKABLE int topLevelWindowHeight() const; + Q_INVOKABLE bool grabTopLevelWindow(const QString &path) const; + Q_INVOKABLE void quitApplication() const; + +Q_SIGNALS: + void serviceStateChanged(); + void readyChanged(); + void devicesChanged(); + void currentDeviceChanged(); + void loadingChanged(); + void savingChanged(); + void featuresChanged(); + void kdeActionsChanged(); + void waveformsChanged(); + void saveErrorChanged(); + void noticeChanged(); + void stagingChanged(); + void saved(bool success); + +private: + struct Write { + StagedModel *model; + QString key; + QString method; + QVariantList args; + }; + + void onServiceStateChanged(); + void loadDevices(); + void loadDevice(bool keepStaged); + void loadButtons(bool keepStaged); + void loadKdeActions(); + void setDevices(const QVariantList &devices); + void upsertDevice(const QVariantMap &device); + void removeDevice(const QString &deviceId); + void pickDevice(); + void setLoading(bool loading); + void setSaving(bool saving); + void setSaveError(const QString &error); + void setNotice(const QString ¬ice); + void runWrites(QList writes, QStringList failures); + void applyWriteResult(const Write &write, const QVariant &result); + QString describe(const PlasmaarClient::Error &error) const; + FeatureState stateFor(const PlasmaarClient::Error &error) const; + void updateReady(); + + PlasmaarClient *m_client; + StagedModel *m_settings; + StagedModel *m_buttons; + StagedModel *m_hapticEvents; + QVariantList m_devices; + QString m_currentDeviceId; + bool m_devicesLoaded = false; + int m_pending = 0; // replies still expected for the current device + bool m_loading = false; // loading another device than the one shown + QString m_loadedDeviceId; + bool m_saving = false; + bool m_ready = false; + quint64 m_generation = 0; // bumped when switching devices, to drop stale replies + FeatureState m_settingsState = FeatureState::Loading; + FeatureState m_buttonsState = FeatureState::Loading; + FeatureState m_hapticEventsState = FeatureState::Loading; + FeatureState m_kdeActionsState = FeatureState::Loading; + QString m_settingsError; + QVariantList m_kdeActions; + QHash m_actionLabels; // "component/action" -> label + QStringList m_eventWaveforms; + QString m_saveError; + QString m_notice; + QString m_snapshotPrefix; + QString m_snapshotScenario; +}; diff --git a/kcm/src/json.cpp b/kcm/src/json.cpp new file mode 100644 index 00000000..1256672c --- /dev/null +++ b/kcm/src/json.cpp @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "json.h" + +#include +#include +#include +#include +#include + +#include +#include + +namespace +{ +QJsonValue toJsonValue(const QVariant &input) +{ + // values handed over from QML may still be wrapped JavaScript values + const QVariant value = input.metaType() == QMetaType::fromType() ? input.value().toVariant() : input; + switch (value.typeId()) { + case QMetaType::UnknownType: + case QMetaType::Nullptr: + return QJsonValue(QJsonValue::Null); + case QMetaType::Bool: + return value.toBool(); + case QMetaType::Double: + case QMetaType::Float: { + const double d = value.toDouble(); + if (std::isfinite(d) && std::trunc(d) == d && std::abs(d) < double(std::numeric_limits::max())) { + return qint64(d); + } + return d; + } + case QMetaType::QVariantMap: { + QJsonObject object; + const QVariantMap map = value.toMap(); + for (auto it = map.cbegin(); it != map.cend(); ++it) { + object.insert(it.key(), toJsonValue(it.value())); + } + return object; + } + case QMetaType::QVariantList: + case QMetaType::QStringList: { + QJsonArray array; + const QVariantList list = value.toList(); + for (const QVariant &item : list) { + array.append(toJsonValue(item)); + } + return array; + } + default: + break; + } + if (value.canConvert() && !value.canConvert()) { + return toJsonValue(QVariant(value.toMap())); + } + if (value.canConvert() && !value.canConvert()) { + return toJsonValue(QVariant(value.toList())); + } + return QJsonValue::fromVariant(value); +} +} + +namespace Json +{ +QVariant parse(const QString &text, bool *ok) +{ + // QJsonDocument only takes objects and arrays at the top level; wrap scalars. + QJsonParseError error; + const QJsonDocument document = QJsonDocument::fromJson(QByteArray("[") + text.toUtf8() + QByteArray("]"), &error); + const bool valid = error.error == QJsonParseError::NoError && document.isArray() && document.array().size() == 1; + if (ok) { + *ok = valid; + } + if (!valid) { + return {}; + } + const QJsonValue value = document.array().at(0); + return value.isNull() ? QVariant::fromValue(nullptr) : value.toVariant(); +} + +QString serialize(const QVariant &value) +{ + const QByteArray wrapped = QJsonDocument(QJsonArray{toJsonValue(value)}).toJson(QJsonDocument::Compact); + return QString::fromUtf8(wrapped.mid(1, wrapped.size() - 2)); +} + +QByteArray canonical(const QVariant &value) +{ + // QJsonObject keeps keys sorted, so the compact form is canonical. + return QJsonDocument(QJsonArray{toJsonValue(value)}).toJson(QJsonDocument::Compact); +} +} diff --git a/kcm/src/json.h b/kcm/src/json.h new file mode 100644 index 00000000..b95c9bff --- /dev/null +++ b/kcm/src/json.h @@ -0,0 +1,27 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +// plasmaard payloads are JSON strings; these helpers convert them to and from QVariant. +namespace Json +{ +// Parses any JSON value (also scalars such as "1200" or "true"). Sets ok to false on malformed input. +QVariant parse(const QString &text, bool *ok = nullptr); + +// Serializes a QVariant (maps, lists, numbers, booleans, strings, null) as compact JSON. +// Integral doubles (QML numbers) are written as integers, because plasmaard checks for ints. +QString serialize(const QVariant &value); + +// A canonical form for comparing values regardless of their C++ number types or map order. +QByteArray canonical(const QVariant &value); + +inline bool equal(const QVariant &a, const QVariant &b) +{ + return canonical(a) == canonical(b); +} +} diff --git a/kcm/src/plasmaarclient.cpp b/kcm/src/plasmaarclient.cpp new file mode 100644 index 00000000..4dbfd591 --- /dev/null +++ b/kcm/src/plasmaarclient.cpp @@ -0,0 +1,183 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "plasmaarclient.h" + +#include "json.h" + +#include +#include +#include +#include +#include +#include + +Q_LOGGING_CATEGORY(KCM_PLASMAAR, "kcm_plasmaar", QtWarningMsg) + +const QString PlasmaarClient::Service = QStringLiteral("io.github.fredaime.Plasmaar"); +const QString PlasmaarClient::Path = QStringLiteral("/io/github/fredaime/Plasmaar"); +const QString PlasmaarClient::Interface = QStringLiteral("io.github.fredaime.Plasmaar1"); + +namespace +{ +// Device calls can take seconds while a Bluetooth device wakes up; plasmaard answers or fails on its own. +constexpr int CallTimeoutMs = 30000; +} + +bool PlasmaarClient::Error::isUnknownMethod() const +{ + return name == QLatin1String("org.freedesktop.DBus.Error.UnknownMethod"); +} + +bool PlasmaarClient::Error::isServiceGone() const +{ + return name == QLatin1String("org.freedesktop.DBus.Error.ServiceUnknown") || name == QLatin1String("org.freedesktop.DBus.Error.NameHasNoOwner") + || name == QLatin1String("org.freedesktop.DBus.Error.Disconnected"); +} + +QString PlasmaarClient::Error::shortName() const +{ + const QString prefix = Interface + QLatin1String(".Error."); + return name.startsWith(prefix) ? name.mid(prefix.size()) : name; +} + +PlasmaarClient::PlasmaarClient(const QDBusConnection &bus, QObject *parent) + : QObject(parent) + , m_bus(bus) + , m_watcher(new QDBusServiceWatcher(Service, bus, QDBusServiceWatcher::WatchForOwnerChange, this)) +{ + connect(m_watcher, &QDBusServiceWatcher::serviceRegistered, this, &PlasmaarClient::checkService); + connect(m_watcher, &QDBusServiceWatcher::serviceUnregistered, this, [this] { + ++m_checkGeneration; + setServiceState(ServiceState::Missing); + }); + + // QtDBus follows the owner of the well-known name, so these survive service restarts. + const struct { + const char *signal; + const char *slot; + } relays[] = { + {"DeviceAdded", SLOT(onDeviceAdded(QString))}, + {"DeviceChanged", SLOT(onDeviceChanged(QString))}, + {"DeviceRemoved", SLOT(onDeviceRemoved(QString))}, + {"SettingChanged", SLOT(onSettingChanged(QString, QString, QString))}, + {"ButtonActionsChanged", SLOT(onButtonActionsChanged(QString))}, + }; + for (const auto &relay : relays) { + if (!m_bus.connect(Service, Path, Interface, QString::fromLatin1(relay.signal), this, relay.slot)) { + qCWarning(KCM_PLASMAAR) << "cannot listen to" << relay.signal << m_bus.lastError().message(); + } + } +} + +PlasmaarClient::ServiceState PlasmaarClient::serviceState() const +{ + return m_state; +} + +QString PlasmaarClient::apiVersion() const +{ + return m_apiVersion; +} + +void PlasmaarClient::setServiceState(ServiceState state) +{ + if (m_state != state) { + m_state = state; + Q_EMIT serviceStateChanged(); + } +} + +void PlasmaarClient::checkService() +{ + const quint64 generation = ++m_checkGeneration; + call(QStringLiteral("GetVersion"), {}, this, [this, generation](const QVariant &result, const Error &error) { + if (generation != m_checkGeneration) { + return; // a newer check or an unregistration overtook this one + } + if (error.isError()) { + qCDebug(KCM_PLASMAAR) << "plasmaard not available:" << error.name << error.message; + setServiceState(ServiceState::Missing); + return; + } + m_apiVersion = result.toString(); + setServiceState(ServiceState::Running); + }); +} + +void PlasmaarClient::call(const QString &method, const QVariantList &args, QObject *context, Callback callback) +{ + QDBusMessage message = QDBusMessage::createMethodCall(Service, Path, Interface, method); + message.setArguments(args); + dispatch(message, context, std::move(callback)); +} + +void PlasmaarClient::startService(QObject *context, Callback callback) +{ + QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.systemd1"), + QStringLiteral("/org/freedesktop/systemd1"), + QStringLiteral("org.freedesktop.systemd1.Manager"), + QStringLiteral("StartUnit")); + message.setArguments({QStringLiteral("plasmaard.service"), QStringLiteral("replace")}); + dispatch(message, context, std::move(callback)); +} + +void PlasmaarClient::dispatch(const QDBusMessage &message, QObject *context, Callback callback) +{ + auto *watcher = new QDBusPendingCallWatcher(m_bus.asyncCall(message, CallTimeoutMs), this); + QPointer guard(context); + const QString method = message.member(); + connect(watcher, &QDBusPendingCallWatcher::finished, this, [guard, method, callback = std::move(callback)](QDBusPendingCallWatcher *call) { + call->deleteLater(); + if (!guard) { + return; + } + const QDBusMessage reply = call->reply(); + if (reply.type() == QDBusMessage::ErrorMessage) { + qCDebug(KCM_PLASMAAR) << method << "failed:" << reply.errorName() << reply.errorMessage(); + callback(QVariant(), Error{reply.errorName(), reply.errorMessage()}); + return; + } + QVariant result; + if (!reply.arguments().isEmpty()) { + const QVariant first = reply.arguments().constFirst(); + if (first.typeId() == QMetaType::QString) { + bool ok = false; + result = Json::parse(first.toString(), &ok); + if (!ok) { + result = first; // GetVersion and other plain strings + } + } else { + result = first; + } + } + callback(result, Error{}); + }); +} + +void PlasmaarClient::onDeviceAdded(const QString &json) +{ + Q_EMIT deviceAdded(Json::parse(json).toMap()); +} + +void PlasmaarClient::onDeviceChanged(const QString &json) +{ + Q_EMIT deviceChanged(Json::parse(json).toMap()); +} + +void PlasmaarClient::onDeviceRemoved(const QString &deviceId) +{ + Q_EMIT deviceRemoved(deviceId); +} + +void PlasmaarClient::onSettingChanged(const QString &deviceId, const QString &name, const QString &valueJson) +{ + Q_EMIT settingChanged(deviceId, name, Json::parse(valueJson)); +} + +void PlasmaarClient::onButtonActionsChanged(const QString &deviceId) +{ + Q_EMIT buttonActionsChanged(deviceId); +} + +#include "moc_plasmaarclient.cpp" diff --git a/kcm/src/plasmaarclient.h b/kcm/src/plasmaarclient.h new file mode 100644 index 00000000..c85f9824 --- /dev/null +++ b/kcm/src/plasmaarclient.h @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include + +#include + +class QDBusMessage; +class QDBusServiceWatcher; + +/* + * Thin asynchronous client of the plasmaard D-Bus API (docs/dbus-api.md). + * + * Calls never block: each one is a QDBusPendingCallWatcher whose reply is parsed from JSON into a + * QVariant and handed to a callback. Signals are relayed with their payloads parsed. The service may + * come and go (it is a user service), which QDBusServiceWatcher tracks. + */ +class PlasmaarClient : public QObject +{ + Q_OBJECT + +public: + static const QString Service; + static const QString Path; + static const QString Interface; + + enum class ServiceState { + Checking, // not known yet + Running, + Missing, + }; + Q_ENUM(ServiceState) + + struct Error { + QString name; // D-Bus error name; empty when the call succeeded + QString message; + + bool isError() const + { + return !name.isEmpty(); + } + bool isUnknownMethod() const; // an older plasmaard without this method + bool isServiceGone() const; // nobody owns the bus name (anymore) + QString shortName() const; // "NoSuchDevice", … for the plasmaard errors, else the full name + }; + + using Callback = std::function; + + explicit PlasmaarClient(const QDBusConnection &bus = QDBusConnection::sessionBus(), QObject *parent = nullptr); + + ServiceState serviceState() const; + QString apiVersion() const; + + // Calls a method of the plasmaard interface. String arguments are passed as they are; use + // Json::serialize for the *_json ones. The reply (a JSON string for most methods) is parsed; void + // methods give an invalid QVariant. The callback is dropped if context is destroyed first. + void call(const QString &method, const QVariantList &args, QObject *context, Callback callback); + + // Asks systemd --user to start plasmaard.service. + void startService(QObject *context, Callback callback); + + // Checks whether the service is there; then followed automatically as it appears or vanishes. + void checkService(); + +Q_SIGNALS: + void serviceStateChanged(); + void deviceAdded(const QVariantMap &device); + void deviceChanged(const QVariantMap &device); + void deviceRemoved(const QString &deviceId); + void settingChanged(const QString &deviceId, const QString &name, const QVariant &value); + void buttonActionsChanged(const QString &deviceId); + +private Q_SLOTS: + void onDeviceAdded(const QString &json); + void onDeviceChanged(const QString &json); + void onDeviceRemoved(const QString &deviceId); + void onSettingChanged(const QString &deviceId, const QString &name, const QString &valueJson); + void onButtonActionsChanged(const QString &deviceId); + +private: + void setServiceState(ServiceState state); + void dispatch(const QDBusMessage &message, QObject *context, Callback callback); + + QDBusConnection m_bus; + QDBusServiceWatcher *m_watcher; + ServiceState m_state = ServiceState::Checking; + QString m_apiVersion; + quint64 m_checkGeneration = 0; +}; diff --git a/kcm/src/plasmaarkcm.cpp b/kcm/src/plasmaarkcm.cpp new file mode 100644 index 00000000..3558ba5a --- /dev/null +++ b/kcm/src/plasmaarkcm.cpp @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "plasmaarkcm.h" + +#include "controller.h" + +#include + +// Generated by qt_add_qml_module for the static io.github.fredaime.plasmaar module. Calling it also keeps +// the registration code from being dropped by the linker. +void qml_register_types_io_github_fredaime_plasmaar(); + +K_PLUGIN_CLASS_WITH_JSON(PlasmaarKcm, "kcm_plasmaar.json") + +PlasmaarKcm::PlasmaarKcm(QObject *parent, const KPluginMetaData &metaData) + : KQuickConfigModule(parent, metaData) + , m_controller(new Controller(QDBusConnection::sessionBus(), this)) +{ + static const bool qmlTypesRegistered = [] { + qml_register_types_io_github_fredaime_plasmaar(); + return true; + }(); + Q_UNUSED(qmlTypesRegistered) + setButtons(Apply | Default); + + // Nothing is fetched before the host calls load(): it follows changes of representsDefaults only + // once it has set the module up. + connect(m_controller, &Controller::stagingChanged, this, &PlasmaarKcm::updateState); +} + +Controller *PlasmaarKcm::controller() const +{ + return m_controller; +} + +void PlasmaarKcm::updateState() +{ + setNeedsSave(m_controller->needsSave()); + // Without known defaults there is nothing to go back to: this disables the Defaults button. + const bool atDefaults = !m_controller->hasDefaults() || m_controller->atDefaults(); + if (atDefaults == representsDefaults()) { + Q_EMIT representsDefaultsChanged(); // the host may have missed the last change + } + setRepresentsDefaults(atDefaults); +} + +void PlasmaarKcm::load() +{ + KQuickConfigModule::load(); + m_controller->load(); + updateState(); +} + +void PlasmaarKcm::save() +{ + KQuickConfigModule::save(); + m_controller->save(); + updateState(); +} + +void PlasmaarKcm::defaults() +{ + KQuickConfigModule::defaults(); + m_controller->defaults(); + updateState(); +} + +#include "plasmaarkcm.moc" diff --git a/kcm/src/plasmaarkcm.h b/kcm/src/plasmaarkcm.h new file mode 100644 index 00000000..f68755d4 --- /dev/null +++ b/kcm/src/plasmaarkcm.h @@ -0,0 +1,32 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include + +#include "controller.h" + +/* + * "Logitech Devices" in System Settings → Input Devices. The page itself is QML (ui/); this class hands + * it the Controller and maps the KCM buttons (Apply, Reset, Defaults) onto it. + */ +class PlasmaarKcm : public KQuickConfigModule +{ + Q_OBJECT + Q_PROPERTY(Controller *controller READ controller CONSTANT) + +public: + PlasmaarKcm(QObject *parent, const KPluginMetaData &metaData); + + Controller *controller() const; + + void load() override; + void save() override; + void defaults() override; + +private: + void updateState(); + + Controller *m_controller; +}; diff --git a/kcm/src/stagedmodel.cpp b/kcm/src/stagedmodel.cpp new file mode 100644 index 00000000..fdea83d3 --- /dev/null +++ b/kcm/src/stagedmodel.cpp @@ -0,0 +1,462 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "stagedmodel.h" + +#include "json.h" + +namespace +{ +const QString DefaultField = QStringLiteral("default"); + +QVariant nullValue() +{ + return QVariant::fromValue(nullptr); +} + +bool isMap(const QVariant &value) +{ + return value.typeId() == QMetaType::QVariantMap; +} + +QVariant setPath(const QVariant &target, const QStringList &path, int depth, const QVariant &value) +{ + if (depth == path.size()) { + return value; + } + QVariantMap map = target.toMap(); + map.insert(path.at(depth), setPath(map.value(path.at(depth)), path, depth + 1, value)); + return map; +} +} + +StagedModel::StagedModel(const QString &keyField, const QStringList &valueFields, const QStringList &fieldRoles, QObject *parent) + : QAbstractListModel(parent) + , m_keyField(keyField) + , m_valueFields(valueFields) + , m_fieldRoles(fieldRoles) +{ +} + +int StagedModel::rowCount(const QModelIndex &parent) const +{ + return parent.isValid() ? 0 : int(m_rows.size()); +} + +QHash StagedModel::roleNames() const +{ + QHash roles{ + {KeyRole, "key"}, + {EntryRole, "entry"}, + {ValueRole, "liveValue"}, + {PendingRole, "pending"}, + {ChangedRole, "changed"}, + {DefaultValueRole, "defaultValue"}, + {HasDefaultRole, "hasDefault"}, + {IsDefaultRole, "isDefault"}, + {ErrorRole, "writeError"}, + {BusyRole, "busy"}, + }; + for (int i = 0; i < m_fieldRoles.size(); ++i) { + // "role=field" exposes an entry field under another role name + roles.insert(FirstFieldRole + i, m_fieldRoles.at(i).section(QLatin1Char('='), 0, 0).toUtf8()); + } + return roles; +} + +QVariant StagedModel::data(const QModelIndex &index, int role) const +{ + if (!checkIndex(index, CheckIndexOption::IndexIsValid | CheckIndexOption::ParentIsInvalid)) { + return {}; + } + const Row &row = m_rows.at(index.row()); + switch (role) { + case KeyRole: + return keyOf(row.entry); + case EntryRole: + return row.entry; + case ValueRole: + return row.live; + case PendingRole: + return pendingOf(row); + case ChangedRole: + return isChanged(row); + case DefaultValueRole: + return row.entry.value(DefaultField); + case HasDefaultRole: + return row.entry.contains(DefaultField); + case IsDefaultRole: + return !row.entry.contains(DefaultField) || Json::equal(pendingOf(row), row.entry.value(DefaultField)); + case ErrorRole: + return row.error; + case BusyRole: + return row.busy; + default: + break; + } + const int field = role - FirstFieldRole; + if (field >= 0 && field < m_fieldRoles.size()) { + const QString &spec = m_fieldRoles.at(field); + return row.entry.value(spec.contains(QLatin1Char('=')) ? spec.section(QLatin1Char('='), 1) : spec); + } + return {}; +} + +int StagedModel::count() const +{ + return int(m_rows.size()); +} + +int StagedModel::revision() const +{ + return m_revision; +} + +int StagedModel::stagingRevision() const +{ + return m_stagingRevision; +} + +bool StagedModel::hasChanges() const +{ + return std::any_of(m_rows.cbegin(), m_rows.cend(), [this](const Row &row) { + return isChanged(row); + }); +} + +bool StagedModel::hasDefaults() const +{ + return std::any_of(m_rows.cbegin(), m_rows.cend(), [](const Row &row) { + return row.entry.contains(DefaultField); + }); +} + +bool StagedModel::atDefaults() const +{ + return std::all_of(m_rows.cbegin(), m_rows.cend(), [this](const Row &row) { + return !row.entry.contains(DefaultField) || Json::equal(pendingOf(row), row.entry.value(DefaultField)); + }); +} + +bool StagedModel::hasErrors() const +{ + return std::any_of(m_rows.cbegin(), m_rows.cend(), [](const Row &row) { + return !row.error.isEmpty(); + }); +} + +QString StagedModel::keyOf(const QVariantMap &entry) const +{ + return entry.value(m_keyField).toString(); +} + +QVariant StagedModel::valueOf(const QVariantMap &entry) const +{ + if (m_valueFields.size() == 1) { + const QVariant value = entry.value(m_valueFields.first()); + return value.isValid() ? value : nullValue(); + } + QVariantMap value; + for (const QString &field : m_valueFields) { + const QVariant fieldValue = entry.value(field); + value.insert(field, fieldValue.isValid() ? fieldValue : nullValue()); + } + return value; +} + +QVariant StagedModel::pendingOf(const Row &row) const +{ + return row.staged.isValid() ? row.staged : row.live; +} + +bool StagedModel::isChanged(const Row &row) const +{ + return row.staged.isValid() && !Json::equal(row.staged, row.live); +} + +void StagedModel::setEntries(const QVariantList &entries, bool keepStaged) +{ + QHash staged; + if (keepStaged) { + for (const Row &row : std::as_const(m_rows)) { + if (row.staged.isValid()) { + staged.insert(keyOf(row.entry), row.staged); + } + } + } + QList rows; + rows.reserve(entries.size()); + for (const QVariant &item : entries) { + Row row; + row.entry = item.toMap(); + row.live = valueOf(row.entry); + const QVariant edit = staged.value(keyOf(row.entry)); + if (edit.isValid() && !Json::equal(edit, row.live)) { + row.staged = edit; + } + rows.append(row); + } + + const bool sameKeys = !rows.isEmpty() && rows.size() == m_rows.size() && std::equal(rows.cbegin(), rows.cend(), m_rows.cbegin(), [this](const Row &a, const Row &b) { + return keyOf(a.entry) == keyOf(b.entry); + }); + if (sameKeys) { + // The same entries again (a refresh): update the rows in place, so that views keep their delegates. + for (qsizetype i = 0; i < rows.size(); ++i) { + rows[i].error = m_rows.at(i).error; + } + m_rows = rows; + QList roles; + const auto names = roleNames(); + for (auto it = names.cbegin(); it != names.cend(); ++it) { + roles.append(it.key()); + } + Q_EMIT dataChanged(index(0, 0), index(int(m_rows.size()) - 1, 0), roles); + ++m_stagingRevision; + Q_EMIT stateChanged(); + return; + } + + const qsizetype oldCount = m_rows.size(); + beginResetModel(); + m_rows = rows; + endResetModel(); + ++m_revision; + ++m_stagingRevision; + if (oldCount != m_rows.size()) { + Q_EMIT countChanged(); + } + Q_EMIT entriesReset(); + Q_EMIT stateChanged(); +} + +QVariantList StagedModel::entries() const +{ + QVariantList result; + result.reserve(m_rows.size()); + for (const Row &row : m_rows) { + result.append(row.entry); + } + return result; +} + +bool StagedModel::setLiveValue(const QString &key, const QVariant &value) +{ + const int index = indexOf(key); + if (index < 0) { + return false; + } + Row &row = m_rows[index]; + bool fieldsChanged = false; + if (m_valueFields.size() == 1) { + row.entry.insert(m_valueFields.first(), value.isValid() ? value : nullValue()); + fieldsChanged = row.entry.remove(QStringLiteral("error")) > 0; // a value arrived, so it can be read now + } else { + const QVariantMap fields = value.toMap(); + for (auto it = fields.cbegin(); it != fields.cend(); ++it) { + row.entry.insert(it.key(), it.value()); + } + } + applyLive(index, valueOf(row.entry), fieldsChanged); + return true; +} + +bool StagedModel::setLiveEntry(const QVariantMap &entry) +{ + const int index = indexOf(keyOf(entry)); + if (index < 0) { + return false; + } + Row &row = m_rows[index]; + for (auto it = entry.cbegin(); it != entry.cend(); ++it) { + row.entry.insert(it.key(), it.value()); + } + applyLive(index, valueOf(row.entry), true); + return true; +} + +void StagedModel::applyLive(int index, const QVariant &newLive, bool fieldsChanged) +{ + Row &row = m_rows[index]; + if (row.staged.isValid() && isMap(row.staged) && isMap(row.live) && isMap(newLive)) { + // keep the keys the user edited, take the others from the service + const QVariantMap oldLive = row.live.toMap(); + const QVariantMap staged = row.staged.toMap(); + QVariantMap merged = newLive.toMap(); + for (auto it = staged.cbegin(); it != staged.cend(); ++it) { + if (!Json::equal(it.value(), oldLive.value(it.key()))) { + merged.insert(it.key(), it.value()); + } + } + row.staged = merged; + } + row.live = newLive; + if (row.staged.isValid() && Json::equal(row.staged, row.live)) { + row.staged = QVariant(); + } + emitRowChanged(index, fieldsChanged); +} + +int StagedModel::indexOf(const QString &key) const +{ + for (int i = 0; i < m_rows.size(); ++i) { + if (keyOf(m_rows.at(i).entry) == key) { + return i; + } + } + return -1; +} + +QVariantMap StagedModel::get(int row) const +{ + return row >= 0 && row < m_rows.size() ? m_rows.at(row).entry : QVariantMap(); +} + +QVariant StagedModel::field(int row, const QString &field) const +{ + return row >= 0 && row < m_rows.size() ? m_rows.at(row).entry.value(field) : QVariant(); +} + +QVariant StagedModel::pendingValue(int row) const +{ + return row >= 0 && row < m_rows.size() ? pendingOf(m_rows.at(row)) : QVariant(); +} + +QVariant StagedModel::liveValue(int row) const +{ + return row >= 0 && row < m_rows.size() ? m_rows.at(row).live : QVariant(); +} + +QString StagedModel::writeError(int row) const +{ + return row >= 0 && row < m_rows.size() ? m_rows.at(row).error : QString(); +} + +void StagedModel::stage(int row, const QVariant &value) +{ + stageRow(row, value); +} + +void StagedModel::stageKey(int row, const QString &key, const QVariant &value) +{ + stagePath(row, {key}, value); +} + +void StagedModel::stagePath(int row, const QStringList &path, const QVariant &value) +{ + if (row < 0 || row >= m_rows.size()) { + return; + } + stageRow(row, setPath(pendingOf(m_rows.at(row)), path, 0, value.isValid() ? value : nullValue())); +} + +void StagedModel::unstage(int row) +{ + if (row < 0 || row >= m_rows.size() || !m_rows.at(row).staged.isValid()) { + return; + } + m_rows[row].staged = QVariant(); + emitRowChanged(row); +} + +void StagedModel::stageRow(int index, const QVariant &value) +{ + if (index < 0 || index >= m_rows.size()) { + return; + } + Row &row = m_rows[index]; + const QVariant newValue = value.isValid() ? value : nullValue(); + row.staged = Json::equal(newValue, row.live) ? QVariant() : newValue; + row.error.clear(); + emitRowChanged(index); +} + +void StagedModel::discard() +{ + for (int i = 0; i < m_rows.size(); ++i) { + Row &row = m_rows[i]; + if (row.staged.isValid() || !row.error.isEmpty()) { + row.staged = QVariant(); + row.error.clear(); + emitRowChanged(i); + } + } +} + +void StagedModel::stageDefaults() +{ + for (int i = 0; i < m_rows.size(); ++i) { + if (m_rows.at(i).entry.contains(DefaultField)) { + stageRow(i, m_rows.at(i).entry.value(DefaultField)); + } + } +} + +QList StagedModel::changes() const +{ + QList result; + for (int i = 0; i < m_rows.size(); ++i) { + const Row &row = m_rows.at(i); + if (!isChanged(row)) { + continue; + } + Change change{i, keyOf(row.entry), row.live, row.staged, row.entry, {}}; + if (isMap(row.live) && isMap(row.staged)) { + const QVariantMap live = row.live.toMap(); + const QVariantMap staged = row.staged.toMap(); + for (auto it = staged.cbegin(); it != staged.cend(); ++it) { + if (!Json::equal(it.value(), live.value(it.key()))) { + change.changedKeys.append(it.key()); + } + } + } + result.append(change); + } + return result; +} + +void StagedModel::setError(int row, const QString &message) +{ + if (row < 0 || row >= m_rows.size() || m_rows.at(row).error == message) { + return; + } + m_rows[row].error = message; + emitRowChanged(row); +} + +void StagedModel::clearErrors() +{ + for (int i = 0; i < m_rows.size(); ++i) { + setError(i, QString()); + } +} + +void StagedModel::setBusy(int row, bool busy) +{ + if (row < 0 || row >= m_rows.size() || m_rows.at(row).busy == busy) { + return; + } + m_rows[row].busy = busy; + const QModelIndex index = createIndex(row, 0); + Q_EMIT dataChanged(index, index, {BusyRole}); + ++m_stagingRevision; + Q_EMIT stateChanged(); +} + +void StagedModel::emitRowChanged(int row, bool fieldsChanged) +{ + // The field roles only when asked: they rarely change and may be large (per-key choice lists), and + // re-reading them rebuilds their JavaScript copies in every delegate. + QList roles{EntryRole, ValueRole, PendingRole, ChangedRole, DefaultValueRole, HasDefaultRole, IsDefaultRole, ErrorRole, BusyRole}; + if (fieldsChanged) { + for (int i = 0; i < m_fieldRoles.size(); ++i) { + roles.append(FirstFieldRole + i); + } + } + const QModelIndex index = createIndex(row, 0); + Q_EMIT dataChanged(index, index, roles); + ++m_stagingRevision; + Q_EMIT stateChanged(); +} + +#include "moc_stagedmodel.cpp" diff --git a/kcm/src/stagedmodel.h b/kcm/src/stagedmodel.h new file mode 100644 index 00000000..9a8cfdf0 --- /dev/null +++ b/kcm/src/stagedmodel.h @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include +#include +#include +#include +#include + +/* + * A list of entries (settings, buttons, haptic events) as plasmaard describes them, with edits staged + * until the KCM is applied. + * + * Every row keeps the entry's live value (what the service reports) and an optional staged value. QML + * shows `pending` (staged if any, else live) and stages edits; save() writes the rows whose staged value + * differs from the live one, and the service's answer (or its change signal) becomes the new live value. + * Staging the live value again unstages the row, so needsSave really means "something would change". + * + * The value of a row is one field of the entry (`value` for settings, `waveform` for haptic events) or, + * with several value fields, a map of them (mode/press/gestures for buttons). Map values can be edited + * key by key (per-key settings, gesture directions): a live update then keeps the user's edited keys and + * takes the others from the service. + */ +class StagedModel : public QAbstractListModel +{ + Q_OBJECT + QML_ELEMENT + QML_UNCREATABLE("Provided by the Controller") + + Q_PROPERTY(int count READ count NOTIFY countChanged) + Q_PROPERTY(int revision READ revision NOTIFY entriesReset) // bumped whenever the entries are replaced + Q_PROPERTY(int stagingRevision READ stagingRevision NOTIFY stateChanged) // bumped on every change of a row + Q_PROPERTY(bool hasChanges READ hasChanges NOTIFY stateChanged) + Q_PROPERTY(bool hasDefaults READ hasDefaults NOTIFY stateChanged) + Q_PROPERTY(bool atDefaults READ atDefaults NOTIFY stateChanged) + Q_PROPERTY(bool hasErrors READ hasErrors NOTIFY stateChanged) + +public: + enum Role { + KeyRole = Qt::UserRole + 1, // the entry's id (setting name, button control, event name), as a string + EntryRole, // the whole entry map + ValueRole, // live value + PendingRole, // staged value, or the live value + ChangedRole, // a staged edit differs from the live value + DefaultValueRole, // the entry's "default", if any + HasDefaultRole, + IsDefaultRole, // pending equals the default (true when there is no default) + ErrorRole, // last write error for this row + BusyRole, // a write is in flight + FirstFieldRole, // then one role per field listed in the constructor + }; + Q_ENUM(Role) + + struct Change { + int row; + QString key; + QVariant live; + QVariant pending; + QVariantMap entry; + QStringList changedKeys; // for map values: the keys whose value differs + }; + + StagedModel(const QString &keyField, const QStringList &valueFields, const QStringList &fieldRoles, QObject *parent = nullptr); + + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role) const override; + QHash roleNames() const override; + + int count() const; + int revision() const; + int stagingRevision() const; + bool hasChanges() const; + bool hasDefaults() const; + bool atDefaults() const; + bool hasErrors() const; + + // Replace all entries. With keepStaged, edits of rows that still exist survive (a refresh). + void setEntries(const QVariantList &entries, bool keepStaged = false); + QVariantList entries() const; + + // The service reports a new live value for an entry (signal or write reply). + bool setLiveValue(const QString &key, const QVariant &value); + // The service sent a whole new entry (e.g. a button after SetButtonAction). + bool setLiveEntry(const QVariantMap &entry); + + Q_INVOKABLE int indexOf(const QString &key) const; + Q_INVOKABLE QVariantMap get(int row) const; // the entry + Q_INVOKABLE QVariant field(int row, const QString &field) const; // one field of the entry (cheaper) + Q_INVOKABLE QVariant pendingValue(int row) const; + Q_INVOKABLE QVariant liveValue(int row) const; + Q_INVOKABLE QString writeError(int row) const; + + // Edits from QML. + Q_INVOKABLE void stage(int row, const QVariant &value); + Q_INVOKABLE void stageKey(int row, const QString &key, const QVariant &value); + Q_INVOKABLE void stagePath(int row, const QStringList &path, const QVariant &value); + Q_INVOKABLE void unstage(int row); + + void discard(); // drop all staged edits + void stageDefaults(); // stage every row's default + QList changes() const; + + void setError(int row, const QString &message); + void clearErrors(); + void setBusy(int row, bool busy); + +Q_SIGNALS: + void countChanged(); + void entriesReset(); + void stateChanged(); + +private: + struct Row { + QVariantMap entry; + QVariant live; + QVariant staged; // invalid: nothing staged + QString error; + bool busy = false; + }; + + QString keyOf(const QVariantMap &entry) const; + QVariant valueOf(const QVariantMap &entry) const; + QVariant pendingOf(const Row &row) const; + bool isChanged(const Row &row) const; + void stageRow(int row, const QVariant &value); + void applyLive(int row, const QVariant &newLive, bool fieldsChanged); + void emitRowChanged(int row, bool fieldsChanged = false); + + QString m_keyField; + QStringList m_valueFields; + QStringList m_fieldRoles; + QList m_rows; + int m_revision = 0; + int m_stagingRevision = 0; +}; diff --git a/kcm/ui/ActionField.qml b/kcm/ui/ActionField.qml new file mode 100644 index 00000000..61260cae --- /dev/null +++ b/kcm/ui/ActionField.qml @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import io.github.fredaime.plasmaar + +// A KDE action ({component, action} or null) shown by its localized label, with buttons to change or remove it. +RowLayout { + id: field + + required property var action + required property Controller controller + property bool editable: true + property int fieldWidth: Kirigami.Units.gridUnit * 16 + + signal pickRequested() + signal picked(var action) + + readonly property bool hasAction: action !== null && action !== undefined && action.component !== undefined + + spacing: Kirigami.Units.smallSpacing + + QQC2.Button { + id: choose + Layout.preferredWidth: field.fieldWidth + enabled: field.editable + icon.name: field.hasAction ? "" : "list-add" + text: { + field.controller.kdeActions; // relabel once the action list arrives + return field.hasAction ? field.controller.actionLabel(field.action) : i18nc("@action:button", "Choose an Action…"); + } + onClicked: field.pickRequested() + + QQC2.ToolTip.visible: hovered && field.hasAction + QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay + QQC2.ToolTip.text: field.hasAction ? i18nc("@info:tooltip KDE action: component, action id", "%1 › %2", field.action.component, field.action.action) : "" + } + + QQC2.ToolButton { + visible: field.hasAction + enabled: field.editable + icon.name: "edit-clear" + display: QQC2.AbstractButton.IconOnly + text: i18nc("@action:button", "Remove Action") + onClicked: field.picked(null) + + QQC2.ToolTip.visible: hovered + QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay + QQC2.ToolTip.text: text + } +} diff --git a/kcm/ui/ButtonsPage.qml b/kcm/ui/ButtonsPage.qml new file mode 100644 index 00000000..2df8d0f2 --- /dev/null +++ b/kcm/ui/ButtonsPage.qml @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import io.github.fredaime.plasmaar + +// Divertable buttons: their mode (normal, action on press, gestures) and the KDE action for the press or +// for each gesture direction. +ColumnLayout { + id: page + + required property Controller controller + required property PickerDialog actionDialog + + readonly property bool canPick: controller.kdeActionsState === Controller.FeatureState.Available + readonly property bool hasGestures: { + const buttons = controller.buttons; + buttons.revision; + for (let i = 0; i < buttons.count; ++i) { + if (Array.from(buttons.field(i, "modes") ?? []).includes("gesture")) { + return true; + } + } + return false; + } + // one width for the mode boxes and the action buttons, so that the column lines up + readonly property int fieldWidth: Kirigami.Units.gridUnit * 16 + + required property var actionEntries // see main.qml + + readonly property var directions: [ + { id: "up", label: i18nc("@label:chooser gesture direction", "Swipe up:") }, + { id: "down", label: i18nc("@label:chooser gesture direction", "Swipe down:") }, + { id: "left", label: i18nc("@label:chooser gesture direction", "Swipe left:") }, + { id: "right", label: i18nc("@label:chooser gesture direction", "Swipe right:") }, + { id: "click", label: i18nc("@label:chooser gesture button pressed and released without moving", "Click without swiping:") } + ] + + function modeLabel(mode: string): string { + switch (mode) { + case "off": + return i18nc("@item:inlistbox button mode", "Normal (its usual function)"); + case "press": + return i18nc("@item:inlistbox button mode", "Run an action when pressed"); + case "gesture": + return i18nc("@item:inlistbox button mode", "Gestures: hold, swipe and release"); + default: + return mode; + } + } + + function pickAction(context: string, current: var, done: var): void { + actionDialog.pick(context, actionEntries, current, done); + } + + spacing: Kirigami.Units.largeSpacing + + Kirigami.PlaceholderMessage { + Layout.fillWidth: true + Layout.margins: Kirigami.Units.gridUnit * 2 + visible: page.controller.buttonsState === Controller.FeatureState.NeedsNewerService + icon.name: "input-mouse" + text: i18nc("@info:placeholder", "Button actions need a newer plasmaard") + explanation: xi18nc("@info:placeholder", + "The running plasmaard service cannot configure button actions yet. Update it, or map the buttons in ~/.config/plasmaar/rules.yaml for now.") + } + + Kirigami.InlineMessage { + Layout.fillWidth: true + type: Kirigami.MessageType.Error + visible: page.controller.buttonsState === Controller.FeatureState.Failed + text: i18nc("@info", "The button actions could not be read.") + } + + Kirigami.InlineMessage { + Layout.fillWidth: true + type: Kirigami.MessageType.Warning + visible: page.controller.buttonsState === Controller.FeatureState.Available + && page.controller.kdeActionsState !== Controller.FeatureState.Available + && page.controller.kdeActionsState !== Controller.FeatureState.Loading + text: i18nc("@info", "The list of KDE actions is not available, so actions cannot be chosen right now.") + } + + QQC2.Label { + Layout.fillWidth: true + Layout.leftMargin: Kirigami.Units.gridUnit * 2 + Layout.rightMargin: Kirigami.Units.gridUnit * 2 + visible: page.controller.buttonsState === Controller.FeatureState.Available + horizontalAlignment: Text.AlignHCenter + wrapMode: Text.Wrap + color: Kirigami.Theme.disabledTextColor + text: page.hasGestures + ? i18nc("@info", "Buttons set to an action or to gestures run KDE Plasma actions instead of their usual function. For a gesture, hold the button, move the mouse in one direction and release it.") + : i18nc("@info", "Keys set to an action run a KDE Plasma action instead of their usual function.") + } + + // the button layouts are twins of this one, so that all their labels line up + Kirigami.FormLayout { + id: anchorForm + Layout.fillWidth: true + } + + Repeater { + model: page.controller.buttons + + delegate: Kirigami.FormLayout { + id: button + + required property int index + required property string name + required property var modes + required property var pending + required property string writeError + required property bool busy + + readonly property string mode: pending.mode ?? "off" + readonly property bool editable: !page.controller.saving + + Layout.fillWidth: true + twinFormLayouts: [anchorForm] + + Item { + Kirigami.FormData.isSection: true + Kirigami.FormData.label: button.name + } + + RowLayout { + Kirigami.FormData.label: i18nc("@label:listbox", "Behavior:") + spacing: Kirigami.Units.smallSpacing + + QQC2.ComboBox { + Layout.preferredWidth: page.fieldWidth + enabled: button.editable + model: button.modes.map(mode => ({ + value: mode, + text: page.modeLabel(mode) + })) + textRole: "text" + valueRole: "value" + currentIndex: button.modes.indexOf(button.mode) + onActivated: page.controller.buttons.stageKey(button.index, "mode", currentValue) + } + + QQC2.BusyIndicator { + visible: button.busy + running: visible + implicitWidth: Kirigami.Units.iconSizes.small + implicitHeight: Kirigami.Units.iconSizes.small + } + } + + ActionField { + Kirigami.FormData.label: i18nc("@label:chooser", "Action:") + fieldWidth: page.fieldWidth + visible: button.mode === "press" + controller: page.controller + action: button.pending.press ?? null + editable: button.editable && page.canPick + onPickRequested: page.pickAction(button.name, action, value => page.controller.buttons.stageKey(button.index, "press", value)) + onPicked: value => page.controller.buttons.stageKey(button.index, "press", value) + } + + Repeater { + model: page.directions + + delegate: ActionField { + id: gesture + required property var modelData + Kirigami.FormData.label: modelData.label + fieldWidth: page.fieldWidth + visible: button.mode === "gesture" + controller: page.controller + action: button.pending.gestures?.[modelData.id] ?? null + editable: button.editable && page.canPick + onPickRequested: page.pickAction(i18nc("@info:placeholder button, gesture direction", "%1, %2", button.name, gesture.modelData.label.replace(/\s*:\s*$/, "")), + action, value => page.controller.buttons.stagePath(button.index, ["gestures", gesture.modelData.id], value)) + onPicked: value => page.controller.buttons.stagePath(button.index, ["gestures", gesture.modelData.id], value) + } + } + + QQC2.Label { + Layout.maximumWidth: Kirigami.Units.gridUnit * 20 + visible: button.writeError !== "" + text: button.writeError + color: Kirigami.Theme.negativeTextColor + wrapMode: Text.Wrap + } + } + } +} diff --git a/kcm/ui/DeviceHeader.qml b/kcm/ui/DeviceHeader.qml new file mode 100644 index 00000000..ae1b38b9 --- /dev/null +++ b/kcm/ui/DeviceHeader.qml @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import io.github.fredaime.plasmaar + +// The selected device: picture, name, connection, battery, ids; and the device picker. +RowLayout { + id: header + + required property Controller controller + + readonly property var device: controller.currentDevice + readonly property bool online: device.online === true + readonly property var battery: device.battery ?? {} + readonly property bool batteryKnown: typeof battery.level === "number" + readonly property bool charging: battery.status === "RECHARGING" || battery.status === "SLOW_RECHARGE" + + function iconFor(kind: string): string { + switch (kind) { + case "keyboard": + return "input-keyboard"; + case "trackball": + case "touchpad": + return "input-touchpad"; + case "headset": + return "audio-headset"; + default: + return "input-mouse"; + } + } + + function batteryIcon(): string { + if (!batteryKnown) { + return "battery-missing"; + } + const level = Math.max(0, Math.min(100, Math.round(battery.level / 10) * 10)); + return "battery-" + String(level).padStart(3, "0") + (charging ? "-charging" : ""); + } + + function batteryStatus(): string { + switch (battery.status) { + case "DISCHARGING": + return i18nc("@info battery state", "discharging"); + case "RECHARGING": + case "SLOW_RECHARGE": + return i18nc("@info battery state", "charging"); + case "FULL": + return i18nc("@info battery state", "fully charged"); + case "ALMOST_FULL": + return i18nc("@info battery state", "almost full"); + case "INVALID_BATTERY": + case "THERMAL_ERROR": + case "UNKNOWN_ERROR": + return i18nc("@info battery state", "battery error"); + default: + return ""; + } + } + + function deviceLabel(entry: var): string { + return entry.online ? entry.name : i18nc("@item:inlistbox device that is switched off", "%1 (offline)", entry.name); + } + + spacing: Kirigami.Units.largeSpacing + + Kirigami.Icon { + Layout.alignment: Qt.AlignTop + implicitWidth: Kirigami.Units.iconSizes.huge + implicitHeight: Kirigami.Units.iconSizes.huge + source: header.iconFor(header.device.kind ?? "") + opacity: header.online ? 1 : 0.6 + } + + ColumnLayout { + Layout.fillWidth: true + spacing: Kirigami.Units.smallSpacing + + Kirigami.Heading { + Layout.fillWidth: true + level: 2 + text: header.device.name ?? "" + elide: Text.ElideRight + } + + RowLayout { + spacing: Kirigami.Units.smallSpacing + + Rectangle { + implicitWidth: Kirigami.Units.smallSpacing * 2 + implicitHeight: implicitWidth + radius: width / 2 + color: header.online ? Kirigami.Theme.positiveTextColor : Kirigami.Theme.disabledTextColor + } + QQC2.Label { + text: header.online ? i18nc("@info device state", "Connected") : i18nc("@info device state", "Offline: switched off, asleep or out of range") + } + + Kirigami.Icon { + Layout.leftMargin: Kirigami.Units.largeSpacing + implicitWidth: Kirigami.Units.iconSizes.small + implicitHeight: Kirigami.Units.iconSizes.small + visible: header.batteryKnown + source: header.batteryIcon() + } + QQC2.Label { + visible: header.batteryKnown + text: { + if (!header.batteryKnown) { + return ""; + } + const level = i18nc("@info battery level", "%1%", header.battery.level); + const status = header.batteryStatus(); + return status ? i18nc("@info battery level, state", "%1 (%2)", level, status) : level; + } + } + } + + QQC2.Label { + Layout.fillWidth: true + font: Kirigami.Theme.smallFont + color: Kirigami.Theme.disabledTextColor + elide: Text.ElideRight + text: { + const parts = []; + const device = header.device; + if (device.codename && device.codename !== device.name) { + parts.push(device.codename); + } + if (device.model_id) { + parts.push(i18nc("@info device id", "Model %1", device.model_id)); + } + if (device.unit_id) { + parts.push(i18nc("@info device id", "Unit %1", device.unit_id)); + } + if (device.serial) { + parts.push(i18nc("@info device id", "Serial %1", device.serial)); + } + if (device.protocol) { + parts.push(i18nc("@info protocol version", "HID++ %1", String(device.protocol))); + } + return parts.join(" · "); + } + } + } + + QQC2.ComboBox { + id: picker + Layout.alignment: Qt.AlignTop + Layout.maximumWidth: Kirigami.Units.gridUnit * 16 + visible: header.controller.devices.length > 1 + // switching would drop the edits, so they have to be applied or reset first + enabled: !header.controller.needsSave && !header.controller.saving + model: header.controller.devices.map(entry => ({ + id: entry.id, + label: header.deviceLabel(entry) + })) + textRole: "label" + valueRole: "id" + currentIndex: header.controller.devices.findIndex(entry => entry.id === header.controller.currentDeviceId) + onActivated: header.controller.currentDeviceId = currentValue + + QQC2.ToolTip.visible: hovered + QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay + QQC2.ToolTip.text: enabled ? i18nc("@info:tooltip", "Choose the device to configure") + : i18nc("@info:tooltip", "Apply or reset your changes before switching to another device") + } +} diff --git a/kcm/ui/HapticsPage.qml b/kcm/ui/HapticsPage.qml new file mode 100644 index 00000000..8a0560e3 --- /dev/null +++ b/kcm/ui/HapticsPage.qml @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import org.kde.kcmutils as KCM +import io.github.fredaime.plasmaar + +// Haptic feedback: intensity, a test button per waveform, and which waveform desktop events play. +ColumnLayout { + id: page + + required property Controller controller + required property PickerDialog choiceDialog + + readonly property bool online: controller.currentDevice.online === true + readonly property var waveforms: controller.waveforms + readonly property bool hasEvents: controller.hapticEventsState === Controller.FeatureState.Available + + // waveform names are device constants such as "SHARP STATE CHANGE" + function waveformLabel(name: string): string { + switch (name) { + case "SHARP STATE CHANGE": + return i18nc("@item haptic waveform", "Sharp state change"); + case "DAMP STATE CHANGE": + return i18nc("@item haptic waveform", "Damped state change"); + case "SHARP COLLISION": + return i18nc("@item haptic waveform", "Sharp collision"); + case "DAMP COLLISION": + return i18nc("@item haptic waveform", "Damped collision"); + case "SUBTLE COLLISION": + return i18nc("@item haptic waveform", "Subtle collision"); + case "WHISPER COLLISION": + return i18nc("@item haptic waveform", "Whisper collision"); + case "HAPPY ALERT": + return i18nc("@item haptic waveform", "Happy alert"); + case "ANGRY ALERT": + return i18nc("@item haptic waveform", "Angry alert"); + case "COMPLETED": + return i18nc("@item haptic waveform", "Completed"); + case "SQUARE": + return i18nc("@item haptic waveform", "Square"); + case "WAVE": + return i18nc("@item haptic waveform", "Wave"); + case "FIREWORK": + return i18nc("@item haptic waveform", "Firework"); + case "MAD": + return i18nc("@item haptic waveform", "Mad"); + case "KNOCK": + return i18nc("@item haptic waveform", "Knock"); + case "JINGLE": + return i18nc("@item haptic waveform", "Jingle"); + case "RINGING": + return i18nc("@item haptic waveform", "Ringing"); + default: + return name.charAt(0) + name.slice(1).toLowerCase(); + } + } + + spacing: Kirigami.Units.largeSpacing + + Kirigami.InlineMessage { + Layout.fillWidth: true + type: Kirigami.MessageType.Warning + text: page.controller.notice + visible: text !== "" + showCloseButton: true + onVisibleChanged: if (!visible) page.controller.clearNotice() + } + + Kirigami.InlineMessage { + Layout.fillWidth: true + type: Kirigami.MessageType.Information + visible: !page.online + text: i18nc("@info", "The device is offline. Switch it on or wake it up to feel the effects.") + } + + Kirigami.FormLayout { + Layout.fillWidth: true + + // the haptic-level setting, drawn like on the settings page + Repeater { + model: page.controller.settings + delegate: SettingRow { + id: level + controller: page.controller + choiceDialog: page.choiceDialog + visible: level.name === "haptic-level" + Kirigami.FormData.label: i18nc("@label:slider", "Intensity:") + } + } + + Item { + Kirigami.FormData.isSection: true + Kirigami.FormData.label: i18nc("@title:group", "Try the Effects") + visible: page.waveforms.length > 0 + } + + GridLayout { + Kirigami.FormData.label: i18nc("@label", "Play:") + Kirigami.FormData.buddyFor: waveformButtons.count > 0 ? waveformButtons.itemAt(0) : null + visible: page.waveforms.length > 0 + columns: 2 + rowSpacing: Kirigami.Units.smallSpacing + columnSpacing: Kirigami.Units.smallSpacing + + Repeater { + id: waveformButtons + model: page.waveforms + delegate: QQC2.Button { + required property string modelData + Layout.fillWidth: true + enabled: page.online + icon.name: "media-playback-start" + text: page.waveformLabel(modelData) + onClicked: page.controller.playHaptic(modelData) + } + } + } + + Item { + Kirigami.FormData.isSection: true + Kirigami.FormData.label: i18nc("@title:group", "Desktop Events") + visible: page.hasEvents + } + + Repeater { + model: page.hasEvents ? page.controller.hapticEvents : null + + delegate: RowLayout { + id: event + + required property int index + required property string label + required property var pending + required property bool isDefault + required property string writeError + required property bool busy + + Kirigami.FormData.label: i18nc("@label:listbox desktop event", "%1:", label) + spacing: Kirigami.Units.smallSpacing + + QQC2.ComboBox { + id: waveformBox + enabled: !page.controller.saving + model: [{ + value: "", + text: i18nc("@item:inlistbox no haptic effect", "None") + }].concat(page.waveforms.map(name => ({ + value: name, + text: page.waveformLabel(name) + }))) + textRole: "text" + valueRole: "value" + currentIndex: event.pending ? page.waveforms.indexOf(event.pending) + 1 : 0 + onActivated: page.controller.hapticEvents.stage(event.index, currentValue === "" ? null : currentValue) + } + + QQC2.ToolButton { + enabled: page.online && !!event.pending + icon.name: "media-playback-start" + display: QQC2.AbstractButton.IconOnly + text: i18nc("@action:button", "Try It") + onClicked: page.controller.playHaptic(event.pending) + QQC2.ToolTip.visible: hovered + QQC2.ToolTip.delay: Kirigami.Units.toolTipDelay + QQC2.ToolTip.text: text + } + + QQC2.BusyIndicator { + visible: event.busy + running: visible + implicitWidth: Kirigami.Units.iconSizes.small + implicitHeight: Kirigami.Units.iconSizes.small + } + + QQC2.Label { + visible: event.writeError !== "" + text: event.writeError + color: Kirigami.Theme.negativeTextColor + } + } + } + + QQC2.Label { + visible: page.controller.hapticEventsState === Controller.FeatureState.NeedsNewerService + Layout.maximumWidth: Kirigami.Units.gridUnit * 20 + wrapMode: Text.Wrap + color: Kirigami.Theme.disabledTextColor + text: i18nc("@info", "Haptic feedback for desktop events needs a newer plasmaard.") + } + } +} diff --git a/kcm/ui/KeyCell.qml b/kcm/ui/KeyCell.qml new file mode 100644 index 00000000..a13d3a44 --- /dev/null +++ b/kcm/ui/KeyCell.qml @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import org.kde.kcmutils as KCM + +// The value of one key in a per-key setting: a combo box, a searchable list for long ones, or a spin box. +Item { + id: keyCell + + required property var column // {label, keys: {key id: {value, name, choices | min, max}}} + required property string keyId + required property string keyName + required property var value + required property var defaultValue + required property bool editable + required property PickerDialog choiceDialog + + signal edited(var value) + + readonly property var space: column.keys[keyId] + readonly property var choices: space.choices ? Array.from(space.choices) : [] + readonly property int choiceIndex: choices.findIndex(choice => choice.value === value) + readonly property bool isDefault: defaultValue === undefined || defaultValue === value + + implicitWidth: loader.implicitWidth + implicitHeight: loader.implicitHeight + + Loader { + id: loader + anchors.fill: parent + sourceComponent: keyCell.space.choices === undefined ? spin : (keyCell.choices.length > 40 ? search : combo) + } + + Component { + id: combo + QQC2.ComboBox { + enabled: keyCell.editable + model: keyCell.choices + textRole: "name" + valueRole: "value" + currentIndex: keyCell.choiceIndex + onActivated: keyCell.edited(currentValue) + Accessible.name: i18nc("@label accessible name: setting, key", "%1, %2", keyCell.column.label, keyCell.keyName) + KCM.SettingHighlighter { + highlight: !keyCell.isDefault + } + } + } + + Component { + id: search + QQC2.Button { + enabled: keyCell.editable + icon.name: "search" + text: keyCell.choiceIndex >= 0 ? keyCell.choices[keyCell.choiceIndex].name : String(keyCell.value ?? "") + onClicked: keyCell.choiceDialog.pick(i18nc("@title:window setting, key", "%1: %2", keyCell.column.label, keyCell.keyName), + keyCell.choices.map(choice => ({ + value: choice.value, + label: choice.name, + section: "" + })), keyCell.value, value => keyCell.edited(value)) + Accessible.name: i18nc("@label accessible name: setting, key", "%1, %2", keyCell.column.label, keyCell.keyName) + KCM.SettingHighlighter { + highlight: !keyCell.isDefault + } + } + } + + Component { + id: spin + QQC2.SpinBox { + enabled: keyCell.editable + from: keyCell.space.min ?? 0 + to: keyCell.space.max ?? 0 + editable: true + value: typeof keyCell.value === "number" ? keyCell.value : from + onValueModified: keyCell.edited(value) + Accessible.name: i18nc("@label accessible name: setting, key", "%1, %2", keyCell.column.label, keyCell.keyName) + KCM.SettingHighlighter { + highlight: !keyCell.isDefault + } + } + } +} diff --git a/kcm/ui/KeyMapTable.qml b/kcm/ui/KeyMapTable.qml new file mode 100644 index 00000000..9ed23c15 --- /dev/null +++ b/kcm/ui/KeyMapTable.qml @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import org.kde.kcmutils as KCM +import io.github.fredaime.plasmaar + +// The per-key settings (MAP_CHOICE: reprogrammable-keys, divert-keys, …) side by side: one row per key or +// button, one column per setting. +ColumnLayout { + id: table + + required property Controller controller + required property PickerDialog choiceDialog + + readonly property bool online: controller.currentDevice.online === true + + readonly property var columns: { + const settings = controller.settings; + settings.revision; + const result = []; + for (let i = 0; i < settings.count; ++i) { + if (settings.field(i, "kind") === "MAP_CHOICE" && settings.field(i, "display")) { + const keys = {}; // key id -> {value, name, choices | min, max} + const order = []; + for (const key of Array.from(settings.field(i, "keys") ?? [])) { + keys[String(key.value)] = key; + order.push(String(key.value)); + } + result.push({ + row: i, + name: settings.field(i, "name"), + label: settings.field(i, "label"), + description: settings.field(i, "description"), + writable: settings.field(i, "writable") === true, + defaults: settings.field(i, "default") ?? null, + keys: keys, + order: order + }); + } + } + return result; + } + + // every key of every column, in the order the device lists them + readonly property var keys: { + const seen = new Map(); + for (const column of columns) { + for (const value of column.order) { + if (!seen.has(value)) { + seen.set(value, column.keys[value].name); + } + } + } + return Array.from(seen, ([value, name]) => ({ value, name })); + } + + // the cells of the grid, row by row + readonly property var cells: { + const result = [{ type: "corner" }]; + for (const column of columns) { + result.push({ type: "header", column }); + } + for (const key of keys) { + result.push({ type: "key", key }); + for (const column of columns) { + result.push({ type: "cell", column, key }); + } + } + return result; + } + + function pending(column: var): var { + controller.settings.stagingRevision; // follow edits and live updates + return controller.settings.pendingValue(column.row) ?? {}; + } + + function rowError(column: var): string { + controller.settings.stagingRevision; + return controller.settings.writeError(column.row); + } + + readonly property int columnWidth: Kirigami.Units.gridUnit * 13 + + visible: columns.length > 0 + spacing: Kirigami.Units.largeSpacing + + Kirigami.Heading { + Layout.fillWidth: true // lets the table take the page's width, so that it is centered + horizontalAlignment: Text.AlignHCenter + level: 3 + type: Kirigami.Heading.Type.Primary + text: i18nc("@title:group", "Keys and Buttons") + } + + GridLayout { + Layout.alignment: Qt.AlignHCenter + Layout.fillWidth: false + columns: table.columns.length + 1 + rowSpacing: Kirigami.Units.smallSpacing + columnSpacing: Kirigami.Units.largeSpacing + + Repeater { + model: table.cells + + delegate: Loader { + id: cell + required property var modelData + Layout.alignment: modelData.type === "key" ? Qt.AlignRight | Qt.AlignVCenter : Qt.AlignLeft | Qt.AlignVCenter + // fixed column widths; long key names (K850) and headers wrap + Layout.fillWidth: false + Layout.preferredWidth: modelData.type === "cell" || modelData.type === "header" ? table.columnWidth : -1 + Layout.maximumWidth: modelData.type === "key" ? Kirigami.Units.gridUnit * 13 : table.columnWidth + sourceComponent: { + switch (modelData.type) { + case "header": + return header; + case "key": + return keyLabel; + case "cell": + return modelData.column.keys[modelData.key.value] !== undefined ? editor : null; + default: + return null; + } + } + + Component { + id: header + ColumnLayout { + spacing: 0 + RowLayout { + spacing: Kirigami.Units.smallSpacing + QQC2.Label { + Layout.fillWidth: true + text: cell.modelData.column.label + font.bold: true + wrapMode: Text.Wrap + } + Kirigami.ContextualHelpButton { + visible: cell.modelData.column.description !== "" + toolTipText: cell.modelData.column.description + } + } + QQC2.Label { + Layout.fillWidth: true + readonly property string error: table.rowError(cell.modelData.column) + visible: error !== "" + text: error + color: Kirigami.Theme.negativeTextColor + wrapMode: Text.Wrap + } + } + } + + Component { + id: keyLabel + QQC2.Label { + text: i18nc("@label:key name in the key table", "%1:", cell.modelData.key.name) + horizontalAlignment: Text.AlignRight + wrapMode: Text.Wrap + } + } + + Component { + id: editor + KeyCell { + column: cell.modelData.column + keyId: cell.modelData.key.value + keyName: cell.modelData.key.name + value: table.pending(cell.modelData.column)[cell.modelData.key.value] + defaultValue: cell.modelData.column.defaults === null ? undefined : cell.modelData.column.defaults[cell.modelData.key.value] + editable: cell.modelData.column.writable && table.online && !table.controller.saving + choiceDialog: table.choiceDialog + onEdited: value => table.controller.settings.stageKey(cell.modelData.column.row, cell.modelData.key.value, value) + } + } + } + } + } +} diff --git a/kcm/ui/PickerDialog.qml b/kcm/ui/PickerDialog.qml new file mode 100644 index 00000000..0be20c11 --- /dev/null +++ b/kcm/ui/PickerDialog.qml @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami + +// A searchable list to pick one value from many: KDE actions (grouped by component) or long choice lists. +// One instance is shared by a page; pick() fills it and calls back with the chosen value. +Kirigami.SearchDialog { + id: dialog + + property string searchPlaceholder + property var entries: [] // [{value, label, section, keywords}] + property var current: null + property var callback: null + + function pick(context: string, list: var, currentValue: var, done: var): void { + searchFieldPlaceholderText = context ? i18nc("@info:placeholder search field: what is being chosen", "Search: %1", context) : searchPlaceholder; + entries = list; + current = currentValue; + callback = done; + refill(""); + open(); + } + + function same(a: var, b: var): bool { + return JSON.stringify(a ?? null) === JSON.stringify(b ?? null); + } + + function refill(text: string): void { + results.clear(); + const needle = text.trim().toLowerCase(); + const rows = []; + entries.forEach((entry, index) => { + const haystack = `${entry.label} ${entry.section ?? ""} ${entry.keywords ?? ""}`.toLowerCase(); + if (needle === "" || haystack.includes(needle)) { + rows.push({ + label: entry.label, + section: entry.section ?? "", + entryIndex: index, + isCurrent: same(entry.value, current) + }); + } + }); + results.append(rows); + } + + function choose(entryIndex: int): void { + const done = callback; + const value = entries[entryIndex].value; + close(); + if (done) { + done(value); + } + } + + // as in SearchDialog, but safe while the window is torn down + width: Math.min(Kirigami.Units.gridUnit * 35, (parent?.width ?? 0) - leftMargin - rightMargin) + height: Math.min(Kirigami.Units.gridUnit * 20, parent?.height ?? 0) + searchFieldPlaceholderText: searchPlaceholder + emptyText: i18nc("@info:placeholder", "No match") + + onTextChanged: refill(text) + onAccepted: { + const item = currentItem as QQC2.ItemDelegate; + if (item) { + item.click(); + } + } + onClosed: callback = null + + model: ListModel { + id: results + } + + section.property: "section" + section.delegate: Kirigami.ListSectionHeader { + required property string section + width: ListView.view.width + text: section + visible: section !== "" + height: visible ? implicitHeight : 0 + } + + delegate: QQC2.ItemDelegate { + required property string label + required property int entryIndex + required property bool isCurrent + width: ListView.view.width + text: label + icon.name: isCurrent ? "checkmark" : "" + highlighted: ListView.isCurrentItem + onClicked: dialog.choose(entryIndex) + } +} diff --git a/kcm/ui/SettingRow.qml b/kcm/ui/SettingRow.qml new file mode 100644 index 00000000..002a28a4 --- /dev/null +++ b/kcm/ui/SettingRow.qml @@ -0,0 +1,254 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import org.kde.kcmutils as KCM +import io.github.fredaime.plasmaar + +// One setting of the schema as a form row, drawn according to its kind. Edits are staged in the model. +ColumnLayout { + id: row + + // from the settings model + required property int index + required property string name + required property string label + required property string description + required property string kind + required property bool writable + required property var choices + required property var min + required property var max + required property var pending + required property bool isDefault + required property string writeError + required property var readError + required property bool busy + + // from the page + required property Controller controller + required property PickerDialog choiceDialog + + readonly property bool readable: readError === undefined || readError === null + readonly property bool online: controller.currentDevice.online === true + readonly property bool editable: writable && readable && online && !controller.saving + + // choice lists: long numeric ones (dpi) become a stepped slider, long named ones a searchable list + readonly property var choiceList: kind === "CHOICE" && choices ? Array.from(choices) : [] + readonly property bool numericChoices: choiceList.length > 12 && choiceList.every(choice => String(choice.value) === choice.name) + readonly property int choiceIndex: choiceList.findIndex(choice => choice.value === pending) + + function stage(value: var): void { + controller.settings.stage(index, value); + } + + function summary(value: var): string { + if (value === null || value === undefined) { + return ""; + } + if (typeof value === "boolean") { + return value ? i18nc("@info setting value", "On") : i18nc("@info setting value", "Off"); + } + if (typeof value === "object") { + const keys = Object.keys(value); + if (keys.length > 0 && keys.every(key => typeof value[key] === "boolean")) { + // a set of flags (MULTIPLE_TOGGLE): the ones that are on + const on = keys.filter(key => value[key]); + return on.length > 0 ? on.join(", ") : i18nc("@info no flag is set", "None"); + } + return keys.map(key => `${key}: ${row.summary(value[key])}`).join(", "); + } + return String(value); + } + + spacing: Kirigami.Units.smallSpacing + Kirigami.FormData.label: i18nc("@label:setting form label", "%1:", label) + Kirigami.FormData.buddyFor: editor.item as Item + + RowLayout { + spacing: Kirigami.Units.smallSpacing + + Loader { + id: editor + active: row.visible // rows of other sections stay empty + enabled: row.editable // also greys out the form label + sourceComponent: { + if (!row.readable) { + return unreadable; + } + if (!row.writable) { + return readOnly; + } + switch (row.kind) { + case "TOGGLE": + return toggle; + case "RANGE": + return range; + case "CHOICE": + if (row.numericChoices) { + return steppedChoice; + } + return row.choiceList.length > 40 ? searchableChoice : choice; + default: + return readOnly; + } + } + } + + Kirigami.ContextualHelpButton { + visible: row.description !== "" + toolTipText: row.description + } + + QQC2.BusyIndicator { + visible: row.busy + running: visible + implicitWidth: Kirigami.Units.iconSizes.small + implicitHeight: Kirigami.Units.iconSizes.small + } + } + + QQC2.Label { + Layout.fillWidth: true + Layout.maximumWidth: Kirigami.Units.gridUnit * 16 + visible: row.writeError !== "" + text: row.writeError + color: Kirigami.Theme.negativeTextColor + wrapMode: Text.Wrap + } + + Component { + id: toggle + QQC2.Switch { + checked: row.pending === true + onToggled: row.stage(checked) + KCM.SettingHighlighter { + highlight: !row.isDefault + } + } + } + + Component { + id: choice + QQC2.ComboBox { + model: row.choiceList + textRole: "name" + valueRole: "value" + currentIndex: row.choiceIndex + onActivated: row.stage(currentValue) + KCM.SettingHighlighter { + highlight: !row.isDefault + } + } + } + + Component { + id: searchableChoice + QQC2.Button { + icon.name: "search" + text: row.choiceIndex >= 0 ? row.choiceList[row.choiceIndex].name : row.summary(row.pending) + onClicked: row.choiceDialog.pick(row.label, row.choiceList.map(entry => ({ + value: entry.value, + label: entry.name, + section: "" + })), row.pending, value => row.stage(value)) + KCM.SettingHighlighter { + highlight: !row.isDefault + } + } + } + + Component { + id: steppedChoice + RowLayout { + id: stepped + spacing: Kirigami.Units.smallSpacing + readonly property int step: row.choiceList.length > 1 ? row.choiceList[1].value - row.choiceList[0].value : 1 + + function nearest(value: real): int { + let best = row.choiceList[0].value; + for (const entry of row.choiceList) { + if (Math.abs(entry.value - value) < Math.abs(best - value)) { + best = entry.value; + } + } + return best; + } + + QQC2.Slider { + Layout.preferredWidth: Kirigami.Units.gridUnit * 10 + from: 0 + to: row.choiceList.length - 1 + // no stepSize: too many steps for tick marks; moves are rounded to a choice + value: Math.max(0, row.choiceIndex) + onMoved: row.stage(row.choiceList[Math.round(value)].value) + KCM.SettingHighlighter { + highlight: !row.isDefault + } + } + QQC2.SpinBox { + from: row.choiceList[0].value + to: row.choiceList[row.choiceList.length - 1].value + stepSize: Math.max(1, stepped.step) + editable: true + value: typeof row.pending === "number" ? row.pending : from + onValueModified: row.stage(stepped.nearest(value)) + } + } + } + + Component { + id: range + RowLayout { + spacing: Kirigami.Units.smallSpacing + QQC2.Slider { + Layout.preferredWidth: Kirigami.Units.gridUnit * 10 + from: row.min + to: row.max + // tick marks only for short ranges; moves are rounded to integers anyway + stepSize: to - from > 20 ? 0 : 1 + value: typeof row.pending === "number" ? row.pending : row.min + onMoved: row.stage(Math.round(value)) + KCM.SettingHighlighter { + highlight: !row.isDefault + } + } + QQC2.SpinBox { + from: row.min + to: row.max + editable: true + value: typeof row.pending === "number" ? row.pending : row.min + onValueModified: row.stage(value) + } + } + } + + Component { + id: readOnly + QQC2.Label { + text: { + const value = row.summary(row.pending); + return value ? i18nc("@info setting value that cannot be changed here", "%1 (read-only)", value) : i18nc("@info", "Read-only"); + } + color: Kirigami.Theme.disabledTextColor + wrapMode: Text.Wrap + Layout.maximumWidth: Kirigami.Units.gridUnit * 20 + } + } + + Component { + id: unreadable + QQC2.Label { + text: row.online ? i18nc("@info", "Could not be read: %1", String(row.readError)) + : i18nc("@info", "Unknown while the device is offline") + color: Kirigami.Theme.disabledTextColor + wrapMode: Text.Wrap + Layout.maximumWidth: Kirigami.Units.gridUnit * 20 + } + } +} diff --git a/kcm/ui/SettingsPage.qml b/kcm/ui/SettingsPage.qml new file mode 100644 index 00000000..ad96b416 --- /dev/null +++ b/kcm/ui/SettingsPage.qml @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import io.github.fredaime.plasmaar + +// The device's settings, drawn from the schema plasmaard sends, grouped in sections; per-key maps +// (button remapping and diversion) as a table at the end. +ColumnLayout { + id: page + + required property Controller controller + required property PickerDialog choiceDialog + + readonly property bool online: controller.currentDevice.online === true + + // on the haptics page instead + readonly property var elsewhere: ["haptic-level", "haptic-play"] + + readonly property var allSections: [ + { id: "wheel", title: i18nc("@title:group", "Scroll Wheel") }, + { id: "thumb", title: i18nc("@title:group", "Thumb Wheel") }, + { id: "pointer", title: i18nc("@title:group", "Pointer") }, + { id: "buttons", title: i18nc("@title:group", "Buttons") }, + { id: "keyboard", title: i18nc("@title:group", "Keyboard") }, + { id: "lighting", title: i18nc("@title:group", "Lighting") }, + { id: "audio", title: i18nc("@title:group", "Audio") }, + { id: "connection", title: i18nc("@title:group", "Connection") }, + { id: "other", title: i18nc("@title:group", "Other Settings") } + ] + + function sectionOf(name: string): string { + if (name.startsWith("thumb-")) { + return "thumb"; + } + if (/^(hires-|hi-res-|lowres-|smooth-scroll|side-scroll|scroll-|smart-shift|divert-crown|crown-)/.test(name)) { + return "wheel"; + } + if (/^(dpi|pointer_speed|speed-change|report_rate|onboard_profiles)/.test(name)) { + return "pointer"; + } + if (/^(force-sensing|analog-button|divert-gkeys|gesture2-)/.test(name)) { + return "buttons"; + } + if (/^(fn-swap|multiplatform|disable-keyboard-keys|hand-detection)/.test(name)) { + return "keyboard"; + } + if (/^(backlight|led|rgb|brightness|m-key-leds|mr-key-led|per-key-lighting)/.test(name)) { + return "lighting"; + } + if (/^(headset|sidetone|equalizer|adc_power)/.test(name)) { + return "audio"; + } + if (name === "change-host") { + return "connection"; + } + return "other"; + } + + function inForm(name: string, kind: string, display: bool): bool { + return display && kind !== "MAP_CHOICE" && !elsewhere.includes(name); + } + + readonly property var sections: { + const settings = controller.settings; + settings.revision; // recompute when the device's settings are replaced + const used = new Set(); + for (let i = 0; i < settings.count; ++i) { + const name = settings.field(i, "name"); + if (inForm(name, settings.field(i, "kind"), settings.field(i, "display"))) { + used.add(sectionOf(name)); + } + } + return allSections.filter(section => used.has(section.id)); + } + + spacing: Kirigami.Units.largeSpacing + + Kirigami.InlineMessage { + Layout.fillWidth: true + type: Kirigami.MessageType.Information + visible: !page.online && page.controller.settings.count > 0 + text: i18nc("@info", "The device is offline. These are the last known values; switch it on or wake it up to change them.") + } + + Kirigami.InlineMessage { + Layout.fillWidth: true + type: Kirigami.MessageType.Error + visible: page.controller.settingsState === Controller.FeatureState.Failed + text: i18nc("@info", "The settings could not be read: %1", page.controller.settingsError) + } + + Kirigami.PlaceholderMessage { + Layout.fillWidth: true + Layout.margins: Kirigami.Units.gridUnit * 2 + visible: page.controller.settingsState === Controller.FeatureState.Unavailable + icon.name: "configure" + text: i18nc("@info:placeholder", "This device has no settings") + } + + // the section layouts are twins of this one, so that all their labels line up + Kirigami.FormLayout { + id: anchorForm + Layout.fillWidth: true + } + + Repeater { + model: page.sections + + delegate: Kirigami.FormLayout { + id: sectionForm + + required property var modelData + + Layout.fillWidth: true + twinFormLayouts: [anchorForm] + + Item { + Kirigami.FormData.isSection: true + Kirigami.FormData.label: sectionForm.modelData.title + } + + Repeater { + model: page.controller.settings + + delegate: SettingRow { + id: setting + required property bool display + controller: page.controller + choiceDialog: page.choiceDialog + visible: page.inForm(setting.name, setting.kind, setting.display) + && page.sectionOf(setting.name) === sectionForm.modelData.id + } + } + } + } + + KeyMapTable { + Layout.fillWidth: true + Layout.topMargin: Kirigami.Units.largeSpacing + controller: page.controller + choiceDialog: page.choiceDialog + } +} diff --git a/kcm/ui/SnapshotRunner.qml b/kcm/ui/SnapshotRunner.qml new file mode 100644 index 00000000..d161d27a --- /dev/null +++ b/kcm/ui/SnapshotRunner.qml @@ -0,0 +1,147 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import org.kde.kirigami as Kirigami +import io.github.fredaime.plasmaar + +// Snapshot mode (PLASMAAR_KCM_SNAPSHOT=/path/prefix): once the data has loaded, show every page of every +// device, grow the window to fit it, save --.png, then quit. Used to review the +// module headless; see docs/kcm.md. It never writes to the service, except in the "apply-errors" scenario +// that kcm/run-snapshots.sh only enables against the mock service. +Item { + id: runner + + required property var page // the KCM root page + required property Controller controller + required property PickerDialog actionDialog + + readonly property string prefix: controller.snapshotPrefix + readonly property int windowWidth: 920 + property var steps: [] // functions; one that returns false runs again at the next tick + property bool started: false + + function fitWindow(): void { + const flickable = page.flickable; + // contentHeight leaves out the page's padding: add some slack so that no scroll bar shows + const overflow = Math.ceil(flickable.contentHeight - flickable.height) + Kirigami.Units.gridUnit * 2; + controller.resizeTopLevelWindows(windowWidth, Math.max(560, controller.topLevelWindowHeight() + overflow)); + } + + function shoot(name: string): void { + const path = `${prefix}-${name}.png`; + console.info(controller.grabTopLevelWindow(path) ? `snapshot: ${path}` : `snapshot FAILED: ${path}`); + } + + function slug(name: string): string { + return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); + } + + function loaded(): bool { + return controller.ready && !controller.loading; + } + + // the pages of the device that is shown, and the action picker if asked + function pageSteps(device: string, withPicker: bool): var { + const result = []; + for (const entry of page.pages) { + const id = entry.id; + result.push(() => { + page.currentPage = id; + controller.resizeTopLevelWindows(windowWidth, 560); + }, () => fitWindow(), () => shoot(`${device}-${id}`)); + } + if (withPicker && page.pages.some(entry => entry.id === "buttons") && controller.buttons.count > 0 + && controller.kdeActionsState === Controller.FeatureState.Available) { + result.push(() => { + page.currentPage = "buttons"; + controller.resizeTopLevelWindows(windowWidth, 720); + }, () => { + const buttons = controller.buttons; + const row = Math.max(0, buttons.indexOf("195")); + actionDialog.pick(buttons.field(row, "name"), page.actionEntries, buttons.pendingValue(row).gestures?.up ?? null, () => {}); + }, () => shoot(`${device}-buttons-picker`), () => actionDialog.close()); + } + return result; + } + + function deviceSteps(index: int, withPicker: bool): var { + const devices = controller.devices; + if (index >= devices.length) { + return []; + } + const device = devices[index]; + return [() => { + page.currentPage = "settings"; + controller.currentDeviceId = device.id; + }, () => {}, () => loaded(), () => { + // planned now that the device's pages are known; the picker once, for the first device with buttons + const picker = withPicker && controller.buttons.count > 0; + steps = pageSteps(slug(device.name), picker).concat(deviceSteps(index + 1, withPicker && !picker), steps); + }]; + } + + function plan(): var { + if (!page.hasDevice) { + return [() => fitWindow(), () => shoot(controller.serviceState === Controller.ServiceState.Missing ? "missing" : "empty")]; + } + if (controller.snapshotScenario === "apply-errors") { + // stage a few edits and apply them; the mock is started with --fail for some of them + return [() => { + const settings = controller.settings; + settings.stage(settings.indexOf("dpi"), 2400); + settings.stage(settings.indexOf("smart-shift"), 20); + settings.stage(settings.indexOf("hires-smooth-invert"), true); + controller.save(); + }, () => !controller.saving, () => { + steps = pageSteps(`${slug(controller.currentDevice.name)}-apply-errors`, false).concat(steps); + }]; + } + return deviceSteps(0, true); + } + + function step(): void { + if (steps.length === 0) { + controller.quitApplication(); + return; + } + const next = steps.shift(); + if (next() === false) { + steps.unshift(next); // not yet + } + timer.restart(); + } + + Timer { + id: timer + interval: 500 + onTriggered: runner.step() + } + + Timer { + id: settle + interval: 1000 + onTriggered: { + runner.started = true; + runner.steps = runner.plan(); + runner.step(); + } + } + + Component.onCompleted: { + if (controller.ready) { + settle.start(); + } + } + + Connections { + target: runner.controller + function onReadyChanged(): void { + if (runner.controller.ready && !runner.started) { + settle.restart(); + } + } + } +} diff --git a/kcm/ui/main.qml b/kcm/ui/main.qml new file mode 100644 index 00000000..f1af5396 --- /dev/null +++ b/kcm/ui/main.qml @@ -0,0 +1,238 @@ +// SPDX-FileCopyrightText: 2026 plasmaar contributors +// SPDX-License-Identifier: GPL-2.0-or-later + +pragma ComponentBehavior: Bound + +import QtQuick +import QtQuick.Layouts +import QtQuick.Controls as QQC2 +import org.kde.kirigami as Kirigami +import org.kde.kcmutils as KCM +import io.github.fredaime.plasmaar + +KCM.SimpleKCM { + id: root + + readonly property Controller controller: kcm.controller // qmllint disable unqualified + + readonly property bool serviceRunning: controller.serviceState === Controller.ServiceState.Running + readonly property bool hasDevice: serviceRunning && controller.currentDeviceId !== "" + readonly property bool pagesShown: hasDevice && !controller.loading + + // the pages that make sense for the current device + readonly property var pages: { + const result = [{ + id: "settings", + title: i18nc("@title:tab", "Settings"), + icon: "configure" + }]; + const buttons = controller.buttonsState; + if (buttons === Controller.FeatureState.Available || buttons === Controller.FeatureState.Failed + || (buttons === Controller.FeatureState.NeedsNewerService && settingsHave("divert-keys"))) { + result.push({ + id: "buttons", + title: controller.currentDevice.kind === "keyboard" ? i18nc("@title:tab keyboard keys", "Keys") : i18nc("@title:tab", "Buttons"), + icon: "input-mouse-click-left" + }); + } + if (settingsHave("haptic-level") || controller.waveforms.length > 0 + || controller.hapticEventsState === Controller.FeatureState.Available) { + result.push({ + id: "haptics", + title: i18nc("@title:tab", "Haptic Feedback"), + icon: "preferences-desktop-notification-bell" + }); + } + return result; + } + property string currentPage: "settings" + onPagesChanged: { + if (!pages.some(page => page.id === currentPage)) { + currentPage = "settings"; + } + } + + // the KDE actions as picker entries, grouped by component + readonly property var actionEntries: { + const entries = []; + for (const component of controller.kdeActions) { + for (const action of component.actions ?? []) { + entries.push({ + value: { + component: component.component, + action: action.name + }, + label: action.label || action.name, + section: component.label || component.component, + keywords: `${action.name} ${component.component}` + }); + } + } + return entries; + } + + function settingsHave(name: string): bool { + controller.settings.count; // re-evaluate when the settings change + return controller.settings.indexOf(name) >= 0; + } + + implicitWidth: Kirigami.Units.gridUnit * 40 + implicitHeight: Kirigami.Units.gridUnit * 36 + + header: ColumnLayout { + visible: root.hasDevice + spacing: 0 + + DeviceHeader { + Layout.fillWidth: true + Layout.margins: Kirigami.Units.largeSpacing + controller: root.controller + } + + QQC2.TabBar { + id: tabBar + Layout.fillWidth: true + visible: root.pages.length > 1 + currentIndex: root.pages.findIndex(page => page.id === root.currentPage) + onCurrentIndexChanged: { + if (currentIndex >= 0 && currentIndex < root.pages.length) { + root.currentPage = root.pages[currentIndex].id; + } + } + + QQC2.TabButton { + text: root.pages[0].title + icon.name: root.pages[0].icon + } + + Repeater { + model: root.pages.slice(1) + delegate: QQC2.TabButton { + required property var modelData + text: modelData.title + icon.name: modelData.icon + } + } + } + + Kirigami.Separator { + Layout.fillWidth: true + visible: !tabBar.visible + } + } + + ColumnLayout { + id: content + spacing: Kirigami.Units.largeSpacing + + Kirigami.InlineMessage { + Layout.fillWidth: true + type: Kirigami.MessageType.Error + text: root.controller.saveError + visible: text !== "" + showCloseButton: true + } + + Kirigami.InlineMessage { + Layout.fillWidth: true + type: Kirigami.MessageType.Warning + text: root.controller.notice + visible: text !== "" && root.currentPage !== "haptics" + showCloseButton: true + onVisibleChanged: if (!visible) root.controller.clearNotice() + } + + // The pages of the current device. They are rebuilt for another device (while it loads), rather + // than having all their rows replaced under the form layouts. + Loader { + Layout.fillWidth: true + active: root.pagesShown + visible: active + + sourceComponent: ColumnLayout { + spacing: Kirigami.Units.largeSpacing + + SettingsPage { + Layout.fillWidth: true + visible: root.currentPage === "settings" + controller: root.controller + choiceDialog: choicePicker + } + + ButtonsPage { + Layout.fillWidth: true + visible: root.currentPage === "buttons" + controller: root.controller + actionDialog: actionPicker + actionEntries: root.actionEntries + } + + HapticsPage { + Layout.fillWidth: true + visible: root.currentPage === "haptics" + controller: root.controller + choiceDialog: choicePicker + } + } + } + + // --- no device to show --- + + Item { + Layout.fillWidth: true + Layout.preferredHeight: root.flickable.height - Kirigami.Units.largeSpacing * 4 + visible: !root.pagesShown + + Kirigami.LoadingPlaceholder { + anchors.centerIn: parent + visible: root.controller.serviceState === Controller.ServiceState.Checking + || (root.serviceRunning && root.controller.loading) + text: i18nc("@info:placeholder", "Connecting to plasmaard…") + } + + Kirigami.PlaceholderMessage { + anchors.centerIn: parent + width: parent.width - Kirigami.Units.gridUnit * 4 + visible: root.controller.serviceState === Controller.ServiceState.Missing + icon.name: "input-mouse" + text: i18nc("@info:placeholder", "The plasmaard service is not running") + explanation: xi18nc("@info:placeholder", + "Logitech devices are managed by the plasmaard user service. Start it here, or in a terminal with systemctl --user start plasmaard.It starts with your Plasma session once it is installed with make install_user_service.") + helpfulAction: Kirigami.Action { + icon.name: "media-playback-start" + text: i18nc("@action:button", "Start plasmaard") + onTriggered: root.controller.startService() + } + } + + Kirigami.PlaceholderMessage { + anchors.centerIn: parent + width: parent.width - Kirigami.Units.gridUnit * 4 + visible: root.serviceRunning && root.controller.ready && root.controller.devices.length === 0 + icon.name: "input-mouse" + text: i18nc("@info:placeholder", "No Logitech device found") + explanation: i18nc("@info:placeholder", "Switch your mouse or keyboard on, or pair it with this computer over Bluetooth or a Logitech receiver.") + } + } + } + + // shared pickers, opened by the pages + PickerDialog { + id: actionPicker + searchPlaceholder: i18nc("@info:placeholder", "Search KDE actions…") + } + + PickerDialog { + id: choicePicker + searchPlaceholder: i18nc("@info:placeholder", "Search…") + } + + Loader { + active: root.controller.snapshotPrefix !== "" + sourceComponent: SnapshotRunner { + page: root + controller: root.controller + actionDialog: actionPicker + } + } +} diff --git a/tools/mock_plasmaard.py b/tools/mock_plasmaard.py new file mode 100644 index 00000000..44646e32 --- /dev/null +++ b/tools/mock_plasmaard.py @@ -0,0 +1,607 @@ +#!/usr/bin/env python3 +## Copyright (C) 2026 plasmaar contributors +## +## This program 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 2 of the License, or +## (at your option) any later version. +## +## This program 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 this program; if not, write to the Free Software Foundation, Inc., +## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +"""A fake plasmaard for developing and testing D-Bus clients (the System Settings module) without hardware. + +It implements the whole io.github.fredaime.Plasmaar1 contract (docs/dbus-api.md plus the button-action and +haptic-event additions) with data captured from a real MX Master 4, K850 and MX Anywhere 3S +(tools/mock_plasmaard_data.json). State is mutable in memory and every change emits the same signals as the +real service. It owns the bus name on whatever bus DBUS_SESSION_BUS_ADDRESS points to, so run it inside an +isolated bus: + + dbus-run-session -- bash -c 'python3 tools/mock_plasmaard.py & sleep 1; kcmshell6 kcm_plasmaar' + +It refuses to start when the name is already owned (the real plasmaard on your session bus). + +A second interface, io.github.fredaime.PlasmaarMock, lets tests simulate changes made on the device itself: +SetDeviceValue(id, name, value_json), SetOnline(id, online), SetBattery(id, level); and Quit() (the service +going away). +""" + +from __future__ import annotations + +import argparse +import copy +import json +import os +import re +import sys + +from gi.repository import Gio +from gi.repository import GLib + +BUS_NAME = "io.github.fredaime.Plasmaar" +OBJECT_PATH = "/io/github/fredaime/Plasmaar" +INTERFACE = "io.github.fredaime.Plasmaar1" +MOCK_INTERFACE = "io.github.fredaime.PlasmaarMock" +ERROR_PREFIX = INTERFACE + ".Error." + +HERE = os.path.dirname(os.path.abspath(__file__)) +DATA_FILE = os.path.join(HERE, "mock_plasmaard_data.json") +PO_DIR = os.path.join(os.path.dirname(HERE), "po") + +MX4 = "B04200000000-BD2BC136" +K850 = "B34D40620000-FF883310" +MX3S = "B03700000000-3F51C045" + +# Values that differ from what the real devices reported, so that "Defaults" has something to do, and the +# value plasmaard captured when it first saw each device ("default"). Settings not listed keep their current +# value as default; change-host and haptic-play have none (absent, as for a setting plasmaard never saw). +CURRENT_OVERRIDES = {MX4: {"dpi": 1600, "haptic-level": 80, "scroll-ratchet-torque": 60}} +DEFAULT_OVERRIDES = { + MX4: { + "dpi": 1000, + "haptic-level": 100, + "smart-shift": 10, + "divert-keys": {k: 0 for k in ("82", "83", "86", "195", "196", "416")}, + }, + K850: {"fn-swap": True}, +} +NO_DEFAULT = {"change-host", "haptic-play"} + +V1_METHODS = """ + + + + + + + + + + + + + + + + + + + + + + + +""" +ADDED_METHODS = """ + + + + + + + + + + + + + + + + +""" +MOCK_METHODS = f""" + + + + + + + + + + + + + +""" + +ADDED_NAMES = {"ListKdeActions", "GetButtonActions", "SetButtonAction", "GetHapticEvents", "SetHapticEvent"} +DIRECTIONS = ("up", "down", "left", "right", "click") +EVENT_LABELS = { + "notification": ("New notification", "Nouvelle notification"), + "desktop_switch": ("Virtual desktop switch", "Changement de bureau virtuel"), + "battery_low": ("Low battery", "Batterie faible"), +} + + +class ApiError(Exception): + def __init__(self, name, message): + super().__init__(message) + self.dbus_name = name + + +def log(*args): + print("mock_plasmaard:", *args, file=sys.stderr, flush=True) + + +# --- translations, so that labels come "already localized" as from the real service --- + + +def _language(): + for var in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"): + value = os.environ.get(var) + if value: + return value.split(":")[0].split(".")[0].split("_")[0] + return "en" + + +def _po_catalog(lang): + path = os.path.join(PO_DIR, f"{lang}.po") + catalog = {} + if not os.path.exists(path): + return catalog + msgid = msgstr = None + target = None + + def unquote(text): + return json.loads(text) if text.startswith('"') else "" + + def flush(): + if msgid and msgstr: + catalog[msgid] = msgstr + + with open(path, encoding="utf-8") as f: + for line in f: + line = line.strip() + if line.startswith("msgid "): + flush() + msgid, msgstr, target = unquote(line[6:]), None, "id" + elif line.startswith("msgstr "): + msgstr, target = unquote(line[7:]), "str" + elif line.startswith('"') and target == "id": + msgid += unquote(line) + elif line.startswith('"') and target == "str": + msgstr += unquote(line) + elif not line or line.startswith("#"): + target = None + flush() + return catalog + + +class Translator: + def __init__(self, lang): + self.lang = lang + self.catalog = _po_catalog(lang) if lang != "en" else {} + + def __call__(self, text): + if not self.catalog or not isinstance(text, str): + return text + if text in self.catalog: + return self.catalog[text] + # descriptions are several messages joined by newlines + parts = re.split(r"(\n+)", text) + return "".join(self.catalog.get(p, p) for p in parts) + + +# --- the fake devices --- + + +def _expand_choices(choices, shared): + if isinstance(choices, str): + return shared[choices] + if isinstance(choices, dict) and "numeric" in choices: + low, high, step = choices["numeric"] + return [{"value": v, "name": str(v)} for v in range(low, high + 1, step)] + return choices + + +class Device: + def __init__(self, description, settings, shared, tr): + self.info = copy.deepcopy(description) + self.settings = {} + for s in settings: + s = copy.deepcopy(s) + s["label"], s["description"] = tr(s["label"]), tr(s["description"]) + if "choices" in s: + s["choices"] = [{**c, "name": tr(c["name"])} for c in _expand_choices(s["choices"], shared)] + for key in s.get("keys", []): + key["name"] = tr(key["name"]) + if "choices" in key: + key["choices"] = [{**c, "name": tr(c["name"])} for c in _expand_choices(key["choices"], shared)] + self.settings[s["name"]] = s + dev_id = self.id + for name, value in CURRENT_OVERRIDES.get(dev_id, {}).items(): + self.settings[name]["value"] = value + for name, s in self.settings.items(): + if name in NO_DEFAULT or s["value"] is None: + continue + s["default"] = copy.deepcopy(DEFAULT_OVERRIDES.get(dev_id, {}).get(name, s["value"])) + self.buttons = self._initial_buttons() + self.haptic_events = self._initial_haptic_events(tr) + + @property + def id(self): + return self.info["id"] + + def waveforms(self): + play = self.settings.get("haptic-play") + return [c["name"] for c in play["choices"]] if play else [] + + def _initial_buttons(self): + divert = self.settings.get("divert-keys") + if not divert: + return [] + buttons = [] + for key in divert["keys"]: + names = {c["value"] for c in key["choices"]} + modes = ["off"] + (["press"] if 1 in names else []) + (["gesture"] if 2 in names else []) + buttons.append( + { + "control": key["value"], + "name": key["name"], + "modes": modes, + "mode": "off", + "press": None, + "gestures": {d: None for d in DIRECTIONS}, + } + ) + if self.id == MX4: # what docs/kde-actions.md sets up + by_control = {b["control"]: b for b in buttons} + by_control[416].update(mode="press", press={"component": "kwin", "action": "Overview"}) + by_control[195]["mode"] = "gesture" + by_control[195]["gestures"].update( + up={"component": "kwin", "action": "Grid View"}, + down={"component": "kwin", "action": "Show Desktop"}, + left={"component": "kwin", "action": "Switch One Desktop to the Left"}, + right={"component": "kwin", "action": "Switch One Desktop to the Right"}, + ) + return buttons + + def _initial_haptic_events(self, tr): + if not self.waveforms(): + return [] + lang_fr = tr.lang == "fr" + initial = {"notification": "SUBTLE COLLISION", "desktop_switch": "SHARP STATE CHANGE", "battery_low": None} + return [ + {"event": event, "label": labels[1] if lang_fr else labels[0], "waveform": initial[event]} + for event, labels in EVENT_LABELS.items() + ] + + def public_settings(self, with_defaults): + result = [] + for s in self.settings.values(): + s = copy.deepcopy(s) + if not with_defaults: + s.pop("default", None) + if not self.info["online"] and s["value"] is None: + s["error"] = "device is offline" + result.append(s) + return result + + +def _check_choice(value, choices): + if isinstance(value, str): + match = next((c for c in choices if c["name"] == value), None) + if match is not None: + return match["value"] + if isinstance(value, int) and not isinstance(value, bool) and any(c["value"] == value for c in choices): + return value + raise ApiError("InvalidValue", f"{value!r} is not one of {[c['name'] for c in choices][:10]}") + + +def _check_range(value, low, high): + if isinstance(value, bool) or not isinstance(value, int) or not low <= value <= high: + raise ApiError("InvalidValue", f"{value!r} is not an integer in [{low}, {high}]") + return value + + +def _from_json(text): + try: + return json.loads(text) + except (TypeError, ValueError) as e: + raise ApiError("InvalidValue", f"not valid JSON: {text!r}") from e + + +def _to_json(value): + return json.dumps(value) + + +class MockService: + def __init__(self, args): + self.args = args + tr = Translator(_language()) + with open(DATA_FILE, encoding="utf-8") as f: + data = json.load(f) + self.devices = {} + for entry in data["devices"]: + device = Device(entry["device"], entry["settings"], data["shared_choices"], tr) + self.devices[device.id] = device + # MX Anywhere 3S sits in a drawer: offline, battery unknown + mx3s = self.devices.get(MX3S) + if mx3s: + mx3s.info.update(online=False, battery={"level": None, "status": None}) + self.kde_actions = data["kde_actions"] + if tr.lang != "fr": # the captured labels are French; elsewhere show the action ids + for component in self.kde_actions: + for action in component["actions"]: + action["label"] = action["name"] + self.connection = None + self.loop = None + xml = "\n %s%s%s" % ( + INTERFACE, + V1_METHODS, + "" if args.legacy else ADDED_METHODS, + MOCK_METHODS, + ) + self.node_info = Gio.DBusNodeInfo.new_for_xml(xml) + + # --- bus plumbing --- + + def start(self, loop): + self.loop = loop + + def acquired(connection, _name): + self.connection = connection + for interface in self.node_info.interfaces: + connection.register_object(OBJECT_PATH, interface, self._method_call, None, None) + + def name_acquired(_connection, name): + log(f"serving {name} ({'v1 only' if self.args.legacy else 'v1 + additions'}) with", len(self.devices), "devices") + + def name_lost(_connection, name): + log(f"cannot own {name}: is plasmaard already running on this bus? Run me inside dbus-run-session.") + loop.quit() + + Gio.bus_own_name(Gio.BusType.SESSION, BUS_NAME, Gio.BusNameOwnerFlags.DO_NOT_QUEUE, acquired, name_acquired, name_lost) + + def emit(self, signal, signature, args): + if self.args.verbose: + log("signal", signal, args) + self.connection.emit_signal(None, OBJECT_PATH, INTERFACE, signal, GLib.Variant(signature, args)) + + def _method_call(self, _connection, _sender, _path, interface, method, parameters, invocation): + handler = getattr(self, ("mock_" if interface == MOCK_INTERFACE else "do_") + method, None) + if handler is None or (self.args.legacy and method in ADDED_NAMES): + invocation.return_dbus_error("org.freedesktop.DBus.Error.UnknownMethod", f"no method {method}") + return + args = parameters.unpack() + if self.args.verbose: + log("call", method, *(a if len(str(a)) < 120 else str(a)[:120] + "…" for a in args)) + + def reply(): + try: + result = handler(*args) + except ApiError as e: + invocation.return_dbus_error(ERROR_PREFIX + e.dbus_name, str(e)) + else: + invocation.return_value(GLib.Variant("(s)", (result,)) if result is not None else None) + return False + + if self.args.delay and method not in ("GetVersion",): + GLib.timeout_add(self.args.delay, reply) + else: + reply() + + def device(self, dev_id, online=False): + device = self.devices.get(dev_id) + if device is None: + raise ApiError("NoSuchDevice", f"no device {dev_id!r}") + if online and not device.info["online"]: + raise ApiError("DeviceOffline", f"{dev_id} is offline") + return device + + def setting(self, device, name): + setting = device.settings.get(name) + if setting is None: + raise ApiError("NoSuchSetting", f"{device.id} has no setting {name!r}") + return setting + + def check_failure(self, name): + if name in self.args.fail: + raise ApiError("Failed", f"writing {name} failed (simulated by mock_plasmaard --fail)") + + # --- v1 --- + + def do_GetVersion(self): + return "1" + + def do_ListDevices(self): + return _to_json([d.info for d in self.devices.values()]) + + def do_ListSettings(self, dev_id): + return _to_json(self.device(dev_id).public_settings(with_defaults=not self.args.legacy)) + + def do_SetSetting(self, dev_id, name, value_json): + device = self.device(dev_id, online=True) + setting = self.setting(device, name) + value = _from_json(value_json) + kind = setting["kind"] + if kind == "TOGGLE": + if not isinstance(value, bool): + raise ApiError("InvalidValue", f"{name} needs true or false, not {value!r}") + elif kind == "CHOICE": + value = _check_choice(value, setting["choices"]) + elif kind == "RANGE": + value = _check_range(value, setting["min"], setting["max"]) + else: + raise ApiError("NotSupported", f"{name} ({kind}) cannot be written as a whole through the API") + self.check_failure(name) + setting["value"] = value + self.emit("SettingChanged", "(sss)", (dev_id, name, _to_json(value))) + return _to_json(value) + + def do_SetSettingKey(self, dev_id, name, key_json, value_json): + device = self.device(dev_id, online=True) + setting = self.setting(device, name) + if setting["kind"] != "MAP_CHOICE": + raise ApiError("NotSupported", f"{name} is not a per-key setting") + key = _from_json(key_json) + try: + key = int(key) + except (TypeError, ValueError) as e: + raise ApiError("InvalidValue", f"key {key!r} is not an integer") from e + space = next((k for k in setting["keys"] if k["value"] == key), None) + if space is None: + raise ApiError("InvalidValue", f"{name} has no key {key!r}") + value = _from_json(value_json) + if "choices" in space: + value = _check_choice(value, space["choices"]) + else: + value = _check_range(value, space["min"], space["max"]) + self.check_failure(name) + setting["value"][str(key)] = value + self.emit("SettingChanged", "(sss)", (dev_id, name, _to_json(setting["value"]))) + if name == "divert-keys": + self._sync_button_mode(device, key, value) + return _to_json(setting["value"]) + + def do_PlayHaptic(self, dev_id, waveform): + device = self.device(dev_id, online=True) + if not device.waveforms(): + raise ApiError("NotSupported", f"{dev_id} cannot play haptic waveforms") + if waveform not in device.waveforms(): + raise ApiError("InvalidValue", f"{waveform!r} is not one of {device.waveforms()}") + log(f"*bzz* {device.info['name']} plays {waveform}") + return None + + # --- additions --- + + def do_ListKdeActions(self): + return _to_json(self.kde_actions) + + def do_GetButtonActions(self, dev_id): + device = self.device(dev_id) + return _to_json({"device_id": dev_id, "buttons": device.buttons}) + + def do_SetButtonAction(self, dev_id, control, config_json): + device = self.device(dev_id) + button = next((b for b in device.buttons if b["control"] == control), None) + if button is None: + raise ApiError("InvalidValue", f"{dev_id} has no divertable button {control}") + config = _from_json(config_json) + if not isinstance(config, dict) or config.get("mode") not in button["modes"]: + raise ApiError("InvalidValue", f"mode must be one of {button['modes']}") + + def action(value): + if value is None: + return None + if not isinstance(value, dict) or not value.get("component") or not value.get("action"): + raise ApiError("InvalidValue", f"an action is {{'component': …, 'action': …}} or null, not {value!r}") + return {"component": str(value["component"]), "action": str(value["action"])} + + press = action(config.get("press")) + gestures = config.get("gestures") or {} + if not isinstance(gestures, dict) or set(gestures) - set(DIRECTIONS): + raise ApiError("InvalidValue", f"gestures takes the directions {DIRECTIONS}") + gestures = {d: action(gestures.get(d)) for d in DIRECTIONS} + self.check_failure(f"button:{control}") + button.update(mode=config["mode"], press=press, gestures=gestures) + divert = device.settings.get("divert-keys") + wanted = {"off": 0, "press": 1, "gesture": 2}[button["mode"]] + if divert and divert["value"].get(str(control)) != wanted: + divert["value"][str(control)] = wanted + self.emit("SettingChanged", "(sss)", (dev_id, "divert-keys", _to_json(divert["value"]))) + self.emit("ButtonActionsChanged", "(s)", (dev_id,)) + return _to_json(button) + + def _sync_button_mode(self, device, control, divert_value): + button = next((b for b in device.buttons if b["control"] == control), None) + mode = {0: "off", 1: "press", 2: "gesture"}.get(divert_value, "off") + if button and button["mode"] != mode and mode in button["modes"]: + button["mode"] = mode + self.emit("ButtonActionsChanged", "(s)", (device.id,)) + + def do_GetHapticEvents(self, dev_id): + device = self.device(dev_id) + if not device.haptic_events: + raise ApiError("NotSupported", f"{dev_id} has no haptic motor") + return _to_json({"device_id": dev_id, "waveforms": device.waveforms(), "events": device.haptic_events}) + + def do_SetHapticEvent(self, dev_id, event, waveform): + device = self.device(dev_id) + entry = next((e for e in device.haptic_events if e["event"] == event), None) + if entry is None: + raise ApiError("InvalidValue", f"{dev_id} has no haptic event {event!r}") + if waveform and waveform not in device.waveforms(): + raise ApiError("InvalidValue", f"{waveform!r} is not one of {device.waveforms()}") + self.check_failure(f"haptic:{event}") + entry["waveform"] = waveform or None + return _to_json(entry) + + # --- test hooks: changes "made on the device" --- + + def mock_SetDeviceValue(self, dev_id, name, value_json): + device = self.device(dev_id) + setting = self.setting(device, name) + setting["value"] = _from_json(value_json) + self.emit("SettingChanged", "(sss)", (dev_id, name, _to_json(setting["value"]))) + + def mock_SetOnline(self, dev_id, online): + device = self.device(dev_id) + device.info["online"] = bool(online) + self.emit("DeviceChanged", "(s)", (_to_json(device.info),)) + + def mock_SetBattery(self, dev_id, level): + device = self.device(dev_id) + device.info["battery"] = {"level": level, "status": "DISCHARGING"} if level >= 0 else {"level": None, "status": None} + self.emit("DeviceChanged", "(s)", (_to_json(device.info),)) + + def mock_Quit(self): + log("quitting") + GLib.timeout_add(50, self.loop.quit) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--legacy", action="store_true", help="v1 API only, like a plasmaard without the additions") + parser.add_argument( + "--fail", + action="append", + default=[], + metavar="NAME", + help="make writes of this setting fail (also button:, haptic:); repeatable", + ) + parser.add_argument("--delay", type=int, default=0, metavar="MS", help="answer every call after MS milliseconds") + parser.add_argument("--verbose", "-v", action="store_true", help="log calls and signals") + args = parser.parse_args(argv) + if not os.environ.get("DBUS_SESSION_BUS_ADDRESS"): + log("DBUS_SESSION_BUS_ADDRESS is not set; run me inside dbus-run-session") + return 2 + loop = GLib.MainLoop() + MockService(args).start(loop) + try: + loop.run() + except KeyboardInterrupt: + pass + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mock_plasmaard_data.json b/tools/mock_plasmaard_data.json new file mode 100644 index 00000000..5952df72 --- /dev/null +++ b/tools/mock_plasmaard_data.json @@ -0,0 +1,1343 @@ +{ + "comment": "Mock data for tools/mock_plasmaard.py, captured read-only from a real plasmaard (MX Master 4 + K850 + MX Anywhere 3S) and kglobalaccel on 2026-10-03.", + "shared_choices": { + "@k850-remap": [ + {"value": 2147483647, "name": "Default"}, + {"value": 0, "name": "No Output (only as default)"}, + {"value": 16777216, "name": "No Output"}, + {"value": 16778240, "name": "A"}, + {"value": 16778496, "name": "B"}, + {"value": 16778752, "name": "C"}, + {"value": 16779008, "name": "D"}, + {"value": 16779264, "name": "E"}, + {"value": 16779520, "name": "F"}, + {"value": 16779776, "name": "G"}, + {"value": 16780032, "name": "H"}, + {"value": 16780288, "name": "I"}, + {"value": 16780544, "name": "J"}, + {"value": 16780800, "name": "K"}, + {"value": 16781056, "name": "L"}, + {"value": 16781312, "name": "M"}, + {"value": 16781568, "name": "N"}, + {"value": 16781824, "name": "O"}, + {"value": 16782080, "name": "P"}, + {"value": 16782336, "name": "Q"}, + {"value": 16782592, "name": "R"}, + {"value": 16782848, "name": "S"}, + {"value": 16783104, "name": "T"}, + {"value": 16783360, "name": "U"}, + {"value": 16783616, "name": "V"}, + {"value": 16783872, "name": "W"}, + {"value": 16784128, "name": "X"}, + {"value": 16784384, "name": "Y"}, + {"value": 16784640, "name": "Z"}, + {"value": 16784896, "name": "1"}, + {"value": 16785152, "name": "2"}, + {"value": 16785408, "name": "3"}, + {"value": 16785664, "name": "4"}, + {"value": 16785920, "name": "5"}, + {"value": 16786176, "name": "6"}, + {"value": 16786432, "name": "7"}, + {"value": 16786688, "name": "8"}, + {"value": 16786944, "name": "9"}, + {"value": 16787200, "name": "0"}, + {"value": 16787456, "name": "ENTER"}, + {"value": 16787712, "name": "ESC"}, + {"value": 16787968, "name": "BACKSPACE"}, + {"value": 16788224, "name": "TAB"}, + {"value": 16788480, "name": "SPACE"}, + {"value": 16788736, "name": "MINUS"}, + {"value": 16788992, "name": "EQUAL"}, + {"value": 16789248, "name": "LEFTBRACE"}, + {"value": 16789504, "name": "RIGHTBRACE"}, + {"value": 16789760, "name": "BACKSLASH"}, + {"value": 16790016, "name": "HASHTILDE"}, + {"value": 16790272, "name": "SEMICOLON"}, + {"value": 16790528, "name": "APOSTROPHE"}, + {"value": 16790784, "name": "GRAVE"}, + {"value": 16791040, "name": "COMMA"}, + {"value": 16791296, "name": "DOT"}, + {"value": 16791552, "name": "SLASH"}, + {"value": 16791808, "name": "CAPSLOCK"}, + {"value": 16792064, "name": "F1"}, + {"value": 16792320, "name": "F2"}, + {"value": 16792576, "name": "F3"}, + {"value": 16792832, "name": "F4"}, + {"value": 16793088, "name": "F5"}, + {"value": 16793344, "name": "F6"}, + {"value": 16793600, "name": "F7"}, + {"value": 16793856, "name": "F8"}, + {"value": 16794112, "name": "F9"}, + {"value": 16794368, "name": "F10"}, + {"value": 16794624, "name": "F11"}, + {"value": 16794880, "name": "F12"}, + {"value": 16795136, "name": "SYSRQ"}, + {"value": 16795392, "name": "SCROLLLOCK"}, + {"value": 16795648, "name": "PAUSE"}, + {"value": 16795904, "name": "INSERT"}, + {"value": 16796160, "name": "HOME"}, + {"value": 16796416, "name": "PAGEUP"}, + {"value": 16796672, "name": "DELETE"}, + {"value": 16796928, "name": "END"}, + {"value": 16797184, "name": "PAGEDOWN"}, + {"value": 16797440, "name": "RIGHT"}, + {"value": 16797696, "name": "LEFT"}, + {"value": 16797952, "name": "DOWN"}, + {"value": 16798208, "name": "UP"}, + {"value": 16798464, "name": "NUMLOCK"}, + {"value": 16798720, "name": "KPSLASH"}, + {"value": 16798976, "name": "KPASTERISK"}, + {"value": 16799232, "name": "KPMINUS"}, + {"value": 16799488, "name": "KPPLUS"}, + {"value": 16799744, "name": "KPENTER"}, + {"value": 16800000, "name": "KP1"}, + {"value": 16800256, "name": "KP2"}, + {"value": 16800512, "name": "KP3"}, + {"value": 16800768, "name": "KP4"}, + {"value": 16801024, "name": "KP5"}, + {"value": 16801280, "name": "KP6"}, + {"value": 16801536, "name": "KP7"}, + {"value": 16801792, "name": "KP8"}, + {"value": 16802048, "name": "KP9"}, + {"value": 16802304, "name": "KP0"}, + {"value": 16802560, "name": "KPDOT"}, + {"value": 16802816, "name": "102ND"}, + {"value": 16803072, "name": "COMPOSE"}, + {"value": 16803328, "name": "POWER"}, + {"value": 16803584, "name": "KPEQUAL"}, + {"value": 16803840, "name": "F13"}, + {"value": 16804096, "name": "F14"}, + {"value": 16804352, "name": "F15"}, + {"value": 16804608, "name": "F16"}, + {"value": 16804864, "name": "F17"}, + {"value": 16805120, "name": "F18"}, + {"value": 16805376, "name": "F19"}, + {"value": 16805632, "name": "F20"}, + {"value": 16805888, "name": "F21"}, + {"value": 16806144, "name": "F22"}, + {"value": 16806400, "name": "F23"}, + {"value": 16806656, "name": "F24"}, + {"value": 16806912, "name": "OPEN"}, + {"value": 16807168, "name": "HELP"}, + {"value": 16807424, "name": "PROPS"}, + {"value": 16807680, "name": "FRONT"}, + {"value": 16807936, "name": "STOP"}, + {"value": 16808192, "name": "AGAIN"}, + {"value": 16808448, "name": "UNDO"}, + {"value": 16808704, "name": "CUT"}, + {"value": 16808960, "name": "COPY"}, + {"value": 16809216, "name": "PASTE"}, + {"value": 16809472, "name": "FIND"}, + {"value": 16809728, "name": "MUTE"}, + {"value": 16809984, "name": "VOLUMEUP"}, + {"value": 16810240, "name": "VOLUMEDOWN"}, + {"value": 16811264, "name": "KPCOMMA"}, + {"value": 16811776, "name": "RO"}, + {"value": 16812032, "name": "KATAKANAHIRAGANA"}, + {"value": 16812288, "name": "YEN"}, + {"value": 16812544, "name": "HENKAN"}, + {"value": 16812800, "name": "MUHENKAN"}, + {"value": 16813056, "name": "KPJPCOMMA"}, + {"value": 16814080, "name": "HANGEUL"}, + {"value": 16814336, "name": "HANJA"}, + {"value": 16814592, "name": "KATAKANA"}, + {"value": 16814848, "name": "HIRAGANA"}, + {"value": 16815104, "name": "ZENKAKUHANKAKU"}, + {"value": 16823808, "name": "KPLEFTPAREN"}, + {"value": 16824064, "name": "KPRIGHTPAREN"}, + {"value": 16834560, "name": "LEFTCTRL"}, + {"value": 16834816, "name": "LEFTSHIFT"}, + {"value": 16835072, "name": "LEFTALT"}, + {"value": 16835328, "name": "LEFTWINDOWS"}, + {"value": 16835584, "name": "RIGHTCTRL"}, + {"value": 16835840, "name": "RIGHTSHIFT"}, + {"value": 16836096, "name": "RIGHTALT"}, + {"value": 16836352, "name": "RIGHTMETA"}, + {"value": 16836608, "name": "MEDIA PLAYPAUSE"}, + {"value": 16836864, "name": "MEDIA STOPCD"}, + {"value": 16837120, "name": "MEDIA PREVIOUSSONG"}, + {"value": 16837376, "name": "MEDIA NEXTSONG"}, + {"value": 16837632, "name": "MEDIA EJECTCD"}, + {"value": 16837888, "name": "MEDIA VOLUMEUP"}, + {"value": 16838144, "name": "MEDIA VOLUMEDOWN"}, + {"value": 16838400, "name": "MEDIA MUTE"}, + {"value": 16838656, "name": "MEDIA WWW"}, + {"value": 16838912, "name": "MEDIA BACK"}, + {"value": 16839168, "name": "MEDIA FORWARD"}, + {"value": 16839424, "name": "MEDIA STOP"}, + {"value": 16839680, "name": "MEDIA FIND"}, + {"value": 16839936, "name": "MEDIA SCROLLUP"}, + {"value": 16840192, "name": "MEDIA SCROLLDOWN"}, + {"value": 16840448, "name": "MEDIA EDIT"}, + {"value": 16840704, "name": "MEDIA SLEEP"}, + {"value": 16840960, "name": "MEDIA COFFEE"}, + {"value": 16841216, "name": "MEDIA REFRESH"}, + {"value": 16841472, "name": "MEDIA CALC"}, + {"value": 16777222, "name": "Alt+Shift+No Output"}, + {"value": 117452800, "name": "Power"}, + {"value": 117453056, "name": "Reset"}, + {"value": 117453312, "name": "Sleep"}, + {"value": 117453568, "name": "Sleep After"}, + {"value": 117453824, "name": "Sleep Mode"}, + {"value": 117454080, "name": "Illumination"}, + {"value": 117454336, "name": "Function Buttons"}, + {"value": 117456896, "name": "Menu"}, + {"value": 117457152, "name": "Menu/Pick"}, + {"value": 117457408, "name": "Menu Up"}, + {"value": 117457664, "name": "Menu Down"}, + {"value": 117457920, "name": "Menu Left"}, + {"value": 117458176, "name": "Menu Right"}, + {"value": 117458432, "name": "Menu Escape"}, + {"value": 117458688, "name": "Menu Value Increase"}, + {"value": 117458944, "name": "Menu Value Decrease"}, + {"value": 117465088, "name": "Data On Screen"}, + {"value": 117465344, "name": "Closed Caption"}, + {"value": 117465856, "name": "VCR/TV"}, + {"value": 117466368, "name": "Snapshot"}, + {"value": 117467392, "name": "Red"}, + {"value": 117467648, "name": "Green"}, + {"value": 117467904, "name": "Blue"}, + {"value": 117468160, "name": "Yellow"}, + {"value": 117468416, "name": "Aspect Ratio"}, + {"value": 117468928, "name": "Brightness Up"}, + {"value": 117469184, "name": "Brightness Down"}, + {"value": 117469696, "name": "Brightness Toggle"}, + {"value": 117469952, "name": "Brightness Min"}, + {"value": 117470208, "name": "Brightness Max"}, + {"value": 117470464, "name": "Brightness Auto"}, + {"value": 117471488, "name": "Keyboard Illumination Up"}, + {"value": 117471744, "name": "Keyboard Illumination Down"}, + {"value": 117472256, "name": "Keyboard Illumination Toggle"}, + {"value": 117473792, "name": "Mode Step"}, + {"value": 117474048, "name": "Recall Last"}, + {"value": 117474304, "name": "Enter Channel"}, + {"value": 117475328, "name": "Media Select Computer"}, + {"value": 117475584, "name": "Media Select TV"}, + {"value": 117475840, "name": "Media Select WWW"}, + {"value": 117476096, "name": "Media Select DVD"}, + {"value": 117476352, "name": "Media Select Telephone"}, + {"value": 117476608, "name": "Media Select Program Guide"}, + {"value": 117476864, "name": "Media Select Video Phone"}, + {"value": 117477120, "name": "Media Select Games"}, + {"value": 117477376, "name": "Media Select Messages"}, + {"value": 117477632, "name": "Media Select CD"}, + {"value": 117477888, "name": "Media Select VCR"}, + {"value": 117478144, "name": "Media Select Tuner"}, + {"value": 117478400, "name": "Quit"}, + {"value": 117478656, "name": "Help"}, + {"value": 117478912, "name": "Media Select Tape"}, + {"value": 117479168, "name": "Media Select Cable"}, + {"value": 117479424, "name": "Media Select Satellite"}, + {"value": 117479680, "name": "Media Select Security"}, + {"value": 117479936, "name": "Media Select Home"}, + {"value": 117480448, "name": "Channel Increment"}, + {"value": 117480704, "name": "Channel Decrement"}, + {"value": 117481472, "name": "VCR Plus"}, + {"value": 117485568, "name": "Play"}, + {"value": 117485824, "name": "Pause"}, + {"value": 117486080, "name": "Record"}, + {"value": 117486336, "name": "Fast Forward"}, + {"value": 117486592, "name": "Rewind"}, + {"value": 117486848, "name": "Scan Next Track"}, + {"value": 117487104, "name": "Scan Previous Track"}, + {"value": 117487360, "name": "Stop"}, + {"value": 117487616, "name": "Eject"}, + {"value": 117487872, "name": "Random Play"}, + {"value": 117488128, "name": "Select DisC"}, + {"value": 117488384, "name": "Enter Disc"}, + {"value": 117488640, "name": "Repeat"}, + {"value": 117488896, "name": "Tracking"}, + {"value": 117489152, "name": "Track Normal"}, + {"value": 117489408, "name": "Slow Tracking"}, + {"value": 117492992, "name": "Play/Pause"}, + {"value": 117497856, "name": "Volume"}, + {"value": 117498368, "name": "Mute"}, + {"value": 117499136, "name": "Bass Boost"}, + {"value": 117500160, "name": "Volume Up"}, + {"value": 117500416, "name": "Volume Down"}, + {"value": 117503232, "name": "Slow"}, + {"value": 117506048, "name": "Fan Enable"}, + {"value": 117506304, "name": "Fan Speed"}, + {"value": 117506560, "name": "Light"}, + {"value": 117506816, "name": "Light Illumination Level"}, + {"value": 117507072, "name": "Climate Control Enable"}, + {"value": 117507328, "name": "Room Temperature"}, + {"value": 117507584, "name": "Security Enable"}, + {"value": 117507840, "name": "Fire Alarm"}, + {"value": 117508096, "name": "Police Alarm"}, + {"value": 117508352, "name": "Proximity"}, + {"value": 117508608, "name": "Motion"}, + {"value": 117508864, "name": "Duress Alarm"}, + {"value": 117509120, "name": "Holdup Alarm"}, + {"value": 117509376, "name": "Medical Alarm"}, + {"value": 117526528, "name": "Balance Right"}, + {"value": 117526784, "name": "Balance Left"}, + {"value": 117527040, "name": "Bass Increment"}, + {"value": 117527296, "name": "Bass Decrement"}, + {"value": 117527552, "name": "Treble Increment"}, + {"value": 117527808, "name": "Treble Decrement"}, + {"value": 117530624, "name": "Speaker System"}, + {"value": 117530880, "name": "Channel Left"}, + {"value": 117531136, "name": "Channel Right"}, + {"value": 117531392, "name": "Channel Center"}, + {"value": 117531648, "name": "Channel Front"}, + {"value": 117531904, "name": "Channel Center Front"}, + {"value": 117532160, "name": "Channel Side"}, + {"value": 117532416, "name": "Channel Surround"}, + {"value": 117532672, "name": "Channel Low Frequency Enhancement"}, + {"value": 117532928, "name": "Channel Top"}, + {"value": 117533184, "name": "Channel Unknown"}, + {"value": 117534720, "name": "Subchannel"}, + {"value": 117534976, "name": "Subchannel Increment"}, + {"value": 117535232, "name": "Subchannel Decrement"}, + {"value": 117535488, "name": "Alternate Audio Increment"}, + {"value": 117535744, "name": "Alternate Audio Decrement"}, + {"value": 117538816, "name": "Application Launch Buttons"}, + {"value": 117539072, "name": "AL Launch Button Configuration Tool"}, + {"value": 117539328, "name": "AL Programmable Button Configuration"}, + {"value": 117539584, "name": "AL Consumer Control Configuration"}, + {"value": 117539840, "name": "AL Word Processor"}, + {"value": 117540096, "name": "AL Text Editor"}, + {"value": 117540352, "name": "AL Spreadsheet"}, + {"value": 117540608, "name": "AL Graphics Editor"}, + {"value": 117540864, "name": "AL Presentation App"}, + {"value": 117541120, "name": "AL Database App"}, + {"value": 117541376, "name": "AL Email Reader"}, + {"value": 117541632, "name": "AL Newsreader"}, + {"value": 117541888, "name": "AL Voicemail"}, + {"value": 117542144, "name": "AL Contacts/Address Book"}, + {"value": 117542400, "name": "AL Calendar/Schedule"}, + {"value": 117542656, "name": "AL Task/Project Manager"}, + {"value": 117542912, "name": "AL Log/Journal/Timecard"}, + {"value": 117543168, "name": "AL Checkbook/Finance"}, + {"value": 117543424, "name": "AL Calculator"}, + {"value": 117543680, "name": "AL A/V Capture/Playback"}, + {"value": 117543936, "name": "AL Local Machine Browser"}, + {"value": 117544192, "name": "AL LAN/WAN Browser"}, + {"value": 117544448, "name": "AL Internet Browser"}, + {"value": 117544704, "name": "AL Remote Networking/ISP Connect"}, + {"value": 117544960, "name": "AL Network Conference"}, + {"value": 117545216, "name": "AL Network Chat"}, + {"value": 117545472, "name": "AL Telephony/Dialer"}, + {"value": 117545728, "name": "AL Logon"}, + {"value": 117545984, "name": "AL Logoff"}, + {"value": 117546240, "name": "AL Logon/Logoff"}, + {"value": 117546496, "name": "AL Terminal Lock/Screensaver"}, + {"value": 117546752, "name": "AL Control Panel"}, + {"value": 117547008, "name": "AL Command Line Processor/Run"}, + {"value": 117547264, "name": "AL Process/Task Manager"}, + {"value": 117547520, "name": "AL Select Tast/Application"}, + {"value": 117547776, "name": "AL Next Task/Application"}, + {"value": 117548032, "name": "AL Previous Task/Application"}, + {"value": 117548288, "name": "AL Preemptive Halt Task/Application"}, + {"value": 117548544, "name": "AL Integrated Help Center"}, + {"value": 117548800, "name": "AL Documents"}, + {"value": 117549056, "name": "AL Thesaurus"}, + {"value": 117549312, "name": "AL Dictionary"}, + {"value": 117549568, "name": "AL Desktop"}, + {"value": 117549824, "name": "AL Spell Check"}, + {"value": 117550080, "name": "AL Grammar Check"}, + {"value": 117550336, "name": "AL Wireless Status"}, + {"value": 117550592, "name": "AL Keyboard Layout"}, + {"value": 117550848, "name": "AL Virus Protection"}, + {"value": 117551104, "name": "AL Encryption"}, + {"value": 117551360, "name": "AL Screen Saver"}, + {"value": 117551616, "name": "AL Alarms"}, + {"value": 117551872, "name": "AL Clock"}, + {"value": 117552128, "name": "AL File Browser"}, + {"value": 117552384, "name": "AL Power Status"}, + {"value": 117552640, "name": "AL Image Browser"}, + {"value": 117552896, "name": "AL Audio Browser"}, + {"value": 117553152, "name": "AL Movie Browser"}, + {"value": 117553408, "name": "AL Digital Rights Manager"}, + {"value": 117553664, "name": "AL Digital Wallet"}, + {"value": 117554176, "name": "AL Instant Messaging"}, + {"value": 117554432, "name": "AL OEM Features/ Tips/Tutorial Browser"}, + {"value": 117554688, "name": "AL OEM Help"}, + {"value": 117554944, "name": "AL Online Community"}, + {"value": 117555200, "name": "AL Entertainment Content Browser"}, + {"value": 117555456, "name": "AL Online Shopping Browser"}, + {"value": 117555712, "name": "AL SmartCard Information/Help"}, + {"value": 117555968, "name": "AL Market Monitor/Finance Browser"}, + {"value": 117556224, "name": "AL Customized Corporate News Browser"}, + {"value": 117556480, "name": "AL Online Activity Browser"}, + {"value": 117556736, "name": "AL Research/Search Browser"}, + {"value": 117556992, "name": "AL Audio Player"}, + {"value": 117571584, "name": "Generic GUI Application Controls"}, + {"value": 117571840, "name": "AC New"}, + {"value": 117572096, "name": "AC Open"}, + {"value": 117572352, "name": "AC Close"}, + {"value": 117572608, "name": "AC Exit"}, + {"value": 117572864, "name": "AC Maximize"}, + {"value": 117573120, "name": "AC Minimize"}, + {"value": 117573376, "name": "AC Save"}, + {"value": 117573632, "name": "AC Print"}, + {"value": 117573888, "name": "AC Properties"}, + {"value": 117578240, "name": "AC Undo"}, + {"value": 117578496, "name": "AC Copy"}, + {"value": 117578752, "name": "AC Cut"}, + {"value": 117579008, "name": "AC Paste"}, + {"value": 117579264, "name": "AC Select All"}, + {"value": 117579520, "name": "AC Find"}, + {"value": 117579776, "name": "AC Find and Replace"}, + {"value": 117580032, "name": "AC Search"}, + {"value": 117580288, "name": "AC Go To"}, + {"value": 117580544, "name": "AC Home"}, + {"value": 117580800, "name": "AC Back"}, + {"value": 117581056, "name": "AC Forward"}, + {"value": 117581312, "name": "AC Stop"}, + {"value": 117581568, "name": "AC Refresh"}, + {"value": 117581824, "name": "AC Previous Link"}, + {"value": 117582080, "name": "AC Next Link"}, + {"value": 117582336, "name": "AC Bookmarks"}, + {"value": 117582592, "name": "AC History"}, + {"value": 117582848, "name": "AC Subscriptions"}, + {"value": 117583104, "name": "AC Zoom In"}, + {"value": 117583360, "name": "AC Zoom Out"}, + {"value": 117583616, "name": "AC Zoom"}, + {"value": 117583872, "name": "AC Full Screen View"}, + {"value": 117584128, "name": "AC Normal View"}, + {"value": 117584384, "name": "AC View Toggle"}, + {"value": 117584640, "name": "AC Scroll Up"}, + {"value": 117584896, "name": "AC Scroll Down"}, + {"value": 117585152, "name": "AC Scroll"}, + {"value": 117585408, "name": "AC Pan Left"}, + {"value": 117585664, "name": "AC Pan Right"}, + {"value": 117585920, "name": "AC Pan"}, + {"value": 117586176, "name": "AC New Window"}, + {"value": 117586432, "name": "AC Tile Horizontally"}, + {"value": 117586688, "name": "AC Tile Vertically"}, + {"value": 117586944, "name": "AC Format"}, + {"value": 117587200, "name": "AC Edit"}, + {"value": 117587456, "name": "AC Bold"}, + {"value": 117587712, "name": "AC Italics"}, + {"value": 117587968, "name": "AC Underline"}, + {"value": 117588224, "name": "AC Strikethrough"}, + {"value": 117588480, "name": "AC Subscript"}, + {"value": 117588736, "name": "AC Superscript"}, + {"value": 117588992, "name": "AC All Caps"}, + {"value": 117589248, "name": "AC Rotate"}, + {"value": 117589504, "name": "AC Resize"}, + {"value": 117589760, "name": "AC Flip horizontal"}, + {"value": 117590016, "name": "AC Flip Vertical"}, + {"value": 117590272, "name": "AC Mirror Horizontal"}, + {"value": 117590528, "name": "AC Mirror Vertical"}, + {"value": 117590784, "name": "AC Font Select"}, + {"value": 117591040, "name": "AC Font Color"}, + {"value": 117591296, "name": "AC Font Size"}, + {"value": 117591552, "name": "AC Justify Left"}, + {"value": 117591808, "name": "AC Justify Center H"}, + {"value": 117592064, "name": "AC Justify Right"}, + {"value": 117592320, "name": "AC Justify Block H"}, + {"value": 117592576, "name": "AC Justify Top"}, + {"value": 117592832, "name": "AC Justify Center V"}, + {"value": 117593088, "name": "AC Justify Bottom"}, + {"value": 117593344, "name": "AC Justify Block V"}, + {"value": 117593600, "name": "AC Indent Decrease"}, + {"value": 117593856, "name": "AC Indent Increase"}, + {"value": 117594112, "name": "AC Numbered List"}, + {"value": 117594368, "name": "AC Restart Numbering"}, + {"value": 117594624, "name": "AC Bulleted List"}, + {"value": 117594880, "name": "AC Promote"}, + {"value": 117595136, "name": "AC Demote"}, + {"value": 117595392, "name": "AC Yes"}, + {"value": 117595648, "name": "AC No"}, + {"value": 117595904, "name": "AC Cancel"}, + {"value": 117596160, "name": "AC Catalog"}, + {"value": 117596416, "name": "AC Buy/Checkout"}, + {"value": 117596672, "name": "AC Add to Cart"}, + {"value": 117596928, "name": "AC Expand"}, + {"value": 117597184, "name": "AC Expand All"}, + {"value": 117597440, "name": "AC Collapse"}, + {"value": 117597696, "name": "AC Collapse All"}, + {"value": 117597952, "name": "AC Print Preview"}, + {"value": 117598208, "name": "AC Paste Special"}, + {"value": 117598464, "name": "AC Insert Mode"}, + {"value": 117598720, "name": "AC Delete"}, + {"value": 117598976, "name": "AC Lock"}, + {"value": 117599232, "name": "AC Unlock"}, + {"value": 117599488, "name": "AC Protect"}, + {"value": 117599744, "name": "AC Unprotect"}, + {"value": 117600000, "name": "AC Attach Comment"}, + {"value": 117600256, "name": "AC Delete Comment"}, + {"value": 117600512, "name": "AC View Comment"}, + {"value": 117600768, "name": "AC Select Word"}, + {"value": 117601024, "name": "AC Select Sentence"}, + {"value": 117601280, "name": "AC Select Paragraph"}, + {"value": 117601536, "name": "AC Select Column"}, + {"value": 117601792, "name": "AC Select Row"}, + {"value": 117602048, "name": "AC Select Table"}, + {"value": 117602304, "name": "AC Select Object"}, + {"value": 117602560, "name": "AC Redo/Repeat"}, + {"value": 117602816, "name": "AC Sort"}, + {"value": 117603072, "name": "AC Sort Ascending"}, + {"value": 117603328, "name": "AC Sort Descending"}, + {"value": 117603584, "name": "AC Filter"}, + {"value": 117603840, "name": "AC Set Clock"}, + {"value": 117604096, "name": "AC View Clock"}, + {"value": 117604352, "name": "AC Select Time Zone"}, + {"value": 117604608, "name": "AC Edit Time Zones"}, + {"value": 117604864, "name": "AC Set Alarm"}, + {"value": 117605120, "name": "AC Clear Alarm"}, + {"value": 117605376, "name": "AC Snooze Alarm"}, + {"value": 117605632, "name": "AC Reset Alarm"}, + {"value": 117605888, "name": "AC Synchronize"}, + {"value": 117606144, "name": "AC Send/Receive"}, + {"value": 117606400, "name": "AC Send To"}, + {"value": 117606656, "name": "AC Reply"}, + {"value": 117606912, "name": "AC Reply All"}, + {"value": 117607168, "name": "AC Forward Msg"}, + {"value": 117607424, "name": "AC Send"}, + {"value": 117607680, "name": "AC Attach File"}, + {"value": 117607936, "name": "AC Upload"}, + {"value": 117608192, "name": "AC Download Save Target As"}, + {"value": 117608448, "name": "AC Set Borders"}, + {"value": 117608704, "name": "AC Insert Row"}, + {"value": 117608960, "name": "AC Insert Column"}, + {"value": 117609216, "name": "AC Insert File"}, + {"value": 117609472, "name": "AC Insert Picture"}, + {"value": 117609728, "name": "AC Insert Object"}, + {"value": 117609984, "name": "AC Insert Symbol"}, + {"value": 117610240, "name": "AC Save and Close"}, + {"value": 117610496, "name": "AC Rename"}, + {"value": 117610752, "name": "AC Merge"}, + {"value": 117611008, "name": "AC Split"}, + {"value": 117611264, "name": "AC Distribute Horizontally"}, + {"value": 117611520, "name": "AC Distribute Vertically"} + ] + }, + "devices": [ + { + "device": { + "id": "B04200000000-BD2BC136", + "name": "MX Master 4", + "codename": "MX Master 4", + "kind": "mouse", + "online": true, + "protocol": 4.5, + "model_id": "B04200000000", + "unit_id": "BD2BC136", + "serial": "", + "battery": {"level": 45, "status": "DISCHARGING"} + }, + "settings": [ + {"name": "hires-smooth-invert", "label": "Scroll Wheel Direction", "description": "Invert direction for vertical scroll with wheel.", "kind": "TOGGLE", "display": true, "writable": true, "value": false}, + {"name": "hires-smooth-resolution", "label": "Scroll Wheel Resolution", "description": "High-sensitivity mode for vertical scroll with the wheel.\nSet to ignore if scrolling is abnormally fast or slow", "kind": "TOGGLE", "display": true, "writable": true, "value": true}, + {"name": "hires-scroll-mode", "label": "Scroll Wheel Diversion", "description": "Make scroll wheel send HIRES_WHEEL HID++ notifications (which trigger Solaar rules but are otherwise ignored).", "kind": "TOGGLE", "display": true, "writable": true, "value": false}, + {"name": "scroll-ratchet-torque", "label": "Scroll Wheel Ratchet Torque", "description": "Change the torque needed to overcome the ratchet.", "kind": "RANGE", "display": true, "writable": true, "min": 1, "max": 100, "value": 75}, + { + "name": "scroll-ratchet", + "label": "Scroll Wheel Ratcheted", + "description": "Switch the mouse wheel between speed-controlled ratcheting and always freespin.", + "kind": "CHOICE", + "display": true, + "writable": true, + "choices": [ + {"value": 1, "name": "Freespinning"}, + {"value": 2, "name": "Ratcheted"} + ], + "value": 2 + }, + {"name": "smart-shift", "label": "Scroll Wheel Ratchet Speed", "description": "Use the mouse wheel speed to switch between ratcheted and freespinning.\nThe mouse wheel is always ratcheted at 50.", "kind": "RANGE", "display": true, "writable": true, "min": 1, "max": 50, "value": 12}, + {"name": "thumb-scroll-invert", "label": "Thumb Wheel Direction", "description": "Invert thumb wheel scroll direction.", "kind": "TOGGLE", "display": true, "writable": true, "value": false}, + {"name": "thumb-scroll-mode", "label": "Thumb Wheel Diversion", "description": "Make thumb wheel send THUMB_WHEEL HID++ notifications (which trigger Solaar rules but are otherwise ignored).", "kind": "TOGGLE", "display": true, "writable": true, "value": false}, + { + "name": "dpi", + "label": "Sensitivity (DPI)", + "description": "Mouse movement sensitivity\nMay need Onboard Profiles set to Disable to be effective.", + "kind": "CHOICE", + "display": true, + "writable": true, + "choices": { + "numeric": [200, 8000, 50] + }, + "value": 1000 + }, + { + "name": "reprogrammable-keys", + "label": "Key/Button Actions", + "description": "Change the action for the key or button. Overridden by diversion.\nChanging important actions (such as for the left mouse button) can result in an unusable system.", + "kind": "MAP_CHOICE", + "display": true, + "writable": true, + "keys": [ + { + "value": 82, + "name": "Middle Button", + "choices": [ + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 83, "name": "Mouse Back Button"}, + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 195, "name": "Gesture Button"}, + {"value": 196, "name": "Smart Shift"}, + {"value": 416, "name": "unknown:0109"} + ] + }, + { + "value": 83, + "name": "Back Button", + "choices": [ + {"value": 83, "name": "Mouse Back Button"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 195, "name": "Gesture Button"}, + {"value": 196, "name": "Smart Shift"}, + {"value": 416, "name": "unknown:0109"} + ] + }, + { + "value": 86, + "name": "Forward Button", + "choices": [ + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 83, "name": "Mouse Back Button"}, + {"value": 195, "name": "Gesture Button"}, + {"value": 196, "name": "Smart Shift"}, + {"value": 416, "name": "unknown:0109"} + ] + }, + { + "value": 195, + "name": "Mouse Gesture Button", + "choices": [ + {"value": 195, "name": "Gesture Button"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 83, "name": "Mouse Back Button"}, + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 196, "name": "Smart Shift"}, + {"value": 416, "name": "unknown:0109"} + ] + }, + { + "value": 196, + "name": "Smart Shift", + "choices": [ + {"value": 196, "name": "Smart Shift"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 83, "name": "Mouse Back Button"}, + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 195, "name": "Gesture Button"}, + {"value": 416, "name": "unknown:0109"} + ] + }, + { + "value": 416, + "name": "Haptic", + "choices": [ + {"value": 416, "name": "unknown:0109"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 83, "name": "Mouse Back Button"}, + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 195, "name": "Gesture Button"}, + {"value": 196, "name": "Smart Shift"} + ] + } + ], + "value": {"82": 82, "83": 83, "86": 86, "195": 195, "196": 196, "416": 416} + }, + { + "name": "divert-keys", + "label": "Key/Button Diversion", + "description": "Make the key or button send HID++ notifications (Diverted) or initiate Mouse Gestures or Sliding DPI", + "kind": "MAP_CHOICE", + "display": true, + "writable": true, + "keys": [ + { + "value": 82, + "name": "Middle Button", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + }, + { + "value": 83, + "name": "Back Button", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + }, + { + "value": 86, + "name": "Forward Button", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + }, + { + "value": 195, + "name": "Mouse Gesture Button", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + }, + { + "value": 196, + "name": "Smart Shift", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + }, + { + "value": 416, + "name": "Haptic", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + } + ], + "value": {"82": 0, "83": 0, "86": 0, "195": 2, "196": 0, "416": 1} + }, + {"name": "force-sensing", "label": "Force Sensing Button", "description": "Change the force required to activate button.", "kind": "RANGE", "display": true, "writable": true, "min": 4134, "max": 6872, "value": 5167}, + { + "name": "change-host", + "label": "Change Host", + "description": "Switch connection to a different host", + "kind": "CHOICE", + "display": true, + "writable": true, + "choices": [ + {"value": 0, "name": "1:hermes"}, + {"value": 1, "name": "2:HERMES"}, + {"value": 2, "name": "3:hermes"} + ], + "value": 2 + }, + {"name": "haptic-level", "label": "Haptic Feedback Level", "description": "Change power of haptic feedback. (Zero to turn off.)", "kind": "RANGE", "display": true, "writable": true, "min": 0, "max": 100, "value": 100}, + { + "name": "haptic-play", + "label": "Play Haptic Waveform", + "description": "Tell device to play a haptic waveform.", + "kind": "CHOICE", + "display": false, + "writable": true, + "choices": [ + {"value": 0, "name": "SHARP STATE CHANGE"}, + {"value": 1, "name": "DAMP STATE CHANGE"}, + {"value": 2, "name": "SHARP COLLISION"}, + {"value": 3, "name": "DAMP COLLISION"}, + {"value": 4, "name": "SUBTLE COLLISION"}, + {"value": 5, "name": "HAPPY ALERT"}, + {"value": 6, "name": "ANGRY ALERT"}, + {"value": 7, "name": "COMPLETED"}, + {"value": 8, "name": "SQUARE"}, + {"value": 9, "name": "WAVE"}, + {"value": 10, "name": "FIREWORK"}, + {"value": 11, "name": "MAD"}, + {"value": 12, "name": "KNOCK"}, + {"value": 13, "name": "JINGLE"}, + {"value": 14, "name": "RINGING"}, + {"value": 27, "name": "WHISPER COLLISION"} + ], + "value": null + } + ] + }, + { + "device": { + "id": "B34D40620000-FF883310", + "name": "K850 Performance Wireless Keyboard", + "codename": "Keyboard K850", + "kind": "keyboard", + "online": true, + "protocol": 4.5, + "model_id": "B34D40620000", + "unit_id": "FF883310", + "serial": "", + "battery": {"level": 90, "status": "DISCHARGING"} + }, + "settings": [ + {"name": "fn-swap", "label": "Swap Fx function", "description": "When set, the F1..F12 keys will activate their special function,\nand you must hold the FN key to activate their standard function.\n\nWhen unset, the F1..F12 keys will activate their standard function,\nand you must hold the FN key to activate their special function.", "kind": "TOGGLE", "display": true, "writable": true, "value": false}, + { + "name": "persistent-remappable-keys", + "label": "Persistent Key/Button Mapping", + "description": "Permanently change the mapping for the key or button.\nChanging important keys or buttons (such as for the left mouse button) can result in an unusable system.", + "kind": "MAP_CHOICE", + "display": true, + "writable": true, + "keys": [ + {"value": 213, "name": "MultiPlatform Home/Mission Control", "choices": "@k850-remap"}, + {"value": 214, "name": "MultiPlatform Menu/Show/Hide Virtual Keyboard/Launchpad", "choices": "@k850-remap"}, + {"value": 189, "name": "Multiplatform Back", "choices": "@k850-remap"}, + {"value": 212, "name": "MultiPlatform Search", "choices": "@k850-remap"}, + {"value": 6, "name": "Previous", "choices": "@k850-remap"}, + {"value": 4, "name": "Play/Pause old", "choices": "@k850-remap"}, + {"value": 5, "name": "Next", "choices": "@k850-remap"}, + {"value": 3, "name": "Mute", "choices": "@k850-remap"}, + {"value": 2, "name": "Volume Down old", "choices": "@k850-remap"}, + {"value": 1, "name": "Volume Up old", "choices": "@k850-remap"}, + {"value": 194, "name": "Multiplatform Lock", "choices": "@k850-remap"}, + {"value": 221, "name": "Multi Platform Language Switch", "choices": "@k850-remap"}, + {"value": 191, "name": "Screen Capture/Print Screen", "choices": "@k850-remap"}, + {"value": 10, "name": "Calculator", "choices": "@k850-remap"} + ], + "value": {"213": 117580544, "214": 16803072, "189": 117580800, "212": 117580032, "6": 117487104, "4": 117492992, "5": 117486848, "3": 117498368, "2": 117500416, "1": 117500160, "194": 2147483647, "221": 16777222, "191": 16795136, "10": 117543424} + }, + { + "name": "divert-keys", + "label": "Key/Button Diversion", + "description": "Make the key or button send HID++ notifications (Diverted) or initiate Mouse Gestures or Sliding DPI", + "kind": "MAP_CHOICE", + "display": true, + "writable": true, + "keys": [ + { + "value": 209, + "name": "Host Switch Channel 1", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 210, + "name": "Host Switch Channel 2", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 211, + "name": "Host Switch Channel 3", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 213, + "name": "MultiPlatform Home/Mission Control", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 214, + "name": "MultiPlatform Menu/Show/Hide Virtual Keyboard/Launchpad", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 189, + "name": "Multiplatform Back", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 212, + "name": "MultiPlatform Search", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 6, + "name": "Previous", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 4, + "name": "Play/Pause old", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 5, + "name": "Next", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 3, + "name": "Mute", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 2, + "name": "Volume Down old", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 1, + "name": "Volume Up old", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 194, + "name": "Multiplatform Lock", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 221, + "name": "Multi Platform Language Switch", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 191, + "name": "Screen Capture/Print Screen", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 10, + "name": "Calculator", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 193, + "name": "Fn Up", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + }, + { + "value": 192, + "name": "Fn Down", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"} + ] + } + ], + "value": {"1": 0, "2": 0, "3": 0, "4": 0, "5": 0, "6": 0, "10": 0, "189": 0, "191": 0, "192": 0, "193": 0, "194": 0, "209": 0, "210": 0, "211": 0, "212": 0, "213": 0, "214": 0, "221": 0} + }, + { + "name": "disable-keyboard-keys", + "label": "Disable keys", + "description": "Disable specific keyboard keys.", + "kind": "MULTIPLE_TOGGLE", + "display": true, + "writable": false, + "value": {"1": false, "2": false, "4": false, "8": false, "16": false} + }, + { + "name": "multiplatform", + "label": "Set OS", + "description": "Change keys to match OS.", + "kind": "CHOICE", + "display": true, + "writable": true, + "choices": [ + {"value": 0, "name": "Windows"}, + {"value": 1, "name": "MacOS"}, + {"value": 2, "name": "iOS"} + ], + "value": 0 + }, + { + "name": "change-host", + "label": "Change Host", + "description": "Switch connection to a different host", + "kind": "CHOICE", + "display": true, + "writable": true, + "choices": [ + {"value": 0, "name": "1:hermes"}, + {"value": 1, "name": "2:hermes"}, + {"value": 2, "name": "3:HERMES"} + ], + "value": 0 + } + ] + }, + { + "device": { + "id": "B03700000000-3F51C045", + "name": "MX Anywhere 3S", + "codename": "MX Anywhere 3S", + "kind": "mouse", + "online": true, + "protocol": 4.5, + "model_id": "B03700000000", + "unit_id": "3F51C045", + "serial": "", + "battery": {"level": 75, "status": "DISCHARGING"} + }, + "settings": [ + {"name": "hires-smooth-invert", "label": "Scroll Wheel Direction", "description": "Invert direction for vertical scroll with wheel.", "kind": "TOGGLE", "display": true, "writable": true, "value": false}, + {"name": "hires-smooth-resolution", "label": "Scroll Wheel Resolution", "description": "High-sensitivity mode for vertical scroll with the wheel.\nSet to ignore if scrolling is abnormally fast or slow", "kind": "TOGGLE", "display": true, "writable": true, "value": true}, + {"name": "hires-scroll-mode", "label": "Scroll Wheel Diversion", "description": "Make scroll wheel send HIRES_WHEEL HID++ notifications (which trigger Solaar rules but are otherwise ignored).", "kind": "TOGGLE", "display": true, "writable": true, "value": false}, + {"name": "scroll-ratchet-torque", "label": "Scroll Wheel Ratchet Torque", "description": "Change the torque needed to overcome the ratchet.", "kind": "RANGE", "display": true, "writable": true, "min": 1, "max": 100, "value": 50}, + { + "name": "scroll-ratchet", + "label": "Scroll Wheel Ratcheted", + "description": "Switch the mouse wheel between speed-controlled ratcheting and always freespin.", + "kind": "CHOICE", + "display": true, + "writable": true, + "choices": [ + {"value": 1, "name": "Freespinning"}, + {"value": 2, "name": "Ratcheted"} + ], + "value": 2 + }, + {"name": "smart-shift", "label": "Scroll Wheel Ratchet Speed", "description": "Use the mouse wheel speed to switch between ratcheted and freespinning.\nThe mouse wheel is always ratcheted at 50.", "kind": "RANGE", "display": true, "writable": true, "min": 1, "max": 50, "value": 12}, + { + "name": "dpi", + "label": "Sensitivity (DPI)", + "description": "Mouse movement sensitivity\nMay need Onboard Profiles set to Disable to be effective.", + "kind": "CHOICE", + "display": true, + "writable": true, + "choices": { + "numeric": [200, 8000, 50] + }, + "value": 1000 + }, + { + "name": "reprogrammable-keys", + "label": "Key/Button Actions", + "description": "Change the action for the key or button. Overridden by diversion.\nChanging important actions (such as for the left mouse button) can result in an unusable system.", + "kind": "MAP_CHOICE", + "display": true, + "writable": true, + "keys": [ + { + "value": 80, + "name": "Left Button", + "choices": [ + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"} + ] + }, + { + "value": 81, + "name": "Right Button", + "choices": [ + {"value": 81, "name": "Right Click"}, + {"value": 80, "name": "Left Click"} + ] + }, + { + "value": 82, + "name": "Middle Button", + "choices": [ + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 83, "name": "Mouse Back Button"}, + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 196, "name": "Smart Shift"} + ] + }, + { + "value": 83, + "name": "Back Button", + "choices": [ + {"value": 83, "name": "Mouse Back Button"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 196, "name": "Smart Shift"} + ] + }, + { + "value": 86, + "name": "Forward Button", + "choices": [ + {"value": 86, "name": "Mouse Forward Button"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 83, "name": "Mouse Back Button"}, + {"value": 196, "name": "Smart Shift"} + ] + }, + { + "value": 196, + "name": "Smart Shift", + "choices": [ + {"value": 196, "name": "Smart Shift"}, + {"value": 80, "name": "Left Click"}, + {"value": 81, "name": "Right Click"}, + {"value": 82, "name": "Mouse Middle Button"}, + {"value": 83, "name": "Mouse Back Button"}, + {"value": 86, "name": "Mouse Forward Button"} + ] + } + ], + "value": {"80": 80, "81": 81, "82": 82, "83": 83, "86": 86, "196": 196} + }, + { + "name": "divert-keys", + "label": "Key/Button Diversion", + "description": "Make the key or button send HID++ notifications (Diverted) or initiate Mouse Gestures or Sliding DPI", + "kind": "MAP_CHOICE", + "display": true, + "writable": true, + "keys": [ + { + "value": 82, + "name": "Middle Button", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + }, + { + "value": 83, + "name": "Back Button", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + }, + { + "value": 86, + "name": "Forward Button", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + }, + { + "value": 196, + "name": "Smart Shift", + "choices": [ + {"value": 0, "name": "Regular"}, + {"value": 1, "name": "Diverted"}, + {"value": 2, "name": "Mouse Gestures"}, + {"value": 3, "name": "Sliding DPI"} + ] + } + ], + "value": {"82": 0, "83": 0, "86": 0, "196": 0} + }, + { + "name": "change-host", + "label": "Change Host", + "description": "Switch connection to a different host", + "kind": "CHOICE", + "display": true, + "writable": true, + "choices": [ + {"value": 0, "name": "1:hermes"}, + {"value": 1, "name": "2:[LG] webOS TV OLED55C3"}, + {"value": 2, "name": "3:HERMES"} + ], + "value": 0 + } + ] + } + ], + "kde_actions": [ + { + "component": "mediacontrol", + "label": "Contrôleur de média", + "actions": [ + {"name": "stopmedia", "label": "Arrêtez la lecture du média"}, + {"name": "mediavolumeup", "label": "Augmentation du volume pour le média"}, + {"name": "seekforwardmedialong", "label": "Avancement de 30 secondes de la lecture du média"}, + {"name": "seekforwardmedia", "label": "Avancement de 5 secondes de la lecture du média"}, + {"name": "mediavolumedown", "label": "Diminution du volume pour le média"}, + {"name": "playmedia", "label": "Démarrer la lecture du média"}, + {"name": "playpausemedia", "label": "Démarrer / Mettre en pause la lecture du média"}, + {"name": "previousmedia", "label": "Lecture du média précédent"}, + {"name": "nextmedia", "label": "Lecture du média suivant"}, + {"name": "pausemedia", "label": "Mettre en pause la lecture du média"}, + {"name": "seekbackwardmedialong", "label": "Retour arrière de 30 secondes de la lecture du média"}, + {"name": "seekbackwardmedia", "label": "Retour arrière de 5 secondes de la lecture du média"} + ] + }, + { + "component": "org_kde_powerdevil", + "label": "Gestion de l'énergie", + "actions": [ + {"name": "Increase Screen Brightness", "label": "Augmenter la luminosité de l'écran"}, + {"name": "Increase Screen Brightness Small", "label": "Augmenter la luminosité de l'écran de 1 %"}, + {"name": "Increase Keyboard Brightness", "label": "Augmenter la luminosité du clavier"}, + {"name": "powerProfile", "label": "Changer de profil de gestion d'énergie"}, + {"name": "Toggle Keyboard Backlight", "label": "Changer le rétro-éclairage du clavier"}, + {"name": "Decrease Screen Brightness", "label": "Diminuer la luminosité de l'écran"}, + {"name": "Decrease Screen Brightness Small", "label": "Diminuer la luminosité de l'écran de 1 %"}, + {"name": "Decrease Keyboard Brightness", "label": "Diminuer la luminosité du clavier"}, + {"name": "PowerDown", "label": "Forcer l'extinction"}, + {"name": "Hibernate", "label": "Hiberner"}, + {"name": "Sleep", "label": "Suspendre"}, + {"name": "PowerOff", "label": "Éteindre"}, + {"name": "Turn Off Screen", "label": "Éteindre l'écran"} + ] + }, + { + "component": "ksmserver", + "label": "Gestion de sessions", + "actions": [ + {"name": "Log Out", "label": "Afficher l'écran de déconnexion"}, + {"name": "Reboot", "label": "Redémarrer"}, + {"name": "Lock Session", "label": "Verrouiller la session"}, + {"name": "Shut Down", "label": "Éteindre"} + ] + }, + { + "component": "org_kde_krunner_desktop", + "label": "KRunner", + "actions": [ + {"name": "RunClipboard", "label": "Exécuter la commande en utilisant le contenu du presse-papier"}, + {"name": "_launch", "label": "KRunner"} + ] + }, + { + "component": "kwin", + "label": "KWin", + "actions": [ + {"name": "Window Fullscreen", "label": "Afficher la fenêtre en plein écran"}, + {"name": "view_zoom_in", "label": "Agrandir"}, + {"name": "Expose", "label": "Basculer la présentation des fenêtres (Bureau actuel)"}, + {"name": "ExposeClass", "label": "Basculer la présentation des fenêtres (Classe de fenêtres)"}, + {"name": "ExposeAll", "label": "Basculer la présentation des fenêtres (Tous les bureaux)"}, + {"name": "Grid View", "label": "Basculer vers l'affichage en grille"}, + {"name": "Overview", "label": "Basculer vers l'aperçu"}, + {"name": "Edit Tiles", "label": "Basculer vers l'éditeur de tuiles"}, + {"name": "Window Above Other Windows", "label": "Conserver la fenêtre au-dessus des autres"}, + {"name": "Window On All Desktops", "label": "Conserver la fenêtre sur tous les bureaux"}, + {"name": "Show Desktop", "label": "Coup d'œil sur le bureau"}, + {"name": "Window to Next Screen", "label": "Déplacer la fenêtre vers l'écran suivant"}, + {"name": "Kill Window", "label": "Détruire une fenêtre"}, + {"name": "Window One Desktop to the Right", "label": "Envoyer la fenêtre sur le bureau à droite"}, + {"name": "Window One Desktop to the Left", "label": "Envoyer la fenêtre sur le bureau à gauche"}, + {"name": "Cycle Overview", "label": "Faire défiler les vues en aperçu et en grille"}, + {"name": "Window Close", "label": "Fermer la fenêtre"}, + {"name": "Window Maximize", "label": "Maximiser la fenêtre"}, + {"name": "Window Operations Menu", "label": "Menu « Fenêtre »"}, + {"name": "Window Quick Tile Right", "label": "Mettre rapidement en mosaïque une fenêtre à droite"}, + {"name": "Window Quick Tile Left", "label": "Mettre rapidement en mosaïque une fenêtre à gauche"}, + {"name": "Walk Through Windows", "label": "Naviguer parmi les fenêtres"}, + {"name": "Walk Through Windows of Current Application", "label": "Naviguer parmi les fenêtres de l'application courante"}, + {"name": "Switch One Desktop to the Right", "label": "Passer au bureau de droite"}, + {"name": "Switch One Desktop to the Left", "label": "Passer au bureau de gauche"}, + {"name": "Switch One Desktop Down", "label": "Passer au bureau du dessous"}, + {"name": "Switch One Desktop Up", "label": "Passer au bureau du dessus"}, + {"name": "Switch to Previous Desktop", "label": "Passer au bureau précédent"}, + {"name": "Switch to Next Desktop", "label": "Passer au bureau suivant"}, + {"name": "Window Minimize", "label": "Réduire la fenêtre"}, + {"name": "Toggle Night Color", "label": "Suspendre /Poursuivre l'utilisation de la couleur de nuit"}, + {"name": "view_zoom_out", "label": "Zoomer en arrière"}, + {"name": "view_actual_size", "label": "Zoomer jusqu'à la taille réelle"} + ] + }, + { + "component": "plasmashell", + "label": "plasmashell", + "actions": [ + {"name": "activate application launcher", "label": "Activer le lanceur d'applications"}, + {"name": "manage activities", "label": "Afficher le sélecteur d'activités"}, + {"name": "show-on-mouse-pos", "label": "Afficher les éléments du presse-papier à la position de la souris"}, + {"name": "toggle do not disturb", "label": "Basculer « Ne pas déranger »"}, + {"name": "cycle-panels", "label": "Déplacer le focus de clavier entre les panneaux"}, + {"name": "clear-history", "label": "Effacer l'historique du presse-papier"}, + {"name": "next activity", "label": "Parcourir les activités"} + ] + }, + { + "component": "org_kde_spectacle_desktop", + "label": "Spectacle", + "actions": [ + {"name": "ActiveWindowScreenShot", "label": "Capturer la fenêtre active"}, + {"name": "WindowUnderCursorScreenShot", "label": "Capturer la fenêtre sous le curseur"}, + {"name": "FullScreenScreenShot", "label": "Capturer le bureau entier"}, + {"name": "CurrentMonitorScreenShot", "label": "Capturer le moniteur courant"}, + {"name": "RectangularRegionScreenShot", "label": "Capturer une région rectangulaire"}, + {"name": "RecordWindow", "label": "Démarrer / Arrêter l'enregistrement d'une fenêtre"}, + {"name": "RecordRegion", "label": "Démarrer / Arrêter l'enregistrement d'une zone"}, + {"name": "RecordScreen", "label": "Démarrer / Arrêter l'enregistrement de l'écran"}, + {"name": "OpenWithoutScreenshot", "label": "Lancer sans réalisation de capture d'écran"}, + {"name": "_launch", "label": "Spectacle"} + ] + }, + { + "component": "org_kde_plasma_emojier_desktop", + "label": "Sélecteur d'émoticônes", + "actions": [ + {"name": "_launch", "label": "Sélecteur d'émoticônes"} + ] + }, + { + "component": "kmix", + "label": "Volume audio", + "actions": [ + {"name": "push_to_talk", "label": "Appuyer pour parler"}, + {"name": "increase_volume", "label": "Augmenter le volume"}, + {"name": "increase_volume_small", "label": "Augmenter le volume de 1 %"}, + {"name": "increase_microphone_volume", "label": "Augmenter le volume du microphone"}, + {"name": "mic_mute", "label": "Couper le son du microphone"}, + {"name": "decrease_volume", "label": "Diminuer le volume"}, + {"name": "decrease_volume_small", "label": "Diminuer le volume de 1 %"}, + {"name": "decrease_microphone_volume", "label": "Diminuer le volume du microphone"}, + {"name": "mute", "label": "Muet"} + ] + } + ] +}