plasmoides KDE Store/GitHub (gnome-pager, kMenu, kvitals, windowtitle, claude, launchpad)

This commit is contained in:
Josevi
2026-07-08 20:47:59 +02:00
parent ca606377ee
commit dd3b0f6ae8
136 changed files with 20239 additions and 0 deletions
@@ -0,0 +1,23 @@
/*
* Plasma Gnome Pager — config.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* The settings dialog's category list. ConfigCategory.source resolves relative to contents/ui/, so the
* pages live in contents/ui/config/ while this file + main.xml live in contents/config/ (plasmoid.md).
*/
import org.kde.plasma.configuration
ConfigModel {
ConfigCategory {
name: i18n("Behavior")
icon: "preferences-system-windows-actions"
source: "config/ConfigGeneral.qml"
}
ConfigCategory {
name: i18n("Appearance")
icon: "preferences-desktop-color"
source: "config/ConfigAppearance.qml"
}
}
@@ -0,0 +1,139 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Plasma Gnome Pager — configuration schema (KConfigXT)
SPDX-FileCopyrightText: 2026 Kenan Salar
SPDX-License-Identifier: GPL-3.0-or-later
Each <entry name="X"> becomes plasmoid.configuration.X, read live in main.qml (with a `?? <default>`
guard) and passed down as a plain value. Three keys use a `0 = auto` sentinel — their natural default is
theme/HiDPI-derived, which a fixed KConfigXT literal can't hold, so it's resolved in the widget: dotSize,
pillSize (→ match the dots), animationDuration (→ Kirigami.Units.longDuration). See CLAUDE.md "Config flow".
-->
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
http://www.kde.org/standards/kcfg/1.0/kcfg.xsd">
<kcfgfile name=""/>
<group name="General">
<!-- Scroll over the strip to switch desktops. -->
<entry name="enableScroll" type="Bool">
<default>true</default>
</entry>
<!-- When scrolling past the first/last desktop, wrap around (else clamp). -->
<entry name="scrollWrap" type="Bool">
<default>false</default>
</entry>
<!-- Invert the scroll direction (wheel up → next desktop instead of previous). -->
<entry name="invertScroll" type="Bool">
<default>false</default>
</entry>
<!-- What clicking the ALREADY-CURRENT desktop does. Index mirrors Logic.PILL_CLICK_ACTION + the combo
order: 0 = None, 1 = Show Desktop, 2 = Overview, 3 = Grid. Clicking an inactive dot still switches. -->
<entry name="pillClickAction" type="Int">
<default>0</default>
</entry>
<!-- Show the desktop name in a tooltip on hover. -->
<entry name="showTooltips" type="Bool">
<default>true</default>
</entry>
<!-- Also list the windows open on a desktop in its tooltip (needs showTooltips). -->
<entry name="showWindowList" type="Bool">
<default>true</default>
</entry>
<!-- Offer Add/Remove desktop entries in the right-click menu. -->
<entry name="enableAddRemove" type="Bool">
<default>true</default>
</entry>
<!-- Offer a "Rename Current Desktop…" entry in the right-click menu. -->
<entry name="enableRename" type="Bool">
<default>true</default>
</entry>
<!-- GNOME-style dynamic workspaces: auto-keep exactly one empty trailing desktop. -->
<entry name="dynamicWorkspaces" type="Bool">
<default>false</default>
</entry>
<!-- Base name for auto-created desktops ("<prefix> N"); empty = the localized default "Desktop". -->
<entry name="dynamicNamePrefix" type="String">
<default></default>
</entry>
<!-- Morph animation length in ms; 0 = follow the theme (Kirigami.Units.longDuration). -->
<entry name="animationDuration" type="Int">
<default>0</default>
</entry>
</group>
<group name="Appearance">
<!-- Overall pager look. Index mirrors Logic.DOT_STYLE + the combo order:
0 = Sliding pill (GNOME reflow), 1 = Filled & ring (no pill; current = filled dot, others = hollow rings). -->
<entry name="dotStyle" type="Int">
<default>0</default>
</entry>
<!-- Ignore KWin's virtual-desktop grid rows and lay every desktop out in ONE line. Off = honour the grid
(mirror "Rows" from System Settings). Orthogonal to matchDesktopGrid (which sets the direction): single
line alone is a vertical strip on a vertical panel; single line + matchDesktopGrid is one horizontal row. -->
<entry name="singleLine" type="Bool">
<default>false</default>
</entry>
<!-- Vertical panels: run the layout ACROSS the panel instead of down it — for a multi-row grid this mirrors
KWin's orientation (rows top-to-bottom); with singleLine it makes the one line horizontal. Off = the
GNOME-reflow look (run down the panel). No effect on a horizontal panel (already runs across). -->
<entry name="matchDesktopGrid" type="Bool">
<default>false</default>
</entry>
<!-- Inactive-dot diameter in px; 0 = auto (Kirigami.Units.iconSizes.small / 2, HiDPI-aware). -->
<entry name="dotSize" type="Int">
<default>0</default>
</entry>
<!-- Active-pill thickness in px; 0 = auto (match the dot size). Sized independently of the dots. -->
<entry name="pillSize" type="Int">
<default>0</default>
</entry>
<!-- Uniform gap between elements, as a multiple of the dot size (GNOME-tight at 0.5). -->
<entry name="spacingFactor" type="Double">
<default>0.5</default>
</entry>
<!-- Active-capsule length, as a multiple of the pill thickness (its aspect ratio). -->
<entry name="pillWidthFactor" type="Double">
<default>3.5</default>
</entry>
<!-- Opacity of an inactive (dim) dot. -->
<entry name="inactiveOpacity" type="Double">
<default>0.45</default>
</entry>
<!-- Opacity an inactive dot brightens to on hover. -->
<entry name="hoverOpacity" type="Double">
<default>0.8</default>
</entry>
<!-- Brighten the dots of desktops that hold windows (occupied), so they stand out from empty ones. -->
<entry name="showOccupancy" type="Bool">
<default>false</default>
</entry>
<!-- Opacity of the occupied marker (every occupancyStyle uses it; only when showOccupancy is on). -->
<entry name="occupiedOpacity" type="Double">
<default>0.7</default>
</entry>
<!-- How an occupied dot is marked (showOccupancy on). Index mirrors Logic.OCCUPANCY + the combo order:
0 = Filled (whole dot), 1 = Inner dot, 2 = Hollow ring. All use occupiedOpacity + the occupied colour. -->
<entry name="occupancyStyle" type="Int">
<default>0</default>
</entry>
<!-- Follow the color scheme; when false, use activeColor / inactiveColor / occupiedColor below. -->
<entry name="followThemeColors" type="Bool">
<default>true</default>
</entry>
<!-- Custom active-capsule colour (used only when followThemeColors is false). -->
<entry name="activeColor" type="Color">
<default>#3daee9</default>
</entry>
<!-- Custom inactive-dot colour (used only when followThemeColors is false). -->
<entry name="inactiveColor" type="Color">
<default>#eff0f1</default>
</entry>
<!-- Custom occupied-marker colour (used only when followThemeColors is false; else the theme accent). -->
<entry name="occupiedColor" type="Color">
<default>#3daee9</default>
</entry>
</group>
</kcfg>
@@ -0,0 +1,117 @@
/*
* Plasma Gnome Pager — DynamicWorkspacesController.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* GNOME-style dynamic-workspaces controller — a non-visual Item (QtQuick + pure .js only, headless-tested).
* When enabled, keep one empty trailing desktop via ONE KWin add/remove per cycle. The desktop SET is
* global, so coordinator.js does setting SYNC + single-WRITER election (else panels double-add → a flash).
*/
pragma ComponentBehavior: Bound
import QtQuick
import "logic.js" as Logic
import "coordinator.js" as Coordinator // single-writer election + prefix sync across instances
Item {
id: controller
// Inputs (injected by main.qml). dynamicEnabled (not `enabled` — QQuickItem already defines that).
property bool dynamicEnabled: false
property string namePrefix: "" // base name for auto-created desktops ("" = defaultPrefix)
property string defaultPrefix: "Desktop" // i18n default, passed IN so this stays i18n-free; never empty (KWin drops empty-name createDesktop)
property var virtualDesktopInfo: null // the read source (null-safe throughout — transiently absent)
// Per-desktop occupancy bool[], index-aligned with desktopIds. The length guard in dynamicWorkspacePlan
// makes a transient frame (occupancy still lagging a just-changed desktop set) a no-op until it catches up.
property var desktopOccupancy: []
// Outputs (the two things only main.qml's e2e boundary can do).
signal dispatchRequested(var spec) // a built KWin add/remove spec → root.dispatch(spec)
signal syncConfigRequested(bool nextEnabled, string nextPrefix) // mirror the global setting into persisted config
// Internal state.
property bool dynBusy: false
property int dynToken: 0
// Liveness fallback only — the real lock-clear is vdi.desktopIdsChanged below.
readonly property int busyFallbackMs: 750
Timer {
id: dynBusyTimer
interval: controller.busyFallbackMs
onTriggered: controller.dynBusy = false
}
// Join the coordinator (syncConfigRequested is the push channel). Adopt the global if a sibling seeded
// it, else seed it from our value, then evaluate once. Leave on teardown (stop counting in the election).
Component.onCompleted: {
controller.dynToken = Coordinator.join((en, pf) => controller.syncConfigRequested(en, pf));
if (Coordinator.haveGlobal())
controller.syncConfigRequested(Coordinator.globalEnabled(), Coordinator.globalPrefix());
else
Coordinator.publish(controller.dynamicEnabled, controller.namePrefix);
controller.scheduleDynamic();
}
Component.onDestruction: Coordinator.leave(controller.dynToken)
// Our setting changed: if it differs from the global WE changed it → publish to every panel; else it's
// a sync echo → just re-evaluate. Guard the pre-join window (dynToken 0): config onChanged fires before
// Component.onCompleted, and publishing then registers a phantom value that stalls the real writer.
function publishDynamicConfig() {
if (controller.dynToken === 0)
return;
if (!Coordinator.haveGlobal()
|| controller.dynamicEnabled !== Coordinator.globalEnabled()
|| controller.namePrefix !== Coordinator.globalPrefix())
Coordinator.publish(controller.dynamicEnabled, controller.namePrefix);
controller.scheduleDynamic();
}
// Coalesce a burst of occupancy / desktop-set changes into ONE evaluation next tick.
function scheduleDynamic() {
if (!controller.dynamicEnabled)
return;
Qt.callLater(controller.evaluateDynamic);
}
// Compute and dispatch the single action for the freshest state, or nothing. Only the elected writer acts (panels never double-add).
function evaluateDynamic() {
if (!controller.dynamicEnabled || controller.dynBusy)
return;
if (!Coordinator.isWriter(controller.dynToken))
return; // another instance is the single global writer
const ids = controller.virtualDesktopInfo?.desktopIds ?? [];
const plan = Logic.dynamicWorkspacePlan(controller.desktopOccupancy, ids);
if (!plan)
return;
let spec = null;
if (plan.kind === "add") {
// Name "<prefix> N" (prefix synced across panels); position == current count (append), so the number is pos + 1.
const pos = controller.virtualDesktopInfo?.numberOfDesktops ?? ids.length;
spec = Logic.addSpec(pos, Logic.formatDynamicDesktopName(controller.namePrefix, pos + 1, controller.defaultPrefix));
} else if (plan.kind === "remove") {
const count = controller.virtualDesktopInfo?.numberOfDesktops ?? ids.length;
spec = Logic.removeSpec(plan.uuid, count);
}
if (!spec)
return;
controller.dynBusy = true;
controller.dispatchRequested(spec);
dynBusyTimer.restart();
}
// Triggers: occupancy flips, and our own setting changing (routed through publishDynamicConfig so the global syncs before we act).
onDesktopOccupancyChanged: controller.scheduleDynamic()
onDynamicEnabledChanged: controller.publishDynamicConfig()
onNamePrefixChanged: controller.publishDynamicConfig()
// The desktop SET changing is also the signal that OUR add/remove landed → clear the lock and re-evaluate (multi-step trim converges over cycles).
Connections {
target: controller.virtualDesktopInfo
function onDesktopIdsChanged() {
controller.dynBusy = false;
controller.scheduleDynamic();
}
}
}
@@ -0,0 +1,57 @@
/*
* Plasma Gnome Pager — IndicatorMetrics.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Non-visual dot-strip sizing engine (unit-tested by tst_indicatormetrics). EFFECTIVE sizes shrink to fit
* a crowded panel (floored at minDotSize); NATURAL/floor extents (the Layout hints) depend only on
* requests/grid, never on geometry — keep that split or you get a binding loop.
*/
pragma ComponentBehavior: Bound
import QtQuick
import org.kde.kirigami as Kirigami
import "logic.js" as Logic
QtObject {
id: metrics
// Inputs (bound by WorkspaceIndicator).
property int dotSizeRequest: Logic.DEFAULTS.dotSize // px; 0 = auto (HiDPI themed)
property int pillSizeRequest: Logic.DEFAULTS.pillSize // px pill thickness; 0 = auto (match dots)
property real spacingFactor: Logic.DEFAULTS.spacingFactor
property real pillWidthFactor: Logic.DEFAULTS.pillWidthFactor // pill length / pill thickness
property real availableMajor: 0 // live panel allocation along the line axis (0 before layout)
property real availableCross: 0 // live panel allocation across the stacked lines
property int perLine: 0 // desktops per line (KWin columns)
property int lineCount: 0 // stacked lines (KWin rows)
// Natural / floor — geometry-INDEPENDENT, drive the Layout hints (no loop).
readonly property real naturalDotSize: dotSizeRequest > 0 ? dotSizeRequest : Kirigami.Units.iconSizes.small / 2
readonly property real naturalPillSize: pillSizeRequest > 0 ? pillSizeRequest : naturalDotSize
readonly property real pillThicknessRatio: naturalPillSize / naturalDotSize // pill thickness in dot units; carries the dot⇄pill decoupling
readonly property real minDotSize: Math.min(naturalDotSize, Kirigami.Units.iconSizes.small / 4) // legibility floor, clamped ≤ natural
readonly property real naturalStripLength: Logic.lineExtent(perLine, naturalDotSize, naturalDotSize * spacingFactor, naturalPillSize * pillWidthFactor)
readonly property real floorStripLength: Logic.lineExtent(perLine, minDotSize, minDotSize * spacingFactor, minDotSize * pillThicknessRatio * pillWidthFactor)
readonly property real naturalCrossThickness: Logic.lineExtent(lineCount, naturalDotSize, naturalDotSize * spacingFactor, Math.max(naturalDotSize, naturalPillSize))
readonly property real floorCrossThickness: Logic.lineExtent(lineCount, minDotSize, minDotSize * spacingFactor, minDotSize * Math.max(1, pillThicknessRatio))
// Effective — geometry-DEPENDENT rendered sizes (read by each WorkspaceDot). fitDotSize is the
// inverse of lineExtent; +Infinity on an unconstrained axis, so min() picks the binding axis.
readonly property real majorFitDotSize: Logic.fitDotSize(availableMajor, perLine, pillThicknessRatio * pillWidthFactor, spacingFactor)
readonly property real crossFitDotSize: Logic.fitDotSize(availableCross, lineCount, Math.max(1, pillThicknessRatio), spacingFactor)
readonly property real fitDotSize: Math.min(majorFitDotSize, crossFitDotSize)
readonly property real dotSize: Math.max(minDotSize, Math.min(naturalDotSize, fitDotSize)) // shrink-to-fit, capped natural, floored minDotSize
readonly property real pillSize: dotSize * pillThicknessRatio // scales in lockstep with the dot
readonly property real pillWidth: pillSize * pillWidthFactor // active capsule LENGTH (major axis)
readonly property real dotSpacing: dotSize * spacingFactor // uniform gap between every element
// Conserved (capsule-bearing) line extents — the length/thickness of a line that HOLDS the capsule, which
// is the MAX over all lines and is independent of the morph progress. The indicator pins the strip to these
// so a cross-row morph can't resize+recenter it (else the dots "breathe"/drift). Effective (post-scale-to-fit).
// Assumes pillWidth >= dotSize, the same assumption naturalStripLength already makes.
readonly property real stripLength: Logic.lineExtent(perLine, dotSize, dotSpacing, pillWidth)
readonly property real crossThickness: Logic.lineExtent(lineCount, dotSize, dotSpacing, Math.max(dotSize, pillSize))
}
@@ -0,0 +1,80 @@
/*
* Plasma Gnome Pager — RenameDialog.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Rename prompt — a panel-native PlasmaCore.Dialog (top-level Window), declared directly. NOT
* Kirigami.PromptDialog, whose base parents to applicationWindow().overlay (undefined in a plasmoid → it
* would clip to the thin panel). View only: the parent owns visualParent/location and the DBus write.
*/
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import org.kde.plasma.core as PlasmaCore
import org.kde.plasma.components as PlasmaComponents3
import org.kde.kirigami as Kirigami
import "logic.js" as Logic
PlasmaCore.Dialog {
id: renameDialog
property string targetUuid: ""
signal accepted(string uuid, string name)
visible: false
hideOnWindowDeactivate: true // click-away cancels
// Prefill with the current name, select-all and focus for immediate typing.
function openFor(uuid, currentName) {
renameDialog.targetUuid = uuid;
renameField.text = currentName;
renameDialog.visible = true;
renameField.selectAll();
renameField.forceActiveFocus();
}
// Sanitize then emit. An empty/whitespace name (sanitize → "") keeps the prompt open; the parent re-sanitizes, so the write stays guarded.
function commit() {
const clean = Logic.sanitizeDesktopName(renameField.text);
if (clean === "") {
return;
}
renameDialog.accepted(renameDialog.targetUuid, clean);
renameDialog.visible = false;
}
mainItem: ColumnLayout {
spacing: Kirigami.Units.smallSpacing
PlasmaComponents3.Label {
text: i18n("Rename desktop:")
}
PlasmaComponents3.TextField {
id: renameField
Layout.fillWidth: true
Layout.minimumWidth: Kirigami.Units.gridUnit * 12
onAccepted: renameDialog.commit()
Keys.onEscapePressed: renameDialog.visible = false
}
RowLayout {
Layout.alignment: Qt.AlignRight
spacing: Kirigami.Units.smallSpacing
PlasmaComponents3.Button {
text: i18n("Cancel")
icon.name: "dialog-cancel"
onClicked: renameDialog.visible = false
}
PlasmaComponents3.Button {
text: i18n("Rename")
icon.name: "edit-rename"
enabled: renameField.text.trim().length > 0
onClicked: renameDialog.commit()
}
}
}
}
@@ -0,0 +1,60 @@
/*
* Plasma Gnome Pager — ScreenCurrentDesktop.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Resolves the current desktop FOR ONE SCREEN (Plasma 6.7 per-output; unit-tested by tst_screencurrentdesktop).
* currentDesktopByScreenName is a METHOD + SIGNAL, not a notifying property, so currentDesktop is recomputed
* imperatively (a plain binding evaluates once); the prefer-per-screen decision is Logic.resolveCurrentDesktop.
*/
pragma ComponentBehavior: Bound
import QtQuick
import "logic.js" as Logic
Item {
id: resolver
// Inputs (injected by WorkspaceIndicator).
property var virtualDesktopInfo: null
property string screenName: ""
// Output: the current-desktop UUID for screenName (the global current when there is no per-screen info).
property string currentDesktop: ""
function updateCurrentDesktop() {
const vdi = resolver.virtualDesktopInfo;
const globalCurrent = vdi?.currentDesktop ?? "";
let perScreen; // stays undefined unless we have a screen AND the 6.7 API
if (vdi && resolver.screenName && typeof vdi.currentDesktopByScreenName === "function")
perScreen = vdi.currentDesktopByScreenName(resolver.screenName);
resolver.currentDesktop = Logic.resolveCurrentDesktop(perScreen, globalCurrent);
}
// Recompute on every external change ("bind, don't cache"). The always-present signals keep their own
// block (no ignoreUnknownSignals) so a typo here still warns.
Connections {
target: resolver.virtualDesktopInfo
function onCurrentDesktopChanged() {
resolver.updateCurrentDesktop();
}
function onDesktopIdsChanged() {
resolver.updateCurrentDesktop();
}
}
// The per-screen current signal is Plasma 6.7+ only; on 6.5/6.6 it is absent, so ignoreUnknownSignals
// keeps the Connections quiet — the resolver already degrades to the global current (typeof guard above).
Connections {
target: resolver.virtualDesktopInfo
ignoreUnknownSignals: true
function onCurrentDesktopForScreenChanged(screenName) {
if (screenName === resolver.screenName)
resolver.updateCurrentDesktop();
}
}
onScreenNameChanged: resolver.updateCurrentDesktop()
onVirtualDesktopInfoChanged: resolver.updateCurrentDesktop()
Component.onCompleted: resolver.updateCurrentDesktop()
}
@@ -0,0 +1,209 @@
/*
* Plasma Gnome Pager — WindowAggregator.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* The window aggregator — a non-visual Item. ONE unfiltered public TasksModel feeds the tooltip window
* list, GLOBAL dynamic-workspace occupancy, and the PER-SCREEN occupied-dot indicator from a single
* snapshot via pure JS. The desktop set is INJECTED as `virtualDesktopInfo` and this pager's output rect
* as `screenRect`; i18n + HTML formatting stays here (logic.js is i18n-free), so e2e-only.
*/
pragma ComponentBehavior: Bound
import QtQuick
import QtQml // Instantiator (materialise TasksModel rows)
import org.kde.taskmanager as TaskManager // TasksModel/ActivityInfo (read)
import "logic.js" as Logic
Item {
id: aggregator
// The read source (a VirtualDesktopInfo), injected by main.qml. Null-safe throughout (transiently absent).
property var virtualDesktopInfo: null
// The per-dot window-list tooltip wanted? Injected as (showTooltips && showWindowList). When false the
// aggregator is live only for occupancy, skipping tooltip work (drops title/minimise roles; empty tooltips).
property bool windowListActive: true
// Per-screen occupied-dot indicator wanted? Injected as showOccupancy. When false the per-screen occupancy
// reduction (and the ScreenGeometry role that feeds it) is skipped entirely (screenOccupancy stays []).
property bool occupancyActive: false
// Dynamic workspaces wanted? Injected as dynamicWorkspaces. When false the GLOBAL occupancy reduction (whose
// sole consumer is the controller) is skipped entirely (desktopOccupancy stays []).
property bool dynamicActive: false
// This pager's output rect (global compositor space), injected by main.qml from the placed representation's
// Screen attached property. A zero rect → per-screen occupancy degrades to global (see computeDesktopOccupancyForScreen).
property rect screenRect: Qt.rect(0, 0, 0, 0)
property var desktopTooltips: []
property var desktopOccupancy: [] // GLOBAL (all monitors) — consumed by the dynamic-workspaces controller
property var screenOccupancy: [] // PER-SCREEN (this monitor only) — consumed by the occupied-dot indicator
// One materialised TasksModel row, a NAMED inline component so objectAt(i) can be `as`-cast for typed role access (capitalised roles read off `model`).
component WindowRow: QtObject {
required property var model
required property string display // window title (Qt::DisplayRole)
readonly property var windowDesktops: model.VirtualDesktops
readonly property bool onAllDesktops: model.IsOnAllVirtualDesktops
readonly property bool minimized: model.IsMinimized
readonly property bool isWindow: model.IsWindow // false for launchers / startup tasks
readonly property bool skipPager: model.SkipPager // hidden from pagers — never occupies a desktop
readonly property rect windowScreen: model.ScreenGeometry // rect of the OUTPUT this window is on (per-screen occupancy)
}
TaskManager.ActivityInfo {
id: activityInfo
}
TaskManager.TasksModel {
id: tasksModel
groupMode: TaskManager.TasksModel.GroupDisabled
filterByVirtualDesktop: false
filterByActivity: true
activity: activityInfo.currentActivity
}
// The role ints rebuild() reads (PUBLIC enum); other roles are skipped (notably the IsActive focus churn, so
// window-focus changes never wake a rebuild). Built per ACTIVE feature, so an off feature's role can't trigger
// work nothing consumes: VirtualDesktops/IsOnAllVirtualDesktops/IsWindow gate desktop membership (every
// consumer); title + IsMinimized are tooltip-only; SkipPager is occupancy-only (excluded windows); and
// ScreenGeometry is PER-SCREEN-occupancy-only (so monitor-moves don't rebuild when that indicator is off).
readonly property var relevantRoles: {
var roles = [
TaskManager.AbstractTasksModel.VirtualDesktops,
TaskManager.AbstractTasksModel.IsOnAllVirtualDesktops,
TaskManager.AbstractTasksModel.IsWindow
];
if (aggregator.windowListActive)
roles.push(Qt.DisplayRole, TaskManager.AbstractTasksModel.IsMinimized);
if (aggregator.occupancyActive || aggregator.dynamicActive)
roles.push(TaskManager.AbstractTasksModel.SkipPager); // occupancy excludes skip-pager windows
if (aggregator.occupancyActive)
roles.push(TaskManager.AbstractTasksModel.ScreenGeometry); // per-screen occupancy needs the window's output
return roles;
}
// Materialise the rows so objectAt(i) can read role values by name (a C++ model has no model.get(i)).
// Row add/remove triggers a rebuild; role-value changes arrive via the model's dataChanged below.
Instantiator {
id: winInstantiator
model: tasksModel
delegate: WindowRow {}
onObjectAdded: aggregator.scheduleRebuild()
onObjectRemoved: aggregator.scheduleRebuild()
}
// Rebuild on a relevant role change, a full reset, or a desktop-SET change. All funnel through the debounced scheduleRebuild.
Connections {
target: tasksModel
function onDataChanged(topLeft, bottomRight, roles) {
if (Logic.dataChangeAffectsRoles(roles, aggregator.relevantRoles))
aggregator.scheduleRebuild();
}
function onModelReset() {
aggregator.scheduleRebuild();
}
}
Connections {
target: aggregator.virtualDesktopInfo
function onDesktopIdsChanged() {
aggregator.scheduleRebuild();
}
}
// Coalesce a burst of change signals into ONE rebuild per frame. No loop: rows read the model, rebuild() writes, the dots only read.
function scheduleRebuild() {
Qt.callLater(aggregator.rebuild);
}
// Snapshot the materialised rows into a plain JS array, group per desktop (pure logic.js), then format each
// summary. `as WindowRow` gives typed access; normalise VirtualDesktops to plain strings (variant wrappers).
function rebuild() {
let windows = [];
for (let i = 0; i < winInstantiator.count; ++i) {
const o = winInstantiator.objectAt(i) as WindowRow;
if (!o)
continue;
windows.push({
title: o.display || "",
minimized: o.minimized,
onAll: o.onAllDesktops,
isWindow: o.isWindow,
skipPager: o.skipPager,
desktops: (o.windowDesktops || []).map(x => String(x)),
// Plain {x,y,width,height} (a QRect role isn't a plain JS value); null when absent → counts on every screen.
screen: o.windowScreen ? { x: o.windowScreen.x, y: o.windowScreen.y, width: o.windowScreen.width, height: o.windowScreen.height } : null
});
}
const ids = aggregator.virtualDesktopInfo?.desktopIds ?? [];
// Three reductions of the SAME snapshot. Compare-before-assign on EACH (arraysShallowEqual) avoids waking downstream on an unchanged array.
const tooltips = aggregator.windowListActive
? Logic.groupWindowsByDesktop(windows, ids).map(aggregator.formatSubText)
: [];
if (!Logic.arraysShallowEqual(tooltips, aggregator.desktopTooltips))
aggregator.desktopTooltips = tooltips;
// GLOBAL occupancy (all monitors) for the dynamic-workspaces controller — the desktop SET is global.
// Skipped (→ []) unless dynamic workspaces is on (its sole consumer); compare-before-assign as below.
const occupancy = aggregator.dynamicActive ? Logic.computeDesktopOccupancy(windows, ids) : [];
if (!Logic.arraysShallowEqual(occupancy, aggregator.desktopOccupancy))
aggregator.desktopOccupancy = occupancy;
// PER-SCREEN occupancy (this monitor only) for the occupied-dot indicator. Skipped (→ []) unless that
// indicator is on. A zero screenRect degrades to global, so on a single monitor it equals the global array
// — reuse that array directly when dynamic already computed it, instead of recomputing the same thing.
let screenOcc = [];
if (aggregator.occupancyActive) {
screenOcc = (aggregator.dynamicActive && !Logic.isValidScreenRect(aggregator.screenRect))
? occupancy
: Logic.computeDesktopOccupancyForScreen(windows, ids, aggregator.screenRect);
}
if (!Logic.arraysShallowEqual(screenOcc, aggregator.screenOccupancy))
aggregator.screenOccupancy = screenOcc;
}
// One window title as escaped rich text, falling back to a localized "Untitled Window" (shared fallback).
function titleHtml(title) {
return Logic.sanitizeHtml(title.length ? title : i18nc("@item:intext window with no title", "Untitled Window"));
}
// One desktop's window list as a rich-text <ul> capped at Logic.windowListMaximum + an "…and N other windows" overflow (stock pager's generateWindowList).
function formatList(titles) {
const total = titles.length;
const max = Logic.windowListMaximum(total);
let t = "<ul><li>" + titles.slice(0, max).map(x => aggregator.titleHtml(x)).join("</li><li>") + "</li></ul>";
if (total > max)
t += i18ncp("@info:tooltip overflow label", "…and %1 other window", "…and %1 other windows", total - max);
return t;
}
// Assemble one desktop's subText from its { visible, minimized } summary (the stock pager's
// updateSubTextIfNeeded). The leading <style> kills the <ul>'s default margin.
function formatSubText(s) {
let t = "";
if (s.visible.length === 1)
t += aggregator.titleHtml(s.visible[0]);
else if (s.visible.length > 1)
t += i18ncp("@info:tooltip start of list", "%1 Window:", "%1 Windows:", s.visible.length) + aggregator.formatList(s.visible);
if (s.visible.length && s.minimized.length)
t += s.visible.length === 1 ? "<br><br>" : "<br>";
if (s.minimized.length > 0)
t += i18ncp("@info:tooltip", "%1 Minimized Window:", "%1 Minimized Windows:", s.minimized.length) + aggregator.formatList(s.minimized);
return t.length ? "<style>ul { margin: 0; }</style>" + t : "";
}
// Toggling a feature at runtime changes both rebuild()'s output and its triggers, so force one rebuild on
// each flip (ON repopulates that feature's array, OFF clears it to []).
onWindowListActiveChanged: aggregator.scheduleRebuild()
onOccupancyActiveChanged: aggregator.scheduleRebuild()
onDynamicActiveChanged: aggregator.scheduleRebuild()
// The panel was dragged to another monitor (new output rect) → recompute per-screen occupancy for the new
// screen. Only the occupied-dot indicator consumes per-screen occupancy, so it's a no-op when that's off.
onScreenRectChanged: if (aggregator.occupancyActive) aggregator.scheduleRebuild()
Component.onCompleted: aggregator.rebuild()
}
@@ -0,0 +1,199 @@
/*
* Plasma Gnome Pager — WorkspaceDot.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* One workspace element (GNOME-style REFLOW model): the element IS the workspace, no overlay. Inactive =
* dim circle; active = a wider highlighted capsule (the pill). Colour, sizing, and the morph arrive as
* properties from the indicator (Kirigami-derived defaults so a dot renders standalone and headless).
*/
pragma ComponentBehavior: Bound
import QtQuick
import org.kde.kirigami as Kirigami
import org.kde.plasma.core as PlasmaCore // ToolTipArea
import "logic.js" as Logic
Item {
id: dot
// Inputs supplied by WorkspaceIndicator's Repeater delegate (with sane defaults).
property bool active: false
property int dotStyle: Logic.DEFAULTS.dotStyle // overall look (Logic.DOT_STYLE); Ring → non-current dots are hollow rings
property real dotSize: Kirigami.Units.iconSizes.small / 2
property real pillSize: Kirigami.Units.iconSizes.small / 2 // active-pill thickness, sized independently of the dot
property real pillWidthFactor: Logic.DEFAULTS.pillWidthFactor // capsule length / pill thickness
readonly property real pillWidth: dot.pillSize * dot.pillWidthFactor
property real inactiveOpacity: Logic.DEFAULTS.inactiveOpacity
property real hoverOpacity: Logic.DEFAULTS.hoverOpacity
property bool occupied: false // this desktop holds windows (showOccupancy feature; always false when off)
property real occupiedOpacity: Logic.DEFAULTS.occupiedOpacity // opacity of the occupied marker (all styles)
property int occupancyStyle: Logic.DEFAULTS.occupancyStyle // how an occupied dot is marked (Logic.OCCUPANCY)
property string desktopName: "" // tooltip mainText
property bool showTooltips: Logic.DEFAULTS.showTooltips
property string tooltipText: "" // tooltip subText: HTML window list, pre-formatted by main.qml (empty = name-only)
// Colours follow the scheme when followThemeColors (default), else the custom activeColor/inactiveColor/occupiedColor.
property bool followThemeColors: Logic.DEFAULTS.followThemeColors
property color activeColor: Kirigami.Theme.highlightColor
property color inactiveColor: Kirigami.Theme.textColor
property color occupiedColor: Kirigami.Theme.highlightColor // occupied marker (custom; theme accent when following the scheme)
property int animationDuration: Logic.DEFAULTS.animationDuration // ms; 0 = follow theme (resolved by effectiveDuration)
property bool vertical: false // major axis: false = horizontal panel (widen), true = vertical (grow tall)
property bool animate: false // morph gate, latched by the indicator after first valid placement (no grow-in on reload)
// Extent along the MAJOR (strip) axis and the CROSS axis: capsule when active, dot otherwise.
readonly property real longExtent: dot.active ? dot.pillWidth : dot.dotSize
readonly property real crossExtent: dot.active ? dot.pillSize : dot.dotSize
// Resolved colours: the theme accent/text when following the scheme, else the custom config colours.
readonly property color resolvedActive: dot.followThemeColors ? Kirigami.Theme.highlightColor : dot.activeColor
readonly property color resolvedInactive: dot.followThemeColors ? Kirigami.Theme.textColor : dot.inactiveColor
readonly property color resolvedOccupied: dot.followThemeColors ? Kirigami.Theme.highlightColor : dot.occupiedColor
// Occupied-indicator overlay flags (showOccupancy on) — both drawn ON TOP of the normal dim dot.
readonly property bool showInnerDot: Logic.innerDotVisible(dot.active, dot.occupied, dot.occupancyStyle) // InnerDot style: occupied → centre dot
readonly property bool showRing: Logic.ringOverlayVisible(dot.active, dot.occupied, dot.occupancyStyle, dot.dotStyle) // Ring occupancy overlay (suppressed in the Filled & ring look)
// "Filled & ring" style. The ring OUTLINE (hasRing) is decoupled from the INTERIOR (bodyIsHollow): a
// non-current dot always draws the ring border, and its interior is transparent UNLESS the Filled
// occupancy marker fills it (ringFilled → ring + filled background). Both false in the Pill style.
readonly property bool ringStyle: Logic.isRingStyle(dot.dotStyle)
readonly property bool hasRing: Logic.dotHasRing(dot.dotStyle, dot.active)
readonly property bool bodyIsHollow: Logic.dotBodyIsHollow(dot.dotStyle, dot.active, dot.occupied, dot.occupancyStyle)
readonly property bool ringFilled: Logic.dotBodyFilled(dot.dotStyle, dot.active, dot.occupied, dot.occupancyStyle) // occupied + Filled: ring outline + filled interior
// Filled-occupied ring interior: the occupied colour with its own alpha baked in (so the ring outline stays opaque). Only meaningful when ringFilled.
readonly property color filledBodyColor: Qt.rgba(dot.resolvedOccupied.r, dot.resolvedOccupied.g, dot.resolvedOccupied.b, dot.occupiedOpacity)
// Morph duration: configured value, else themed default, 0 when "reduce animations" is on. One source for the Behaviors below.
readonly property int effectiveDuration: Logic.effectiveDuration(dot.animationDuration, Kirigami.Units.longDuration)
readonly property bool morphEnabled: dot.animate && dot.effectiveDuration > 0
readonly property alias hovered: mouseArea.containsMouse
signal activated // emitted on click; the indicator turns it into a switch request
// Accessibility: announced to Orca etc. as a button named after the desktop, checkable/checked
// mirroring `active` so an AT can tell WHICH dot is current; press routes through activated() like a click.
Accessible.role: Accessible.Button
Accessible.name: dot.desktopName
Accessible.checkable: true
Accessible.checked: dot.active
Accessible.onPressAction: dot.activated()
// Footprint tracks the (possibly animating) capsule on both axes so the strip reflows smoothly.
implicitWidth: capsule.width
implicitHeight: capsule.height
// Per-dot tooltip (wrapping the content is canonical). Gated by showTooltips + a non-empty name (no empty tooltips while names lag ids).
PlasmaCore.ToolTipArea {
id: tooltip
anchors.fill: parent
active: dot.showTooltips && dot.desktopName !== ""
mainText: dot.desktopName
subText: dot.tooltipText
textFormat: Text.RichText // window list is an HTML <ul>, like the stock pager
// The dot/capsule. radius is min(width,height)/2 — orientation-agnostic stadium ends. Size
// bindings are independent ternaries (no own/parent geometry), so no loop with implicitWidth/Height.
Rectangle {
id: capsule
width: dot.vertical ? dot.crossExtent : dot.longExtent
height: dot.vertical ? dot.longExtent : dot.crossExtent
radius: Math.min(capsule.width, capsule.height) / 2
anchors.centerIn: parent
// The dot body. Pill style: the active capsule, a Filled-occupied dot, or the dim dot (dotColor).
// "Filled & ring" style: a hollow interior (transparent), OR a Filled-occupied interior (occupied
// colour at occupiedOpacity, baked into the fill so the ring border below stays crisp), else dotColor.
color: dot.bodyIsHollow ? "transparent"
: dot.ringFilled ? dot.filledBodyColor
: Logic.dotColor(dot.active, dot.occupied, dot.occupancyStyle, dot.resolvedActive, dot.resolvedInactive, dot.resolvedOccupied)
// Ring outline: drawn for every non-current dot in the Filled & ring style (in the dim/inactive colour), independent of the fill.
border.width: dot.hasRing ? Logic.ringThickness(dot.dotSize) : 0
border.color: dot.resolvedInactive
// In the Filled & ring style the body is full opacity (crisp rings; the occupied fill carries its own alpha above); the Pill style uses the dim/hover/occupied logic.
opacity: dot.ringStyle ? 1.0 : Logic.dotOpacity(dot.active, mouseArea.containsMouse, dot.occupied, dot.occupancyStyle, dot.inactiveOpacity, dot.hoverOpacity, dot.occupiedOpacity)
// Morph, gated by morphEnabled. The major axis always morphs; the cross axis too when pillSize != dotSize (so width and/or height fire).
Behavior on width {
enabled: dot.morphEnabled
NumberAnimation {
duration: dot.effectiveDuration
easing.type: Easing.OutCubic
}
}
Behavior on height {
enabled: dot.morphEnabled
NumberAnimation {
duration: dot.effectiveDuration
easing.type: Easing.OutCubic
}
}
Behavior on color {
enabled: dot.morphEnabled
ColorAnimation {
duration: dot.effectiveDuration
}
}
// Ring⇄fill: the border grows/shrinks as a dot switches between hollow-ring and filled in the "Filled & ring" style.
Behavior on border.width {
enabled: dot.morphEnabled
NumberAnimation {
duration: dot.effectiveDuration
easing.type: Easing.OutCubic
}
}
Behavior on opacity {
enabled: dot.morphEnabled
NumberAnimation {
duration: dot.effectiveDuration
}
}
}
// Occupied-dot overlay (InnerDot / Ring styles), drawn ON TOP of the dim dot. Behind a Loader so when
// occupancy is off (the default) NEITHER Rectangle exists — the dot then carries no extra scene-graph
// nodes. Only the style in use is built (showInnerDot/showRing are mutually exclusive, both false when
// active or Filled). A sibling of the capsule (its own opacity); centred on the CAPSULE for exact placement.
Loader {
id: occupancyOverlay
anchors.centerIn: capsule
active: dot.showInnerDot || dot.showRing
sourceComponent: dot.showRing ? ringComponent : innerDotComponent
}
// InnerDot style: a small occupied-colour dot in the dot's centre. Uses the occupied-opacity slider, like the other styles.
Component {
id: innerDotComponent
Rectangle {
width: Logic.innerDotDiameter(dot.dotSize)
height: width
radius: width / 2
color: dot.resolvedOccupied
opacity: dot.occupiedOpacity
}
}
// Ring style: a hollow occupied-colour ring at the dot's rim (the dim dot stays visible behind it). Uses the occupied-opacity slider, like the other styles.
Component {
id: ringComponent
Rectangle {
width: dot.dotSize
height: width
radius: width / 2
color: "transparent"
border.width: Logic.ringThickness(dot.dotSize)
border.color: dot.resolvedOccupied
opacity: dot.occupiedOpacity
}
}
// Click/hover target. acceptedButtons stays LeftButton (default) so a right-click falls
// through to the applet's context menu.
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true
onClicked: dot.activated()
}
}
}
@@ -0,0 +1,281 @@
/*
* Plasma Gnome Pager — WorkspaceIndicator.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* The dot strip (GNOME REFLOW model). Layout + scroll + wiring only: delegates size math to
* IndicatorMetrics and the per-screen current to ScreenCurrentDesktop, binds live to VirtualDesktopInfo,
* reports clicks/scroll via switchRequested. Imports no org.kde.plasma.*, so it stays headless-testable.
*/
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import "logic.js" as Logic
Item {
id: indicator
// Reactive read-only desktop state, supplied by main.qml. NOT `required` — Plasma's representation loader fails creation SILENTLY on that; null + guard instead.
property var virtualDesktopInfo: null
// Null-safe live views. The desktop SET is global; only "which is current" is per-screen (below).
readonly property var desktopIds: virtualDesktopInfo?.desktopIds ?? []
readonly property var desktopNames: virtualDesktopInfo?.desktopNames ?? []
// Per-desktop tooltip subText (window list), index-aligned with desktopIds. Default [] → name-only tooltip.
property var desktopTooltips: []
// This panel's output (KWin connector name, e.g. "DP-1") from the Screen attached property so it reflects THIS monitor. Tests override; "" → global.
property string screenName: Screen.name
// This panel's output RECT in the virtual-desktop space (Screen has no `geometry`), read by main.qml to
// drive per-screen occupancy. Tests override; a zero rect → occupancy degrades to global (single-monitor look).
property rect screenRect: Qt.rect(Screen.virtualX, Screen.virtualY, Screen.width, Screen.height)
// The current desktop FOR THIS SCREEN (Plasma 6.7 per-output), resolved by ScreenCurrentDesktop.
readonly property string currentDesktop: screenCurrent.currentDesktop
ScreenCurrentDesktop {
id: screenCurrent
virtualDesktopInfo: indicator.virtualDesktopInfo
screenName: indicator.screenName
}
// Behaviour flags, supplied by main.qml (defaults match the schema).
property bool enableScroll: Logic.DEFAULTS.enableScroll
property bool scrollWrap: Logic.DEFAULTS.scrollWrap
property bool invertScroll: Logic.DEFAULTS.invertScroll // flip the wheel-sign → direction mapping
property bool showTooltips: Logic.DEFAULTS.showTooltips
// Panel orientation. false = horizontal row (also the Planar/floating default); true = vertical column.
property bool vertical: false
// When true, ignore KWin's grid rows and lay every desktop out in ONE line (forces desktopRows = 1 below).
// ORTHOGONAL to matchDesktopGrid: this sets the line COUNT, that sets the DIRECTION — so singleLine +
// matchDesktopGrid on a vertical panel gives a single HORIZONTAL row, while singleLine alone is a vertical strip.
property bool singleLine: Logic.DEFAULTS.singleLine
// When true on a vertical panel, run the layout ACROSS the panel instead of down it: for a multi-row grid that
// mirrors KWin's orientation (rows top-to-bottom, the GNOME-reflow default is to transpose it down); with
// singleLine it makes the one line horizontal. No effect on a horizontal panel (it already runs across).
property bool matchDesktopGrid: Logic.DEFAULTS.matchDesktopGrid
// Effective major-axis orientation: true = down the panel (vertical), false = across it (horizontal). ALL grid
// geometry below (the two Grid flows, the metrics axis, the Layout hints, the dot's capsule axis) keys off THIS.
// singleLine changes the line COUNT (above), matchDesktopGrid the DIRECTION — independent.
readonly property bool gridVertical: vertical && !matchDesktopGrid
// Running total of hi-res/touchpad wheel deltas; whole notches become steps (the remainder carries).
property real wheelAccumulator: 0
readonly property int wheelNotchDelta: Logic.DEFAULTS.wheelNotchDelta
readonly property int desktopCount: desktopIds.length
// KWin's grid row count, read live (null-guarded, >= 1). We MIRROR KWin so "Rows" re-lays out reactively —
// unless singleLine forces it to 1 (collapse the grid into one line of all desktops).
readonly property int desktopRows: singleLine ? 1 : (virtualDesktopInfo?.desktopLayoutRows > 0 ? virtualDesktopInfo.desktopLayoutRows : 1)
// Desktops per line (columns = ceil(count / rows)) and the row-major split into lines.
readonly property int perLine: Logic.gridColumns(desktopCount, desktopRows)
readonly property var lines: Logic.chunk(desktopIds, perLine)
readonly property int lineCount: lines.length
// Active element index, or -1 for any transient state (empty ids, empty/absent current) → no capsule.
readonly property int activeIndex: desktopIds.indexOf(currentDesktop)
// Overall pager look (Logic.DOT_STYLE). The "Filled & ring" style has NO pill, so we neutralize the
// pill params below: feeding pillWidthFactor=1 + pillSizeRequest=0 makes the metrics AND each dot size
// every element uniformly (the active extent collapses to dotSize) without touching IndicatorMetrics.
property int dotStyle: Logic.DEFAULTS.dotStyle
readonly property bool ringStyle: Logic.isRingStyle(dotStyle)
readonly property real effPillWidthFactor: ringStyle ? 1.0 : pillWidthFactor
readonly property int effPillSizeRequest: ringStyle ? 0 : pillSizeRequest
// Config requests fed to the sizing engine; dotSize/pillSize `0 = auto` resolved in IndicatorMetrics.
property int dotSizeRequest: Logic.DEFAULTS.dotSize // px override; 0 = auto
property int pillSizeRequest: Logic.DEFAULTS.pillSize // px pill thickness; 0 = auto (match dots)
property real spacingFactor: Logic.DEFAULTS.spacingFactor // uniform gap as a multiple of a dot
property real pillWidthFactor: Logic.DEFAULTS.pillWidthFactor // active capsule length, × the pill thickness
property real inactiveOpacity: Logic.DEFAULTS.inactiveOpacity
property real hoverOpacity: Logic.DEFAULTS.hoverOpacity // inactive-dot hover brighten target
// Occupied-dot indicator: when showOccupancy, an occupied dot (desktopOccupancy[globalIndex]) is marked per occupancyStyle.
property bool showOccupancy: Logic.DEFAULTS.showOccupancy
property var desktopOccupancy: [] // per-desktop bool[], index-aligned with desktopIds (per-screen, from main.qml)
property real occupiedOpacity: Logic.DEFAULTS.occupiedOpacity // marker opacity (all styles)
property int occupancyStyle: Logic.DEFAULTS.occupancyStyle // Filled/InnerDot/Ring (Logic.OCCUPANCY)
// The sizing engine: requests + grid shape + live geometry → effective sizes + extents (forwarded below).
IndicatorMetrics {
id: metrics
dotSizeRequest: indicator.dotSizeRequest
pillSizeRequest: indicator.effPillSizeRequest // ring style: 0 → pill thickness == dot (no pill)
spacingFactor: indicator.spacingFactor
pillWidthFactor: indicator.effPillWidthFactor // ring style: 1 → active extent == dot (no pill)
availableMajor: indicator.gridVertical ? indicator.height : indicator.width
availableCross: indicator.gridVertical ? indicator.width : indicator.height
perLine: indicator.perLine
lineCount: indicator.lineCount
}
// Effective (rendered) sizes — scale-to-fit applied; == natural when there is room.
readonly property real dotSize: metrics.dotSize
readonly property real pillSize: metrics.pillSize // effective pill thickness (tracks the dot)
readonly property real pillWidth: metrics.pillWidth // active capsule LENGTH (major axis)
readonly property real dotSpacing: metrics.dotSpacing // uniform gap between every element
// Conserved (capsule-bearing) extents — the strip is pinned to these so a cross-row morph can't drift it.
readonly property real stripLength: metrics.stripLength
readonly property real crossThickness: metrics.crossThickness
// Natural/floor extents (geometry-independent — feed the Layout hints; no loop).
readonly property real naturalDotSize: metrics.naturalDotSize
readonly property real naturalPillSize: metrics.naturalPillSize
readonly property real pillThicknessRatio: metrics.pillThicknessRatio
readonly property real minDotSize: metrics.minDotSize
readonly property real naturalStripLength: metrics.naturalStripLength
readonly property real floorStripLength: metrics.floorStripLength
readonly property real naturalCrossThickness: metrics.naturalCrossThickness
readonly property real floorCrossThickness: metrics.floorCrossThickness
// Colour + animation config, passed straight through to each dot (the indicator draws nothing itself).
property bool followThemeColors: Logic.DEFAULTS.followThemeColors
property color activeColor: Kirigami.Theme.highlightColor
property color inactiveColor: Kirigami.Theme.textColor
property color occupiedColor: Kirigami.Theme.highlightColor // occupied-marker colour (custom; theme accent when following the scheme)
property int animationDuration: Logic.DEFAULTS.animationDuration // ms; 0 = follow the theme
// Raised on a click or scroll; main.qml turns the UUID into a KWin switch.
signal switchRequested(string uuid)
// Raised when the ALREADY-CURRENT desktop's dot (the pill) is clicked/pressed; main.qml maps it to the
// configured pill-click action. Scroll never raises this (handleWheel only ever emits switchRequested).
signal activeClicked()
// Wheel → switch. Thin wrapper; the branching (notch accumulation, clamp/wrap, -1 ignore) is in logic.js and unit-tested.
function handleWheel(angleDeltaY: real) {
if (!indicator.enableScroll)
return;
const acc = Logic.accumulateWheel(indicator.wheelAccumulator, angleDeltaY, indicator.wheelNotchDelta);
indicator.wheelAccumulator = acc.remainder;
if (acc.steps === 0)
return; // sub-notch motion accumulated; nothing to do yet
// Default: wheel up (+) → previous desktop; down (−) → next, so negate. invertScroll keeps the sign.
const dir = indicator.invertScroll ? acc.steps : -acc.steps;
const next = Logic.stepIndex(indicator.activeIndex, indicator.desktopIds.length, dir, indicator.scrollWrap);
if (next < 0 || next === indicator.activeIndex)
return; // empty/unknown source, or a clamped no-op at an end
const uuid = indicator.desktopIds[next];
if (!uuid)
return; // transient empty id (robustness.md: guard before use)
indicator.switchRequested(uuid);
}
// Size hints. Major axis: preferred==max==naturalStripLength, min==floorStripLength (panel can compress
// → dots scale to fit). Cross axis: preferred==natural, max==-1 (fill thickness), min==floor. Swaps with `gridVertical`.
implicitWidth: gridVertical ? naturalCrossThickness : naturalStripLength
implicitHeight: gridVertical ? naturalStripLength : naturalCrossThickness
Layout.minimumWidth: gridVertical ? floorCrossThickness : floorStripLength
Layout.preferredWidth: implicitWidth
Layout.maximumWidth: gridVertical ? -1 : naturalStripLength
Layout.minimumHeight: gridVertical ? floorStripLength : floorCrossThickness
Layout.preferredHeight: implicitHeight
Layout.maximumHeight: gridVertical ? naturalStripLength : -1
// Gate the morph so the FIRST valid placement is instant (no grow-in on reload), later switches animate.
// ScreenCurrentDesktop (a child) resolves currentDesktop in its onCompleted first, so activeIndex is valid here.
property bool animate: false
onActiveIndexChanged: {
if (activeIndex >= 0 && !animate) {
Qt.callLater(() => indicator.animate = true);
}
}
Component.onCompleted: {
if (activeIndex >= 0) {
animate = true;
}
}
// Scroll-to-switch. This MouseArea sits BEHIND the dots, accepts no buttons/hover, so clicks/hover pass through while a wheel propagates here.
MouseArea {
id: wheelArea
anchors.fill: parent
acceptedButtons: Qt.NoButton
onWheel: wheel => indicator.handleWheel(wheel.angleDelta.y)
}
// Two nested positioners mirror KWin's grid: OUTER stacks lines on the cross axis, INNER the dots on the major axis (one 2-D Grid would fatten a column).
Grid {
id: strip
anchors.centerIn: parent
// Pin to the conserved extent so a cross-row morph can't resize+recenter the strip (else the dots drift).
// Content-sized would dip mid-morph as the capsule moves between lines; this keeps the footprint constant.
width: indicator.gridVertical ? indicator.crossThickness : indicator.stripLength
height: indicator.gridVertical ? indicator.stripLength : indicator.crossThickness
spacing: indicator.dotSpacing
rows: indicator.gridVertical ? 1 : -1
columns: indicator.gridVertical ? -1 : 1
Repeater {
// `lines` is [] while the source is transiently null/empty, so the outer Repeater is empty.
model: indicator.lines
delegate: Grid {
id: lineStrip
required property var modelData // this line's UUIDs (a row-major chunk)
required property int index // line index (KWin row)
spacing: indicator.dotSpacing
rows: indicator.gridVertical ? -1 : 1
columns: indicator.gridVertical ? 1 : -1
// Centre every element on the CROSS axis: the line is as thick as its tallest element (the capsule when pillSize > dotSize).
verticalItemAlignment: indicator.gridVertical ? Grid.AlignTop : Grid.AlignVCenter
horizontalItemAlignment: indicator.gridVertical ? Grid.AlignHCenter : Grid.AlignLeft
Repeater {
model: lineStrip.modelData
delegate: WorkspaceDot {
id: workspaceDot
required property string modelData
required property int index
// Position in the flat desktopIds/desktopNames: earlier lines are full at perLine.
readonly property int globalIndex: lineStrip.index * indicator.perLine + workspaceDot.index
vertical: indicator.gridVertical
dotStyle: indicator.dotStyle
dotSize: indicator.dotSize
pillSize: indicator.pillSize // == dotSize in ring mode (no pill)
pillWidthFactor: indicator.effPillWidthFactor // == 1 in ring mode (active extent == dot)
inactiveOpacity: indicator.inactiveOpacity
hoverOpacity: indicator.hoverOpacity
// Gating on showOccupancy here keeps a stale/short desktopOccupancy array harmless when the feature is off.
occupied: indicator.showOccupancy && (indicator.desktopOccupancy[workspaceDot.globalIndex] ?? false)
occupiedOpacity: indicator.occupiedOpacity
occupancyStyle: indicator.occupancyStyle
followThemeColors: indicator.followThemeColors
activeColor: indicator.activeColor
inactiveColor: indicator.inactiveColor
occupiedColor: indicator.occupiedColor
animationDuration: indicator.animationDuration
active: indicator.currentDesktop === workspaceDot.modelData
animate: indicator.animate
// Each dot's tooltip name + window-list subText (|| "" guards the transient frame where names/tooltips lag ids).
desktopName: indicator.desktopNames[workspaceDot.globalIndex] || ""
tooltipText: indicator.desktopTooltips[workspaceDot.globalIndex] || ""
showTooltips: indicator.showTooltips
// Clicking the current desktop's pill runs the configured action; any other dot switches.
onActivated: workspaceDot.active ? indicator.activeClicked() : indicator.switchRequested(workspaceDot.modelData)
}
}
}
}
}
}
@@ -0,0 +1,251 @@
/*
* Plasma Gnome Pager — ConfigAppearance.qml (Appearance settings page)
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* The Appearance page, built on ConfigPageBase. Ratios use ConfigSlider; dotSize/pillSize are integer
* sliders where 0 reads "Default"/"Match dots" (the 0 = auto sentinel). Colours use ColorButton, lazy-loaded
* with the dialog so the import never affects the always-on widget. Each `cfg_<key>` MUST match main.xml.
*/
pragma ComponentBehavior: Bound // the occupancyStyle delegate references outer ids (occupancyStyle/root)
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.kquickcontrols as KQuickControls
ConfigPageBase {
id: root
property alias cfg_dotStyle: dotStyle.currentIndex
property alias cfg_singleLine: singleLine.checked
property alias cfg_matchDesktopGrid: matchDesktopGrid.checked
property alias cfg_dotSize: dotSize.value
property alias cfg_pillSize: pillSize.value
property alias cfg_spacingFactor: spacingFactor.value
property alias cfg_pillWidthFactor: pillWidthFactor.value
property alias cfg_inactiveOpacity: inactiveOpacity.value
property alias cfg_hoverOpacity: hoverOpacity.value
property alias cfg_showOccupancy: showOccupancy.checked
property alias cfg_occupancyStyle: occupancyStyle.currentIndex
property alias cfg_occupiedOpacity: occupiedOpacity.value
property alias cfg_followThemeColors: followThemeColors.checked
property alias cfg_activeColor: activeColor.color
property alias cfg_inactiveColor: inactiveColor.color
property alias cfg_occupiedColor: occupiedColor.color
// Injected by the config dialog from the main.xml defaults; read by the Defaults handler below.
property int cfg_dotStyleDefault
property bool cfg_singleLineDefault
property bool cfg_matchDesktopGridDefault
property int cfg_dotSizeDefault
property int cfg_pillSizeDefault
property real cfg_spacingFactorDefault
property real cfg_pillWidthFactorDefault
property real cfg_inactiveOpacityDefault
property real cfg_hoverOpacityDefault
property bool cfg_showOccupancyDefault
property int cfg_occupancyStyleDefault
property real cfg_occupiedOpacityDefault
property bool cfg_followThemeColorsDefault
property color cfg_activeColorDefault
property color cfg_inactiveColorDefault
property color cfg_occupiedColorDefault
// This page's keys + compare kind; ConfigPageBase binds isModified + the Defaults reset off it
// (reals within epsilon, colours via Qt.colorEqual).
configKeys: [
{ n: "dotStyle", t: "int" },
{ n: "singleLine", t: "bool" },
{ n: "matchDesktopGrid", t: "bool" },
{ n: "dotSize", t: "int" },
{ n: "pillSize", t: "int" },
{ n: "spacingFactor", t: "real" },
{ n: "pillWidthFactor", t: "real" },
{ n: "inactiveOpacity", t: "real" },
{ n: "hoverOpacity", t: "real" },
{ n: "showOccupancy", t: "bool" },
{ n: "occupancyStyle", t: "int" },
{ n: "occupiedOpacity", t: "real" },
{ n: "followThemeColors", t: "bool" },
{ n: "activeColor", t: "color" },
{ n: "inactiveColor", t: "color" },
{ n: "occupiedColor", t: "color" }
]
// Which pager style is selected, by the dotStyle combo index (order matches Logic.DOT_STYLE / main.xml:
// 0 = Sliding pill, 1 = Filled & ring). The pill knobs only apply to Sliding pill; Filled & ring disables
// the redundant Hollow ring occupancy marker. Named once here so the index checks aren't repeated below.
readonly property bool pillStyle: dotStyle.currentIndex === 0
readonly property bool ringStyle: dotStyle.currentIndex === 1
Kirigami.FormLayout {
QQC2.ComboBox {
id: dotStyle
Kirigami.FormData.label: i18n("Pager style:")
// Order MUST match Logic.DOT_STYLE / main.xml dotStyle (currentIndex is stored as the index).
model: [i18n("Sliding pill"), i18n("Filled & ring")]
Layout.preferredWidth: root.fieldWidth // match the other field widths (ConfigPageBase.fieldWidth)
// Filled & ring disables the Hollow ring occupancy marker (index 2) — the dot is already a ring —
// so migrate a previously-chosen Hollow ring to Filled (0) when the user switches to it.
onActivated: {
if (root.ringStyle && occupancyStyle.currentIndex === 2)
occupancyStyle.currentIndex = 0;
}
}
QQC2.CheckBox {
id: singleLine
Kirigami.FormData.label: i18n("Multiple rows:")
text: i18n("Show all desktops in a single line")
}
QQC2.Label {
// Hint: ignore the KWin grid entirely and lay everything out as one strip following the panel.
text: i18n("Ignore the grid rows from System Settings and lay every desktop out in one strip along the panel (a single vertical strip on a vertical panel).")
wrapMode: Text.WordWrap
opacity: 0.7
font: Kirigami.Theme.smallFont
Layout.fillWidth: true
Layout.preferredWidth: root.fieldWidth // wrap within the field column
}
QQC2.CheckBox {
id: matchDesktopGrid
Kirigami.FormData.label: i18n("Vertical panels:")
text: i18n("Match the virtual-desktop grid layout")
// Orthogonal to "single line": this sets the direction (across vs. down), so it composes — single
// line + match grid gives a single HORIZONTAL row. Hence no longer greyed while single line is on.
}
QQC2.Label {
// Hint: this only matters on a vertical panel (a horizontal panel already mirrors the grid).
text: i18n("Arrange the dots like the desktop grid in System Settings (rows top to bottom) instead of running them down the panel. No effect on horizontal panels.")
wrapMode: Text.WordWrap
opacity: 0.7
font: Kirigami.Theme.smallFont
Layout.fillWidth: true
Layout.preferredWidth: root.fieldWidth // wrap within the field column
}
ConfigSlider {
id: dotSize
label: i18n("Dot size:")
from: 0
to: 64
stepSize: 1
// 0 = auto: the widget falls back to the HiDPI-aware themed size.
format: v => v === 0 ? i18n("Default") : i18np("%1 px", "%1 px", Math.round(v))
}
ConfigSlider {
id: pillSize
// "Thickness" (not "size") disambiguates from "Pill length:" below — the pill's two axes (also avoids an msgmerge fuzzy collision).
label: i18n("Pill thickness:")
enabled: root.pillStyle // the pill only exists in the Sliding pill style
from: 0
to: 64
stepSize: 1
// 0 = auto: the pill thickness matches the (effective) dot size, so the pill tracks the dots.
format: v => v === 0 ? i18n("Match dots") : i18np("%1 px", "%1 px", Math.round(v))
}
ConfigSlider {
id: spacingFactor
label: i18n("Spacing:")
from: 0.0
to: 2.0
stepSize: 0.05
format: v => i18n("%1× dot", v.toFixed(2))
}
ConfigSlider {
id: pillWidthFactor
label: i18n("Pill length:")
enabled: root.pillStyle // the pill only exists in the Sliding pill style
from: 1.0
to: 10.0
stepSize: 0.1
// Length as a multiple of the PILL thickness (its aspect ratio), not the dot size.
format: v => i18n("%1× pill", v.toFixed(1))
}
ConfigSlider {
id: inactiveOpacity
label: i18n("Inactive opacity:")
from: 0.0
to: 1.0
stepSize: 0.01 // 1% increments for fine control (drag or arrow keys)
format: v => Math.round(v * 100) + "%"
}
ConfigSlider {
id: hoverOpacity
label: i18n("Hover opacity:")
from: 0.0
to: 1.0
stepSize: 0.01 // 1% increments for fine control (drag or arrow keys)
format: v => Math.round(v * 100) + "%"
}
QQC2.CheckBox {
id: showOccupancy
Kirigami.FormData.label: i18n("Occupied desktops:")
text: i18n("Highlight desktops with open windows")
}
QQC2.ComboBox {
id: occupancyStyle
Kirigami.FormData.label: i18n("Indicator style:")
enabled: showOccupancy.checked
// Order MUST match Logic.OCCUPANCY / main.xml occupancyStyle (currentIndex is stored as the index).
model: [i18n("Filled"), i18n("Inner dot"), i18n("Hollow ring")]
// "Hollow ring" (index 2) is redundant in the Filled & ring pager style — the dot is ALREADY a
// hollow ring — so disable that item there (selection blocked; a stored value is suppressed at runtime).
delegate: QQC2.ItemDelegate {
id: occStyleItem
required property int index
required property string modelData
width: occupancyStyle.width
text: occStyleItem.modelData
enabled: !(root.ringStyle && occStyleItem.index === 2)
highlighted: occupancyStyle.highlightedIndex === occStyleItem.index
}
}
ConfigSlider {
id: occupiedOpacity
label: i18n("Occupied opacity:")
enabled: showOccupancy.checked // every indicator style uses the occupied-marker opacity
from: 0.0
to: 1.0
stepSize: 0.01 // 1% increments for fine control (drag or arrow keys)
format: v => Math.round(v * 100) + "%"
}
Item {
Kirigami.FormData.isSection: true // a little vertical breathing room before the colours
}
QQC2.CheckBox {
id: followThemeColors
Kirigami.FormData.label: i18n("Colors:")
text: i18n("Follow the color scheme")
}
KQuickControls.ColorButton {
id: activeColor
Kirigami.FormData.label: i18n("Active desktop:")
enabled: !followThemeColors.checked // custom colours apply only when not following the theme
showAlphaChannel: false
}
KQuickControls.ColorButton {
id: inactiveColor
Kirigami.FormData.label: i18n("Inactive desktop:")
enabled: !followThemeColors.checked
showAlphaChannel: false
}
KQuickControls.ColorButton {
id: occupiedColor
Kirigami.FormData.label: i18n("Occupied desktop:")
enabled: !followThemeColors.checked // the occupied marker; theme accent is used while following the scheme
showAlphaChannel: false
}
}
}
@@ -0,0 +1,145 @@
/*
* Plasma Gnome Pager — ConfigGeneral.qml (Behavior settings page)
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* The Behavior page, built on ConfigPageBase. Each `cfg_<key>` alias MUST match a main.xml entry exactly
* (the dialog wires load/save); `cfg_<key>Default` is injected from the schema.
*/
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
ConfigPageBase {
id: root
property alias cfg_enableScroll: enableScroll.checked
property alias cfg_scrollWrap: scrollWrap.checked
property alias cfg_invertScroll: invertScroll.checked
property alias cfg_pillClickAction: pillClickAction.currentIndex
property alias cfg_showTooltips: showTooltips.checked
property alias cfg_showWindowList: showWindowList.checked
property alias cfg_enableAddRemove: enableAddRemove.checked
property alias cfg_enableRename: enableRename.checked
property alias cfg_dynamicWorkspaces: dynamicWorkspaces.checked
property alias cfg_dynamicNamePrefix: dynamicNamePrefix.text
property alias cfg_animationDuration: animationDuration.value
// Injected by the config dialog from the main.xml defaults; read by the Defaults handler below.
property bool cfg_enableScrollDefault
property bool cfg_scrollWrapDefault
property bool cfg_invertScrollDefault
property int cfg_pillClickActionDefault
property bool cfg_showTooltipsDefault
property bool cfg_showWindowListDefault
property bool cfg_enableAddRemoveDefault
property bool cfg_enableRenameDefault
property bool cfg_dynamicWorkspacesDefault
property string cfg_dynamicNamePrefixDefault
property int cfg_animationDurationDefault
// This page's keys + compare kind; ConfigPageBase binds isModified AND the Defaults reset off it.
configKeys: [
{ n: "enableScroll", t: "bool" },
{ n: "scrollWrap", t: "bool" },
{ n: "invertScroll", t: "bool" },
{ n: "pillClickAction", t: "int" },
{ n: "showTooltips", t: "bool" },
{ n: "showWindowList", t: "bool" },
{ n: "enableAddRemove", t: "bool" },
{ n: "enableRename", t: "bool" },
{ n: "dynamicWorkspaces", t: "bool" },
{ n: "dynamicNamePrefix", t: "string" },
{ n: "animationDuration", t: "int" }
]
Kirigami.FormLayout {
QQC2.CheckBox {
id: enableScroll
Kirigami.FormData.label: i18n("Mouse:")
text: i18n("Scroll over the pager to switch desktops")
}
QQC2.CheckBox {
id: scrollWrap
text: i18n("Wrap around at the first and last desktop")
enabled: enableScroll.checked // wrap only matters when scrolling is on
}
QQC2.CheckBox {
id: invertScroll
text: i18n("Invert the scroll direction")
enabled: enableScroll.checked // inversion only matters when scrolling is on
}
QQC2.ComboBox {
id: pillClickAction
Kirigami.FormData.label: i18n("Click current desktop:")
// Order MUST match Logic.PILL_CLICK_ACTION / main.xml pillClickAction (currentIndex is stored as the index).
model: [i18n("Nothing"), i18n("Show Desktop"), i18n("Overview"), i18n("Grid")]
Layout.preferredWidth: root.fieldWidth // match the other field widths (ConfigPageBase.fieldWidth)
}
QQC2.Label {
// Clarify the action only fires on the highlighted (current) desktop; other dots just switch.
text: i18n("Action when clicking the highlighted current desktop. Clicking any other desktop switches to it.")
wrapMode: Text.WordWrap
opacity: 0.7
font: Kirigami.Theme.smallFont
Layout.fillWidth: true
Layout.preferredWidth: root.fieldWidth // wrap within the field column
}
QQC2.CheckBox {
id: showTooltips
Kirigami.FormData.label: i18n("Tooltips:")
text: i18n("Show the desktop name on hover")
}
QQC2.CheckBox {
id: showWindowList
text: i18n("List the open windows in the tooltip")
enabled: showTooltips.checked // the window list only shows when tooltips are on
}
QQC2.CheckBox {
id: enableAddRemove
Kirigami.FormData.label: i18n("Menu:")
text: i18n("Add and remove desktops from the right-click menu")
// Greyed while dynamic workspaces is on (mutually exclusive); value preserved, returns when off.
enabled: !dynamicWorkspaces.checked
}
QQC2.CheckBox {
id: enableRename
text: i18n("Rename the current desktop from the right-click menu")
}
QQC2.CheckBox {
id: dynamicWorkspaces
Kirigami.FormData.label: i18n("Dynamic desktops:")
text: i18n("Automatically add and remove desktops (GNOME-style)")
}
QQC2.Label {
// Hint explaining the exclusivity above, so a new user sees why Add/Remove greys out.
text: i18n("While on, desktops are managed automatically — the menu Add/Remove options are disabled.")
visible: dynamicWorkspaces.checked
wrapMode: Text.WordWrap
opacity: 0.7
font: Kirigami.Theme.smallFont
Layout.fillWidth: true
Layout.preferredWidth: root.fieldWidth // wrap within the field column
}
QQC2.TextField {
id: dynamicNamePrefix
Kirigami.FormData.label: i18n("New desktop name:")
// Base name for auto-created desktops (number appended); empty → the placeholder default.
enabled: dynamicWorkspaces.checked
placeholderText: i18nc("@info default base name for auto-created virtual desktops", "Desktop")
Layout.preferredWidth: root.fieldWidth // match the slider track width (ConfigPageBase.fieldWidth)
}
ConfigSlider {
id: animationDuration
label: i18n("Animation duration:")
from: 0
to: 2000
stepSize: 25 // clean 25 ms increments (SnapAlways is the ConfigSlider default)
// 0 = follow the theme's default (and the global "reduce animations" setting).
format: v => v === 0 ? i18n("Default") : i18np("%1 ms", "%1 ms", Math.round(v))
}
}
}
@@ -0,0 +1,58 @@
/*
* Plasma Gnome Pager — ConfigPageBase.qml (shared settings-page base)
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Shared skeleton for every settings page: a Kirigami.ScrollablePage for the KDE header + scrolling, plus
* the "Defaults" button the Plasma footer lacks (defined ONCE here). A derived page only declares its
* `configKeys` { n, t } list; the modified-check and the Defaults reset are bound off it here, once.
*/
import QtQuick
import org.kde.kirigami as Kirigami
Kirigami.ScrollablePage {
id: root
// The derived page's keys + compare kind ({ n, t }); drives both isModified and the Defaults reset.
property var configKeys: []
// True when any key differs from its default (gates the Defaults action). Bound off configKeys here
// so a derived page need only declare the list; empty configKeys ⇒ false (unmodified).
property bool isModified: configKeys.some(k => root.fieldChanged(root, k.n, k.t))
// Field-column width for non-slider fields; kept equal to ConfigSlider.trackWidth so every row lines up.
readonly property int fieldWidth: Kirigami.Units.gridUnit * 18
// Tolerance for real-valued "differs from default": SnapAlways can land a value a ULP off the default.
readonly property real epsilon: 1e-9
// Does cfg_<name> differ from cfg_<name>Default? Type-aware: reals within epsilon, colours via Qt.colorEqual, else exact.
function fieldChanged(page, name, kind) {
var a = page["cfg_" + name];
var b = page["cfg_" + name + "Default"];
if (kind === "real")
return Math.abs(a - b) > root.epsilon;
if (kind === "color")
return !Qt.colorEqual(a, b);
return a !== b;
}
// Reset cfg_<name> to its injected schema default.
function resetField(page, name) {
page["cfg_" + name] = page["cfg_" + name + "Default"];
}
// Raised by the Defaults action; resets every configKeys entry to its injected schema default.
signal defaultsRequested()
onDefaultsRequested: configKeys.forEach(k => root.resetField(root, k.n))
actions: [
Kirigami.Action {
text: i18n("Defaults")
icon.name: "edit-undo-symbolic"
enabled: root.isModified
onTriggered: root.defaultsRequested()
}
]
}
@@ -0,0 +1,61 @@
/*
* Plasma Gnome Pager — ConfigSlider.qml (reusable config-page control)
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* A FormLayout row of a Slider + a right-hand value read-out. One `format` closure (value → string) drives
* BOTH the read-out AND its reserved width (widest of from/to) so the label can't reflow mid-drag. The
* track is a FIXED width (NOT fillWidth) so sliders match across both pages; the value label absorbs slack.
*/
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
RowLayout {
id: root
property alias value: slider.value
property alias from: slider.from
property alias to: slider.to
property alias stepSize: slider.stepSize
property alias snapMode: slider.snapMode
property string label: "" // the row's Kirigami.FormData label
property var format: (v) => String(v) // value → read-out string (drives text AND reserved width)
// Fixed track length, matched to ConfigPageBase.fieldWidth so every row's field column lines up.
readonly property int trackWidth: Kirigami.Units.gridUnit * 18
Kirigami.FormData.label: root.label
QQC2.Slider {
id: slider
// Fixed track length (NOT fillWidth): a fillWidth track would stretch wider on the Behavior page's long labels. min == preferred so it can't shrink.
Layout.preferredWidth: root.trackWidth
Layout.minimumWidth: root.trackWidth
snapMode: QQC2.Slider.SnapAlways // clean increments even when dragged (override via alias)
}
QQC2.Label {
id: valueLabel
text: root.format(slider.value)
horizontalAlignment: Text.AlignRight
// fillWidth so extra column width is absorbed here — the right-aligned read-out pins to the column edge and the slider keeps its length.
Layout.fillWidth: true
// Reserve the widest the read-out can get (+ buffer) so the cell never resizes mid-drag.
Layout.minimumWidth: Math.max(valueMetricsFrom.advanceWidth, valueMetricsTo.advanceWidth) + Kirigami.Units.smallSpacing
Layout.preferredWidth: Layout.minimumWidth
TextMetrics {
id: valueMetricsFrom
font: valueLabel.font
text: root.format(slider.from)
}
TextMetrics {
id: valueMetricsTo
font: valueLabel.font
text: root.format(slider.to)
}
}
}
@@ -0,0 +1,62 @@
/*
* Plasma Gnome Pager — coordinator.js
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Cross-instance coordination for dynamic workspaces. plasmashell runs every panel in ONE QML engine and a
* `.pragma library` is one instance per engine, so the module state below is SHARED across all pagers (the
* only pure-QML way). Provides SETTING SYNC + SINGLE-WRITER election (lowest token writes).
*/
.pragma library
.import "logic.js" as Logic
var _present = {}; // token -> true: instances currently joined (the election candidates)
var _subs = {}; // token -> onSync(enabled, prefix): how to push the global value to each instance
var _enabled = false; // GLOBAL dynamic-workspaces enabled, synced across all panels
var _prefix = ""; // GLOBAL auto-created-desktop name prefix, synced across all panels
var _haveGlobal = false; // has any instance established the global yet?
var _seq = 0; // hands out unique, monotonically increasing tokens
// Register this instance. `onSync(enabled, prefix)` is how publish() pushes the global value here. Returns
// the unique token (store it; pass it to leave()/isWriter()). Never 0 (the caller's "not joined" sentinel).
function join(onSync) {
_seq += 1;
_present[_seq] = true;
_subs[_seq] = onSync;
return _seq;
}
// Deregister on destruction so a removed panel stops counting toward the election and is not notified.
function leave(token) {
delete _present[token];
delete _subs[token];
}
function haveGlobal() { return _haveGlobal; }
function globalEnabled() { return _enabled; }
function globalPrefix() { return _prefix; }
// Set the single global setting and push it to EVERY instance. Called by the panel the user toggled, and
// once at startup by the first instance to seed the global.
function publish(enabled, prefix) {
_enabled = !!enabled;
_prefix = prefix;
_haveGlobal = true;
for (var t in _subs) {
try {
_subs[t](_enabled, _prefix);
} catch (_e) {
/* an instance torn down mid-iteration: ignore */
}
}
}
// Is THIS instance the single writer — the lowest-token present instance, and only when globally enabled?
// Feeding {token: _enabled} to the pure election yields the lowest present token when on, or -1 when off.
function isWriter(token) {
var reg = {};
for (var t in _present)
reg[t] = _enabled;
return Logic.electDynamicWriter(reg) === Number(token);
}
@@ -0,0 +1,556 @@
/*
* Plasma Gnome Pager — logic.js
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Pure, dependency-free branching logic (no Plasma/Qt deps), headless-tested by tst_logic.qml.
* `.pragma library`: one stateless instance, no QML ids/context.
*/
.pragma library
// QML-side config fallback defaults (the `?? Logic.DEFAULTS.<key>` guard), mirroring main.xml.
// dotSize/pillSize/animationDuration 0 = "auto" sentinel; wheelNotchDelta has no schema entry.
var DEFAULTS = Object.freeze({
// Behaviour
enableScroll: true,
scrollWrap: false,
invertScroll: false, // wheel up → next desktop instead of previous
showTooltips: true,
showWindowList: true,
enableAddRemove: true,
enableRename: true,
dynamicWorkspaces: false, // GNOME-style: auto-keep one empty trailing desktop
dynamicNamePrefix: "", // base name for auto-created desktops ("" = i18n default "Desktop")
pillClickAction: 0, // what clicking the CURRENT desktop's pill does; see PILL_CLICK_ACTION (0 = None)
animationDuration: 0, // ms; 0 = follow the theme
// Appearance
dotStyle: 0, // overall look; see DOT_STYLE (0 = Sliding pill, mirrors main.xml)
singleLine: false, // ignore KWin's grid rows: lay every desktop out in ONE strip along the panel
matchDesktopGrid: false, // vertical panel: render the grid in KWin orientation instead of transposing
dotSize: 0, // px; 0 = auto (HiDPI themed)
pillSize: 0, // px pill thickness; 0 = auto (match dots)
spacingFactor: 0.5,
pillWidthFactor: 3.5, // pill length / pill thickness (aspect ratio)
inactiveOpacity: 0.45,
hoverOpacity: 0.8,
showOccupancy: false, // mark the dots of desktops that hold windows
occupiedOpacity: 0.7, // opacity of the occupied marker (all styles); empty < occupied < hover < active
occupancyStyle: 0, // HOW an occupied dot is marked; see OCCUPANCY (0 = Filled, mirrors main.xml)
followThemeColors: true,
activeColor: "#3daee9", // used only when followThemeColors is false
inactiveColor: "#eff0f1", // used only when followThemeColors is false
occupiedColor: "#3daee9", // occupied-marker colour; used only when followThemeColors is false (else theme accent)
wheelNotchDelta: 120 // angleDelta units per mouse notch (no schema entry)
});
// Occupied-dot indicator styles (showOccupancy on). The int values MIRROR the main.xml occupancyStyle
// choices and the ConfigAppearance combo order, so a stored index always maps to the same style. Every
// style marks the OCCUPIED dot using the occupied colour + occupiedOpacity; they differ only in shape:
// Filled — the whole occupied dot is filled with the occupied colour.
// InnerDot — a small occupied-colour dot drawn on top of an otherwise-dim dot.
// Ring — a hollow occupied-colour ring drawn on top of an otherwise-dim dot.
// InnerDot and Ring keep the normal dim dot as their background and add an overlay marker; only Filled
// recolours/brightens the dot body itself.
var OCCUPANCY = Object.freeze({ Filled: 0, InnerDot: 1, Ring: 2 });
// Overall pager look (the top-level style selector — a DIFFERENT axis from OCCUPANCY above). The int
// values MIRROR the main.xml dotStyle choices and the ConfigAppearance combo order, so a stored index
// always maps to the same style.
// Pill — GNOME REFLOW: dim filled dots, the current desktop morphs into a wider highlighted pill.
// Ring — "Filled & ring": no pill, every dot the same size; the current desktop is a solid filled
// circle and non-current desktops are hollow rings (transparent body + border). Occupancy still
// composes via Filled/InnerDot (Ring occupancy is suppressed — see ringOverlayVisible).
var DOT_STYLE = Object.freeze({ Pill: 0, Ring: 1 });
// Is the "Filled & ring" pager look active? The one predicate the dot-style branching keys off — used by
// the ring helpers below and by the QML tier — so the DOT_STYLE.Ring comparison lives in exactly one place.
function isRingStyle(dotStyle) {
return dotStyle === DOT_STYLE.Ring;
}
// Action taken when the ALREADY-CURRENT desktop's pill is clicked (default None). Int values MIRROR the
// main.xml pillClickAction choices and the ConfigGeneral combo order, so a stored index always maps to the
// same action. Each non-None action TOGGLES a KWin global shortcut (see pillClickSpec); clicking an
// inactive dot still just switches desktops.
var PILL_CLICK_ACTION = Object.freeze({ None: 0, ShowDesktop: 1, Overview: 2, Grid: 3 });
// Coerce to string, mapping null/undefined to "". Shared by the sanitize* functions.
function toStringOrEmpty(value) {
return (value === undefined || value === null) ? "" : String(value);
}
// Step the active index by delta → new index in [0, count-1], or -1 to ignore (empty/transient). wrap clamps/wraps.
function stepIndex(currentIndex, count, delta, wrap) {
if (count <= 0)
return -1;
if (currentIndex < 0 || currentIndex >= count)
return -1;
var i = currentIndex + delta;
if (wrap)
return ((i % count) + count) % count; // true modulo (handles negatives)
if (i < 0)
return 0;
if (i > count - 1)
return count - 1;
return i;
}
// Never remove the last desktop — there must always be at least one.
function canRemoveDesktop(count) {
return count > 1;
}
// UUID of the last desktop, or "" when the list is null/empty (guards transient state).
function lastDesktopId(ids) {
if (!ids || ids.length === 0)
return "";
return ids[ids.length - 1];
}
// Current desktop for one screen (Plasma 6.7 per-output): prefer the per-screen value, else global —
// degrades when the screen is unknown, the feature is off, or Plasma is older.
function resolveCurrentDesktop(perScreen, global) {
if (perScreen !== undefined && perScreen !== null && perScreen !== "")
return String(perScreen);
return global ? String(global) : "";
}
// Accumulate hi-res/touchpad wheel deltas and emit whole notches as integer steps. Returns { steps,
// remainder } — feed `remainder` back as `accumulated` next event so sub-notch motion is not lost.
function accumulateWheel(accumulated, deltaY, threshold) {
var t = (threshold > 0) ? threshold : DEFAULTS.wheelNotchDelta;
var total = accumulated + deltaY;
var steps = (total / t) | 0; // truncate toward zero
return { steps: steps, remainder: total - steps * t };
}
// Opacity of the DOT body (brightest first): active capsule full (1.0); hover brightens to hoverOpacity;
// a Filled-style occupied dot (whose body IS the marker) brightens to occupiedOpacity; else inactiveOpacity.
// InnerDot and Ring keep a dim body — their markers are OVERLAYS that carry occupiedOpacity themselves.
// `occupied` is always false when showOccupancy is off, so the empty look is unchanged.
function dotOpacity(active, hovered, occupied, style, inactiveOpacity, hoverOpacity, occupiedOpacity) {
if (active)
return 1.0;
if (hovered)
return hoverOpacity;
if (occupied && style === OCCUPANCY.Filled)
return occupiedOpacity;
return inactiveOpacity;
}
// Which colour fills the dot BODY, from three pre-resolved colours (the caller resolves theme-vs-custom):
// the active capsule → activeColor; a Filled-style occupied dot → occupiedColor; otherwise inactiveColor
// (an empty dot, or the dim body under the InnerDot/Ring styles, whose markers are drawn as overlays on top).
function dotColor(active, occupied, style, activeColor, inactiveColor, occupiedColor) {
if (active)
return activeColor;
if (occupied && style === OCCUPANCY.Filled)
return occupiedColor;
return inactiveColor;
}
// Ring outline/border thickness for a given dot diameter (px, min 1). Shared by the "Filled & ring" body
// outline and the Ring-occupancy overlay rim — one geometry rule, the `0.18` factor in a single place.
function ringThickness(dotSize) {
return Math.max(1, Math.round(dotSize * 0.18));
}
// Inner-dot occupancy marker diameter for a given dot diameter (the InnerDot style centre dot) — a
// fixed fraction of the dot, kept here so the geometry constant lives in one place (cf. ringThickness).
function innerDotDiameter(dotSize) {
return dotSize * 0.45;
}
// "Filled & ring" dot-style (DOT_STYLE.Ring): does THIS dot draw the ring OUTLINE (border)? Every
// non-current dot does, regardless of occupancy — so a Filled-occupied dot is a filled disc WITH the
// ring still around it ("ring and dot background"). Always false in the Pill style and for the current
// (filled-circle) dot.
function dotHasRing(dotStyle, active) {
return isRingStyle(dotStyle) && !active;
}
// "Filled & ring" dot-style: is the dot's INTERIOR hollow (transparent fill)? True for a non-current ring
// dot UNLESS the Filled occupancy marker is filling its interior (occupied + Filled). Decoupled from
// dotHasRing so an occupied+Filled dot keeps its ring outline but gets a filled background. Always false
// in the Pill style, so the default look is unchanged.
function dotBodyIsHollow(dotStyle, active, occupied, occupancyStyle) {
if (!isRingStyle(dotStyle))
return false;
if (active)
return false; // current desktop: filled circle
if (occupied && occupancyStyle === OCCUPANCY.Filled)
return false; // Filled occupancy fills the ring interior
return true;
}
// "Filled & ring" dot-style: is the dot's INTERIOR filled rather than hollow? The third body state — a ring
// OUTLINE plus a filled background (occupied + Filled occupancy). Composed from dotHasRing/dotBodyIsHollow
// so all three ring body predicates live (and are tested) in one place. Always false in the Pill style.
function dotBodyFilled(dotStyle, active, occupied, occupancyStyle) {
return dotHasRing(dotStyle, active) && !dotBodyIsHollow(dotStyle, active, occupied, occupancyStyle);
}
// Ring style: an OCCUPIED inactive dot shows a hollow occupied-colour ring OVERLAY on top of the dim dot
// (empty/active do not). Suppressed in the DOT_STYLE.Ring look, where the dot body is ALREADY a ring
// (a ring-on-a-ring would be redundant), so Ring occupancy has no visible effect in that style.
function ringOverlayVisible(active, occupied, style, dotStyle) {
return style === OCCUPANCY.Ring && !active && occupied && !isRingStyle(dotStyle);
}
// InnerDot style: an OCCUPIED inactive dot shows a small occupied-colour dot OVERLAY in its centre (empty/active do not).
function innerDotVisible(active, occupied, style) {
return style === OCCUPANCY.InnerDot && !active && occupied;
}
// Morph duration: reduce-animations (themeDuration <= 0) wins → 0; else the override, else the themed default.
function effectiveDuration(requested, themeDuration) {
if (themeDuration <= 0)
return 0;
return requested > 0 ? requested : themeDuration;
}
// Desktops per line, mirroring KWin's grid: columns = ceil(count / rows). 0 for empty; missing/<1 rows → 1.
function gridColumns(count, rows) {
if (count <= 0)
return 0;
var r = (rows && rows > 0) ? rows : 1;
return Math.ceil(count / r);
}
// Split `arr` into row-major chunks of at most `size` (the grid lines; last may be shorter). [] for null/empty/size<1.
function chunk(arr, size) {
if (!arr || arr.length === 0 || !size || size < 1)
return [];
var out = [];
for (var i = 0; i < arr.length; i += size)
out.push(arr.slice(i, i + size));
return out;
}
// Shallow element-wise equality for arrays of primitives — the aggregator's compare-before-assign
// guard (a QML var property notifies on every reassignment, even to an equal fresh array).
function arraysShallowEqual(a, b) {
if (a === b)
return true;
if (!a || !b || a.length !== b.length)
return false;
for (var i = 0; i < a.length; i++)
if (a[i] !== b[i])
return false;
return true;
}
// Total extent of one reflow line: `count` slots with uniform `gap`, exactly ONE active capsule
// (`activeExtent`), the rest dots. `dotSize` for count <= 0. Cross axis passes activeExtent == dotSize.
function lineExtent(count, dotSize, gap, activeExtent) {
if (count <= 0)
return dotSize;
return activeExtent + (count - 1) * (dotSize + gap);
}
// Dot size that makes ONE full line exactly fill `available` — the inverse of lineExtent. +Infinity
// when there's nothing to fit (so the caller's min(natural, fit) keeps natural). Caller clamps.
function fitDotSize(available, perLine, pillWidthFactor, spacingFactor) {
if (available <= 0 || perLine <= 0)
return Number.POSITIVE_INFINITY;
var denom = pillWidthFactor + (perLine - 1) * (1 + spacingFactor);
if (denom <= 0)
return Number.POSITIVE_INFINITY;
return available / denom;
}
// Title count before "…and N other windows": 4, but all 5 when exactly 5 (stock KDE pager rule).
function windowListMaximum(count) {
return count === 5 ? 5 : 4;
}
// HTML-escape a window title for the rich-text tooltip: markup chars + no-break space, NOT the ordinary space (must wrap).
function sanitizeHtml(input) {
var table = {
">": "&gt;",
"<": "&lt;",
"&": "&amp;",
"'": "&apos;",
"\"": "&quot;",
"\u00a0": "&nbsp;"
};
return toStringOrEmpty(input).replace(/[<>&'"\u00a0]/g, function (c) {
return table[c];
});
}
// Cap (chars) on a user-entered desktop name, so an absurd name stays sane in the tooltip/markup.
var MAX_DESKTOP_NAME_LENGTH = 100;
// Normalise a user-entered name before the setDesktopName write: trim, empty/whitespace → "" (no-op sentinel), cap length.
function sanitizeDesktopName(input) {
var s = toStringOrEmpty(input).trim();
if (s.length === 0)
return "";
return s.length > MAX_DESKTOP_NAME_LENGTH ? s.slice(0, MAX_DESKTOP_NAME_LENGTH) : s;
}
// Does `window`'s own `desktops` list name `uuid`? The membership primitive shared by the tooltip and
// occupancy predicates below (each adds its own on-all/skipPager handling). Missing list → false.
function windowListsDesktop(window, uuid) {
return !!(window.desktops && window.desktops.indexOf(uuid) !== -1);
}
// Tooltip membership: a real window that is on-all or whose `desktops` lists uuid. Null/missing → false.
function windowIsOnDesktop(window, uuid) {
if (!window || !window.isWindow)
return false;
return !!(window.onAll || windowListsDesktop(window, uuid));
}
// Group a flat window snapshot into per-desktop { visible:[title…], minimized:[title…] }, index-aligned
// with `desktopIds`. Titles stay RAW (i18n + HTML happen in main.qml). Null windows → empty; null ids → [].
function groupWindowsByDesktop(windows, desktopIds) {
if (!desktopIds || desktopIds.length === 0)
return [];
var wins = windows || [];
var out = [];
for (var d = 0; d < desktopIds.length; d++) {
var uuid = desktopIds[d];
var visible = [];
var minimized = [];
for (var i = 0; i < wins.length; i++) {
var w = wins[i];
if (!windowIsOnDesktop(w, uuid))
continue;
if (w.minimized)
minimized.push(w.title);
else
visible.push(w.title);
}
out.push({ visible: visible, minimized: minimized });
}
return out;
}
// Dynamic workspaces (GNOME-style, default OFF): the PURE decision layer keeping one empty trailing
// desktop — main.qml dispatches the single add/remove these return.
// Does `window` make a desktop NON-EMPTY for dynamic workspaces? Real window only; UNLIKE
// windowIsOnDesktop, on-all/skipPager do NOT count (would pin every desktop); minimized DO count.
function windowOccupiesDesktop(window, uuid) {
if (!window || !window.isWindow)
return false;
if (window.onAll || window.skipPager)
return false;
return windowListsDesktop(window, uuid);
}
// Reduce a window snapshot to a per-desktop occupancy boolean[], index-aligned with `desktopIds`:
// each entry is true when ANY window satisfies the `occupies(window, uuid)` predicate. Null windows →
// all-false; null/empty ids → []. The shared scaffold for the global and per-screen reducers below.
function foldDesktopOccupancy(windows, desktopIds, occupies) {
if (!desktopIds || desktopIds.length === 0)
return [];
var wins = windows || [];
var out = [];
for (var d = 0; d < desktopIds.length; d++) {
var uuid = desktopIds[d];
var occupied = false;
for (var i = 0; i < wins.length; i++) {
if (occupies(wins[i], uuid)) {
occupied = true;
break;
}
}
out.push(occupied);
}
return out;
}
// Global (screen-agnostic) per-desktop occupancy boolean[], index-aligned with `desktopIds`.
function computeDesktopOccupancy(windows, desktopIds) {
return foldDesktopOccupancy(windows, desktopIds, windowOccupiesDesktop);
}
// A usable screen rect: present with a positive size. A null/zero rect means "don't know" → callers
// fall back to GLOBAL (screen-agnostic) occupancy rather than hiding windows (robustness.md).
function isValidScreenRect(r) {
return !!r && r.width > 0 && r.height > 0;
}
// Per-screen occupancy (Plasma 6.7 "switch desktops independently per screen"): a window only marks a
// desktop occupied on the pager whose monitor it is physically on. Extends windowOccupiesDesktop with a
// screen-ORIGIN match (each output has a unique top-left; width/height can differ between the window's
// reported screen rect and the pager's under per-output scaling, so compare (x,y) only — integers, exact).
// NEVER drops a window: an unknown target rect (pager not placed) OR an unknown own screen (e.g. a window
// with no geometry) counts everywhere, degrading to the global behaviour.
function windowOccupiesDesktopOnScreen(window, uuid, screenRect) {
if (!windowOccupiesDesktop(window, uuid))
return false;
if (!isValidScreenRect(screenRect))
return true;
var ws = window.screen;
if (!isValidScreenRect(ws))
return true;
return ws.x === screenRect.x && ws.y === screenRect.y;
}
// Per-desktop occupancy boolean[] for ONE pager's screen, index-aligned with `desktopIds`. An unknown
// `screenRect` delegates to computeDesktopOccupancy → the byte-identical GLOBAL array, so single-monitor
// setups and pre-placement frames behave exactly as before (no per-screen difference).
function computeDesktopOccupancyForScreen(windows, desktopIds, screenRect) {
if (!isValidScreenRect(screenRect))
return computeDesktopOccupancy(windows, desktopIds);
return foldDesktopOccupancy(windows, desktopIds, function (w, uuid) {
return windowOccupiesDesktopOnScreen(w, uuid, screenRect);
});
}
// The SINGLE dynamic-workspace action, or null (one per call → re-triggering converges to one trailing
// empty): 0 trailing empties → add; >=2 → remove the LAST; else null. Only the trailing run is managed.
// Transient frames no-op (null/empty arrays, or occupancy.length !== desktopIds.length).
function dynamicWorkspacePlan(occupancy, desktopIds) {
if (!occupancy || !desktopIds)
return null;
var n = desktopIds.length;
if (n === 0 || occupancy.length !== n)
return null;
var trailing = 0;
for (var i = n - 1; i >= 0 && !occupancy[i]; i--)
trailing++;
if (trailing === 0)
return { kind: "add" };
if (trailing >= 2 && canRemoveDesktop(n))
return { kind: "remove", uuid: desktopIds[n - 1] };
return null;
}
// Name for an auto-created desktop: "<base> <number>". NEVER empty — KWin silently drops createDesktop on an empty name.
function formatDynamicDesktopName(prefix, number, fallback) {
var base = sanitizeDesktopName(prefix);
if (base === "")
base = sanitizeDesktopName(fallback);
if (base === "")
base = "Desktop";
return base + " " + number;
}
// Elect the single dynamic-workspace "writer" among the pager instances: the ENABLED instance with the
// smallest coordinator token (-1 when none enabled). Without it two pagers double-create on a fill → flash.
function electDynamicWriter(registry) {
if (!registry)
return -1;
var winner = -1;
for (var token in registry) {
if (!registry[token])
continue;
var t = Number(token);
if (winner === -1 || t < winner)
winner = t;
}
return winner;
}
// Should a TasksModel dataChanged(…, roles) trigger a rebuild? Only when a relevant role changed —
// skips the high-frequency IsActive focus churn. Empty/absent `changedRoles` is Qt's "all changed" → yes.
function dataChangeAffectsRoles(changedRoles, relevantRoles) {
if (!changedRoles || changedRoles.length === 0)
return true;
for (var i = 0; i < changedRoles.length; i++)
if (relevantRoles.indexOf(changedRoles[i]) !== -1)
return true;
return false;
}
/*
* KWin DBus call SHAPES. Each builder returns { service, path, iface, member, args } (or null on a
* robustness guard); main.qml maps each arg { t, v } to a DBus.* constructor. The exact strings/types
* matter — a wrong one fails SILENTLY (KWin drops the call), so these are unit-tested.
*/
var KWIN_SERVICE = "org.kde.KWin";
var KWIN_VDM_PATH = "/VirtualDesktopManager";
var KWIN_VDM_IFACE = "org.kde.KWin.VirtualDesktopManager";
var DBUS_PROPERTIES_IFACE = "org.freedesktop.DBus.Properties";
// kglobalaccel's public Component interface: invokeShortcut(uniqueName) TOGGLES a KWin global shortcut.
// Used by the pill-click action — public/stable and avoids the version-suffixed effect DBus paths (e.g.
// /org/kde/KWin/Effect/Overview/<ver>) that break across KWin upgrades. Same session bus as KWin.
var KGLOBALACCEL_SERVICE = "org.kde.kglobalaccel";
var KGLOBALACCEL_KWIN_PATH = "/component/kwin";
var KGLOBALACCEL_COMPONENT_IFACE = "org.kde.kglobalaccel.Component";
// Shared envelope for the createDesktop/removeDesktop/setDesktopName writes (all on KWIN_VDM_IFACE;
// switchSpec differs). Key order is load-bearing — tst_logic compares specs via JSON.stringify.
function vdmCall(member, args) {
return {
service: KWIN_SERVICE,
path: KWIN_VDM_PATH,
iface: KWIN_VDM_IFACE,
member: member,
args: args
};
}
// Switch the (global) current desktop to `uuid` via the VirtualDesktopManager "current" property (null
// for a falsy uuid). The variant arg wraps a PLAIN string — a wrapped DBus.string is silently rejected.
function switchSpec(uuid) {
if (!uuid)
return null;
return {
service: KWIN_SERVICE,
path: KWIN_VDM_PATH,
iface: DBUS_PROPERTIES_IFACE,
member: "Set",
args: [{ t: "s", v: KWIN_VDM_IFACE }, { t: "s", v: "current" }, { t: "v", v: uuid }]
};
}
// Append a new desktop at `position` (createDesktop(uint32, string)). `position|0` coerces a transient undefined/NaN to 0.
function addSpec(position, name) {
return vdmCall("createDesktop", [{ t: "u", v: position | 0 }, { t: "s", v: String(name) }]);
}
// Remove the desktop `uuid` (removeDesktop(string)). null for a falsy uuid OR count <= 1 (never-remove-last).
function removeSpec(uuid, count) {
if (!uuid || !canRemoveDesktop(count))
return null;
return vdmCall("removeDesktop", [{ t: "s", v: uuid }]);
}
// Rename `uuid` to `name` (setDesktopName(string, string)) via sanitizeDesktopName; null for falsy uuid / empty name.
function renameSpec(uuid, name) {
var clean = sanitizeDesktopName(name);
if (!uuid || !clean)
return null;
return vdmCall("setDesktopName", [{ t: "s", v: uuid }, { t: "s", v: clean }]);
}
// Invoke (toggle) a KWin global shortcut by its unique name (invokeShortcut(string)); null for a falsy
// name. Key order is load-bearing — tst_logic compares specs via JSON.stringify.
function invokeShortcutSpec(name) {
if (!name)
return null;
return {
service: KGLOBALACCEL_SERVICE,
path: KGLOBALACCEL_KWIN_PATH,
iface: KGLOBALACCEL_COMPONENT_IFACE,
member: "invokeShortcut",
args: [{ t: "s", v: name }]
};
}
// Map a pill-click action (PILL_CLICK_ACTION) to its KWin shortcut spec, or null for None / any unknown
// value (a safe no-op). The shortcut UNIQUE NAMES are DBus identifiers (verified live) — NEVER i18n-wrapped,
// which is why they live here in the i18n-free logic tier. KWin's name for the "Grid" option is "Grid View".
function pillClickSpec(action) {
switch (action) {
case PILL_CLICK_ACTION.ShowDesktop:
return invokeShortcutSpec("Show Desktop");
case PILL_CLICK_ACTION.Overview:
return invokeShortcutSpec("Overview");
case PILL_CLICK_ACTION.Grid:
return invokeShortcutSpec("Grid View");
default:
return null;
}
}
@@ -0,0 +1,300 @@
/*
* Plasma Gnome Pager — main.qml
*
* SPDX-FileCopyrightText: 2026 Kenan Salar
* SPDX-License-Identifier: GPL-3.0-or-later
*
* Root PlasmoidItem: owns the virtual-desktop data source (read) and the KWin DBus helpers (write),
* and renders the dot strip inline in the panel. This is the e2e boundary (not headless-testable).
*/
pragma ComponentBehavior: Bound
import QtQuick
import org.kde.plasma.plasmoid
// Public, stable imports only — never org.kde.plasma.private.* (robustness.md).
import org.kde.plasma.core as PlasmaCore // PlasmaCore.Action + PlasmaCore.Types
import org.kde.taskmanager as TaskManager // VirtualDesktopInfo + TasksModel/ActivityInfo (read)
import org.kde.plasma.workspace.dbus as DBus // KWin DBus (switch/add/remove/rename)
import org.kde.kcmutils as KCM // KCMLauncher — open the system Virtual Desktops settings module
import "logic.js" as Logic
PlasmoidItem {
id: root
Plasmoid.icon: "virtual-desktops" // match metadata.json's Icon (theme-safe Breeze name)
// Passive always-on widget, no background of its own (dots float on the panel — the GNOME look).
Plasmoid.status: PlasmaCore.Types.PassiveStatus
Plasmoid.backgroundHints: PlasmaCore.Types.NoBackground
// Panel orientation, passed DOWN as a plain bool so the sub-components stay Plasmoid-free. Planar/Floating → horizontal.
readonly property bool isVertical: Plasmoid.formFactor === PlasmaCore.Types.Vertical
// Behaviour settings, read live from main.xml. Each `?? Logic.DEFAULTS` guards the transient-undefined frame (undefined → false).
readonly property bool enableScroll: Plasmoid.configuration.enableScroll ?? Logic.DEFAULTS.enableScroll
readonly property bool scrollWrap: Plasmoid.configuration.scrollWrap ?? Logic.DEFAULTS.scrollWrap
readonly property bool invertScroll: Plasmoid.configuration.invertScroll ?? Logic.DEFAULTS.invertScroll
// Action when the current desktop's pill is clicked (default None); see Logic.PILL_CLICK_ACTION.
readonly property int pillClickAction: Plasmoid.configuration.pillClickAction ?? Logic.DEFAULTS.pillClickAction
readonly property bool showTooltips: Plasmoid.configuration.showTooltips ?? Logic.DEFAULTS.showTooltips
readonly property bool showWindowList: Plasmoid.configuration.showWindowList ?? Logic.DEFAULTS.showWindowList
readonly property bool enableAddRemove: Plasmoid.configuration.enableAddRemove ?? Logic.DEFAULTS.enableAddRemove
readonly property bool enableRename: Plasmoid.configuration.enableRename ?? Logic.DEFAULTS.enableRename
// Dynamic workspaces (default OFF): auto-keep one empty trailing desktop; dynamicNamePrefix is the created-desktop base name ("" = "Desktop").
readonly property bool dynamicWorkspaces: Plasmoid.configuration.dynamicWorkspaces ?? Logic.DEFAULTS.dynamicWorkspaces
readonly property string dynamicNamePrefix: Plasmoid.configuration.dynamicNamePrefix ?? Logic.DEFAULTS.dynamicNamePrefix
// Manual Add/Remove only when enabled AND dynamic workspaces off — the two conflict. Reused by the contextualActions below.
readonly property bool canAddRemove: enableAddRemove && !dynamicWorkspaces
// Appearance/animation settings, read the same way. dotSize/pillSize/animationDuration use a 0 = auto sentinel resolved in the indicator/dot.
readonly property int animationDuration: Plasmoid.configuration.animationDuration ?? Logic.DEFAULTS.animationDuration
// Overall pager look (Sliding pill / Filled & ring — see Logic.DOT_STYLE); the indicator neutralizes the pill in ring mode.
readonly property int dotStyle: Plasmoid.configuration.dotStyle ?? Logic.DEFAULTS.dotStyle
// Ignore KWin's grid rows: lay every desktop out in one strip along the panel (a vertical strip on a vertical panel).
readonly property bool singleLine: Plasmoid.configuration.singleLine ?? Logic.DEFAULTS.singleLine
// Vertical panels: lay the grid out in KWin orientation (rows top-to-bottom) instead of transposing it down the panel.
readonly property bool matchDesktopGrid: Plasmoid.configuration.matchDesktopGrid ?? Logic.DEFAULTS.matchDesktopGrid
readonly property int dotSize: Plasmoid.configuration.dotSize ?? Logic.DEFAULTS.dotSize
readonly property int pillSize: Plasmoid.configuration.pillSize ?? Logic.DEFAULTS.pillSize
readonly property real spacingFactor: Plasmoid.configuration.spacingFactor ?? Logic.DEFAULTS.spacingFactor
readonly property real pillWidthFactor: Plasmoid.configuration.pillWidthFactor ?? Logic.DEFAULTS.pillWidthFactor
readonly property real inactiveOpacity: Plasmoid.configuration.inactiveOpacity ?? Logic.DEFAULTS.inactiveOpacity
readonly property real hoverOpacity: Plasmoid.configuration.hoverOpacity ?? Logic.DEFAULTS.hoverOpacity
// Occupied-dot indicator (default OFF): mark desktops that hold windows (reuses the occupancy snapshot below).
// occupancyStyle picks HOW (Filled/InnerDot/Ring — see Logic.OCCUPANCY); occupiedOpacity applies to every style.
readonly property bool showOccupancy: Plasmoid.configuration.showOccupancy ?? Logic.DEFAULTS.showOccupancy
readonly property real occupiedOpacity: Plasmoid.configuration.occupiedOpacity ?? Logic.DEFAULTS.occupiedOpacity
readonly property int occupancyStyle: Plasmoid.configuration.occupancyStyle ?? Logic.DEFAULTS.occupancyStyle
readonly property bool followThemeColors: Plasmoid.configuration.followThemeColors ?? Logic.DEFAULTS.followThemeColors
readonly property color activeColor: Plasmoid.configuration.activeColor ?? Logic.DEFAULTS.activeColor
readonly property color inactiveColor: Plasmoid.configuration.inactiveColor ?? Logic.DEFAULTS.inactiveColor
readonly property color occupiedColor: Plasmoid.configuration.occupiedColor ?? Logic.DEFAULTS.occupiedColor
// A pager renders inline. Plasma instantiates NO representation unless a fullRepresentation exists, so
// the dot strip IS the full representation, forced inline via preferredRepresentation.
preferredRepresentation: fullRepresentation
fullRepresentation: WorkspaceIndicator {
vertical: root.isVertical
virtualDesktopInfo: vdi
enableScroll: root.enableScroll
scrollWrap: root.scrollWrap
invertScroll: root.invertScroll
showTooltips: root.showTooltips
desktopTooltips: root.desktopTooltips
dotStyle: root.dotStyle
singleLine: root.singleLine
matchDesktopGrid: root.matchDesktopGrid
// dotSize/pillSize passed as raw 0=auto requests; resolved in the indicator (pillSize 0 = match dots).
dotSizeRequest: root.dotSize
pillSizeRequest: root.pillSize
spacingFactor: root.spacingFactor
pillWidthFactor: root.pillWidthFactor
inactiveOpacity: root.inactiveOpacity
hoverOpacity: root.hoverOpacity
showOccupancy: root.showOccupancy
desktopOccupancy: root.screenOccupancy // PER-SCREEN: only mark dots for windows on THIS pager's monitor
occupiedOpacity: root.occupiedOpacity
occupancyStyle: root.occupancyStyle
followThemeColors: root.followThemeColors
activeColor: root.activeColor
inactiveColor: root.inactiveColor
occupiedColor: root.occupiedColor
animationDuration: root.animationDuration
onSwitchRequested: uuid => root.switchTo(uuid)
// Clicking the current desktop's pill: dispatch the configured action (pillClickSpec is null for None → no-op).
onActiveClicked: root.dispatch(Logic.pillClickSpec(root.pillClickAction))
}
// Reactive read-only desktop state — bind, never cache; updates on ANY change. Writes go through KWin DBus below.
TaskManager.VirtualDesktopInfo {
id: vdi
}
// Per-desktop tooltip subText (rich-text window list), gated by showTooltips && showWindowList INDEPENDENTLY of the Loader.
readonly property var desktopTooltips: (root.showTooltips && root.showWindowList && tooltipLoader.item)
? (tooltipLoader.item as WindowAggregator).desktopTooltips : []
// GLOBAL per-desktop occupancy boolean[] from the snapshot, consumed by the dynamic-workspaces controller (the desktop SET is global). Empty [] when the Loader is inactive.
readonly property var desktopOccupancy: tooltipLoader.item ? (tooltipLoader.item as WindowAggregator).desktopOccupancy : []
// PER-SCREEN per-desktop occupancy (this monitor only) from the SAME snapshot, consumed by the occupied-dot indicator. Empty [] when the Loader is inactive.
readonly property var screenOccupancy: tooltipLoader.item ? (tooltipLoader.item as WindowAggregator).screenOccupancy : []
// This pager's output rect, read from the placed representation (Screen.* is only valid on the on-screen item).
// Empty until placed → per-screen occupancy degrades to global. Cast mirrors `tooltipLoader.item as WindowAggregator`.
readonly property rect screenRect: root.fullRepresentationItem
? (root.fullRepresentationItem as WorkspaceIndicator).screenRect : Qt.rect(0, 0, 0, 0)
// The window-list machinery lives behind a Loader (zero cost when unused). Needed by the tooltip list, dynamic workspaces, OR the occupied-dot indicator — gate is the OR.
Loader {
id: tooltipLoader
active: (root.showTooltips && root.showWindowList) || root.dynamicWorkspaces || root.showOccupancy
sourceComponent: aggregatorComponent
}
Component {
id: aggregatorComponent
WindowAggregator {
virtualDesktopInfo: vdi // inject the read source (the aggregator is data-source-agnostic)
screenRect: root.screenRect // inject this pager's output rect (drives per-screen occupancy)
// Each feature gate is injected as a plain bool so the aggregator computes ONLY the reductions an
// active consumer reads (an off feature's array stays []). windowListActive also trims tooltip-only roles.
windowListActive: root.showTooltips && root.showWindowList
occupancyActive: root.showOccupancy // per-screen occupancy → occupied-dot indicator
dynamicActive: root.dynamicWorkspaces // global occupancy → dynamic-workspaces controller
}
}
// Every desktop write goes through KWin's VirtualDesktopManager. The CALL SHAPES live in logic.js's
// *Spec builders; here we only DISPATCH a built spec (async fire-and-forget). A null spec is a no-op.
function dispatch(spec) {
if (!spec) {
return;
}
// Async fire-and-forget — VirtualDesktopInfo reflects the resulting state, not a return value.
// We capture the reply ONLY to warn on a rejected call (the silent-DBus-drop class this widget avoids).
const reply = DBus.SessionBus.asyncCall({
"service": spec.service,
"path": spec.path,
"iface": spec.iface,
"member": spec.member,
"arguments": spec.args.map(a => root.toDBusArg(a))
});
if (reply) {
reply.finished.connect(() => {
if (reply.isError) {
console.warn("plasma-gnome-pager: DBus call failed:", spec.member, "-", reply.error.name, reply.error.message);
}
});
}
}
// Map ONE spec arg { t, v } to its DBus.* constructor. The "v" case wraps a PLAIN value — a wrapped DBus.string is silently rejected by KWin.
function toDBusArg(a) {
switch (a.t) {
case "s":
return new DBus.string(a.v);
case "u":
return new DBus.uint32(a.v);
case "i":
return new DBus.int32(a.v);
case "v":
return new DBus.variant(a.v);
default:
// Unknown type letter: warn LOUDLY rather than fail silently (the silent-DBus-drop class this widget avoids).
console.warn("plasma-gnome-pager: toDBusArg got unknown DBus type letter", a.t);
return a.v;
}
}
function switchTo(uuid) {
root.dispatch(Logic.switchSpec(uuid));
}
// Append a new desktop at the end. `?? 0` keeps a transient-undefined count out of the uint32 (i18n label stays here).
function addDesktop() {
root.dispatch(Logic.addSpec(vdi.numberOfDesktops ?? 0, i18n("New Desktop")));
}
// Remove a desktop by UUID. removeSpec enforces never-remove-last (returns null).
function removeDesktop(uuid) {
root.dispatch(Logic.removeSpec(uuid, vdi.numberOfDesktops));
}
// "Remove" targets the last desktop (the one addDesktop appended).
function removeLastDesktop() {
root.removeDesktop(Logic.lastDesktopId(vdi.desktopIds));
}
// Dynamic workspaces (GNOME-style): one GLOBAL behaviour keeping an empty trailing desktop. The non-visual controller emits the two signals below.
DynamicWorkspacesController {
id: dynamicController
dynamicEnabled: root.dynamicWorkspaces
namePrefix: root.dynamicNamePrefix
// i18n default base name, passed IN so the controller stays i18n-free (never empty — KWin drops createDesktop on an empty name).
defaultPrefix: i18nc("@info default base name for auto-created virtual desktops", "Desktop")
virtualDesktopInfo: vdi
desktopOccupancy: root.desktopOccupancy
onDispatchRequested: spec => root.dispatch(spec)
onSyncConfigRequested: (nextEnabled, nextPrefix) => {
// Mirror the global setting into this instance's persisted config (value-guarded so sync→onChanged→publish can't loop).
if (Plasmoid.configuration.dynamicWorkspaces !== nextEnabled)
Plasmoid.configuration.dynamicWorkspaces = nextEnabled;
if (Plasmoid.configuration.dynamicNamePrefix !== nextPrefix)
Plasmoid.configuration.dynamicNamePrefix = nextPrefix;
}
}
// Rename a desktop via KWin setDesktopName. renameSpec sanitizes and rejects empty (null → no-op); `vdi` reports the new name.
function renameDesktop(uuid, name) {
root.dispatch(Logic.renameSpec(uuid, name));
}
// Open the rename prompt prefilled with the desktop's current name (resolved from the live vdi arrays, guarded for the transient frame).
function openRenameDialog(uuid) {
if (!uuid) {
return;
}
const ids = vdi.desktopIds ?? [];
const names = vdi.desktopNames ?? [];
renameDialog.openFor(uuid, names[ids.indexOf(uuid)] ?? "");
}
// Open the system "Virtual Desktops" settings module (like the stock pager). NOT a DBus write — an imperative
// GUI launch via the public KCMLauncher, so it lives here, not in logic.js. Module name is platform-branched.
function openVirtualDesktopsKcm() {
KCM.KCMLauncher.openSystemSettings(Qt.platform.pluginName.includes("wayland")
? "kcm_kwin_virtualdesktops"
: "kcm_kwin_virtualdesktops_x11");
}
// Right-click menu. Add/Remove gated by canAddRemove (they conflict with dynamic workspaces); Remove
// also disables at the last desktop. "Configure Virtual Desktops…" is always shown and opens the SYSTEM
// KCM (distinct from "Configure Workspaces…", which Plasma auto-adds for THIS widget's own settings).
Plasmoid.contextualActions: [
PlasmaCore.Action {
text: i18n("Add Desktop")
icon.name: "list-add"
priority: Plasmoid.LowPriorityAction
visible: root.canAddRemove
enabled: root.canAddRemove
onTriggered: root.addDesktop()
},
PlasmaCore.Action {
text: i18n("Remove Last Desktop")
icon.name: "list-remove"
priority: Plasmoid.LowPriorityAction
visible: root.canAddRemove
enabled: root.canAddRemove && Logic.canRemoveDesktop(vdi.numberOfDesktops)
onTriggered: root.removeLastDesktop()
},
PlasmaCore.Action {
text: i18n("Rename Current Desktop…")
icon.name: "edit-rename"
priority: Plasmoid.LowPriorityAction
visible: root.enableRename
enabled: root.enableRename
onTriggered: root.openRenameDialog(vdi.currentDesktop)
},
PlasmaCore.Action {
text: i18n("Configure Virtual Desktops…")
icon.name: "preferences-desktop-virtual" // the icon the Virtual Desktops KCM itself uses
priority: Plasmoid.LowPriorityAction
onTriggered: root.openVirtualDesktopsKcm()
}
]
// Rename prompt — the view lives in RenameDialog.qml; here we only place it and turn accepted() into the KWin write.
RenameDialog {
id: renameDialog
visualParent: root.fullRepresentationItem
location: Plasmoid.location
onAccepted: (uuid, name) => root.renameDesktop(uuid, name)
}
}
@@ -0,0 +1,35 @@
{
"KPackageStructure": "Plasma/Applet",
"X-Plasma-API-Minimum-Version": "6.0",
"X-Plasma-Provides": [
"org.kde.plasma.virtualdesktops"
],
"KPlugin": {
"Id": "com.github.kenansalar.plasma-gnome-pager",
"Name": "Plasma Gnome Pager",
"Description": "A GNOME-style virtual desktop switcher: dots with a pill on the current workspace.",
"Description[de]": "Ein Arbeitsflächen-Umschalter im GNOME-Stil: Punkte mit einer Pille auf der aktuellen Arbeitsfläche.",
"Description[fr]": "Un sélecteur de bureaux virtuels façon GNOME : des points avec une pilule sur l'espace de travail actuel.",
"Description[es]": "Un cambiador de escritorios virtuales al estilo de GNOME: puntos con una píldora en el espacio de trabajo actual.",
"Description[el]": "Εναλλάκτης εικονικών επιφανειών εργασίας σε στυλ GNOME: κουκκίδες με ένα χάπι στον τρέχοντα χώρο εργασίας.",
"Description[it]": "Un selettore di desktop virtuali in stile GNOME: punti con una pillola sullo spazio di lavoro attuale.",
"Description[tr]": "GNOME tarzı bir sanal masaüstü değiştirici: geçerli çalışma alanında bir hap ile noktalar.",
"Description[pt]": "Um comutador de áreas de trabalho virtuais ao estilo do GNOME: pontos com uma pílula no espaço de trabalho atual.",
"Description[pt_BR]": "Um alternador de áreas de trabalho virtuais no estilo do GNOME: pontos com uma pílula no espaço de trabalho atual.",
"Description[ar]": "مبدّل أسطح المكتب الافتراضية بنمط GNOME: نقاط مع كبسولة على مساحة العمل الحالية.",
"Description[zh_CN]": "GNOME 风格的虚拟桌面切换器:用圆点表示桌面,当前工作区显示为胶囊。",
"Description[ru]": "Переключатель виртуальных рабочих столов в стиле GNOME: точки с капсулой на текущем рабочем пространстве.",
"Description[ja]": "GNOME 風の仮想デスクトップ切り替えツール:デスクトップをドットで表示し、現在のワークスペースをカプセルで示します。",
"Category": "Windows and Tasks",
"Icon": "virtual-desktops",
"Version": "1.7.0",
"License": "GPL-3.0-or-later",
"Website": "https://github.com/KenanSalar/plasma-gnome-pager",
"BugReportUrl": "https://github.com/KenanSalar/plasma-gnome-pager/issues",
"Authors": [
{
"Name": "Kenan Salar"
}
]
}
}
@@ -0,0 +1,22 @@
import QtQuick
import org.kde.plasma.configuration
ConfigModel {
ConfigCategory {
name: i18n("General")
icon: "preferences-desktop-plasma"
source: "config/ConfigGeneral.qml"
}
ConfigCategory {
name: i18n("Edit Menu")
icon: "application-menu"
source: "config/ConfigMenuJson.qml"
}
ConfigCategory {
name: i18n("Edit JSON")
icon: "code-context"
source: "config/ConfigEditJson.qml"
}
}
@@ -0,0 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
http://www.kde.org/standards/kcfg/1.0/kcfg.xsd" >
<kcfgfile name=""/>
<group name="General">
<entry name="icon" type="String">
<label>The name of the icon to use for the compact representation (e.g. on a small panel).</label>
<default>start-here-kde-symbolic</default>
</entry>
<entry name="useCustomButtonImage" type="Bool">
<label>Whether to use a custom image instead of an icon in the compact representation (e.g. on a small panel).</label>
<default>false</default>
</entry>
<entry name="customButtonImage" type="Url">
<label>The URL of the custom image to use instead of an icon in the compact representation (e.g. on a small panel).</label>
<default></default>
</entry>
<entry name="showIcons" type="Bool">
<label>Whether to show icons in the menu.</label>
<default>false</default>
</entry>
<entry name="menuWidth" type="Int">
<label>Width of the menu dropdown in pixels. Use 0 for default width.</label>
<default>240</default>
</entry>
<entry name="buttonHeight" type="Int">
<label>Height of each menu item (button) in pixels. Use 0 for default height.</label>
<default>28</default>
</entry>
<entry name="menuJson" type="String">
<label>JSON object defining the menu structure. Each item can have: name, icon, command, submenu (array of items), separator (bool).</label>
<default>[
{
"name": "About This Computer",
"icon": "help-hint",
"command": "kinfocenter"
},
{
"separator": true
},
{
"name": "System Preferences...",
"icon": "settings-configure",
"command": "systemsettings"
},
{
"name": "App Store...",
"icon": "update-none",
"command": "plasma-discover"
},
{
"separator": true
},
{
"name": "Force Quit...",
"icon": "error",
"command": "xkill"
},
{
"separator": true
},
{
"name": "Sleep",
"icon": "system-suspend",
"command": "systemctl suspend"
},
{
"name": "Restart...",
"icon": "system-reboot",
"command": "qdbus org.kde.LogoutPrompt /LogoutPrompt promptReboot"
},
{
"name": "Shut Down...",
"icon": "system-shutdown",
"command": "qdbus org.kde.LogoutPrompt /LogoutPrompt promptShutDown"
},
{
"separator": true
},
{
"name": "Lock Screen",
"icon": "system-lock-screen",
"command": "qdbus org.freedesktop.ScreenSaver /ScreenSaver Lock"
},
{
"name": "Log Out",
"icon": "system-log-out",
"command": "qdbus org.kde.LogoutPrompt /LogoutPrompt promptLogout"
}
]</default>
</entry>
</group>
</kcfg>
@@ -0,0 +1,251 @@
import QtQuick
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.ksvg as KSvg
import org.kde.plasma.components as PlasmaComponents3
/**
* ItemListDelegate - Delegate component that renders each individual menu item
*
* This component is used by ItemListView to display each menu item. It:
*
* 1. Renders the visual representation of menu items (icon, label, arrow for submenus)
* 2. Handles separator rendering with a visible line between menu sections
* 3. Executes commands when menu items are clicked
* 4. Handles keyboard navigation (Enter/Return key presses)
* 5. Manages hover states and visual feedback
* 6. Shows submenu indicators (arrows) for items with children
* 7. Provides accessibility roles and descriptions
*
* Used in ItemListView.qml as the delegate property, which means one instance
* of this component is created for each item in the menu model. Without this
* component, menu items would not be displayed at all.
*/
PlasmaComponents3.ItemDelegate {
id: item
width: ListView.view.width
// ListView uses itemSpacing between items (set by ItemListView)
property int itemSpacing: Kirigami.Units.smallSpacing
// 0 = no space (smallest), 0.1 = tiny, 0.25 = small, 0.5 = medium
readonly property int separatorVerticalMargin: Math.max(0, Math.round(Kirigami.Units.smallSpacing * 0))
// Text items: content height only. Separator: margin + line + margin
height: actualIsSeparator && !showSeparators ? 0 : (actualIsSeparator ? (separatorVerticalMargin * 2 + 2) : (buttonHeight > 0 ? buttonHeight : implicitHeight))
topPadding: 0
bottomPadding: 0
// if it's not disabled and is either a leaf node or a node with children
enabled: !actualIsSeparator && !disabled && (!isParent || (isParent && actualHasChildren))
required property int index
required property bool isSeparator
required property bool hasChildren
required property bool isParent
// Override isSeparator to read from source model if FunnelModel doesn't pass it through
property bool actualIsSeparator: {
// First try the model's isSeparator (works if FunnelModel passes it through)
if (isSeparator) {
return true;
}
// If not, try to get it from the source model directly
const sourceModel = ListView.view ? (ListView.view.model.sourceModel || ListView.view.model) : null;
if (sourceModel && sourceModel.get) {
try {
const modelItem = sourceModel.get(index);
if (modelItem && modelItem.isSeparator) {
return modelItem.isSeparator;
}
} catch (e) {
// Ignore errors
}
}
return isSeparator; // Fallback to the original value
}
// Override hasChildren to read from source model if FunnelModel doesn't pass it through
property bool actualHasChildren: {
// First try the model's hasChildren (works if FunnelModel passes it through)
if (hasChildren) {
return true;
}
// If not, try to get it from the source model directly
const sourceModel = ListView.view ? (ListView.view.model.sourceModel || ListView.view.model) : null;
if (sourceModel && sourceModel.get) {
try {
const modelItem = sourceModel.get(index);
if (modelItem && modelItem.hasChildren) {
return modelItem.hasChildren;
}
} catch (e) {
// Ignore errors
}
}
return hasChildren; // Fallback to the original value
}
required property bool disabled
required property url url
required property string description
required property string decoration
required property var model // for display, which would shadow ItemDelegate
required property bool showIcons
readonly property bool iconAndLabelsShouldlookSelected: pressed && !actualHasChildren
property bool showSeparators: true
/** When > 0, height of this menu item in pixels; set by ItemListView. 0 = use implicit height. */
property int buttonHeight: 0
property bool dialogDefaultRight: Application.layoutDirection !== Qt.RightToLeft
signal interactionConcluded
Accessible.role: actualIsSeparator ? Accessible.Separator : Accessible.ListItem
Accessible.description: isParent
? i18nc("@action:inmenu accessible description for opening submenu", "Open category")
: i18nc("@action:inmenu accessible description for opening app or file", "Launch")
text: model.display
icon.name: decoration
onActualHasChildrenChanged: {
if (!actualHasChildren && ListView.view.currentItem === item) {
ListView.view.currentIndex = -1;
}
}
onClicked: {
if (!item.actualHasChildren) {
// Try to get command from model and execute directly via executable
const model = item.ListView.view ? item.ListView.view.model : null;
if (model) {
// Get sourceModel from FunnelModel if it exists
const sourceModel = model.sourceModel || model;
// Get the item from the sourceModel
const modelItem = sourceModel && sourceModel.get ? sourceModel.get(index) : null;
if (modelItem) {
const cmd = modelItem.command ? String(modelItem.command) : null;
if (cmd) {
// Try to get executable from sourceModel and execute directly
if (sourceModel && sourceModel.executable && typeof sourceModel.executable.exec === 'function') {
sourceModel.executable.exec(cmd);
item.interactionConcluded();
return;
}
// Fallback: try model's executable (FunnelModel)
if (model.executable && typeof model.executable.exec === 'function') {
model.executable.exec(cmd);
item.interactionConcluded();
return;
}
}
}
}
// Fallback to trigger function
if (item.ListView.view && item.ListView.view.model) {
if (typeof item.ListView.view.model.trigger === 'function') {
const result = item.ListView.view.model.trigger(index, "", null);
if (result) {
item.interactionConcluded()
}
} else {
item.interactionConcluded()
}
} else {
item.interactionConcluded()
}
}
}
DragHandler {
target: null
onActiveChanged: {
if (active && item.url) {
// we need dragHelper and can't use attached Drag; submenus are destroyed too soon and Plasma crashes
dragHelper.startDrag(kicker, item.url, item.decoration)
}
}
}
contentItem: RowLayout {
id: row
spacing: Kirigami.Units.smallSpacing * 2
LayoutMirroring.enabled: (Application.layoutDirection === Qt.RightToLeft)
Kirigami.Icon {
id: icon
Layout.alignment: Qt.AlignVCenter
implicitWidth: Kirigami.Units.iconSizes.small
implicitHeight: implicitWidth
visible: item.showIcons & !item.actualIsSeparator
animated: false
selected: item.iconAndLabelsShouldlookSelected
source: item.icon.name
}
PlasmaComponents3.Label {
id: label
enabled: !item.isParent || (item.isParent && item.actualHasChildren)
LayoutMirroring.enabled: (Application.layoutDirection === Qt.RightToLeft)
visible: !item.actualIsSeparator
Layout.fillWidth: true
Layout.alignment: Qt.AlignVCenter
Layout.leftMargin: Kirigami.Units.smallSpacing
verticalAlignment: Text.AlignVCenter
textFormat: Text.PlainText
wrapMode: Text.NoWrap
elide: Text.ElideRight
color: item.iconAndLabelsShouldlookSelected ? Kirigami.Theme.highlightedTextColor : Kirigami.Theme.textColor
text: item.text
}
Kirigami.Icon {
id: arrow
Layout.alignment: Qt.AlignVCenter
implicitWidth: visible ? Kirigami.Units.iconSizes.small : 0
implicitHeight: implicitWidth
visible: item.actualHasChildren && !item.actualIsSeparator
opacity: (item.ListView.view.currentIndex === item.index) ? 1.0 : 0.4
selected: item.iconAndLabelsShouldlookSelected
source: item.dialogDefaultRight
? "go-next-symbolic"
: "go-next-rtl-symbolic"
}
}
// Separator line - outside RowLayout, directly in ItemDelegate
Rectangle {
id: separatorLine
anchors.left: parent.left
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
height: (item.actualIsSeparator && item.showSeparators) ? 1.6 : 0
visible: item.actualIsSeparator && item.showSeparators
color: Qt.rgba(0, 0, 0, 0.10) // 12% opacity black like kMenu
z: 10 // Above contentItem
}
Keys.onReturnPressed: item.clicked()
Keys.onEnterPressed: Keys.returnPressed()
}
@@ -0,0 +1,99 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.plasma.core as PlasmaCore
import org.kde.plasma.private.kicker as Kicker
/**
* ItemListDialog - Component that creates submenus (nested menus) for items with children
*
* This component is used to display nested submenus when a menu item has children.
* It:
*
* 1. Wraps an ItemListView in a Kicker.SubMenu to create a floating submenu dialog
* 2. Handles the model for nested menu items via FunnelModel
* 3. Manages submenu positioning and layout mirroring (RTL support)
* 4. Propagates interaction signals (interactionConcluded) to close the entire menu
* 5. Handles window deactivation to close submenus when clicking outside
* 6. Maintains a reference to the parent ItemListView for signal propagation
*
* Used in ItemListView.qml via the itemListDialogComponent property. When a menu
* item with children is hovered or selected, ItemListView creates an instance of
* this component to display the submenu. Without this component, nested menus
* would not work.
*/
Kicker.SubMenu {
id: itemDialog
property alias model: funnelModel.sourceModel
property Component itemListDialogComponent: null
property int index: -1
property bool aboutToBeDestroyed: false
property ItemListView parentItemListView: null
property alias mainSearchField: itemListView.mainSearchField
signal interactionConcluded
visible: true
location: PlasmaCore.Types.Floating
offset: Kirigami.Units.smallSpacing
LayoutMirroring.enabled: dialogMirrored
onInteractionConcluded: itemDialog.interactionConcluded()
onWindowDeactivated: {
if (!aboutToBeDestroyed) {
interactionConcluded()
}
}
mainItem: ItemListView {
id: itemListView
height: implicitHeight
width: Math.min(Math.max(Layout.minimumWidth, implicitWidth), Layout.maximumWidth)
iconsEnabled: itemDialog.parentItemListView ? itemDialog.parentItemListView.iconsEnabled : false
buttonHeight: itemDialog.parentItemListView ? itemDialog.parentItemListView.buttonHeight : 0
itemSpacing: itemDialog.parentItemListView ? itemDialog.parentItemListView.itemSpacing : Kirigami.Units.smallSpacing
LayoutMirroring.enabled: itemDialog.LayoutMirroring.enabled
dialog: itemDialog
itemListDialogComponent: itemDialog.itemListDialogComponent
model: funnelModel
onInteractionConcluded: itemDialog.interactionConcluded()
Kicker.FunnelModel {
id: funnelModel
property bool sorted: sourceModel?.sorted ?? false
Component.onCompleted: {
// kicker.reset is not available in this context, skip connection
// funnelModel.reset will be called automatically when needed
}
onCountChanged: {
if (sourceModel && count === 0) {
itemDialog.delayedDestroy();
}
}
onSourceModelChanged: {
itemListView.currentIndex = -1;
itemListView.resetDelegateSizing();
}
}
}
function delayedDestroy() {
aboutToBeDestroyed = true;
Qt.callLater(() => itemDialog.destroy());
}
}
@@ -0,0 +1,391 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.plasma.components as PlasmaComponents3
import org.kde.plasma.extras as PlasmaExtras
import org.kde.plasma.private.kicker as Kicker
PlasmaComponents3.ScrollView {
id: itemList
signal exited
signal keyNavigationAtListEnd
signal navigateLeftRequested
signal navigateRightRequested
signal interactionConcluded
function propagateInteractionConcludedToRoot() {
// Find the root ItemListView and call interactionConcluded on it
let root = itemList;
while (root.dialog && root.dialog.parentItemListView) {
root = root.dialog.parentItemListView;
}
root.interactionConcluded();
}
readonly property var actualScrollBarWidth: (itemList.contentHeight > itemList.height ? PlasmaComponents3.ScrollBar.vertical.width : 0)
property Item mainSearchField: null
property Kicker.SubMenu dialog: null
property Kicker.SubMenu childDialog: null
property bool iconsEnabled: false
property Component itemListDialogComponent: null
property alias currentIndex: listView.currentIndex
property alias currentItem: listView.currentItem
property alias keyNavigationWraps: listView.keyNavigationWraps
property alias model: listView.model
property alias count: listView.count
property alias resetOnExitDelay: resetIndexTimer.interval
property alias showSeparators: listView.showSeparators
property alias listView: listView
/** When > 0, fixed width for the menu in pixels; 0 = use default width. */
property int menuWidth: 0
/** When > 0, height of each menu item (button) in pixels; 0 = use default (implicit) height. */
property int buttonHeight: 0
/** Vertical gap between every menu item (and around separators); one value for consistent spacing. */
property int itemSpacing: Kirigami.Units.smallSpacing
implicitWidth: listView.implicitWidth + actualScrollBarWidth
implicitHeight: listView.contentHeight
readonly property int _defaultMinWidth: Kirigami.Units.gridUnit * 14
Layout.minimumWidth: menuWidth > 0 ? menuWidth : _defaultMinWidth
Layout.maximumWidth: menuWidth > 0 ? menuWidth : Math.round(_defaultMinWidth * 1.5)
Layout.maximumHeight: contentHeight
PlasmaComponents3.ScrollBar.horizontal.policy: PlasmaComponents3.ScrollBar.AlwaysOff
function resetDelegateSizing() { // only needed when submenus are reused, called from ItemListDialog
listView.maxDelegateImplicitWidth = 0
}
function subMenuForCurrentItem(focusOnSpawn=false) {
// Menu is always expanded when shown, so we don't need to check kicker.expanded
if (!itemList.model || listView.currentIndex === -1) {
return;
}
const currentItem = listView.currentItem as ItemListDelegate;
if (!currentItem) {
return;
}
if (!currentItem.actualHasChildren) {
clearChildDialog();
return;
}
if (!itemList.childDialog) {
// Get the source model from FunnelModel if it exists, otherwise use model directly
const sourceModel = (model && model.sourceModel) ? model.sourceModel : model;
if (!sourceModel) {
return;
}
if (!sourceModel.modelForRow) {
return;
}
let subModel = null;
try {
subModel = sourceModel.modelForRow(listView.currentIndex);
} catch (e) {
return;
}
if (!subModel) {
return;
}
if (!itemList.itemListDialogComponent) {
return;
}
if (!subModel || typeof subModel.count === 'undefined' || subModel.count === 0) {
return;
}
// Create the dialog with the submenu model
// Kicker.SubMenu with Floating should be parented to null (top-level)
const dialog = itemList.itemListDialogComponent.createObject(null, {
visualParent: listView.currentItem,
model: subModel,
visible: true,
dialogMirrored: itemList.LayoutMirroring.enabled,
itemListDialogComponent: itemList.itemListDialogComponent
});
if (dialog) {
itemList.childDialog = dialog;
dialog.index = listView.currentIndex;
dialog.visible = true;
dialog.parentItemListView = itemList;
// Connect child dialog's interactionConcluded to propagate to root
// This ensures commands in child dialogs close the entire menu
dialog.interactionConcluded.connect(() => {
if (dialog.parentItemListView) {
dialog.parentItemListView.propagateInteractionConcludedToRoot();
}
});
if (focusOnSpawn && dialog.mainItem) {
const childListView = dialog.mainItem as ItemListView;
childListView.currentIndex = 0;
// Use Qt.callLater to ensure the dialog is fully initialized before setting focus
Qt.callLater(() => {
if (childListView && childListView.listView) {
childListView.forceActiveFocus(Qt.TabFocusReason);
// Also ensure the ListView inside gets focus
childListView.listView.forceActiveFocus(Qt.TabFocusReason);
}
});
}
}
} else {
const sourceModel = (model && model.sourceModel) ? model.sourceModel : model;
const subModel = (sourceModel && sourceModel.modelForRow) ? sourceModel.modelForRow(itemList.currentIndex) : null;
if (subModel) {
itemList.childDialog.model = subModel;
itemList.childDialog.visualParent = listView.currentItem;
itemList.childDialog.index = listView.currentIndex;
}
}
}
function clearChildDialog() {
if (childDialog) {
childDialog.delayedDestroy();
childDialog = null;
}
}
Keys.priority: Keys.AfterItem
Keys.forwardTo: [itemList.mainSearchField]
onHoveredChanged: {
if (hovered) {
resetIndexTimer.stop();
} else if (itemList.childDialog && listView.currentIndex != itemList.childDialog?.index) {
listView.currentIndex = childDialog.index
} else if ((!itemList.childDialog || !itemList.dialog)
&& (!itemList.currentItem || !(itemList.currentItem as ItemListDelegate).menu.opened)) {
resetIndexTimer.start();
}
}
ListView {
id: listView
width: itemList.availableWidth
implicitHeight: contentHeight
implicitWidth: itemList.Layout.minimumWidth
property int maxDelegateImplicitWidth: 0 // used to set implicitWidth
property bool showSeparators: !model.sorted // separators are mostly useless when sorted
Binding on implicitWidth {
value: listView.maxDelegateImplicitWidth
delayed: true // only resize once all delegates are loaded
when: listView.maxDelegateImplicitWidth > 0
}
currentIndex: -1
focus: true
clip: height < contentHeight + topMargin + bottomMargin
boundsBehavior: Flickable.StopAtBounds
snapMode: ListView.SnapToItem
// Same gap between every item (text and separator) for consistent margin
spacing: itemList.itemSpacing
keyNavigationEnabled: false
cacheBuffer: 10000 // try to load all delegates for sizing; krunner won't return too many anyway
Accessible.name: itemList.Accessible.name
Accessible.role: Accessible.List
function updateImplicitWidth () {
implicitWidth = maxDelegateImplicitWidth
}
delegate: ItemListDelegate {
showSeparators: listView.showSeparators
showIcons: itemList.iconsEnabled
buttonHeight: itemList.buttonHeight
itemSpacing: itemList.itemSpacing
dialogDefaultRight: !itemList.LayoutMirroring.enabled
hoverEnabled: itemList.hoverEnabled
onInteractionConcluded: {
// If we're in a submenu, propagate directly to root to ensure menu closes
if (itemList.dialog && itemList.dialog.parentItemListView) {
itemList.propagateInteractionConcludedToRoot();
} else {
// At root level, emit normally
itemList.interactionConcluded();
}
}
onHoveredChanged: {
if (hovered & !actualIsSeparator) {
listView.currentIndex = index
itemList.forceActiveFocus()
dialogSpawnTimer.restart()
} else if (listView.currentIndex === index) {
dialogSpawnTimer.stop()
}
}
Connections {
target: itemList.mainSearchField
function onTextChanged() {
listView.maxDelegateImplicitWidth = 0
}
}
onImplicitWidthChanged: {
listView.maxDelegateImplicitWidth = Math.max(listView.maxDelegateImplicitWidth, implicitWidth)
}
}
highlight: PlasmaExtras.Highlight {
width: listView.width
visible: !(listView.currentItem as ItemListDelegate)?.actualIsSeparator
pressed: !!((listView.currentItem as ItemListDelegate)?.pressed && (listView.currentItem as ItemListDelegate)?.actualHasChildren)
active: !!(listView.currentItem as ItemListDelegate)?.hovered
}
highlightMoveDuration: 0
onCountChanged: {
if (currentIndex == 0 && !itemList.mainSearchField.activeFocus) {
currentItem?.forceActiveFocus();
} else {
currentIndex = -1;
}
}
onCurrentIndexChanged: {
if (currentIndex === itemList.childDialog?.index) {
return;
}
const delegate = currentItem as ItemListDelegate;
if (currentIndex === -1 || (delegate && !delegate.actualHasChildren)) {
dialogSpawnTimer.stop();
itemList.clearChildDialog();
} else if (delegate && delegate.actualHasChildren) {
// Item has children, restart timer to show submenu
// Don't restart timer here - let the hover handler do it
// The timer will fire and call subMenuForCurrentItem
}
}
Connections {
target: (listView.currentItem as ItemListDelegate)?.menu ?? null
function onClosed() {
resetIndexTimer.restart()
}
}
function handleLeftRightArrowEnter(event: KeyEvent) : void {
let backArrowKey = (event.key === Qt.Key_Left && !itemList.LayoutMirroring.enabled) ||
(event.key === Qt.Key_Right && itemList.LayoutMirroring.enabled)
let forwardArrowKey = (event.key === Qt.Key_Right && !itemList.LayoutMirroring.enabled) ||
(event.key === Qt.Key_Left && itemList.LayoutMirroring.enabled)
if (backArrowKey) {
if (itemList.dialog != null) {
itemList.dialog.destroy();
} else {
itemList.navigateLeftRequested();
}
} else if (forwardArrowKey || event.key === Qt.Key_Return || event.key === Qt.Key_Enter) {
if (listView.currentItem !== null && (listView.currentItem as ItemListDelegate).actualHasChildren) {
if (itemList.childDialog === null) {
itemList.subMenuForCurrentItem(true);
} else {
const childListView = itemList.childDialog.mainItem as ItemListView;
if (childListView) {
childListView.forceActiveFocus(Qt.TabFocusReason);
// Ensure the ListView inside gets focus for keyboard navigation
if (childListView.listView) {
childListView.listView.forceActiveFocus(Qt.TabFocusReason);
}
childListView.currentIndex = 0;
}
}
} else if (forwardArrowKey) {
itemList.navigateRightRequested();
} else {
event.accepted = false;
}
}
}
function handleUpDownArrow(event: KeyEvent) : void {
let moveIndex = (event.key === Qt.Key_Up) ? listView.decrementCurrentIndex : listView.incrementCurrentIndex
if (!listView.keyNavigationWraps && ((event.key === Qt.Key_Up && listView.currentIndex == 0) ||
(event.key === Qt.Key_Down && listView.currentIndex == listView.count - 1))) {
itemList.keyNavigationAtListEnd();
} else {
moveIndex();
if (listView.currentItem !== null) {
if ((listView.currentItem as ItemListDelegate).actualIsSeparator) {
moveIndex();
}
listView.currentItem.forceActiveFocus(Qt.TabFocusReason);
}
}
}
Keys.onLeftPressed: event => handleLeftRightArrowEnter(event)
Keys.onRightPressed: event => handleLeftRightArrowEnter(event)
Keys.onEnterPressed: event => handleLeftRightArrowEnter(event)
Keys.onReturnPressed: event => handleLeftRightArrowEnter(event)
Keys.onUpPressed: event => handleUpDownArrow(event)
Keys.onDownPressed: event => handleUpDownArrow(event)
Keys.onEscapePressed: {
// If we're in a child dialog, propagate to root by traversing parent chain
if (itemList.dialog && itemList.dialog.parentItemListView) {
// We're in a child dialog, find root and call it
let root = itemList.dialog.parentItemListView;
while (root.dialog && root.dialog.parentItemListView) {
root = root.dialog.parentItemListView;
}
root.interactionConcluded();
} else {
// We're at root level, just emit the signal
itemList.interactionConcluded();
}
}
Keys.onPressed: event => {
if (event.key !== Qt.Key_Tab && event.text !== "") {
itemList.mainSearchField?.forceActiveFocus(Qt.ShortcutFocusReason);
}
}
Timer {
id: dialogSpawnTimer
interval: 100
repeat: false
onTriggered: {
itemList.subMenuForCurrentItem();
}
}
Timer {
id: resetIndexTimer
interval: (itemList.dialog != null) ? 50 : 150
repeat: false
onTriggered: {
if (itemList.focus && !(itemList.childDialog?.mainItem as ItemListView)?.hovered) {
itemList.currentIndex = -1;
itemList.exited();
}
}
}
}
}
@@ -0,0 +1,324 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQml
import org.kde.plasma.private.kicker as Kicker
/**
* JsonMenuModel - Data model that converts JSON menu configuration into a ListModel
*
* This component is the core data layer for the JSON-based menu system. It:
*
* 1. Parses the JSON menu data from Plasmoid.configuration.menuJson
* 2. Converts the JSON into a ListModel that ItemListView can display
* 3. Handles nested submenus by creating child models dynamically
* 4. Executes commands when menu items are clicked (via the trigger function)
* 5. Manages separators, icons, and other menu item properties
* 6. Menu order follows the JSON order (no alphabetical sorting)
*
* Used in main.qml as rootModel, which is passed to MenuRepresentation and then
* to ItemListView to display the menu. Without this component, the menu would
* not work - it's the bridge between JSON configuration and the UI.
*/
ListModel {
id: root
property string jsonData: ""
property bool sorted: false
property var executable: null
property var _submenuCache: ({}) // Cache submenu items by index
signal refreshed()
function refresh() {
root.clear();
root._submenuCache = {}; // Clear cache
if (!jsonData || jsonData === "") {
refreshed();
return;
}
try {
const menuItems = JSON.parse(jsonData);
populateModel(menuItems, root);
refreshed();
} catch (e) {
console.error("JsonMenuModel: Error parsing menu JSON:", e);
refreshed();
}
}
function populateModel(items, parentModel) {
if (!Array.isArray(items)) {
return;
}
if (!parentModel) {
return;
}
items.forEach((item, index) => {
if (item.separator) {
parentModel.append({
display: "",
decoration: "",
url: "",
isSeparator: true,
hasChildren: false,
isParent: false,
disabled: false,
description: "",
model: {}
});
} else {
const hasSubmenu = item.submenu && Array.isArray(item.submenu) && item.submenu.length > 0;
const command = item.command || "";
const url = command ? ("file://" + command) : "";
const submenuItems = item.submenu || [];
// Store submenu items in cache for later retrieval
if (parentModel === root && hasSubmenu) {
root._submenuCache[parentModel.count] = submenuItems;
}
parentModel.append({
display: item.name || "",
decoration: item.icon || "",
url: url,
isSeparator: false,
hasChildren: hasSubmenu,
isParent: hasSubmenu,
disabled: item.disabled || false,
description: item.description || item.name || "",
command: command,
submenuItems: submenuItems, // Store in model item too (might not be accessible)
model: {
display: item.name || "",
description: item.description || item.name || ""
}
});
}
});
}
// Helper function to execute commands - accessible from submenu models via root
function executeCommand(cmd) {
if (executable && typeof executable.exec === 'function') {
executable.exec(String(cmd));
return true;
}
console.error("JsonMenuModel.executeCommand: executable not available");
return false;
}
function createSubMenuModel(submenuItems, parentExecutable) {
// Create a cache for this submodel's submenu items
const submenuCache = {};
const subModel = Qt.createQmlObject(`
import QtQuick
import QtQml
ListModel {
property var executable: null
property bool sorted: false
property var _submenuCache: ({})
function trigger(index, actionId, actionArgument) {
if (index < 0 || index >= count) {
return false;
}
const item = get(index);
if (item.isSeparator || item.disabled || item.hasChildren) {
return false;
}
if (item.command && executable && typeof executable.exec === 'function') {
executable.exec(String(item.command));
return true;
}
return false;
}
function modelForRow(index) {
if (index < 0 || index >= count) {
return null;
}
const item = get(index);
if (!item.hasChildren) {
return null;
}
// Get submenuItems from cache first, then try item directly
let submenuItems = _submenuCache[index];
if (!submenuItems) {
submenuItems = item.submenuItems;
}
if (!submenuItems || !Array.isArray(submenuItems) || submenuItems.length === 0) {
return null;
}
// For nested submenus, recursively call the parent's createSubMenuModel
const execToPass = executable || (root && root.executable ? root.executable : null);
if (root && root.createSubMenuModel) {
return root.createSubMenuModel(submenuItems, execToPass);
}
return null;
}
}
`, root);
// Set properties with error handling
// Assign executable property
try {
if (parentExecutable) {
subModel.executable = parentExecutable;
} else if (root.executable) {
subModel.executable = root.executable;
}
} catch (e) {
console.error("JsonMenuModel.createSubMenuModel: Cannot assign executable:", e);
}
try {
subModel.sorted = root.sorted;
} catch (e) {
console.error("JsonMenuModel.createSubMenuModel: Cannot assign sorted:", e);
}
// Populate the model directly in the createSubMenuModel function
if (Array.isArray(submenuItems)) {
submenuItems.forEach((item, index) => {
if (item.separator) {
subModel.append({
display: "",
decoration: "",
url: "",
isSeparator: true,
hasChildren: false,
isParent: false,
disabled: false,
description: "",
model: {}
});
} else {
const hasSubmenu = item.submenu && Array.isArray(item.submenu) && item.submenu.length > 0;
const command = item.command || "";
const url = command ? ("file://" + command) : "";
const itemSubmenuItems = item.submenu || [];
// Store submenu items in cache for later retrieval
if (hasSubmenu) {
submenuCache[subModel.count] = itemSubmenuItems;
}
// Ensure hasChildren is explicitly a boolean
const hasChildrenValue = Boolean(hasSubmenu);
const isParentValue = Boolean(hasSubmenu);
subModel.append({
display: item.name || "",
decoration: item.icon || "",
url: url,
isSeparator: false,
hasChildren: hasChildrenValue,
isParent: isParentValue,
disabled: Boolean(item.disabled || false),
description: item.description || item.name || "",
command: command,
submenuItems: itemSubmenuItems, // Store in model item too (might not be accessible)
model: {
display: item.name || "",
description: item.description || item.name || ""
}
});
}
});
}
// Assign the cache to the submodel
try {
subModel._submenuCache = submenuCache;
} catch (e) {
console.error("JsonMenuModel.createSubMenuModel: Cannot assign _submenuCache:", e);
}
return subModel;
}
function modelForRow(index) {
if (index < 0 || index >= root.count) {
return null;
}
const item = root.get(index);
if (!item.hasChildren) {
return null;
}
// Get submenuItems from cache (since ListModel might not preserve arbitrary properties)
let submenuItems = root._submenuCache[index];
if (!submenuItems) {
// Fallback: try to get from item directly
if (item.submenuItems) {
submenuItems = item.submenuItems;
} else {
// Last resort: parse JSON again to get submenu items
try {
const menuItems = JSON.parse(root.jsonData);
if (Array.isArray(menuItems) && index < menuItems.length) {
const jsonItem = menuItems[index];
if (jsonItem && jsonItem.submenu) {
submenuItems = jsonItem.submenu;
}
}
} catch (e) {
console.error("JsonMenuModel.modelForRow: Error parsing JSON:", e);
}
}
}
if (!submenuItems || !Array.isArray(submenuItems) || submenuItems.length === 0) {
return null;
}
const subModel = createSubMenuModel(submenuItems, executable);
return subModel;
}
function trigger(index, actionId, actionArgument) {
if (index < 0 || index >= root.count) {
return false;
}
const item = root.get(index);
if (item.isSeparator || item.disabled) {
return false;
}
if (item.hasChildren) {
// Has submenu, don't close
return false;
}
if (item.command && executable) {
executable.exec(String(item.command));
return true;
}
return false;
}
function labelForRow(index) {
if (index < 0 || index >= root.count) {
return "";
}
return root.get(index).display;
}
onJsonDataChanged: {
refresh();
}
Component.onCompleted: {
refresh();
}
}
@@ -0,0 +1,132 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.plasma.components as PlasmaComponents3
import org.kde.plasma.core as PlasmaCore
import org.kde.plasma.plasmoid
/**
* MenuRepresentation - Main UI component that displays the menu
*
* This component is the primary visual representation of the menu. It:
*
* 1. Wraps the menu in a ScrollView for scrolling when content exceeds available space
* 2. Contains the main ItemListView that displays menu items from the JsonMenuModel
* 3. Handles keyboard focus and navigation
* 4. Manages hover blocking to prevent accidental hover activation when using keyboard
* 5. Connects signals between the model and the view (interactionConcluded, reset, etc.)
* 6. Handles layout and sizing constraints
*
* Used in main.qml as the fullRepresentation component, which displays when the
* plasmoid button is clicked. This is the main entry point for the menu UI.
*/
PlasmaComponents3.ScrollView {
id: root
required property var rootModel
required property Component itemListDialogComponent
signal interactionConcluded
focus: true
Layout.minimumWidth: Math.min(mainRow.width, mainRow.implicitWidth, Screen.width - Kirigami.Units.largeSpacing * 4)
Layout.maximumWidth: Layout.minimumWidth
contentWidth: mainRow.implicitWidth
Layout.minimumHeight: rootList.implicitHeight
Layout.maximumHeight: Layout.minimumHeight
function reset() {
rootList.currentIndex = -1;
hoverBlock.reset();
}
RowLayout {
id: mainRow
anchors.fill: parent
spacing: Kirigami.Units.smallSpacing
LayoutMirroring.enabled: ((Plasmoid.location === PlasmaCore.Types.RightEdge)
|| (Application.layoutDirection === Qt.RightToLeft && Plasmoid.location !== PlasmaCore.Types.LeftEdge))
ItemListView {
id: rootList
Layout.alignment: Qt.AlignTop
Layout.fillHeight: true
Layout.fillWidth: true
menuWidth: Plasmoid.configuration.menuWidth || 0
buttonHeight: Plasmoid.configuration.buttonHeight || 0
visible: true
iconsEnabled: Plasmoid.configuration.showIcons
hoverEnabled: !hoverBlock.enabled
itemListDialogComponent: root.itemListDialogComponent
model: root.rootModel
LayoutMirroring.enabled: mainRow.LayoutMirroring.enabled
showSeparators: true // keep even if sorted, the one between recents and categories works
onInteractionConcluded: root.interactionConcluded()
Component.onCompleted: {
rootList.exited.connect(root.reset);
}
}
}
Component.onCompleted: {
kicker.modelRefreshed.connect(() => {
root.reset()
});
kicker.reset.connect(reset)
rootModel.refresh();
// Give list focus when menu opens so keyboard navigation works without hovering first
if (root.visible) {
Qt.callLater(() => rootList.forceActiveFocus(Qt.PopupFocusReason));
}
}
Connections {
target: root
function onVisibleChanged() {
if (root.visible) {
Qt.callLater(() => rootList.forceActiveFocus(Qt.PopupFocusReason));
}
}
}
MouseArea {
id: hoverBlock // don't hover-activate until mouse is moved to not interfere with keyboard use
anchors.fill: parent
hoverEnabled: true
propagateComposedEvents: true // clicking should still work if hovering is blocked
property bool mouseMoved: false
function reset() {
mouseMoved = false
enabled = true
}
onPositionChanged: if (!mouseMoved) {
mouseMoved = true
} else {
enabled = false // this immediately triggers other hover events when bound to their hoverEnabled
}
}
}
@@ -0,0 +1,48 @@
/*
SPDX-FileCopyrightText: 2024
SPDX-License-Identifier: GPL-2.0-or-later
*/
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls as QQC2
import org.kde.kcmutils as KCM
import org.kde.kirigami as Kirigami
KCM.SimpleKCM {
id: configEditJson
property string cfg_menuJson: plasmoid.configuration.menuJson || "[]"
ColumnLayout {
Layout.fillWidth: true
Layout.fillHeight: true
QQC2.Label {
text: i18n("Edit the menu structure as JSON. Each item can have: name, icon, command, submenu (array of items), or separator (true).")
wrapMode: Text.WordWrap
Layout.fillWidth: true
Layout.bottomMargin: Kirigami.Units.smallSpacing
}
QQC2.TextArea {
id: jsonField
Layout.fillWidth: true
Layout.fillHeight: true
Layout.minimumHeight: Kirigami.Units.gridUnit * 15
text: configEditJson.cfg_menuJson
placeholderText: "[]"
wrapMode: TextArea.NoWrap
selectByMouse: true
font.family: "monospace"
onTextChanged: {
if (text !== configEditJson.cfg_menuJson) {
configEditJson.cfg_menuJson = text;
}
}
}
}
}
@@ -0,0 +1,166 @@
/*
SPDX-FileCopyrightText: 2014 Eike Hein <hein@kde.org>
SPDX-License-Identifier: GPL-2.0-or-later
*/
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls as QQC2
import org.kde.draganddrop as DragDrop
import org.kde.iconthemes as KIconThemes
import org.kde.kcmutils as KCM
import org.kde.kirigami as Kirigami
import org.kde.ksvg as KSvg
import org.kde.plasma.core as PlasmaCore
KCM.SimpleKCM {
id: configGeneral
property string cfg_icon: plasmoid.configuration.icon
property bool cfg_useCustomButtonImage: plasmoid.configuration.useCustomButtonImage
property string cfg_customButtonImage: plasmoid.configuration.customButtonImage
property alias cfg_showIcons: showIcons.checked
property alias cfg_menuWidth: menuWidthSpinBox.value
property alias cfg_buttonHeight: buttonHeightSpinBox.value
Kirigami.FormLayout {
anchors.left: parent.left
anchors.right: parent.right
QQC2.Button {
id: iconButton
Kirigami.FormData.label: i18n("Icon:")
implicitWidth: previewFrame.width + Kirigami.Units.smallSpacing * 2
implicitHeight: previewFrame.height + Kirigami.Units.smallSpacing * 2
checkable: true
checked: dropArea.containsAcceptableDrag
onPressed: iconMenu.opened ? iconMenu.close() : iconMenu.open()
DragDrop.DropArea {
id: dropArea
property bool containsAcceptableDrag: false
anchors.fill: parent
onDragEnter: event => {
const urlString = event.mimeData.url.toString();
const extensions = [".png", ".xpm", ".svg", ".svgz"];
containsAcceptableDrag = urlString.startsWith("file:///")
&& extensions.some(extension => urlString.endsWith(extension));
if (!containsAcceptableDrag) {
event.ignore();
}
}
onDragLeave: event => {
containsAcceptableDrag = false
}
onDrop: event => {
if (containsAcceptableDrag) {
iconDialog.setCustomButtonImage(event.mimeData.url.toString().substr("file://".length));
}
containsAcceptableDrag = false;
}
}
KIconThemes.IconDialog {
id: iconDialog
function setCustomButtonImage(image) {
configGeneral.cfg_customButtonImage = image || configGeneral.cfg_icon || "start-here-kde-symbolic"
configGeneral.cfg_useCustomButtonImage = true;
}
onIconNameChanged: (iconName) => {
if (iconName != "") {
setCustomButtonImage(iconName)
}
}
}
KSvg.FrameSvgItem {
id: previewFrame
anchors.centerIn: parent
imagePath: plasmoid.location === PlasmaCore.Types.Vertical || plasmoid.location === PlasmaCore.Types.Horizontal
? "widgets/panel-background" : "widgets/background"
width: Kirigami.Units.iconSizes.large + fixedMargins.left + fixedMargins.right
height: Kirigami.Units.iconSizes.large + fixedMargins.top + fixedMargins.bottom
Kirigami.Icon {
anchors.centerIn: parent
width: Kirigami.Units.iconSizes.large
height: width
source: configGeneral.cfg_useCustomButtonImage ? configGeneral.cfg_customButtonImage : configGeneral.cfg_icon
}
}
QQC2.Menu {
id: iconMenu
y: parent.height
onClosed: iconButton.checked = false;
QQC2.MenuItem {
text: i18nc("@item:inmenu Open icon chooser dialog", "Choose…")
icon.name: "document-open-folder"
onClicked: iconDialog.open()
}
QQC2.MenuItem {
text: i18nc("@item:inmenu Reset icon to default", "Clear Icon")
icon.name: "edit-clear"
onClicked: {
configGeneral.cfg_icon = "start-here-kde-symbolic"
configGeneral.cfg_customButtonImage = ""
configGeneral.cfg_useCustomButtonImage = false
}
}
}
}
Item {
Kirigami.FormData.isSection: true
}
QQC2.CheckBox {
id: showIcons
Kirigami.FormData.label: i18n("General:")
text: i18n("Show icons in the menu")
}
RowLayout {
spacing: 0
Rectangle { Layout.bottomMargin: 20 }
}
RowLayout {
Kirigami.FormData.label: i18n("Menu Width:")
QQC2.SpinBox {
id: menuWidthSpinBox
from: 0
// INT_MAX (2^31-1): max value for config Int type; effectively no upper limit for width
to: 2147483647
}
}
RowLayout {
Kirigami.FormData.label: i18n("Button Height:")
QQC2.SpinBox {
id: buttonHeightSpinBox
from: 0
// INT_MAX (2^31-1): max value for config Int type; effectively no upper limit
to: 2147483647
}
}
}
}
@@ -0,0 +1,43 @@
/*
SPDX-FileCopyrightText: 2024
SPDX-License-Identifier: GPL-2.0-or-later
*/
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls as QQC2
import org.kde.kcmutils as KCM
import org.kde.kirigami as Kirigami
KCM.SimpleKCM {
id: configMenuJson
property string cfg_menuJson
MenuBuilder {
id: menuBuilder
anchors.fill: parent
Connections {
target: menuBuilder
function onJsonOutputChanged() {
// Update configuration property when JSON changes
// This ensures the Apply button becomes enabled
cfg_menuJson = menuBuilder.jsonOutput;
}
}
Component.onCompleted: {
// Load JSON when MenuBuilder is ready
Qt.callLater(() => {
const jsonData = plasmoid.configuration.menuJson;
menuBuilder.loadFromJson(jsonData || "[]");
// Set initial value to match loaded data
cfg_menuJson = menuBuilder.jsonOutput;
});
}
}
}
@@ -0,0 +1,954 @@
/*
SPDX-FileCopyrightText: 2024
SPDX-License-Identifier: GPL-2.0-or-later
*/
import QtQuick
import QtQuick.Layouts
import QtQuick.Controls as QQC2
import org.kde.kirigami as Kirigami
import org.kde.plasma.components as PlasmaComponents3
import org.kde.iconthemes as KIconThemes
/**
* MenuBuilder - Visual menu editor with hierarchical tree view and property editor
*
* This component provides a KDE Menu Editor-like interface for editing the JSON menu structure.
* It features:
* - Left pane: Hierarchical tree view with expandable/collapsible items
* - Right pane: Property editor for the selected menu item
* - Toolbar: Add, Delete, Move Up/Down buttons
* - Real-time JSON generation from the edited structure
*/
Item {
id: root
property var menuData: []
property string jsonOutput: ""
function loadFromJson(jsonString) {
try {
if (!jsonString || jsonString.trim() === "" || jsonString === "[]") {
// Use default menu from main.xml
jsonString = '[{"name":"About This Computer","icon":"help-hint","command":"kinfocenter"},{"separator":true},{"name":"System Preferences...","icon":"settings-configure","command":"systemsettings"},{"name":"App Store...","icon":"update-none","command":"plasma-discover"},{"separator":true},{"name":"Force Quit...","icon":"error","command":"xkill"},{"separator":true},{"name":"Sleep","icon":"system-suspend","command":"systemctl suspend"},{"name":"Restart...","icon":"system-reboot","command":"qdbus6 org.kde.LogoutPrompt /LogoutPrompt promptReboot"},{"name":"Shut Down...","icon":"system-shutdown","command":"qdbus6 org.kde.LogoutPrompt /LogoutPrompt promptShutDown"},{"separator":true},{"name":"Lock Screen","icon":"system-lock-screen","command":"qdbus6 org.freedesktop.ScreenSaver /ScreenSaver Lock"},{"name":"Log Out","icon":"system-log-out","command":"qdbus6 org.kde.LogoutPrompt /LogoutPrompt promptLogout"}]';
}
const parsed = JSON.parse(jsonString);
menuData = Array.isArray(parsed) ? parsed : [];
expandedPaths = [];
rebuildTreeModel();
jsonOutput = JSON.stringify(menuData, null, 2);
} catch (e) {
console.error("MenuBuilder: Failed to parse JSON:", e);
menuData = [];
expandedPaths = [];
treeModel.clear();
}
}
function buildTreeModel(items, parentItem, level) {
if (level === undefined) level = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
// An item has children if it has a submenu property (even if empty)
// This allows empty submenus to show the expand/collapse chevron
const hasChildren = !!(item.submenu && Array.isArray(item.submenu));
const modelItem = {
itemData: item,
itemIndex: i,
parentItem: parentItem,
isExpanded: false,
level: level,
hasChildren: hasChildren,
parentArray: parentItem ? parentItem.itemData.submenu : menuData
};
treeModel.append(modelItem);
// Recursively add children if parent is expanded (but initially all collapsed)
// We'll rebuild when expanding
}
}
function rebuildTreeModel() {
treeModel.clear();
if (!menuData || menuData.length === 0) {
return;
}
buildTreeModelRecursive(menuData, null, 0, "");
}
function buildTreeModelRecursive(items, parentItem, level, parentPath) {
if (!items || items.length === 0) return;
if (parentPath === undefined) parentPath = "";
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (!item) continue;
// An item has children if it has a submenu property (even if empty)
// This allows empty submenus to show the expand/collapse chevron
const hasChildren = !!(item.submenu && Array.isArray(item.submenu));
const isLastChild = (i === items.length - 1);
const currentPath = parentPath === "" ? String(i) : parentPath + "/" + i;
const isExpanded = root.isItemExpanded(item, currentPath);
treeModel.append({
itemData: item,
itemIndex: i,
parentItem: parentItem,
isExpanded: isExpanded,
level: level,
hasChildren: hasChildren,
isLastChild: isLastChild,
parentArray: parentItem ? parentItem.itemData.submenu : menuData,
path: currentPath
});
// Add children if this item is expanded and has children
if (hasChildren && isExpanded && item.submenu.length > 0) {
const currentModelItem = treeModel.get(treeModel.count - 1);
buildTreeModelRecursive(item.submenu, currentModelItem, level + 1, currentPath);
}
}
}
property var expandedPaths: [] // Store paths instead of object references
property var collapsedPaths: [] // Store paths of explicitly collapsed items
property string selectedPath: ""
function isItemExpanded(itemData, path) {
// Use path to check if expanded, since object references change after rebuild
if (path === undefined || path === "") return false;
// If explicitly collapsed, return false
if (collapsedPaths.indexOf(path) >= 0) return false;
// By default, expand all items that have children
if (itemData && itemData.submenu && Array.isArray(itemData.submenu) && itemData.submenu.length > 0) {
return true;
}
// Otherwise check if explicitly in expandedPaths (for backwards compatibility)
return expandedPaths.indexOf(path) >= 0;
}
function setItemExpanded(itemData, expanded, path) {
if (path === undefined || path === "") return;
if (expanded) {
// Remove from collapsedPaths if present
const collapsedIndex = collapsedPaths.indexOf(path);
if (collapsedIndex >= 0) {
collapsedPaths.splice(collapsedIndex, 1);
// Force property change notification
collapsedPaths = collapsedPaths.slice();
}
// Add to expandedPaths if not present (for backwards compatibility)
const expandedIndex = expandedPaths.indexOf(path);
if (expandedIndex < 0) {
expandedPaths.push(path);
// Force property change notification
expandedPaths = expandedPaths.slice();
}
} else {
// Add to collapsedPaths if not present
const collapsedIndex = collapsedPaths.indexOf(path);
if (collapsedIndex < 0) {
collapsedPaths.push(path);
// Force property change notification
collapsedPaths = collapsedPaths.slice();
}
// Remove from expandedPaths if present (for backwards compatibility)
const expandedIndex = expandedPaths.indexOf(path);
if (expandedIndex >= 0) {
expandedPaths.splice(expandedIndex, 1);
// Force property change notification
expandedPaths = expandedPaths.slice();
}
}
}
function updateJson() {
jsonOutput = JSON.stringify(menuData, null, 2);
}
function findItemByPath(path) {
if (path === "" || path === "/") return null;
const parts = path.split("/").filter(p => p !== "");
let current = menuData;
for (let i = 0; i < parts.length; i++) {
const index = parseInt(parts[i]);
if (current && current[index]) {
if (i === parts.length - 1) {
return current[index];
} else {
current = current[index].submenu || [];
}
} else {
return null;
}
}
return null;
}
function updateItemInMenuData(path, property, value) {
if (path === "" || path === "/") return;
const parts = path.split("/").filter(p => p !== "");
let current = menuData;
for (let i = 0; i < parts.length; i++) {
const index = parseInt(parts[i]);
if (current && current[index]) {
if (i === parts.length - 1) {
// Found the item, update it
current[index][property] = value;
return;
} else {
current = current[index].submenu || [];
}
} else {
return;
}
}
}
function findItemInData(itemData, parentArray) {
if (!parentArray) parentArray = menuData;
for (let i = 0; i < parentArray.length; i++) {
if (parentArray[i] === itemData) {
return { array: parentArray, index: i };
}
if (parentArray[i].submenu) {
const found = findItemInData(itemData, parentArray[i].submenu);
if (found) return found;
}
}
return null;
}
function getPathForItem(itemData, parentArray, parentPath) {
if (!parentArray) parentArray = menuData;
if (parentPath === undefined) parentPath = "";
for (let i = 0; i < parentArray.length; i++) {
const currentPath = parentPath === "" ? String(i) : parentPath + "/" + i;
if (parentArray[i] === itemData) {
return currentPath;
}
if (parentArray[i].submenu) {
const found = getPathForItem(itemData, parentArray[i].submenu, currentPath);
if (found) return found;
}
}
return null;
}
function addItem(parentItemData, afterIndex) {
const newItem = {
name: "New Item",
icon: "",
command: ""
};
if (parentItemData && parentItemData.submenu) {
// Add to parent's submenu
const insertIndex = afterIndex !== undefined && afterIndex >= 0 ? afterIndex + 1 : parentItemData.submenu.length;
parentItemData.submenu.splice(insertIndex, 0, newItem);
} else if (parentItemData) {
// Parent exists but no submenu - create it
parentItemData.submenu = [newItem];
} else {
// Add to root level
const insertIndex = afterIndex !== undefined && afterIndex >= 0 ? afterIndex + 1 : menuData.length;
menuData.splice(insertIndex, 0, newItem);
}
rebuildTreeModel();
updateJson();
}
function deleteItem(itemData) {
if (!selectedPath || selectedPath === "") return;
const parts = selectedPath.split("/").filter(p => p !== "");
if (parts.length === 1) {
// Root level item
menuData.splice(parseInt(parts[0]), 1);
} else {
// Nested item: navigate to the parent array (same logic as moveItem)
let current = menuData;
for (let i = 0; i < parts.length - 1; i++) {
const index = parseInt(parts[i]);
if (current && current[index] && current[index].submenu) {
current = current[index].submenu;
} else {
return; // Invalid path
}
}
const targetIndex = parseInt(parts[parts.length - 1]);
current.splice(targetIndex, 1);
}
selectedItem = null;
selectedPath = "";
rebuildTreeModel();
updateJson();
}
function moveItem(itemData, direction) {
if (!selectedPath || selectedPath === "") return;
const parts = selectedPath.split("/").filter(p => p !== "");
let current = menuData;
let targetArray = menuData;
let currentIndex = 0;
// Navigate to the parent array containing the item
if (parts.length === 1) {
// Root level item
targetArray = menuData;
currentIndex = parseInt(parts[0]);
} else {
// Nested item - navigate to parent
for (let i = 0; i < parts.length - 1; i++) {
const index = parseInt(parts[i]);
if (current && current[index] && current[index].submenu) {
current = current[index].submenu;
} else {
return; // Invalid path
}
}
targetArray = current;
currentIndex = parseInt(parts[parts.length - 1]);
}
// Calculate new index
const newIndex = direction === "up" ? currentIndex - 1 : currentIndex + 1;
if (newIndex < 0 || newIndex >= targetArray.length) return;
// Move the item
const item = targetArray.splice(currentIndex, 1)[0];
targetArray.splice(newIndex, 0, item);
// Force update to trigger change detection (same as other functions)
menuData = JSON.parse(JSON.stringify(menuData));
// Rebuild the tree model
rebuildTreeModel();
updateJson();
// Calculate new path after move
const newPathParts = parts.slice();
newPathParts[newPathParts.length - 1] = String(newIndex);
const newPath = newPathParts.join("/");
// Restore selection after rebuild
Qt.callLater(() => {
const restoredItem = findItemByPath(newPath);
if (restoredItem) {
selectedItem = restoredItem;
selectedPath = newPath;
}
});
}
property var selectedItem: null // Direct reference to item in menuData
// Computed property to check if selected item is a parent (has submenu)
// This needs to be reactive to changes in selectedItem and its submenu property
readonly property bool selectedItemIsParent: {
if (!selectedItem) return false;
// Check if submenu property exists and is an array (even if empty)
const hasSubmenu = selectedItem.hasOwnProperty('submenu') &&
selectedItem.submenu !== undefined &&
selectedItem.submenu !== null &&
Array.isArray(selectedItem.submenu);
return hasSubmenu;
}
// Helper function to get array and index from path
function getArrayAndIndexFromPath(path) {
if (!path || path === "") return null;
const parts = path.split("/").filter(p => p !== "");
let current = menuData;
for (let i = 0; i < parts.length - 1; i++) {
const index = parseInt(parts[i]);
if (current && current[index] && current[index].submenu) {
current = current[index].submenu;
} else {
return null;
}
}
const lastIndex = parseInt(parts[parts.length - 1]);
return { array: current, index: lastIndex };
}
// Computed property to check if selected item can be moved up
readonly property bool canMoveUp: {
if (!selectedItem || !selectedPath) return false;
const info = getArrayAndIndexFromPath(selectedPath);
if (!info) return false;
return info.index > 0;
}
// Computed property to check if selected item can be moved down
readonly property bool canMoveDown: {
if (!selectedItem || !selectedPath) return false;
const info = getArrayAndIndexFromPath(selectedPath);
if (!info) return false;
return info.index < info.array.length - 1;
}
ColumnLayout {
anchors.fill: parent
spacing: 0
// Toolbar
RowLayout {
Layout.fillWidth: true
Layout.preferredHeight: Kirigami.Units.gridUnit * 2
Layout.leftMargin: Kirigami.Units.smallSpacing
Layout.rightMargin: Kirigami.Units.smallSpacing
Layout.topMargin: Kirigami.Units.smallSpacing
Layout.bottomMargin: Kirigami.Units.mediumSpacing
QQC2.Button {
icon.name: "list-add"
text: i18n("Add Item")
onClicked: {
const newItem = {
name: "New Item",
icon: "",
command: ""
};
// Save current selection path before making changes
const savedPath = selectedPath;
if (selectedItem && selectedPath) {
// Find the item in menuData using the path (not the stale reference)
const currentItem = root.findItemByPath(selectedPath);
if (currentItem) {
// Check if selected item is a parent (has submenu property)
// Even if submenu is empty, it's still a parent
if (currentItem.submenu !== undefined && Array.isArray(currentItem.submenu)) {
// Add as child of the parent
// Ensure submenu exists (create if it doesn't)
if (!currentItem.submenu) {
currentItem.submenu = [];
}
currentItem.submenu.push(newItem);
root.setItemExpanded(currentItem, true, selectedPath);
} else {
// Add as sibling after selected item
const found = root.findItemInData(currentItem);
if (found) {
found.array.splice(found.index + 1, 0, newItem);
} else {
menuData.push(newItem);
}
}
} else {
menuData.push(newItem);
}
} else {
// No item selected, add to root level
menuData.push(newItem);
}
// Force update to trigger change detection
root.menuData = JSON.parse(JSON.stringify(menuData));
// Restore selection after menuData update
if (savedPath) {
const restoredItem = root.findItemByPath(savedPath);
if (restoredItem) {
root.selectedItem = restoredItem;
root.selectedPath = savedPath;
}
}
root.rebuildTreeModel();
root.updateJson();
// Select the new item
Qt.callLater(() => {
const newItemPath = root.getPathForItem(newItem);
if (newItemPath) {
root.selectedItem = newItem;
root.selectedPath = newItemPath;
}
});
}
}
QQC2.Button {
icon.name: "folder-new"
text: i18n("Add Folder")
onClicked: {
const newItem = {
name: "New Folder",
icon: "folder",
submenu: []
};
// Save current selection path before making changes
const savedPath = selectedPath;
if (selectedItem && selectedPath) {
// Find the item in menuData using the path (not the stale reference)
const currentItem = root.findItemByPath(selectedPath);
if (currentItem) {
// Check if selected item is a parent (has submenu property)
// Even if submenu is empty, it's still a parent
if (currentItem.submenu !== undefined && Array.isArray(currentItem.submenu)) {
// Add as child of the parent
currentItem.submenu.push(newItem);
root.setItemExpanded(currentItem, true, selectedPath);
} else {
// Add as sibling after selected item
const found = root.findItemInData(currentItem);
if (found) {
found.array.splice(found.index + 1, 0, newItem);
} else {
menuData.push(newItem);
}
}
} else {
menuData.push(newItem);
}
} else {
// No item selected, add to root level
menuData.push(newItem);
}
// Force update to trigger change detection
root.menuData = JSON.parse(JSON.stringify(menuData));
// Restore selection after menuData update
if (savedPath) {
const restoredItem = root.findItemByPath(savedPath);
if (restoredItem) {
root.selectedItem = restoredItem;
root.selectedPath = savedPath;
}
}
root.rebuildTreeModel();
root.updateJson();
// Select and expand the new submenu item
Qt.callLater(() => {
const newItemPath = root.getPathForItem(newItem);
if (newItemPath) {
root.selectedItem = newItem;
root.selectedPath = newItemPath;
root.setItemExpanded(newItem, true, newItemPath);
root.rebuildTreeModel();
// Restore selection after rebuild
Qt.callLater(() => {
const restoredItem = root.findItemByPath(newItemPath);
if (restoredItem) {
root.selectedItem = restoredItem;
root.selectedPath = newItemPath;
}
});
}
});
}
}
QQC2.Button {
icon.name: "insert-horizontal-rule"
text: i18n("Add Separator")
onClicked: {
const newItem = {
separator: true
};
// Use path (like Add Item) so we insert below selection, not at end
const savedPath = selectedPath;
const info = savedPath ? root.getArrayAndIndexFromPath(savedPath) : null;
if (info) {
info.array.splice(info.index + 1, 0, newItem);
} else {
// No selection: add to root level at end
menuData.push(newItem);
}
root.menuData = JSON.parse(JSON.stringify(menuData));
if (savedPath) {
const restoredItem = root.findItemByPath(savedPath);
if (restoredItem) {
root.selectedItem = restoredItem;
root.selectedPath = savedPath;
}
}
root.rebuildTreeModel();
root.updateJson();
}
}
QQC2.Button {
icon.name: "go-up"
// text: i18n("Move Up")
enabled: root.canMoveUp
onClicked: {
if (selectedItem) {
root.moveItem(selectedItem, "up");
}
}
}
QQC2.Button {
icon.name: "go-down"
// text: i18n("Move Down")
enabled: root.canMoveDown
onClicked: {
if (selectedItem) {
root.moveItem(selectedItem, "down");
}
}
}
QQC2.Button {
icon.name: "edit-delete"
// text: i18n("Delete")
enabled: selectedItem !== null
onClicked: {
if (selectedItem) {
root.deleteItem(selectedItem);
}
}
}
Item { Layout.fillWidth: true }
}
// Main content area
RowLayout {
Layout.fillWidth: true
Layout.fillHeight: true
spacing: Kirigami.Units.smallSpacing
// Left pane: Tree view
QQC2.Frame {
Layout.fillHeight: true
Layout.preferredWidth: Kirigami.Units.gridUnit * 15
Layout.minimumWidth: Kirigami.Units.gridUnit * 12
ColumnLayout {
anchors.fill: parent
anchors.margins: Kirigami.Units.smallSpacing
spacing: 0
// Tree view using ListView (TreeView requires C++ models)
QQC2.ScrollView {
id: treeScrollView
Layout.fillWidth: true
Layout.fillHeight: true
ListView {
id: treeView
width: treeScrollView.availableWidth
implicitHeight: contentHeight
model: treeModel
clip: true
// Draw tree lines in the background
// This is a workaround since TreeView requires C++ models
Rectangle {
anchors.fill: parent
color: "transparent"
z: 0
// We'll draw lines in each delegate instead
// This rectangle is just a placeholder
}
delegate: TreeItemDelegate {
id: delegate
width: treeView.width
// Access ListModel properties directly - they're available in delegate scope
property var modelRow: treeModel.get(index)
// Pass them to TreeItemDelegate properties using the model row
itemData: modelRow ? modelRow.itemData : null
level: modelRow ? modelRow.level : 0
hasChildren: modelRow ? modelRow.hasChildren : false
isExpanded: modelRow ? modelRow.isExpanded : false
isLastChild: modelRow ? modelRow.isLastChild : false
isSelected: root.selectedPath && modelRow && root.selectedPath === modelRow.path
// Check if this is the first top-level item (path === "0")
isFirstTopLevel: modelRow && modelRow.level === 0 && modelRow.path === "0"
onSelected: {
// Store direct reference to item in menuData and path
if (modelRow && modelRow.itemData) {
root.selectedItem = modelRow.itemData;
root.selectedPath = modelRow.path || "";
}
}
onToggleExpanded: {
if (modelRow && modelRow.itemData && modelRow.path) {
// Use the model row's isExpanded property directly
const currentExpanded = modelRow.isExpanded;
root.setItemExpanded(modelRow.itemData, !currentExpanded, modelRow.path);
root.rebuildTreeModel();
// Restore selection after rebuild
if (root.selectedPath) {
Qt.callLater(() => {
const restoredItem = root.findItemByPath(root.selectedPath);
if (restoredItem) {
root.selectedItem = restoredItem;
}
});
}
}
}
}
}
}
}
}
// Right pane: Editor
QQC2.Frame {
Layout.fillHeight: true
Layout.fillWidth: true
QQC2.ScrollView {
id: scrollView
anchors.fill: parent
anchors.margins: Kirigami.Units.smallSpacing
anchors.topMargin: Kirigami.Units.mediumSpacing
Kirigami.FormLayout {
id: formLayout
width: scrollView.contentItem ? scrollView.contentItem.width : parent.width
enabled: root.selectedItem !== null
QQC2.Label {
text: i18n("No item selected")
visible: root.selectedItem === null
color: Kirigami.Theme.disabledTextColor
Layout.fillWidth: true
horizontalAlignment: Text.AlignHCenter
}
QQC2.Label {
text: i18n("Separator selected")
visible: root.selectedItem !== null && root.selectedItem.hasOwnProperty("separator") && root.selectedItem.separator === true
color: Kirigami.Theme.disabledTextColor
Layout.fillWidth: true
horizontalAlignment: Text.AlignHCenter
}
RowLayout {
Kirigami.FormData.label: i18n("Name:")
Layout.fillWidth: true
visible: root.selectedItem !== null && !root.selectedItem.separator
enabled: root.selectedItem !== null && !root.selectedItem.separator
QQC2.TextField {
id: nameField
Layout.fillWidth: true
Component.onCompleted: updateText()
function updateText() {
if (root.selectedItem && !root.selectedItem.separator) {
text = root.selectedItem.name || "";
} else {
text = "";
}
}
onTextChanged: {
if (root.selectedItem && root.selectedPath && text !== (root.selectedItem.name || "")) {
root.selectedItem.name = text;
root.updateItemInMenuData(root.selectedPath, "name", text);
root.updateJson();
// Refresh tree to show updated name
const savedPath = root.selectedPath;
Qt.callLater(() => {
root.rebuildTreeModel();
// Restore selection after rebuild
if (savedPath) {
const restoredItem = root.findItemByPath(savedPath);
if (restoredItem) {
root.selectedItem = restoredItem;
root.selectedPath = savedPath;
nameField.updateText();
}
}
});
}
}
Connections {
target: root
function onSelectedItemChanged() {
nameField.updateText();
}
}
}
QQC2.Button {
id: iconButton
Layout.alignment: Qt.AlignVCenter
implicitWidth: Kirigami.Units.iconSizes.medium + Kirigami.Units.smallSpacing * 2
height: nameField.height
checkable: true
onPressed: iconMenu.opened ? iconMenu.close() : iconMenu.open()
icon.name: {
if (root.selectedItem && !root.selectedItem.separator) {
return root.selectedItem.icon || "";
}
return "";
}
KIconThemes.IconDialog {
id: iconDialog
onIconNameChanged: (iconName) => {
if (iconName != "" && root.selectedItem && root.selectedPath) {
root.selectedItem.icon = iconName;
root.updateItemInMenuData(root.selectedPath, "icon", iconName);
root.updateJson();
// Refresh tree to show updated icon
const savedPath = root.selectedPath;
Qt.callLater(() => {
root.rebuildTreeModel();
// Restore selection after rebuild
if (savedPath) {
const restoredItem = root.findItemByPath(savedPath);
if (restoredItem) {
root.selectedItem = restoredItem;
root.selectedPath = savedPath;
}
}
});
}
}
}
QQC2.Menu {
id: iconMenu
y: parent.height
onClosed: iconButton.checked = false;
QQC2.MenuItem {
text: i18nc("@item:inmenu Open icon chooser dialog", "Choose…")
icon.name: "document-open-folder"
onClicked: iconDialog.open()
}
QQC2.MenuItem {
text: i18nc("@item:inmenu Reset icon to default", "Clear Icon")
icon.name: "edit-clear"
onClicked: {
if (root.selectedItem && root.selectedPath) {
root.selectedItem.icon = "";
root.updateItemInMenuData(root.selectedPath, "icon", "");
root.updateJson();
// Refresh tree to show updated icon
const savedPath = root.selectedPath;
Qt.callLater(() => {
root.rebuildTreeModel();
// Restore selection after rebuild
if (savedPath) {
const restoredItem = root.findItemByPath(savedPath);
if (restoredItem) {
root.selectedItem = restoredItem;
root.selectedPath = savedPath;
}
}
});
}
}
}
}
}
}
Item {
id: commandFieldContainer
Kirigami.FormData.label: i18n("Command:")
Layout.fillWidth: true
// Get fresh reference to selected item to ensure submenu property is available
property var currentItem: root.selectedPath ? root.findItemByPath(root.selectedPath) : null
property bool isParent: {
if (!currentItem) return false;
const hasSubmenu = currentItem.hasOwnProperty('submenu') &&
currentItem.submenu !== undefined &&
currentItem.submenu !== null &&
Array.isArray(currentItem.submenu);
return hasSubmenu;
}
visible: {
if (!root.selectedItem || !root.selectedPath) return false;
if (currentItem && currentItem.separator === true) return false;
return !isParent;
}
enabled: visible
implicitWidth: Kirigami.Units.gridUnit * 25
implicitHeight: Kirigami.Units.gridUnit * 6
height: implicitHeight
QQC2.ScrollView {
anchors.fill: parent
clip: true
QQC2.TextArea {
id: commandField
width: commandFieldContainer.width
wrapMode: TextArea.Wrap
selectByMouse: true
onTextChanged: {
if (commandFieldContainer.currentItem && root.selectedPath && text !== (commandFieldContainer.currentItem.command || "")) {
// Only update if not a parent item
if (!commandFieldContainer.isParent) {
commandFieldContainer.currentItem.command = text;
root.updateItemInMenuData(root.selectedPath, "command", text);
root.updateJson();
}
}
}
}
}
Component.onCompleted: updateText()
function updateText() {
if (currentItem && !currentItem.separator && !isParent) {
commandField.text = currentItem.command || "";
} else {
commandField.text = "";
}
}
Connections {
target: root
function onSelectedItemChanged() {
commandFieldContainer.updateText();
}
function onSelectedPathChanged() {
commandFieldContainer.updateText();
}
}
}
}
}
}
}
}
ListModel {
id: treeModel
}
}
@@ -0,0 +1,273 @@
/*
SPDX-FileCopyrightText: 2024
SPDX-License-Identifier: GPL-2.0-or-later
*/
import QtQuick
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.plasma.components as PlasmaComponents3
/**
* TreeItemDelegate - Delegate for individual items in the menu tree view
*
* Displays a menu item in the hierarchical tree with:
* - Expand/collapse indicator for items with children
* - Visual tree lines (vertical and horizontal connectors)
* - Indentation based on nesting level
* - Selection highlighting
* - Icon and name display (or separator indicator)
*/
Rectangle {
id: delegate
// Accept either itemModel (for backwards compatibility) or direct properties
property var itemModel: null
// Direct properties - these override itemModel if set
property var itemData: null
property int level: 0
property bool hasChildren: false
property bool isExpanded: false
property bool isSelected: false
property bool isLastChild: false // Whether this is the last child at its level
property bool isFirstTopLevel: false // Whether this is the first top-level item
property var parentPaths: [] // Array of parent paths to determine tree line drawing
// Resolve itemData - use direct property if set (check for undefined too), otherwise use itemModel
readonly property var resolvedItemData: (itemData !== null && itemData !== undefined) ? itemData : (itemModel ? itemModel.itemData : null)
readonly property int resolvedLevel: (itemData !== null && itemData !== undefined) ? level : (itemModel ? itemModel.level : 0)
readonly property bool resolvedHasChildren: (itemData !== null && itemData !== undefined) ? hasChildren : (itemModel ? itemModel.hasChildren : false)
readonly property bool resolvedIsExpanded: (itemData !== null && itemData !== undefined) ? isExpanded : (itemModel ? itemModel.isExpanded : false)
readonly property bool resolvedIsLastChild: (itemData !== null && itemData !== undefined) ? isLastChild : (itemModel ? itemModel.isLastChild : false)
readonly property bool isSeparator: resolvedItemData ? resolvedItemData.separator : false
signal selected()
signal toggleExpanded()
height: isSeparator ? (Kirigami.Units.gridUnit * 0.75) : (Kirigami.Units.gridUnit * 2)
// Darker selection background so text (highlightedTextColor) is easier to read
color: isSelected ? Qt.darker(Kirigami.Theme.highlightColor, 2) : (mouseArea.containsMouse ? Kirigami.Theme.alternateBackgroundColor : "transparent")
// Draw tree lines - make them clearly visible
// Vertical lines for each parent level (these connect siblings at that level)
// Children draw lines for levels 0 to resolvedLevel-1 (all their parent levels)
Repeater {
model: resolvedLevel
delegate: Rectangle {
// Position at the center of the expand button for this level
x: {
// All vertical lines should be evenly spaced gridUnit apart from base position
// Base position: smallSpacing + iconSize/2
// modelData represents the parent level
// modelData === 0: parent is level 0, so draw at level 0 chevron center (base + gridUnit)
// modelData === 1: parent is level 1, so draw at level 1 chevron center (base + 2*gridUnit)
// modelData === 2: parent is level 2, so draw at level 2 chevron center (base + 3*gridUnit)
// etc.
var baseX = Kirigami.Units.smallSpacing + (Kirigami.Units.iconSizes.small / 2);
// Parent level is modelData, so parent's chevron center is at base + (modelData + 1) * gridUnit
return baseX + ((modelData + 1) * Kirigami.Units.gridUnit) - 0.5;
}
y: 0
width: 1
// If this is the last child at its immediate parent level, only draw to middle; otherwise full height
// However, if this item has children, the line for the immediate parent level should continue through full height
height: {
if (resolvedIsLastChild && modelData === resolvedLevel - 1) {
// Last child at immediate parent level: draw to middle, unless this item has children (then full height)
return resolvedHasChildren ? parent.height : (parent.height / 2);
} else {
// Not last child: full height
return parent.height;
}
}
// Use a visible gray color
color: "#888888"
z: 0
}
}
// Vertical line for top-level items (level 0) - connects siblings at root level
// Also drawn for all descendants of top-level items (level > 0) to continue the line
Rectangle {
// Draw for level 0 items and all their descendants (level > 0)
visible: true // Draw for all items to continue the top-level line
// Top-level vertical line at base position (left edge)
x: Kirigami.Units.smallSpacing + (Kirigami.Units.iconSizes.small / 2) - 0.5
y: isFirstTopLevel ? ((parent.height / 2) - 1) : 0 // Start from middle minus 1px for first item, top for others
width: 1
// For level 0: draw full height for all top-level items except last (if no children)
// For first top-level item: start from middle minus 1px, so height is half plus 1px
// For level > 0: always draw full height to continue the line through all descendants
height: {
if (resolvedLevel === 0) {
if (isFirstTopLevel) {
// First top-level item: start from middle minus 1px, so draw half height plus 1px
return (parent.height / 2) + 1;
} else {
// Level 0: only stop at middle for the very last top-level item (if it has no children)
return (resolvedIsLastChild && !resolvedHasChildren) ? (parent.height / 2) : parent.height;
}
} else {
// Level > 0: always full height to continue the top-level line through all nested descendants
return parent.height;
}
}
color: "#888888"
z: 0
}
// Horizontal line for top-level items (level 0) - connects from vertical line to item
Rectangle {
visible: resolvedLevel === 0 && !isSeparator
// Start from the top-level vertical line position
x: Kirigami.Units.smallSpacing + (Kirigami.Units.iconSizes.small / 2)
y: parent.height / 2 - 0.5
// Extend from vertical line to just before chevron
// For items with icons: shorter line to avoid touching
// For submenus with arrows: longer line (original width)
width: resolvedHasChildren
? (Kirigami.Units.gridUnit - (Kirigami.Units.iconSizes.small / 2)) // Submenu with arrow: original width
: (Kirigami.Units.gridUnit - (Kirigami.Units.iconSizes.small / 2) - Kirigami.Units.smallSpacing) // Item with icon: shorter
height: 1
color: "#888888"
z: 0
}
// Vertical line for this item's own level (if it has children and is expanded)
// This creates the consistent line that extends from this item through all its children
// For level 0 items with children, this draws the vertical line at the base position (continuing from main vertical line)
// For level 1+ items, this draws the vertical line at their indented position
// This line starts from the chevron (middle) and extends down, not above the chevron
Rectangle {
visible: resolvedHasChildren && resolvedIsExpanded
x: {
// Align with chevron center
// Content leftMargin: smallSpacing + (level + 1) * gridUnit
// Chevron center: leftMargin + iconSize/2
// = smallSpacing + (level + 1) * gridUnit + iconSize/2
var leftMargin = Kirigami.Units.smallSpacing + ((resolvedLevel + 1) * Kirigami.Units.gridUnit);
return leftMargin + (Kirigami.Units.iconSizes.small / 2) - 0.5;
}
y: parent.height / 2 // Start from middle (where chevron is), not from top
width: 1
height: parent.height / 2 // Extend to bottom of item
// This line will be continued by children drawing their portion for this level
color: "#888888"
z: 0
}
// Horizontal line connecting this item to its parent's vertical line (omit for separators)
Rectangle {
visible: resolvedLevel > 0 && !isSeparator
// Start from parent's vertical line (at base position for level 0 parents, indented for level 1+ parents)
x: {
// Connect from parent's vertical line
// Parent's vertical line is at: base + (parentLevel + 1) * gridUnit
// Parent level is resolvedLevel - 1
var baseX = Kirigami.Units.smallSpacing + (Kirigami.Units.iconSizes.small / 2);
var parentLevel = resolvedLevel - 1;
return baseX + ((parentLevel + 1) * Kirigami.Units.gridUnit);
}
y: parent.height / 2 - 0.5
// Extend to this item's indented content position (same width whether has children or not)
// The line should stop well before the icon/chevron area to avoid hitting icons
width: {
// Extend from parent's vertical line to just before chevron
// Parent's vertical line: base + (parentLevel + 1) * gridUnit
// This item's leftMargin: smallSpacing + (level + 1) * gridUnit
// Chevron center: leftMargin + iconSize/2 = smallSpacing + (level + 1) * gridUnit + iconSize/2
// Parent's vertical line: base + (parentLevel + 1) * gridUnit = smallSpacing + iconSize/2 + (parentLevel + 1) * gridUnit
// Distance: (level + 1) * gridUnit + iconSize/2 - (parentLevel + 1) * gridUnit - iconSize/2
// = (level - parentLevel) * gridUnit = gridUnit (since level = parentLevel + 1)
// For items with icons: shorter line to avoid touching
// For submenus with arrows: longer line (original width)
return resolvedHasChildren
? (Kirigami.Units.gridUnit - (Kirigami.Units.iconSizes.small / 2)) // Submenu with arrow: original width
: (Kirigami.Units.gridUnit - (Kirigami.Units.iconSizes.small / 2) - Kirigami.Units.smallSpacing); // Item with icon: shorter
}
height: 1
color: "#888888"
z: 0
}
MouseArea {
id: mouseArea
anchors.fill: parent
hoverEnabled: true
onClicked: {
delegate.selected();
}
}
RowLayout {
anchors.fill: parent
// Indent all items to make space for the top-level vertical line
anchors.leftMargin: {
// Align chevrons with vertical lines
// Vertical lines are at: base + (level + 1) * gridUnit
// Chevron center should be at vertical line position
// So leftMargin = vertical line position - iconSize/2
// = smallSpacing + iconSize/2 + (level + 1) * gridUnit - iconSize/2
// = smallSpacing + (level + 1) * gridUnit
return Kirigami.Units.smallSpacing + ((resolvedLevel + 1) * Kirigami.Units.gridUnit);
}
anchors.rightMargin: Kirigami.Units.smallSpacing
spacing: Kirigami.Units.smallSpacing
z: 2 // Ensure content is above tree lines
// Expand/collapse button with background to prevent lines from touching
Rectangle {
visible: resolvedHasChildren
Layout.preferredWidth: Kirigami.Units.iconSizes.small
Layout.preferredHeight: Kirigami.Units.iconSizes.small
// Always use theme background to create visible spacing from tree lines
color: Kirigami.Theme.backgroundColor
radius: 2
z: 1 // Ensure it's above the tree lines
PlasmaComponents3.ToolButton {
anchors.fill: parent
icon.name: resolvedIsExpanded ? "arrow-down" : "arrow-right"
onClicked: {
delegate.toggleExpanded();
}
}
}
// Icon (positioned where chevron would be for alignment, hidden for parent items with children)
Kirigami.Icon {
source: isSeparator ? "" : (resolvedItemData ? (resolvedItemData.icon || "application-x-executable") : "application-x-executable")
Layout.preferredWidth: isSeparator ? 0 : Kirigami.Units.iconSizes.small
Layout.preferredHeight: isSeparator ? 0 : Kirigami.Units.iconSizes.small
visible: !isSeparator && !resolvedHasChildren
}
// Name label (for regular items)
PlasmaComponents3.Label {
visible: !isSeparator
Layout.fillWidth: true
text: resolvedItemData ? (resolvedItemData.name || i18n("Unnamed")) : i18n("Unnamed")
elide: Text.ElideRight
color: isSelected ? Kirigami.Theme.highlightedTextColor : Kirigami.Theme.textColor
}
}
// Separator line (for separator items) - start at vertical tree line so there is no gap
Rectangle {
visible: isSeparator
// Align left edge with the vertical line that runs down the left of this item's group.
// Level 0: top-level vertical line at baseX - 0.5.
// Level L>0: that line is the parent's vertical (Repeater modelData 0..L-1); the left edge
// for our group is at baseX + L*gridUnit - 0.5 (same as Repeater with modelData = L-1).
x: Kirigami.Units.smallSpacing + (Kirigami.Units.iconSizes.small / 2) + (resolvedLevel * Kirigami.Units.gridUnit) - 0.5
width: parent.width - x - Kirigami.Units.smallSpacing
anchors.verticalCenter: parent.verticalCenter
height: 1
color: Kirigami.Theme.separatorColor || "#888888"
z: 2 // Above tree lines
}
}
@@ -0,0 +1,108 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.plasma.components as PlasmaComponents3
import org.kde.plasma.core as PlasmaCore
import org.kde.plasma.plasmoid
import org.kde.plasma.plasma5support as Plasma5Support
import org.kde.plasma.private.kicker as Kicker
PlasmoidItem {
id: kicker
anchors.fill: parent
signal reset
signal modelRefreshed
switchWidth: !fullRepresentationItem ? 0 : fullRepresentationItem.Layout.minimumWidth
switchHeight: !fullRepresentationItem ? 0 : fullRepresentationItem.Layout.minimumHeight
fullRepresentation: menuRepresentationComponent
readonly property Component itemListDialogComponent: Component {
ItemListDialog {}
}
property Item dragSource: null
Plasmoid.icon: Plasmoid.configuration.useCustomButtonImage ? Plasmoid.configuration.customButtonImage : Plasmoid.configuration.icon
Component {
id: menuRepresentationComponent
MenuRepresentation {
rootModel: rootModel
itemListDialogComponent: kicker.itemListDialogComponent
onInteractionConcluded: kicker.expanded = false
}
}
JsonMenuModel {
id: rootModel
jsonData: Plasmoid.configuration.menuJson || ""
sorted: false
executable: executable
onRefreshed: {
kicker.modelRefreshed();
}
}
Connections {
target: Plasmoid.configuration
function onMenuJsonChanged() {
rootModel.jsonData = Plasmoid.configuration.menuJson;
}
}
Kicker.DragHelper {
id: dragHelper
dragIconSize: Kirigami.Units.iconSizes.medium
}
Plasma5Support.DataSource {
id: executable
engine: "executable"
connectedSources: []
onNewData: (sourceName) => disconnectSource(sourceName)
function exec(cmd) {
executable.connectSource(cmd)
}
}
Kicker.WindowSystem { // only for X11; TODO Plasma 6.8: remove (also from plasma-workspace)
id: windowSystem
}
Connections {
target: kicker
function onExpandedChanged(expanded) {
if (!expanded) {
kicker.reset();
}
}
}
function resetDragSource() {
dragSource = null;
}
Component.onCompleted: {
if (Plasmoid.hasOwnProperty("activationTogglesExpanded")) {
Plasmoid.activationTogglesExpanded = true
}
rootModel.refreshed.connect(modelRefreshed);
dragHelper.dropped.connect(resetDragSource);
}
}
@@ -0,0 +1,22 @@
{
"KPackageStructure": "Plasma/Applet",
"KPlugin": {
"Authors": [
{
"Name": "51n7"
}
],
"Category": "Application Launchers",
"Description": "A plasmoid (desktop widget) that provides a system menu with essential options, not unlike the apple menu found in MacOS.",
"Icon": "start-here-kde",
"Id": "org.51n7.kMenu",
"License": "GPL-2.0+",
"Name": "kMenu",
"ServiceTypes": [
"Plasma/Applet"
],
"Version": "1.0",
"Website": "https://github.com/51n7/kMenu"
},
"X-Plasma-API-Minimum-Version": "6.0"
}
@@ -0,0 +1,130 @@
# Header entry was created by Lokalize.
#
#: ../contents/config/config.qml:8
# SPDX-FileCopyrightText: 2024 Max le Fou <buttbadger@gmail.com>
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Last-Translator: Max le Fou <buttbadger@gmail.com>\n"
"PO-Revision-Date: 2024-05-15 12:13+0200\n"
"Project-Id-Version: \n"
"Language-Team: French <kde-francophone@kde.org>\n"
"Language: fr\n"
"MIME-Version: 1.0\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
"X-Generator: Lokalize 24.02.2\n"
#: ../contents/config/config.qml:8
msgid "General"
msgstr "Général"
#: ../contents/config/config.qml:14
msgid "Overrides"
msgstr "Remplacements"
#: ../contents/ui/config/ConfigGeneral.qml:49
msgid "Toolbar Icon:"
msgstr "Icône:"
#: ../contents/ui/config/ConfigGeneral.qml:87
msgid "Choose..."
msgstr "Choisir..."
#: ../contents/ui/config/ConfigGeneral.qml:92
msgid "Clear Icon..."
msgstr "Supprimer l'icône"
#: ../contents/ui/config/ConfigGeneral.qml:130
msgid "Show List Icons"
msgstr "Voir la liste des icônes"
#: ../contents/ui/config/ConfigGeneral.qml:136
msgid "Show Menu Items:"
msgstr "Voir les éléments du menu"
#: ../contents/ui/config/ConfigGeneral.qml:140
#: ../contents/ui/main.qml:74
msgid "About This Computer"
msgstr "À propos de l'ordinateur"
#: ../contents/ui/config/ConfigOverrides.qml:26
msgid "About This Computer:"
msgstr "À propos de l'ordinateur :"
#: ../contents/ui/config/ConfigGeneral.qml:144
#: ../contents/ui/main.qml:94
msgid "System Preferences"
msgstr "Préférences"
#: ../contents/ui/config/ConfigOverrides.qml:34
msgid "System Preferences:"
msgstr "Préférences :"
#: ../contents/ui/config/ConfigGeneral.qml:148
#: ../contents/ui/main.qml:102
msgid "App Store"
msgstr "App Store"
#: ../contents/ui/config/ConfigOverrides.qml:42
msgid "App Store:"
msgstr "App Store :"
#: ../contents/ui/config/ConfigGeneral.qml:152
#: ../contents/ui/main.qml:120
msgid "Force Quit"
msgstr "Forcer à quitter"
#: ../contents/ui/config/ConfigOverrides.qml:50
msgid "Force Quit:"
msgstr "Forcer à quitter :"
#: ../contents/ui/config/ConfigGeneral.qml:156
#: ../contents/ui/main.qml:138
msgid "Sleep"
msgstr "Mise en veille"
#: ../contents/ui/config/ConfigOverrides.qml:58
msgid "Sleep:"
msgstr "Mise en veille :"
#: ../contents/ui/config/ConfigGeneral.qml:160
#: ../contents/ui/main.qml:146
msgid "Restart"
msgstr "Redémarrer"
#: ../contents/ui/config/ConfigOverrides.qml:66
msgid "Restart:"
msgstr "Redémarrer :"
#: ../contents/ui/config/ConfigGeneral.qml:164
#: ../contents/ui/main.qml:154
msgid "Shut Down"
msgstr "Éteindre"
#: ../contents/ui/config/ConfigOverrides.qml:74
msgid "Shut Down:"
msgstr "Éteindre :"
#: ../contents/ui/config/ConfigGeneral.qml:168
#: ../contents/ui/main.qml:172
msgid "Lock Screen"
msgstr "Verrouillage écran"
#: ../contents/ui/config/ConfigOverrides.qml:82
msgid "Lock Screen:"
msgstr "Verrouillage écran :"
#: ../contents/ui/config/ConfigGeneral.qml:172
#: ../contents/ui/main.qml:180
msgid "Log Out"
msgstr "Déconnexion"
#: ../contents/ui/config/ConfigOverrides.qml:90
msgid "Log Out:"
msgstr "Déconnexion :"
#: ../contents/ui/config/ConfigGeneral.qml:180
msgid "Size:"
msgstr "Taille :"
@@ -0,0 +1,112 @@
#: ../contents/config/config.qml:8
msgid "General"
msgstr ""
#: ../contents/config/config.qml:14
msgid "Overrides"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:49
msgid "Toolbar Icon:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:87
msgid "Choose..."
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:92
msgid "Clear Icon..."
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:130
msgid "Show List Icons"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:136
msgid "Show Menu Items:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:140
#: ../contents/ui/main.qml:74
msgid "About This Computer"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:26
msgid "About This Computer:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:144
#: ../contents/ui/main.qml:94
msgid "System Preferences"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:34
msgid "System Preferences:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:148
#: ../contents/ui/main.qml:102
msgid "App Store"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:42
msgid "App Store:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:152
#: ../contents/ui/main.qml:120
msgid "Force Quit"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:50
msgid "Force Quit:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:156
#: ../contents/ui/main.qml:138
msgid "Sleep"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:58
msgid "Sleep:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:160
#: ../contents/ui/main.qml:146
msgid "Restart"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:66
msgid "Restart:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:164
#: ../contents/ui/main.qml:154
msgid "Shut Down"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:74
msgid "Shut Down:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:168
#: ../contents/ui/main.qml:172
msgid "Lock Screen"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:82
msgid "Lock Screen:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:172
#: ../contents/ui/main.qml:180
msgid "Log Out"
msgstr ""
#: ../contents/ui/config/ConfigOverrides.qml:90
msgid "Log Out:"
msgstr ""
#: ../contents/ui/config/ConfigGeneral.qml:180
msgid "Size:"
msgstr ""
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 3 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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,212 @@
# Claude Usage Widget
A KDE Plasma 6 widget that displays your Claude Code usage statistics in the taskbar.
![Popup](screenshots/popup.png)
## Features
- **Compact Panel Display**: Shows session and weekly usage percentages right in your taskbar
![Panel](screenshots/panel.png)
- **Color-coded Indicators**: Green (<50%), Yellow (<80%), Red (≥80%)
- **Detailed Popup**: Click to see full statistics
- Session and weekly usage with progress bars
- Reset times for both limits
- Per-model breakdown (Sonnet/Opus)
- Your subscription plan badge
- **Configurable Refresh**: Default 5 min polling (adjustable in settings)
- **Smart Rate Limit Handling**: Uses `retry-after` header, exponential backoff, and token watcher for automatic recovery
- **Local Cache**: Remembers last data on restart (up to 24h)
- **Stale Detection**: Widget dims when data is outdated
- **Error Handling**: Clear messages when not logged in, token expired, or rate limited
- **Custom API Support**: Optional proxy/gateway with custom base URL and API key
- **15 Languages**: EN, HU, DE, FR, ES, IT, PT, RU, PL, NL, TR, JA, KO, ZH-CN, ZH-TW
- **No Dependencies**: Pure QML, no Python or external tools required
## Requirements
- KDE Plasma 6.0 or later
- Claude Code CLI installed and logged in
## Installation
### From KDE Store
1. Right-click on your panel
2. Select "Add Widgets..."
3. Click "Get New Widgets..." > "Download New Plasma Widgets..."
4. Search for "Claude Usage"
5. Click Install
### Manual Installation
```bash
kpackagetool6 -t Plasma/Applet -i claude-usage-widget.plasmoid
```
### From Source
```bash
git clone https://github.com/izll/plasma-claude-usage.git
cd claude-usage-widget
kpackagetool6 -t Plasma/Applet -i .
```
## Usage
1. Make sure you're logged in to Claude Code (run `claude` in terminal)
2. Add the widget to your panel
3. Click the widget to see detailed usage statistics
## Configuration
Right-click the widget and select **Configure...** to open the settings.
### Custom API Base URL (optional)
By default the widget reads your OAuth credentials from `~/.claude/.credentials.json` and calls `https://api.anthropic.com` directly — no configuration needed.
If you use a custom API proxy or gateway, you can override this:
| Setting | Description |
|---|---|
| **Base URL** | Your proxy URL, e.g. `https://your-proxy.example.com` |
| **API key** | Your `ANTHROPIC_API_KEY` |
> **Note:** The widget calls `/api/oauth/usage`, not the standard `/v1/messages` endpoint. Use the root URL without any path suffix — e.g. `https://api.anthropic.com`, not `https://api.anthropic.com/v1`.
When a base URL is configured, the widget authenticates with `x-api-key` instead of the OAuth token. Leave the Base URL field empty to go back to the default credentials file method.
## How It Works
The widget calls the Anthropic usage API directly from QML. No data is stored or sent anywhere else.
### API Endpoint
```
GET https://api.anthropic.com/api/oauth/usage
Headers:
Authorization: Bearer <oauth-token> (default mode)
x-api-key: <api-key> (custom base URL mode)
anthropic-beta: oauth-2025-04-20
```
## Troubleshooting
### "Not logged in" error
Make sure you're logged in to Claude Code:
```bash
claude
```
### "Token expired" error
Your OAuth token has expired. Run Claude Code again to refresh it:
```bash
claude
```
The widget also has an "Open Claude" button for this.
### "Rate limited" error
The API allows ~4 requests per 5-minute window. The widget handles this automatically:
- Reads the `retry-after` header and waits the specified time
- Falls back to exponential backoff (5/10/15 min)
- Monitors for token refresh and recovers instantly
To avoid rate limiting, keep the refresh interval at 5 minutes or higher.
### "Invalid API key" error
The API key in the widget settings is wrong or revoked. Open **Configure...** and update it.
### "Endpoint not found — check base URL" error
The base URL in the widget settings doesn't point to a valid API. Make sure you're using the root URL without `/v1`, e.g. `https://api.anthropic.com`.
### Widget shows 0%
- Click the refresh button in the popup
- Check logs: `journalctl --user -f | grep -i claude`
## File Structure
```
claude-usage-widget/
├── metadata.json # Widget metadata
├── install.sh # Installation script
├── contents/
│ ├── config/
│ │ └── main.xml # Configuration schema
│ ├── ui/
│ │ ├── main.qml # Widget implementation
│ │ ├── configGeneral.qml # Settings UI
│ │ └── Translations.qml # i18n (15 languages)
│ └── icons/
│ └── claude.svg # Claude logo (orange)
└── screenshots/ # Preview images
```
## License
GPL-3.0-or-later
## Author
izll
## Version History
### 1.3.6 (2026)
- Vertical layout option for taller panels (thanks @nahall, issue #5)
- Panel metrics can now be stacked vertically to save horizontal space
### 1.3.5 (2026)
- Widget picker now shows proper preview image (progress ring + Claude logo + USAGE)
- About page shows correct icon via auto-install to system icon theme
- New `contents/screenshot.png` for KPackage widget picker preview
### 1.3.2 (2026)
- Fix widget icon not showing in panel widget picker dialog
### 1.3.1 (2026)
- Configurable background opacity for desktop mode (thanks @Endle)
- Background opacity only applies on desktop, panel keeps default Plasma theme
- Default opacity set to 100% for consistent upgrade experience
### 1.3.0 (2026)
- Three panel display styles: Text (classic), Circular (ring charts), Bar (vertical bars)
- Claude icon can be hidden in panel
- Tooltip shows all enabled metrics
### 1.2.5 (2026)
- Configurable panel metrics: choose Session, Weekly, Sonnet independently
- Sonnet weekly usage can now be displayed in the panel (off by default)
### 1.2.1 (2026)
- Remove false decimal precision from percentage displays (thanks @robinpie)
### 1.2.0 (2026)
- Smart rate limit handling with `retry-after` header support
- Exponential backoff with automatic recovery
- Token watcher: instantly recovers when Claude Code refreshes the token
- Local data cache: shows last known values on restart (up to 24h)
- Stale detection: widget dims when data is outdated
- Default refresh interval changed to 5 min to prevent rate limiting
- Rate limit warning in popup and settings for intervals under 5 min
### 1.1.0 (2026)
- Custom API base URL and API key support for proxy/gateway users
- 429 rate limit handling with auto-retry
- Token expired state with "Open Claude" button
- Dynamic Claude Code version detection for User-Agent
- All strings translated across 15 languages
- Install script added
### 1.0.0 (2025)
- Initial release
- Session and weekly usage display
- Per-model breakdown (Sonnet/Opus)
- Configurable refresh interval
- Error handling for login issues
@@ -0,0 +1,15 @@
/*
SPDX-FileCopyrightText: 2025 izll
SPDX-License-Identifier: GPL-3.0-or-later
*/
import QtQuick
import org.kde.plasma.configuration
ConfigModel {
ConfigCategory {
name: i18n("General")
icon: "configure"
source: "configGeneral.qml"
}
}
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0
http://www.kde.org/standards/kcfg/1.0/kcfg.xsd">
<kcfgfile name=""/>
<group name="General">
<entry name="language" type="String">
<label>UI Language</label>
<default>system</default>
</entry>
<entry name="refreshInterval" type="Int">
<label>Refresh interval in minutes</label>
<default>5</default>
</entry>
<entry name="panelLayout" type="String">
<label>Panel layout direction (horizontal or vertical)</label>
<default>horizontal</default>
</entry>
<entry name="showIcon" type="Bool">
<label>Show Claude icon in panel</label>
<default>true</default>
</entry>
<entry name="panelStyle" type="String">
<label>Panel display style (text or circular)</label>
<default>text</default>
</entry>
<entry name="showSession" type="Bool">
<label>Show session (5hr) usage in panel</label>
<default>true</default>
</entry>
<entry name="showWeekly" type="Bool">
<label>Show weekly (7day) usage in panel</label>
<default>true</default>
</entry>
<entry name="showSonnet" type="Bool">
<label>Show Sonnet weekly usage in panel</label>
<default>false</default>
</entry>
<entry name="baseUrl" type="String">
<label>Custom API base URL (leave empty to use ~/.claude/.credentials.json)</label>
<default></default>
</entry>
<entry name="apiKey" type="String">
<label>API key (required when custom base URL is set)</label>
<default></default>
</entry>
<entry name="backgroundOpacity" type="Double">
<label>Background opacity (0.0 = transparent, 1.0 = opaque)</label>
<default>1.0</default>
</entry>
</group>
</kcfg>
@@ -0,0 +1,26 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<defs>
<linearGradient id="progressGrad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#4ade80"/>
<stop offset="50%" style="stop-color:#facc15"/>
<stop offset="100%" style="stop-color:#ef4444"/>
</linearGradient>
</defs>
<!-- Outer progress ring (background) -->
<circle cx="256" cy="256" r="180" fill="none" stroke="currentColor" stroke-width="28" opacity="0.2"/>
<!-- Progress arc (showing ~70% usage) -->
<circle cx="256" cy="256" r="180" fill="none" stroke="url(#progressGrad)" stroke-width="28"
stroke-linecap="round" stroke-dasharray="792 1131"
transform="rotate(-90 256 256)"/>
<!-- Claude logo (scaled and centered) - orange color -->
<g transform="translate(136, 136) scale(15)" fill="#D97757">
<path d="m3.127 10.604 3.135-1.76.053-.153-.053-.085H6.11l-.525-.032-1.791-.048-1.554-.065-1.505-.08-.38-.081L0 7.832l.036-.234.32-.214.455.04 1.009.069 1.513.105 1.097.064 1.626.17h.259l.036-.105-.089-.065-.068-.064-1.566-1.062-1.695-1.121-.887-.646-.48-.327-.243-.306-.104-.67.435-.48.585.04.15.04.593.456 1.267.981 1.654 1.218.242.202.097-.068.012-.049-.109-.181-.9-1.626-.96-1.655-.428-.686-.113-.411a2 2 0 0 1-.068-.484l.496-.674L4.446 0l.662.089.279.242.411.94.666 1.48 1.033 2.014.302.597.162.553.06.17h.105v-.097l.085-1.134.157-1.392.154-1.792.052-.504.25-.605.497-.327.387.186.319.456-.045.294-.19 1.23-.37 1.93-.243 1.29h.142l.161-.16.654-.868 1.097-1.372.484-.545.565-.601.363-.287h.686l.505.751-.226.775-.707.895-.585.759-.839 1.13-.524.904.048.072.125-.012 1.897-.403 1.024-.186 1.223-.21.553.258.06.263-.218.536-1.307.323-1.533.307-2.284.54-.028.02.032.04 1.029.098.44.024h1.077l2.005.15.525.346.315.424-.053.323-.807.411-3.631-.863-.872-.218h-.12v.073l.726.71 1.331 1.202 1.667 1.55.084.383-.214.302-.226-.032-1.464-1.101-.565-.497-1.28-1.077h-.084v.113l.295.432 1.557 2.34.08.718-.112.234-.404.141-.444-.08-.911-1.28-.94-1.44-.759-1.291-.093.053-.448 4.821-.21.246-.484.186-.403-.307-.214-.496.214-.98.258-1.28.21-1.016.19-1.263.112-.42-.008-.028-.092.012-.953 1.307-1.448 1.957-1.146 1.227-.274.109-.477-.247.045-.44.266-.39 1.586-2.018.956-1.25.617-.723-.004-.105h-.036l-4.212 2.736-.75.096-.324-.302.04-.496.154-.162 1.267-.871z"/>
</g>
<!-- Usage label with background -->
<rect x="156" y="380" width="200" height="56" rx="12" ry="12" fill="#1e293b" stroke="#475569" stroke-width="2"/>
<text x="256" y="423" text-anchor="middle" font-family="Arial, sans-serif" font-size="42" font-weight="bold" fill="#e2e8f0">USAGE</text>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#D97757" class="bi bi-claude" viewBox="0 0 16 16">
<path d="m3.127 10.604 3.135-1.76.053-.153-.053-.085H6.11l-.525-.032-1.791-.048-1.554-.065-1.505-.08-.38-.081L0 7.832l.036-.234.32-.214.455.04 1.009.069 1.513.105 1.097.064 1.626.17h.259l.036-.105-.089-.065-.068-.064-1.566-1.062-1.695-1.121-.887-.646-.48-.327-.243-.306-.104-.67.435-.48.585.04.15.04.593.456 1.267.981 1.654 1.218.242.202.097-.068.012-.049-.109-.181-.9-1.626-.96-1.655-.428-.686-.113-.411a2 2 0 0 1-.068-.484l.496-.674L4.446 0l.662.089.279.242.411.94.666 1.48 1.033 2.014.302.597.162.553.06.17h.105v-.097l.085-1.134.157-1.392.154-1.792.052-.504.25-.605.497-.327.387.186.319.456-.045.294-.19 1.23-.37 1.93-.243 1.29h.142l.161-.16.654-.868 1.097-1.372.484-.545.565-.601.363-.287h.686l.505.751-.226.775-.707.895-.585.759-.839 1.13-.524.904.048.072.125-.012 1.897-.403 1.024-.186 1.223-.21.553.258.06.263-.218.536-1.307.323-1.533.307-2.284.54-.028.02.032.04 1.029.098.44.024h1.077l2.005.15.525.346.315.424-.053.323-.807.411-3.631-.863-.872-.218h-.12v.073l.726.71 1.331 1.202 1.667 1.55.084.383-.214.302-.226-.032-1.464-1.101-.565-.497-1.28-1.077h-.084v.113l.295.432 1.557 2.34.08.718-.112.234-.404.141-.444-.08-.911-1.28-.94-1.44-.759-1.291-.093.053-.448 4.821-.21.246-.484.186-.403-.307-.214-.496.214-.98.258-1.28.21-1.016.19-1.263.112-.42-.008-.028-.092.012-.953 1.307-1.448 1.957-1.146 1.227-.274.109-.477-.247.045-.44.266-.39 1.586-2.018.956-1.25.617-.723-.004-.105h-.036l-4.212 2.736-.75.096-.324-.302.04-.496.154-.162 1.267-.871z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -0,0 +1,22 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48">
<defs>
<linearGradient id="progressGrad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#4ade80"/>
<stop offset="50%" style="stop-color:#facc15"/>
<stop offset="100%" style="stop-color:#ef4444"/>
</linearGradient>
</defs>
<!-- Progress ring background -->
<circle cx="24" cy="24" r="20" fill="none" stroke="currentColor" stroke-width="3" opacity="0.2"/>
<!-- Progress arc -->
<circle cx="24" cy="24" r="20" fill="none" stroke="url(#progressGrad)" stroke-width="3"
stroke-linecap="round" stroke-dasharray="88 126"
transform="rotate(-90 24 24)"/>
<!-- Claude logo (scaled) -->
<g transform="translate(9, 9) scale(1.875)" fill="#D97757">
<path d="m3.127 10.604 3.135-1.76.053-.153-.053-.085H6.11l-.525-.032-1.791-.048-1.554-.065-1.505-.08-.38-.081L0 7.832l.036-.234.32-.214.455.04 1.009.069 1.513.105 1.097.064 1.626.17h.259l.036-.105-.089-.065-.068-.064-1.566-1.062-1.695-1.121-.887-.646-.48-.327-.243-.306-.104-.67.435-.48.585.04.15.04.593.456 1.267.981 1.654 1.218.242.202.097-.068.012-.049-.109-.181-.9-1.626-.96-1.655-.428-.686-.113-.411a2 2 0 0 1-.068-.484l.496-.674L4.446 0l.662.089.279.242.411.94.666 1.48 1.033 2.014.302.597.162.553.06.17h.105v-.097l.085-1.134.157-1.392.154-1.792.052-.504.25-.605.497-.327.387.186.319.456-.045.294-.19 1.23-.37 1.93-.243 1.29h.142l.161-.16.654-.868 1.097-1.372.484-.545.565-.601.363-.287h.686l.505.751-.226.775-.707.895-.585.759-.839 1.13-.524.904.048.072.125-.012 1.897-.403 1.024-.186 1.223-.21.553.258.06.263-.218.536-1.307.323-1.533.307-2.284.54-.028.02.032.04 1.029.098.44.024h1.077l2.005.15.525.346.315.424-.053.323-.807.411-3.631-.863-.872-.218h-.12v.073l.726.71 1.331 1.202 1.667 1.55.084.383-.214.302-.226-.032-1.464-1.101-.565-.497-1.28-1.077h-.084v.113l.295.432 1.557 2.34.08.718-.112.234-.404.141-.444-.08-.911-1.28-.94-1.44-.759-1.291-.093.053-.448 4.821-.21.246-.484.186-.403-.307-.214-.496.214-.98.258-1.28.21-1.016.19-1.263.112-.42-.008-.028-.092.012-.953 1.307-1.448 1.957-1.146 1.227-.274.109-.477-.247.045-.44.266-.39 1.586-2.018.956-1.25.617-.723-.004-.105h-.036l-4.212 2.736-.75.096-.324-.302.04-.496.154-.162 1.267-.871z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

@@ -0,0 +1,790 @@
/*
SPDX-FileCopyrightText: 2025 izll
SPDX-License-Identifier: GPL-3.0-or-later
*/
import QtQuick
QtObject {
id: translations
property string currentLanguage: "system"
property int version: 0
onCurrentLanguageChanged: {
version++;
}
readonly property var strings: ({
"en_US": {
"Claude Usage": "Claude Usage",
"Session (5hr)": "Session (5hr)",
"Weekly (7day)": "Weekly (7day)",
"By Model (Weekly)": "By Model (Weekly)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Resets at:",
"Resets:": "Resets:",
"Updated:": "Updated:",
"Loading...": "Loading...",
"Refresh": "Refresh",
"Not logged in": "Not logged in",
"Token expired": "Token expired",
"API error": "API error",
"Run 'claude' to log in": "Run 'claude' to log in",
"No model breakdown available": "No model breakdown available",
"Language:": "Language:",
"System default": "System default",
"d": "d",
"h": "h",
"m": "m",
"Refresh interval:": "Refresh interval:",
"minutes": "minutes",
"Open Claude": "Open Claude",
"Rate limited": "Rate limited",
"Auto-retry in 1 min": "Auto-retry in 1 min",
"Custom API (optional)": "Custom API (optional)",
"Base URL:": "Base URL:",
"API key:": "API key:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Leave empty to use ~/.claude/.credentials.json (default)",
"Check base URL and API key in widget settings": "Check base URL and API key in widget settings",
"API key not configured": "API key not configured",
"Invalid API key": "Invalid API key",
"Endpoint not found": "Endpoint not found",
"Values under 5 min may cause rate limiting": "Values under 5 min may cause rate limiting",
"Panel display": "Panel display",
"Show in panel:": "Show in panel:",
"Icon:": "Icon:",
"Show Claude icon": "Show Claude icon",
"Style:": "Style:",
"Text": "Text",
"Circular": "Circular",
"Bar": "Bar",
"Layout:": "Layout:",
"Horizontal": "Horizontal",
"Vertical": "Vertical",
"Background opacity (desktop):": "Background opacity (desktop):"
},
"hu_HU": {
"Claude Usage": "Claude használat",
"Session (5hr)": "Munkamenet (5 óra)",
"Weekly (7day)": "Heti (7 nap)",
"By Model (Weekly)": "Modell szerint (Heti)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Visszaáll:",
"Resets:": "Visszaáll:",
"Updated:": "Frissítve:",
"Loading...": "Betöltés...",
"Refresh": "Frissítés",
"Not logged in": "Nincs bejelentkezve",
"Token expired": "Lejárt token",
"API error": "API hiba",
"Run 'claude' to log in": "Futtasd a 'claude' parancsot",
"No model breakdown available": "Nincs modell bontás",
"Language:": "Nyelv:",
"System default": "Rendszer alapértelmezett",
"d": "n",
"h": "ó",
"m": "p",
"Refresh interval:": "Frissítési gyakoriság:",
"minutes": "perc",
"Open Claude": "Claude megnyitása",
"Rate limited": "Korlát elérve",
"Auto-retry in 1 min": "Automatikus újrapróbálás 1 perc múlva",
"Custom API (optional)": "Egyéni API (opcionális)",
"Base URL:": "Alap URL:",
"API key:": "API kulcs:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Hagyd üresen a ~/.claude/.credentials.json használatához (alapértelmezett)",
"Check base URL and API key in widget settings": "Ellenőrizd az alap URL-t és API kulcsot a widget beállításokban",
"API key not configured": "API kulcs nincs beállítva",
"Invalid API key": "Érvénytelen API kulcs",
"Endpoint not found": "Végpont nem található",
"Values under 5 min may cause rate limiting": "5 perc alatti értékek rate limitet okozhatnak",
"Panel display": "Panel megjelenítés",
"Show in panel:": "Megjelenítés a panelen:",
"Icon:": "Ikon:",
"Show Claude icon": "Claude ikon megjelenítése",
"Style:": "Stílus:",
"Text": "Szöveges",
"Circular": "Kördiagram",
"Bar": "Sávdiagram",
"Layout:": "Elrendezés:",
"Horizontal": "Vízszintes",
"Vertical": "Függőleges",
"Background opacity (desktop):": "Háttér átlátszóság (asztal):"
},
"de_DE": {
"Claude Usage": "Claude Nutzung",
"Session (5hr)": "Sitzung (5 Std)",
"Weekly (7day)": "Wöchentlich (7 Tage)",
"By Model (Weekly)": "Nach Modell (Wöchentlich)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Setzt zurück um:",
"Resets:": "Setzt zurück:",
"Updated:": "Aktualisiert:",
"Loading...": "Laden...",
"Refresh": "Aktualisieren",
"Not logged in": "Nicht angemeldet",
"Token expired": "Token abgelaufen",
"API error": "API-Fehler",
"Run 'claude' to log in": "Führen Sie 'claude' aus",
"No model breakdown available": "Keine Modellaufschlüsselung verfügbar",
"Language:": "Sprache:",
"System default": "Systemstandard",
"d": "T",
"h": "Std",
"m": "Min",
"Refresh interval:": "Aktualisierungsintervall:",
"minutes": "Minuten",
"Open Claude": "Claude öffnen",
"Rate limited": "Rate-Limit erreicht",
"Auto-retry in 1 min": "Automatische Wiederholung in 1 Min",
"Custom API (optional)": "Benutzerdefinierte API (optional)",
"Base URL:": "Basis-URL:",
"API key:": "API-Schlüssel:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Leer lassen für ~/.claude/.credentials.json (Standard)",
"Check base URL and API key in widget settings": "Überprüfen Sie Basis-URL und API-Schlüssel in den Widget-Einstellungen",
"API key not configured": "API-Schlüssel nicht konfiguriert",
"Invalid API key": "Ungültiger API-Schlüssel",
"Endpoint not found": "Endpunkt nicht gefunden",
"Values under 5 min may cause rate limiting": "Werte unter 5 Min können Rate-Limiting verursachen",
"Panel display": "Panel-Anzeige",
"Show in panel:": "Im Panel anzeigen:",
"Icon:": "Symbol:",
"Show Claude icon": "Claude-Symbol anzeigen",
"Style:": "Stil:",
"Text": "Text",
"Circular": "Kreisförmig",
"Bar": "Balken",
"Layout:": "Layout:",
"Horizontal": "Horizontal",
"Vertical": "Vertikal",
"Background opacity (desktop):": "Hintergrund-Deckkraft (Desktop):"
},
"fr_FR": {
"Claude Usage": "Utilisation Claude",
"Session (5hr)": "Session (5h)",
"Weekly (7day)": "Hebdomadaire (7j)",
"By Model (Weekly)": "Par modèle (Hebdo)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Réinitialisation à:",
"Resets:": "Réinitialisation:",
"Updated:": "Mis à jour:",
"Loading...": "Chargement...",
"Refresh": "Actualiser",
"Not logged in": "Non connecté",
"Token expired": "Token expiré",
"API error": "Erreur API",
"Run 'claude' to log in": "Exécutez 'claude' pour vous connecter",
"No model breakdown available": "Pas de détail par modèle",
"Language:": "Langue:",
"System default": "Système par défaut",
"d": "j",
"h": "h",
"m": "min",
"Refresh interval:": "Intervalle de rafraîchissement:",
"minutes": "minutes",
"Open Claude": "Ouvrir Claude",
"Rate limited": "Limite atteinte",
"Auto-retry in 1 min": "Nouvel essai auto dans 1 min",
"Custom API (optional)": "API personnalisée (optionnel)",
"Base URL:": "URL de base:",
"API key:": "Clé API:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Laisser vide pour utiliser ~/.claude/.credentials.json (par défaut)",
"Check base URL and API key in widget settings": "Vérifiez l'URL de base et la clé API dans les paramètres",
"API key not configured": "Clé API non configurée",
"Invalid API key": "Clé API invalide",
"Endpoint not found": "Point d'accès introuvable",
"Values under 5 min may cause rate limiting": "Les valeurs inférieures à 5 min peuvent causer un rate limiting",
"Panel display": "Affichage du panneau",
"Show in panel:": "Afficher dans le panneau:",
"Icon:": "Icône:",
"Show Claude icon": "Afficher l'icône Claude",
"Style:": "Style:",
"Text": "Texte",
"Circular": "Circulaire",
"Bar": "Barre",
"Layout:": "Disposition:",
"Horizontal": "Horizontal",
"Vertical": "Vertical",
"Background opacity (desktop):": "Opacité du fond (bureau):"
},
"es_ES": {
"Claude Usage": "Uso de Claude",
"Session (5hr)": "Sesión (5h)",
"Weekly (7day)": "Semanal (7 días)",
"By Model (Weekly)": "Por modelo (Semanal)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Se reinicia a las:",
"Resets:": "Se reinicia:",
"Updated:": "Actualizado:",
"Loading...": "Cargando...",
"Refresh": "Actualizar",
"Not logged in": "No conectado",
"Token expired": "Token expirado",
"API error": "Error de API",
"Run 'claude' to log in": "Ejecuta 'claude' para iniciar sesión",
"No model breakdown available": "Sin desglose por modelo",
"Language:": "Idioma:",
"System default": "Predeterminado del sistema",
"d": "d",
"h": "h",
"m": "min",
"Refresh interval:": "Intervalo de actualización:",
"minutes": "minutos",
"Open Claude": "Abrir Claude",
"Rate limited": "Límite alcanzado",
"Auto-retry in 1 min": "Reintento automático en 1 min",
"Custom API (optional)": "API personalizada (opcional)",
"Base URL:": "URL base:",
"API key:": "Clave API:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Dejar vacío para usar ~/.claude/.credentials.json (predeterminado)",
"Check base URL and API key in widget settings": "Verifica la URL base y la clave API en la configuración del widget",
"API key not configured": "Clave API no configurada",
"Invalid API key": "Clave API inválida",
"Endpoint not found": "Punto de acceso no encontrado",
"Values under 5 min may cause rate limiting": "Valores menores a 5 min pueden causar rate limiting",
"Panel display": "Visualización del panel",
"Show in panel:": "Mostrar en el panel:",
"Icon:": "Icono:",
"Show Claude icon": "Mostrar icono de Claude",
"Style:": "Estilo:",
"Text": "Texto",
"Circular": "Circular",
"Bar": "Barra",
"Layout:": "Disposición:",
"Horizontal": "Horizontal",
"Vertical": "Vertical",
"Background opacity (desktop):": "Opacidad del fondo (escritorio):"
},
"it_IT": {
"Claude Usage": "Utilizzo Claude",
"Session (5hr)": "Sessione (5h)",
"Weekly (7day)": "Settimanale (7gg)",
"By Model (Weekly)": "Per modello (Settimanale)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Si azzera alle:",
"Resets:": "Si azzera:",
"Updated:": "Aggiornato:",
"Loading...": "Caricamento...",
"Refresh": "Aggiorna",
"Not logged in": "Non connesso",
"Token expired": "Token scaduto",
"API error": "Errore API",
"Run 'claude' to log in": "Esegui 'claude' per accedere",
"No model breakdown available": "Nessun dettaglio per modello",
"Language:": "Lingua:",
"System default": "Predefinito di sistema",
"d": "g",
"h": "h",
"m": "min",
"Refresh interval:": "Intervallo di aggiornamento:",
"minutes": "minuti",
"Open Claude": "Apri Claude",
"Rate limited": "Limite raggiunto",
"Auto-retry in 1 min": "Riprova automatica tra 1 min",
"Custom API (optional)": "API personalizzata (opzionale)",
"Base URL:": "URL base:",
"API key:": "Chiave API:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Lasciare vuoto per usare ~/.claude/.credentials.json (predefinito)",
"Check base URL and API key in widget settings": "Controlla URL base e chiave API nelle impostazioni del widget",
"API key not configured": "Chiave API non configurata",
"Invalid API key": "Chiave API non valida",
"Endpoint not found": "Endpoint non trovato",
"Values under 5 min may cause rate limiting": "Valori sotto 5 min possono causare rate limiting",
"Panel display": "Visualizzazione pannello",
"Show in panel:": "Mostra nel pannello:",
"Icon:": "Icona:",
"Show Claude icon": "Mostra icona Claude",
"Style:": "Stile:",
"Text": "Testo",
"Circular": "Circolare",
"Bar": "Barra",
"Layout:": "Disposizione:",
"Horizontal": "Orizzontale",
"Vertical": "Verticale",
"Background opacity (desktop):": "Opacità sfondo (desktop):"
},
"pt_BR": {
"Claude Usage": "Uso do Claude",
"Session (5hr)": "Sessão (5h)",
"Weekly (7day)": "Semanal (7 dias)",
"By Model (Weekly)": "Por modelo (Semanal)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Reinicia às:",
"Resets:": "Reinicia:",
"Updated:": "Atualizado:",
"Loading...": "Carregando...",
"Refresh": "Atualizar",
"Not logged in": "Não conectado",
"Token expired": "Token expirado",
"API error": "Erro de API",
"Run 'claude' to log in": "Execute 'claude' para fazer login",
"No model breakdown available": "Sem detalhamento por modelo",
"Language:": "Idioma:",
"System default": "Padrão do sistema",
"d": "d",
"h": "h",
"m": "min",
"Refresh interval:": "Intervalo de atualização:",
"minutes": "minutos",
"Open Claude": "Abrir Claude",
"Rate limited": "Limite atingido",
"Auto-retry in 1 min": "Tentativa automática em 1 min",
"Custom API (optional)": "API personalizada (opcional)",
"Base URL:": "URL base:",
"API key:": "Chave API:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Deixe vazio para usar ~/.claude/.credentials.json (padrão)",
"Check base URL and API key in widget settings": "Verifique a URL base e a chave API nas configurações do widget",
"API key not configured": "Chave API não configurada",
"Invalid API key": "Chave API inválida",
"Endpoint not found": "Endpoint não encontrado",
"Values under 5 min may cause rate limiting": "Valores abaixo de 5 min podem causar rate limiting",
"Panel display": "Exibição do painel",
"Show in panel:": "Mostrar no painel:",
"Icon:": "Ícone:",
"Show Claude icon": "Mostrar ícone do Claude",
"Style:": "Estilo:",
"Text": "Texto",
"Circular": "Circular",
"Bar": "Barra",
"Layout:": "Layout:",
"Horizontal": "Horizontal",
"Vertical": "Vertical",
"Background opacity (desktop):": "Opacidade do fundo (área de trabalho):"
},
"ru_RU": {
"Claude Usage": "Использование Claude",
"Session (5hr)": "Сессия (5ч)",
"Weekly (7day)": "Неделя (7 дней)",
"By Model (Weekly)": "По модели (Неделя)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Сброс в:",
"Resets:": "Сброс:",
"Updated:": "Обновлено:",
"Loading...": "Загрузка...",
"Refresh": "Обновить",
"Not logged in": "Не авторизован",
"Token expired": "Токен истёк",
"API error": "Ошибка API",
"Run 'claude' to log in": "Запустите 'claude' для входа",
"No model breakdown available": "Нет данных по моделям",
"Language:": "Язык:",
"System default": "По умолчанию системы",
"d": "д",
"h": "ч",
"m": "мин",
"Refresh interval:": "Интервал обновления:",
"minutes": "минут",
"Open Claude": "Открыть Claude",
"Rate limited": "Лимит достигнут",
"Auto-retry in 1 min": "Автоповтор через 1 мин",
"Custom API (optional)": "Пользовательский API (необязательно)",
"Base URL:": "Базовый URL:",
"API key:": "API ключ:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Оставьте пустым для ~/.claude/.credentials.json (по умолчанию)",
"Check base URL and API key in widget settings": "Проверьте базовый URL и API ключ в настройках виджета",
"API key not configured": "API ключ не настроен",
"Invalid API key": "Неверный API ключ",
"Endpoint not found": "Конечная точка не найдена",
"Values under 5 min may cause rate limiting": "Значения менее 5 мин могут вызвать ограничение запросов",
"Panel display": "Отображение панели",
"Show in panel:": "Показывать в панели:",
"Icon:": "Иконка:",
"Show Claude icon": "Показать иконку Claude",
"Style:": "Стиль:",
"Text": "Текст",
"Circular": "Круговой",
"Bar": "Столбик",
"Layout:": "Расположение:",
"Horizontal": "Горизонтально",
"Vertical": "Вертикально",
"Background opacity (desktop):": "Прозрачность фона (рабочий стол):"
},
"pl_PL": {
"Claude Usage": "Użycie Claude",
"Session (5hr)": "Sesja (5h)",
"Weekly (7day)": "Tygodniowo (7 dni)",
"By Model (Weekly)": "Wg modelu (Tygodniowo)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Resetuje o:",
"Resets:": "Resetuje:",
"Updated:": "Zaktualizowano:",
"Loading...": "Ładowanie...",
"Refresh": "Odśwież",
"Not logged in": "Nie zalogowany",
"Token expired": "Token wygasł",
"API error": "Błąd API",
"Run 'claude' to log in": "Uruchom 'claude' aby się zalogować",
"No model breakdown available": "Brak podziału na modele",
"Language:": "Język:",
"System default": "Domyślny systemowy",
"d": "d",
"h": "g",
"m": "min",
"Refresh interval:": "Częstotliwość odświeżania:",
"minutes": "minut",
"Open Claude": "Otwórz Claude",
"Rate limited": "Limit osiągnięty",
"Auto-retry in 1 min": "Automatyczne ponowienie za 1 min",
"Custom API (optional)": "Własne API (opcjonalne)",
"Base URL:": "Bazowy URL:",
"API key:": "Klucz API:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Pozostaw puste aby użyć ~/.claude/.credentials.json (domyślne)",
"Check base URL and API key in widget settings": "Sprawdź bazowy URL i klucz API w ustawieniach widgetu",
"API key not configured": "Klucz API nie skonfigurowany",
"Invalid API key": "Nieprawidłowy klucz API",
"Endpoint not found": "Punkt końcowy nie znaleziony",
"Values under 5 min may cause rate limiting": "Wartości poniżej 5 min mogą powodować rate limiting",
"Panel display": "Wyświetlanie panelu",
"Show in panel:": "Pokaż w panelu:",
"Icon:": "Ikona:",
"Show Claude icon": "Pokaż ikonę Claude",
"Style:": "Styl:",
"Text": "Tekst",
"Circular": "Kołowy",
"Bar": "Pasek",
"Layout:": "Układ:",
"Horizontal": "Poziomy",
"Vertical": "Pionowy",
"Background opacity (desktop):": "Przezroczystość tła (pulpit):"
},
"nl_NL": {
"Claude Usage": "Claude Gebruik",
"Session (5hr)": "Sessie (5u)",
"Weekly (7day)": "Wekelijks (7 dagen)",
"By Model (Weekly)": "Per model (Wekelijks)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Reset om:",
"Resets:": "Reset:",
"Updated:": "Bijgewerkt:",
"Loading...": "Laden...",
"Refresh": "Vernieuwen",
"Not logged in": "Niet ingelogd",
"Token expired": "Token verlopen",
"API error": "API-fout",
"Run 'claude' to log in": "Voer 'claude' uit om in te loggen",
"No model breakdown available": "Geen modeluitsplitsing beschikbaar",
"Language:": "Taal:",
"System default": "Systeemstandaard",
"d": "d",
"h": "u",
"m": "min",
"Refresh interval:": "Vernieuwingsinterval:",
"minutes": "minuten",
"Open Claude": "Claude openen",
"Rate limited": "Limiet bereikt",
"Auto-retry in 1 min": "Automatisch opnieuw over 1 min",
"Custom API (optional)": "Aangepaste API (optioneel)",
"Base URL:": "Basis-URL:",
"API key:": "API-sleutel:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Laat leeg om ~/.claude/.credentials.json te gebruiken (standaard)",
"Check base URL and API key in widget settings": "Controleer basis-URL en API-sleutel in de widgetinstellingen",
"API key not configured": "API-sleutel niet geconfigureerd",
"Invalid API key": "Ongeldige API-sleutel",
"Endpoint not found": "Eindpunt niet gevonden",
"Values under 5 min may cause rate limiting": "Waarden onder 5 min kunnen rate limiting veroorzaken",
"Panel display": "Panelweergave",
"Show in panel:": "Tonen in paneel:",
"Icon:": "Pictogram:",
"Show Claude icon": "Claude-pictogram tonen",
"Style:": "Stijl:",
"Text": "Tekst",
"Circular": "Circulair",
"Bar": "Balk",
"Layout:": "Indeling:",
"Horizontal": "Horizontaal",
"Vertical": "Verticaal",
"Background opacity (desktop):": "Achtergrond dekking (bureaublad):"
},
"tr_TR": {
"Claude Usage": "Claude Kullanımı",
"Session (5hr)": "Oturum (5sa)",
"Weekly (7day)": "Haftalık (7 gün)",
"By Model (Weekly)": "Modele göre (Haftalık)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "Sıfırlanma:",
"Resets:": "Sıfırlanma:",
"Updated:": "Güncellendi:",
"Loading...": "Yükleniyor...",
"Refresh": "Yenile",
"Not logged in": "Giriş yapılmadı",
"Token expired": "Token süresi doldu",
"API error": "API hatası",
"Run 'claude' to log in": "Giriş için 'claude' çalıştırın",
"No model breakdown available": "Model dağılımı mevcut değil",
"Language:": "Dil:",
"System default": "Sistem varsayılanı",
"d": "g",
"h": "sa",
"m": "dk",
"Refresh interval:": "Yenileme aralığı:",
"minutes": "dakika",
"Open Claude": "Claude'u Aç",
"Rate limited": "Limit aşıldı",
"Auto-retry in 1 min": "1 dk sonra otomatik yeniden deneme",
"Custom API (optional)": "Özel API (isteğe bağlı)",
"Base URL:": "Temel URL:",
"API key:": "API anahtarı:",
"Leave empty to use ~/.claude/.credentials.json (default)": "Varsayılan ~/.claude/.credentials.json için boş bırakın",
"Check base URL and API key in widget settings": "Widget ayarlarında temel URL ve API anahtarını kontrol edin",
"API key not configured": "API anahtarı yapılandırılmadı",
"Invalid API key": "Geçersiz API anahtarı",
"Endpoint not found": "Uç nokta bulunamadı",
"Values under 5 min may cause rate limiting": "5 dk altındaki değerler rate limiting'e neden olabilir",
"Panel display": "Panel görünümü",
"Show in panel:": "Panelde göster:",
"Icon:": "Simge:",
"Show Claude icon": "Claude simgesini göster",
"Style:": "Stil:",
"Text": "Metin",
"Circular": "Dairesel",
"Bar": "Çubuk",
"Layout:": "Düzen:",
"Horizontal": "Yatay",
"Vertical": "Dikey",
"Background opacity (desktop):": "Arka plan opaklığı (masaüstü):"
},
"ja_JP": {
"Claude Usage": "Claude 使用状況",
"Session (5hr)": "セッション (5時間)",
"Weekly (7day)": "週間 (7日)",
"By Model (Weekly)": "モデル別 (週間)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "リセット:",
"Resets:": "リセット:",
"Updated:": "更新:",
"Loading...": "読み込み中...",
"Refresh": "更新",
"Not logged in": "未ログイン",
"Token expired": "トークン期限切れ",
"API error": "APIエラー",
"Run 'claude' to log in": "'claude'を実行してログイン",
"No model breakdown available": "モデル別データなし",
"Language:": "言語:",
"System default": "システムデフォルト",
"d": "日",
"h": "時",
"m": "分",
"Refresh interval:": "更新間隔:",
"minutes": "分",
"Open Claude": "Claudeを開く",
"Rate limited": "レート制限",
"Auto-retry in 1 min": "1分後に自動リトライ",
"Custom API (optional)": "カスタムAPI(オプション)",
"Base URL:": "ベースURL:",
"API key:": "APIキー:",
"Leave empty to use ~/.claude/.credentials.json (default)": "空欄で ~/.claude/.credentials.json を使用(デフォルト)",
"Check base URL and API key in widget settings": "ウィジェット設定でベースURLとAPIキーを確認",
"API key not configured": "APIキー未設定",
"Invalid API key": "無効なAPIキー",
"Endpoint not found": "エンドポイントが見つかりません",
"Values under 5 min may cause rate limiting": "5分未満の値はレート制限を引き起こす可能性があります",
"Panel display": "パネル表示",
"Show in panel:": "パネルに表示:",
"Icon:": "アイコン:",
"Show Claude icon": "Claudeアイコンを表示",
"Style:": "スタイル:",
"Text": "テキスト",
"Circular": "サークル",
"Bar": "バー",
"Layout:": "レイアウト:",
"Horizontal": "横",
"Vertical": "縦",
"Background opacity (desktop):": "背景の不透明度(デスクトップ):"
},
"ko_KR": {
"Claude Usage": "Claude 사용량",
"Session (5hr)": "세션 (5시간)",
"Weekly (7day)": "주간 (7일)",
"By Model (Weekly)": "모델별 (주간)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "초기화:",
"Resets:": "초기화:",
"Updated:": "업데이트:",
"Loading...": "로딩 중...",
"Refresh": "새로고침",
"Not logged in": "로그인 안됨",
"Token expired": "토큰 만료",
"API error": "API 오류",
"Run 'claude' to log in": "'claude'를 실행하여 로그인",
"No model breakdown available": "모델별 데이터 없음",
"Language:": "언어:",
"System default": "시스템 기본값",
"d": "일",
"h": "시",
"m": "분",
"Refresh interval:": "새로고침 간격:",
"minutes": "분",
"Open Claude": "Claude 열기",
"Rate limited": "속도 제한",
"Auto-retry in 1 min": "1분 후 자동 재시도",
"Custom API (optional)": "사용자 정의 API (선택사항)",
"Base URL:": "기본 URL:",
"API key:": "API 키:",
"Leave empty to use ~/.claude/.credentials.json (default)": "기본값 ~/.claude/.credentials.json 사용 시 비워두세요",
"Check base URL and API key in widget settings": "위젯 설정에서 기본 URL과 API 키를 확인하세요",
"API key not configured": "API 키 미설정",
"Invalid API key": "잘못된 API 키",
"Endpoint not found": "엔드포인트를 찾을 수 없음",
"Values under 5 min may cause rate limiting": "5분 미만의 값은 속도 제한을 유발할 수 있습니다",
"Panel display": "패널 표시",
"Show in panel:": "패널에 표시:",
"Icon:": "아이콘:",
"Show Claude icon": "Claude 아이콘 표시",
"Style:": "스타일:",
"Text": "텍스트",
"Circular": "원형",
"Bar": "바",
"Layout:": "레이아웃:",
"Horizontal": "가로",
"Vertical": "세로",
"Background opacity (desktop):": "배경 불투명도 (데스크톱):"
},
"zh_CN": {
"Claude Usage": "Claude 使用情况",
"Session (5hr)": "会话 (5小时)",
"Weekly (7day)": "每周 (7天)",
"By Model (Weekly)": "按模型 (每周)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "重置时间:",
"Resets:": "重置:",
"Updated:": "更新时间:",
"Loading...": "加载中...",
"Refresh": "刷新",
"Not logged in": "未登录",
"Token expired": "令牌已过期",
"API error": "API 错误",
"Run 'claude' to log in": "运行 'claude' 登录",
"No model breakdown available": "无模型明细",
"Language:": "语言:",
"System default": "系统默认",
"d": "天",
"h": "时",
"m": "分",
"Refresh interval:": "刷新间隔:",
"minutes": "分钟",
"Open Claude": "打开 Claude",
"Rate limited": "速率限制",
"Auto-retry in 1 min": "1分钟后自动重试",
"Custom API (optional)": "自定义API(可选)",
"Base URL:": "基础URL:",
"API key:": "API密钥:",
"Leave empty to use ~/.claude/.credentials.json (default)": "留空以使用 ~/.claude/.credentials.json(默认)",
"Check base URL and API key in widget settings": "请在小部件设置中检查基础URL和API密钥",
"API key not configured": "API密钥未配置",
"Invalid API key": "无效的API密钥",
"Endpoint not found": "端点未找到",
"Values under 5 min may cause rate limiting": "低于5分钟的值可能导致速率限制",
"Panel display": "面板显示",
"Show in panel:": "在面板中显示:",
"Icon:": "图标:",
"Show Claude icon": "显示Claude图标",
"Style:": "样式:",
"Text": "文本",
"Circular": "圆形",
"Bar": "柱状",
"Layout:": "布局:",
"Horizontal": "水平",
"Vertical": "垂直",
"Background opacity (desktop):": "背景不透明度(桌面):"
},
"zh_TW": {
"Claude Usage": "Claude 使用狀況",
"Session (5hr)": "工作階段 (5小時)",
"Weekly (7day)": "每週 (7天)",
"By Model (Weekly)": "依模型 (每週)",
"Sonnet": "Sonnet",
"Opus": "Opus",
"Resets at:": "重置時間:",
"Resets:": "重置:",
"Updated:": "更新時間:",
"Loading...": "載入中...",
"Refresh": "重新整理",
"Not logged in": "未登入",
"Token expired": "權杖已過期",
"API error": "API 錯誤",
"Run 'claude' to log in": "執行 'claude' 登入",
"No model breakdown available": "無模型明細",
"Language:": "語言:",
"System default": "系統預設",
"d": "天",
"h": "時",
"m": "分",
"Refresh interval:": "重新整理間隔:",
"minutes": "分鐘",
"Open Claude": "開啟 Claude",
"Rate limited": "速率限制",
"Auto-retry in 1 min": "1分鐘後自動重試",
"Custom API (optional)": "自訂API(選填)",
"Base URL:": "基礎URL:",
"API key:": "API金鑰:",
"Leave empty to use ~/.claude/.credentials.json (default)": "留空以使用 ~/.claude/.credentials.json(預設)",
"Check base URL and API key in widget settings": "請在小工具設定中檢查基礎URL和API金鑰",
"API key not configured": "API金鑰未設定",
"Invalid API key": "無效的API金鑰",
"Endpoint not found": "端點未找到",
"Values under 5 min may cause rate limiting": "低於5分鐘的值可能導致速率限制",
"Panel display": "面板顯示",
"Show in panel:": "在面板中顯示:",
"Icon:": "圖標:",
"Show Claude icon": "顯示Claude圖標",
"Style:": "樣式:",
"Text": "文字",
"Circular": "圓形",
"Bar": "柱狀",
"Layout:": "佈局:",
"Horizontal": "水平",
"Vertical": "垂直",
"Background opacity (desktop):": "背景不透明度(桌面):"
}
})
readonly property string systemLanguage: {
let locale = Qt.locale().name;
return locale;
}
function getEffectiveLanguage() {
if (currentLanguage === "system") {
let sysLang = systemLanguage;
if (strings[sysLang]) {
return sysLang;
}
let langCode = sysLang.split("_")[0];
for (let key in strings) {
if (key.startsWith(langCode + "_")) {
return key;
}
}
return "en_US";
}
return currentLanguage;
}
function tr(text) {
let v = version;
let lang = getEffectiveLanguage();
if (strings[lang] && strings[lang][text]) {
return strings[lang][text];
}
if (strings["en_US"] && strings["en_US"][text]) {
return strings["en_US"][text];
}
return text;
}
}
@@ -0,0 +1,191 @@
/*
SPDX-FileCopyrightText: 2025 izll
SPDX-License-Identifier: GPL-3.0-or-later
*/
import QtQuick
import QtQuick.Controls as QQC2
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.kcmutils as KCM
KCM.SimpleKCM {
id: configPage
property string cfg_language
property int cfg_refreshInterval
property string cfg_panelLayout
property bool cfg_showIcon
property string cfg_panelStyle
property bool cfg_showSession
property bool cfg_showWeekly
property bool cfg_showSonnet
property string cfg_baseUrl
property string cfg_apiKey
property double cfg_backgroundOpacity
// Translation helper
Translations {
id: trans
currentLanguage: cfg_language || "system"
}
function tr(text) { return trans.tr(text); }
readonly property var languageValues: [
"system", "en_US", "hu_HU", "de_DE", "fr_FR", "es_ES",
"it_IT", "pt_BR", "ru_RU", "pl_PL", "nl_NL", "tr_TR",
"ja_JP", "ko_KR", "zh_CN", "zh_TW"
]
readonly property var languageNames: [
tr("System default"), "English", "Magyar", "Deutsch",
"Français", "Español", "Italiano", "Português (Brasil)",
"Русский", "Polski", "Nederlands", "Türkçe",
"日本語", "한국어", "简体中文", "繁體中文"
]
Kirigami.FormLayout {
QQC2.ComboBox {
id: languageCombo
Kirigami.FormData.label: tr("Language:")
model: languageNames
currentIndex: languageValues.indexOf(cfg_language)
onActivated: index => {
cfg_language = languageValues[index]
}
}
RowLayout {
Kirigami.FormData.label: tr("Refresh interval:")
QQC2.SpinBox {
id: refreshSpinBox
from: 1
to: 999
stepSize: 1
value: cfg_refreshInterval
onValueChanged: {
cfg_refreshInterval = value
}
}
QQC2.Label {
text: tr("minutes")
}
}
QQC2.Label {
visible: cfg_refreshInterval < 5
text: "⚠ " + tr("Values under 5 min may cause rate limiting")
color: Kirigami.Theme.negativeTextColor
font.italic: true
Layout.fillWidth: true
}
Kirigami.Separator {
Kirigami.FormData.isSection: true
Kirigami.FormData.label: tr("Panel display")
}
QQC2.ComboBox {
Kirigami.FormData.label: tr("Layout:")
model: [tr("Horizontal"), tr("Vertical")]
currentIndex: cfg_panelLayout === "vertical" ? 1 : 0
onCurrentIndexChanged: cfg_panelLayout = currentIndex === 1 ? "vertical" : "horizontal"
}
QQC2.CheckBox {
Kirigami.FormData.label: tr("Icon:")
text: tr("Show Claude icon")
checked: cfg_showIcon
onCheckedChanged: cfg_showIcon = checked
}
QQC2.ComboBox {
Kirigami.FormData.label: tr("Style:")
model: [tr("Text"), tr("Circular"), tr("Bar")]
currentIndex: cfg_panelStyle === "circular" ? 1 : cfg_panelStyle === "bar" ? 2 : 0
onCurrentIndexChanged: {
var styles = ["text", "circular", "bar"]
cfg_panelStyle = styles[currentIndex]
}
}
QQC2.CheckBox {
Kirigami.FormData.label: tr("Show in panel:")
text: tr("Session (5hr)")
checked: cfg_showSession
onCheckedChanged: cfg_showSession = checked
}
QQC2.CheckBox {
text: tr("Weekly (7day)")
checked: cfg_showWeekly
onCheckedChanged: cfg_showWeekly = checked
}
QQC2.CheckBox {
text: tr("Sonnet")
checked: cfg_showSonnet
onCheckedChanged: cfg_showSonnet = checked
}
RowLayout {
Kirigami.FormData.label: tr("Background opacity (desktop):")
QQC2.Slider {
id: opacitySlider
from: 0.0
to: 1.0
stepSize: 0.05
value: cfg_backgroundOpacity
Layout.preferredWidth: Kirigami.Units.gridUnit * 10
onMoved: {
cfg_backgroundOpacity = value
}
}
QQC2.Label {
text: Math.round(opacitySlider.value * 100) + "%"
Layout.preferredWidth: Kirigami.Units.gridUnit * 2
}
}
Kirigami.Separator {
Kirigami.FormData.isSection: true
Kirigami.FormData.label: tr("Custom API (optional)")
}
QQC2.TextField {
id: baseUrlField
Kirigami.FormData.label: tr("Base URL:")
placeholderText: "https://api.anthropic.com"
text: cfg_baseUrl
onTextChanged: cfg_baseUrl = text
Layout.fillWidth: true
}
QQC2.Label {
text: tr("Leave empty to use ~/.claude/.credentials.json (default)")
font.italic: true
opacity: 0.7
Layout.fillWidth: true
}
QQC2.TextField {
id: apiKeyField
Kirigami.FormData.label: tr("API key:")
placeholderText: "sk-ant-..."
text: cfg_apiKey
echoMode: TextInput.Password
enabled: cfg_baseUrl !== ""
onTextChanged: cfg_apiKey = text
Layout.fillWidth: true
}
}
}
@@ -0,0 +1,16 @@
#!/bin/bash
PLUGIN_ID="org.kde.plasma.claudeusage"
INSTALL_DIR="$HOME/.local/share/plasma/plasmoids/$PLUGIN_ID"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
echo "Installing Claude Usage widget..."
mkdir -p "$INSTALL_DIR"
cp -r "$SCRIPT_DIR/contents" "$INSTALL_DIR/"
cp "$SCRIPT_DIR/metadata.json" "$INSTALL_DIR/"
echo "Installed to $INSTALL_DIR"
echo ""
echo "Restart Plasma to apply changes:"
echo " kquitapp6 plasmashell && kstart plasmashell"
Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

@@ -0,0 +1,36 @@
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512">
<defs>
<linearGradient id="bgGrad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#1a2744"/>
<stop offset="100%" style="stop-color:#0d1829"/>
</linearGradient>
<linearGradient id="progressGrad" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#4ade80"/>
<stop offset="50%" style="stop-color:#facc15"/>
<stop offset="100%" style="stop-color:#ef4444"/>
</linearGradient>
</defs>
<!-- Background with rounded corners -->
<rect x="0" y="0" width="512" height="512" rx="80" ry="80" fill="url(#bgGrad)"/>
<!-- Outer progress ring (background) -->
<circle cx="256" cy="256" r="180" fill="none" stroke="#2d3f5e" stroke-width="28" opacity="0.6"/>
<!-- Progress arc (showing ~70% usage) -->
<circle cx="256" cy="256" r="180" fill="none" stroke="url(#progressGrad)" stroke-width="28"
stroke-linecap="round" stroke-dasharray="792 1131"
transform="rotate(-90 256 256)"/>
<!-- Inner circle background -->
<circle cx="256" cy="256" r="140" fill="#1e3a5f" opacity="0.5"/>
<!-- Claude logo (scaled and centered) - orange color -->
<g transform="translate(136, 136) scale(15)" fill="#D97757">
<path d="m3.127 10.604 3.135-1.76.053-.153-.053-.085H6.11l-.525-.032-1.791-.048-1.554-.065-1.505-.08-.38-.081L0 7.832l.036-.234.32-.214.455.04 1.009.069 1.513.105 1.097.064 1.626.17h.259l.036-.105-.089-.065-.068-.064-1.566-1.062-1.695-1.121-.887-.646-.48-.327-.243-.306-.104-.67.435-.48.585.04.15.04.593.456 1.267.981 1.654 1.218.242.202.097-.068.012-.049-.109-.181-.9-1.626-.96-1.655-.428-.686-.113-.411a2 2 0 0 1-.068-.484l.496-.674L4.446 0l.662.089.279.242.411.94.666 1.48 1.033 2.014.302.597.162.553.06.17h.105v-.097l.085-1.134.157-1.392.154-1.792.052-.504.25-.605.497-.327.387.186.319.456-.045.294-.19 1.23-.37 1.93-.243 1.29h.142l.161-.16.654-.868 1.097-1.372.484-.545.565-.601.363-.287h.686l.505.751-.226.775-.707.895-.585.759-.839 1.13-.524.904.048.072.125-.012 1.897-.403 1.024-.186 1.223-.21.553.258.06.263-.218.536-1.307.323-1.533.307-2.284.54-.028.02.032.04 1.029.098.44.024h1.077l2.005.15.525.346.315.424-.053.323-.807.411-3.631-.863-.872-.218h-.12v.073l.726.71 1.331 1.202 1.667 1.55.084.383-.214.302-.226-.032-1.464-1.101-.565-.497-1.28-1.077h-.084v.113l.295.432 1.557 2.34.08.718-.112.234-.404.141-.444-.08-.911-1.28-.94-1.44-.759-1.291-.093.053-.448 4.821-.21.246-.484.186-.403-.307-.214-.496.214-.98.258-1.28.21-1.016.19-1.263.112-.42-.008-.028-.092.012-.953 1.307-1.448 1.957-1.146 1.227-.274.109-.477-.247.045-.44.266-.39 1.586-2.018.956-1.25.617-.723-.004-.105h-.036l-4.212 2.736-.75.096-.324-.302.04-.496.154-.162 1.267-.871z"/>
</g>
<!-- Usage label with background -->
<rect x="156" y="380" width="200" height="56" rx="12" ry="12" fill="#1e293b" stroke="#475569" stroke-width="2"/>
<text x="256" y="423" text-anchor="middle" font-family="Arial, sans-serif" font-size="42" font-weight="bold" fill="#e2e8f0">USAGE</text>
</svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

@@ -0,0 +1,21 @@
{
"KPackageStructure": "Plasma/Applet",
"KPlugin": {
"Authors": [
{
"Name": "izll"
}
],
"Category": "System Information",
"Description": "Display Claude Code usage statistics (session and weekly limits) in your taskbar. Shows real-time usage percentages with color-coded indicators.",
"EnabledByDefault": true,
"Icon": "claude-usage-widget",
"Id": "org.kde.plasma.claudeusageswitcher",
"License": "GPL-3.0-or-later",
"Name": "Claude Usage",
"Version": "1.3.6",
"Website": "https://github.com/izll/plasma-claude-usage"
},
"X-Plasma-API-Minimum-Version": "6.0",
"X-Plasma-Provides": []
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

@@ -0,0 +1,250 @@
# Changelog
All notable changes to KVitals will be documented in this file.
## [2.10.1] - 2026-06-29
### Fixed
- **Plasmashell Boot Crashes**: Resolved a critical race condition that caused `plasmashell` to enter a crash loop during system boot. Sensor module loading is now deferred until after window attachment is fully complete, preventing the `KirigamiPlasmaStyle` SIGSEGV (#49).
## [2.10.0] - 2026-06-27
### Added
- **Fan Speed Monitoring** (`Metrics` settings): A new standalone "Fan" metric that dynamically discovers and reports fan speeds (including GPU and CPU fans) directly from the system (#47).
- Automatically identifies fans through `SensorTreeModel`.
- Supports RPM and Percentage display units (configurable in `General` settings).
- Fully integrates with compact panel, full popup, and tooltip views.
- Safely handles fans that do not report a maximum RPM by omitting them from percentage-based aggregations to prevent misleading data.
- **Display Mode 'None'** (`General` settings): A new display mode that completely hides the metric labels and icons, showing only the raw values to save space (#47).
- **Config UI Redesign** (`Metrics` settings): The metrics configuration page has been overhauled for better UX, with inline contextual settings (e.g. CPU, GPU, Network options expand directly under their respective metrics) and debounced sensor discovery to eliminate UI freezes on load (#48).
## [2.9.0] - 2026-06-19
### Added
- **Per-GPU Sub-metric Visibility** (`Metrics` settings — GPU Selection): Each GPU entry now has independent **Usage**, **VRAM**, and **Temperature** toggles, letting you show only the metrics you care about without disabling the GPU entirely (#44).
- Toggling a sub-metric off immediately stops polling those sensors — no unnecessary kernel data fetched.
- A **minimum-one** guard prevents all three sub-metrics from being deselected at once (the last checked box is disabled), keeping at least one value visible per GPU.
- Sub-metric checkboxes are automatically disabled when the parent GPU is deselected, matching visual state to functional reality.
- Storage format uses a compact pipe-separated string (`gpu0:usage,vram|gpu1:usage,temp`). GPUs using all defaults are omitted, keeping the config short. Empty string (default) = all three enabled for every GPU — fully backwards-compatible with existing configs.
## [2.8.1] - 2026-05-23
### Fixed
- **Installation via KDE Store leaving stale widget state** (`install-remote.sh`): Users who first installed via the KDE Store (or an older `install-remote.sh`) and then upgraded manually could end up with a mismatched `kpackage/generic/` registration. This caused settings like **Show in compact panel** to silently not apply, because KDE resolves widget configuration from the kpackage path, not the plasmoids path. The remote install script now mirrors the local `install.sh` behaviour exactly: it removes any previous entry under `~/.local/share/kpackage/generic/<id>` (including stale symlinks), creates the install directory under `~/.local/share/plasma/plasmoids/`, and creates a fresh symlink at the kpackage path pointing to it.
## [2.8.0] - 2026-05-22
### Added
- **Disk I/O & Temperature** (`Metrics` settings — Disk I/O & Temp): New metric showing real-time disk read/write rates and the highest drive temperature across all NVMe and SATA drives. Displayed as `DSK: ↓2.1MB ↑76KB · 42°C` in the compact panel (#36).
- Drive temperatures are discovered dynamically via `SensorTreeModel` + `lmsensors` (supports `nvme-pci-*` and `drivetemp-scsi-*` chips) — zero polling overhead when the metric is disabled.
- Dedicated **Disk Temp** threshold sliders added to the Colors settings page (default: warning 45°C, critical 60°C).
- **Unit Preferences** (`General` settings — Unit Preferences section): Choose display units globally across all metrics (#37).
- **Temperature**: Celsius (°C, default) or Fahrenheit (°F). Applies to CPU temp, GPU temp, and Disk temp everywhere — panel, popup, and tooltip.
- **Network / Disk I/O**: Bytes (KB/MB, default) or Bits (Kb/Mb). Applies to Network and Disk I/O rates. Suffix convention follows industry standard: uppercase `B` = bytes, lowercase `b` = bits.
- Threshold slider labels in the Colors settings page update live to reflect the chosen temperature unit (stored values remain in °C for correct sensor comparison).
## [2.7.0] - 2026-05-15
### Added
- **Multi-GPU Support** (`Metrics` settings — GPU Selection): On systems with more than one GPU, each GPU is now listed individually as a separate metric in both the compact panel and the full popup view (#22). Works automatically — no configuration needed on single-GPU machines.
- Each GPU is detected dynamically via `SensorTreeModel` metadata; no persistent subscriptions run during discovery.
- The GPU Selection section in settings shows all discovered GPUs with independent enable/disable checkboxes.
- **GPU Custom Labels** (`Metrics` settings — GPU Selection): On multi-GPU systems, each GPU entry in the panel shows a customizable label. Type a name in the **Label** field (e.g. `iGPU`, `dGPU`) to override the default `GPU 1` / `GPU 2` identifiers. Leave it empty to keep the default numbering.
- **Hybrid GPU power hint**: When two or more GPUs are detected, a contextual note appears in the GPU Selection section explaining that unchecking the discrete GPU prevents KVitals from polling it, allowing it to suspend when idle.
### Fixed
- **Unintended dGPU Wakeup** on hybrid GPU laptops (Intel/AMD + NVIDIA setups using `supergfxctl` / `asusctl`): The previous implementation used permanent `Sensors.Sensor` subscriptions for up to 6 hardcoded GPU slots. These subscriptions polled every GPU continuously, preventing the dGPU from entering its suspended/power-save state even when it was idle (#26).
- **New architecture**: Discovery uses `SensorTreeModel` + `KDescendantsProxyModel` (pure metadata query, no value subscriptions). Data polling uses a single `SensorDataModel` constrained strictly to the GPUs the user has selected.
- **Result**: Deselecting a GPU in settings stops all polling for that GPU immediately. On hybrid setups, unchecking the dGPU allows it to fully suspend.
- **Note**: If the dGPU remains active even after unchecking it in KVitals, the cause is likely unrelated — some Xwayland applications keep the GPU awake independently of any sensor polling. This is a system/compositor-level behavior outside the scope of KVitals.
## [2.6.0] - 2026-05-10
### Added
- **Compact Panel Visibility** (`Metrics` settings): Each metric now has an independent "Show in compact panel" toggle, allowing metrics to appear in the full popup view but stay hidden from the panel bar (#29, thanks @keiishu). Disabling a metric preserves its compact visibility state for when it is re-enabled.
- **CPU Frequency** (`Metrics` settings): Display the average CPU frequency in the widget. Auto-formats as GHz (≥ 1000 MHz) or MHz (#33).
- **Merge into CPU** (compact view): Appends frequency as a second segment next to CPU usage (`CPU: 34% · 3.20 GHz`). Compatible with Merge CPU & Temp — all three values appear as segments.
- **Full view sub-item**: When enabled, CPU Frequency appears as a dedicated row directly under CPU Usage in the popup.
- **Bold Font** (`General` settings): Toggle bold styling for all metric value labels across compact and full views (#30). Defaults to off.
### Fixed
- Inconsistent font weight across metrics in vertical layout: RAM and Network values (rendered via `SegmentsRow`) were always bold while CPU/GPU were not. All value labels now follow the new Bold Font setting uniformly.
## [2.5.0] - 2026-04-30
### Added
- **Layout Type** (`General` settings): Choose between **Horizontal** (default, unchanged) and **Vertical** layout for the compact panel view. In vertical mode, the metric value is displayed on top with the label/icon dimmed below — ideal for tall panels or icon-only display (#11).
- **Metric Grouping** (`Metrics` settings — Grouping section):
- **Merge CPU & Temp**: Combines CPU temperature as a second value next to CPU usage (`CPU: 45% · 62°C`), using the same segment display as GPU. The CPU Temperature entry is hidden from the metric order list while merged.
- **Merge Battery & Power**: Combines power consumption as a second value next to battery level (`BAT: 87% · 12.4W`). Power Consumption entry is hidden from the metric order list while merged.
- **Split GPU Metrics**: Optionally break GPU usage, VRAM and temperature into separate panel entries instead of the default grouped display (default: grouped).
### Changed
- Metric order list now hides absorbed metrics when grouping is active (e.g. "CPU Temperature" disappears when "Merge CPU & Temp" is enabled), keeping the list clean and non-redundant.
- `CompactView` refactored to use a `Loader`-based delegate system, enabling runtime layout switching without widget reload.
### Fixed
- `Unable to assign [undefined] to QColor` runtime error when CPU+Temp or Battery+Power merge was enabled — missing top-level `color` field on segmented metric objects.
- Defensive `|| baseTextColor` fallback added to all value label color bindings in `CompactView`.
## [2.4.0] - 2026-04-01
### Added
- **Custom Font Color**: Override the widget font color to match your panel theme (#20). Configurable via the new **Colors** settings tab.
- **Threshold-Based Coloring**: Metric values dynamically change color when they exceed configurable warning/critical thresholds (#12). Supported metrics:
- CPU usage (default: warning 70%, critical 90%)
- CPU temperature (default: warning 60°C, critical 85°C)
- RAM usage (default: warning 70%, critical 90%)
- GPU usage (default: warning 70%, critical 90%)
- GPU temperature (default: warning 60°C, critical 85°C)
- Battery level (inverted: warning below 30%, critical below 15%)
- **Colors Config Tab**: New settings page with color pickers for font/warning/critical colors and per-metric threshold sliders.
- Sensor modules now expose raw numeric values (`cpuNumericValue`, `tempNumericValue`, `ramPercentage`, `batNumericValue`) for threshold comparison.
- `Utils.resolveColor()` function for flexible threshold-triggered color resolution.
### Fixed
- Fixed the Colors tab color picker turning white after selecting a color; it now uses a stable native platform color dialog and preserves the selected swatch correctly.
### Notes
- Network and Power metrics are excluded from threshold coloring (no meaningful universal threshold).
- Both features are **opt-in** — disabled by default. Existing users are unaffected.
## [2.3.0] - 2026-03-13
### Changed
- **Sensor Module Architecture**: Extracted all sensor logic from `main.qml` into dedicated QML components under `contents/ui/sensors/`:
- `CpuSensors.qml` — CPU usage monitoring
- `MemorySensors.qml` — RAM usage monitoring
- `TempSensors.qml` — CPU temperature monitoring
- `GpuSensors.qml` — GPU usage, VRAM, and temperature monitoring
- `BatterySensors.qml` — Battery and power monitoring with auto-detection
- `NetworkSensors.qml` — Network download/upload speed monitoring
- `Utils.qml` — Shared formatting helpers (byte formatting, rate formatting)
- **View Separation**: Extracted compact and full representations into `CompactView.qml` and `FullView.qml`.
- **Reduced `main.qml`**: From ~700 lines to ~140 lines — now acts purely as an orchestrator.
### Notes
- No user-facing or configuration changes. The widget behaves identically to v2.2.1.
- This refactor improves maintainability and makes it easier to add new sensor types in the future.
## [2.2.1] - 2026-03-07
### Fixed
- **Battery Detection Hotfix**: Replaced `SensorTreeModel` with a crash-free **Two-Stage Hybrid Detection** system (#14):
- **Stage 1 (Silent Probe)**: Silently probes common battery paths (`BAT0`, `BAT1`, `BATT`, etc.) for instant detection without running any subprocesses.
- **Stage 2 (Fallback)**: If no standard battery is found, falls back to a single `qdbus` query to list all sensors, completely avoiding `PlasmaCore.DataSource` file descriptor leaks. Includes a manual config fallback if `qdbus` is unavailable.
## [2.2.0] - 2026-03-05
### Added
- **Custom Metric Order**: Added a new configuration option to arrange metrics (CPU, RAM, GPU, etc.) individually in whatever order you prefer (#7).
- **Dynamic Battery Detection**: Replaced hardcoded `BAT0`/`BAT1` sensors with dynamic `SensorTreeModel` discovery. The widget will now automatically find any battery your system has (BAT0, BATT, CMB0, macsmc-battery, etc.) (#14).
## [2.1.1] - 2026-03-03
### Fixed
- Fixed a "Detected anchors on an item that is managed by a layout" QML warning spanning the journal log caused by a `MouseArea` anchoring inside a `RowLayout` (#13).
## [2.1.0] - 2026-03-01
### Added
- **GPU Metrics Support**: Added VRAM usage and GPU temperature monitoring to the widget.
- GPU data is retrieved natively using KDE KSysGuard sensors (`org.kde.ksysguard.sensors`).
## [2.0.0] - 2026-02-27
### Changed
- **Major Architecture Overhaul**: Replaced the previous `sys-stats.sh` backend with native KDE KSysGuard sensors (`org.kde.ksysguard.sensors`).
- Completely eliminates "file descriptor leak" crashes (Issue #8) and improves overall performance by relying directly on the `ksystemstats` D-Bus daemon instead of constantly spawning bash processes.
- Automatic fallback for battery monitoring (BAT0 and BAT1) logic implemented directly in QML.
## [1.4.1] - 2026-02-24
### Fixed
- RAM usage showing empty on non-English locales — `free` translates its `Mem:` header based on locale, causing the parser to match nothing
- Switched RAM data source from `free -b` to `/proc/meminfo` (locale-independent, faster, more accurate)
## [1.4.0] - 2026-02-22
### Added
- **Display mode setting** — choose between Text, Icons, or Icons + Text for the panel
- **Custom icon picker** — select icons from your installed theme for each metric (via KDE's native icon picker)
- **Icon size slider** — adjust icon size (8–24px) when using icon mode
- **Font customization** — choose any system font and font size for the panel text
- **Settings tabs** — split configuration into General, Metrics, and Icons tabs
- **Reset to defaults** button on the Icons tab
- **CHANGELOG.md** — version history
- **Documentation** — MkDocs site with installation, configuration, architecture, contributing, and troubleshooting guides
## [1.3.0] - 2026-02-16
### Added
- Power consumption tracking (via `/sys/class/power_supply/`) — contributed by [@Pijuli](https://github.com/Pijuli)
### Fixed
- ShellCheck warnings from power consumption PR (SC2034, SC2155)
## [1.2.1] - 2026-02-16
### Fixed
- AMD CPU temperature detection — added `k10temp`, `zenpower`, `zenergy`, `amdgpu` to thermal_zone and hwmon detection
- lm-sensors fallback now matches AMD `Tccd1` label
- Reordered temperature fallback tiers to prioritize CPU-specific sources over generic thermal zones
## [1.2.0] - 2026-02-13
### Added
- Auto-detect network interface via `ip route` with manual override in settings
- Network interface selector in widget configuration
### Fixed
- ShellCheck warnings (SC2010, SC2155)
## [1.1.0] - 2026-02-12
### Changed
- Modularized `sys-stats.sh` into functions
- Enhanced CPU temperature detection with 4-tier fallback (thermal_zone → hwmon → lm-sensors → generic)
## [1.0.0] - 2026-02-12
### Added
- Initial release
- CPU usage (delta-based from `/proc/stat`)
- RAM usage (from `/proc/meminfo`)
- CPU temperature (multi-source detection)
- Battery status with emoji indicators
- Network speed (delta-based from `/proc/net/dev`)
- Configurable update interval
- Toggle visibility per metric
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
yassine.amjad001@gmail.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
@@ -0,0 +1,75 @@
# Contributing to KVitals
Thanks for your interest in contributing! Here's how to get started.
## Development Setup
1. **Clone the repo**
```bash
git clone https://github.com/yassine20011/kvitals.git
cd kvitals
```
2. **Install the widget locally**
```bash
bash install.sh
```
3. **Test changes** — After editing QML files, reinstall:
```bash
bash install.sh
```
Then restart the widget (remove & re-add to panel) or log out / log in.
## Project Structure
```
kvitals/
├── metadata.json # Plugin metadata (version, name, etc.)
├── contents/
│ ├── ui/
│ │ ├── main.qml # Main widget UI
│ │ └── configGeneral.qml # Settings page
│ ├── config/
│ │ └── config.qml # Config entry point
├── install.sh # Local install script
├── install-remote.sh # Remote install (curl/wget)
└── package.sh # Build .plasmoid package
```
## Commit Messages
Use conventional commit prefixes:
- `feat:` — New feature (e.g. `feat: add GPU temperature monitoring`)
- `fix:` — Bug fix (e.g. `fix: handle missing thermal zones`)
- `docs:` — Documentation only (e.g. `docs: update install instructions`)
- `refactor:` — Code restructuring without behavior change
- `chore:` — Build scripts, CI, tooling
## Submitting a Pull Request
1. Fork the repo and create a branch: `git checkout -b feat/my-feature`
2. Make your changes and test locally on Plasma 6
3. Commit with a clear message following the conventions above
4. Push and open a PR against `master`
5. In the PR description, mention:
- What the change does
- Your Plasma version and distro
- Screenshots if it's a visual change
## Reporting Bugs
Please use the [bug report template](https://github.com/yassine20011/kvitals/issues/new?template=bug_report.md) and include:
- Your **Plasma version** (`plasmashell --version`)
- Your **distro** and version
- Steps to reproduce
- Expected vs actual behavior
## Feature Requests
Use the [feature request template](https://github.com/yassine20011/kvitals/issues/new?template=feature_request.md).
## License
By contributing, you agree that your contributions will be licensed under the [GPL-3.0 License](LICENSE).
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 3 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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,105 @@
# KVitals
A lightweight KDE Plasma 6 panel widget that displays live system vitals directly in your top bar.
```
CPU: 26% | RAM: 8.8/39.0G | TEMP: 96°C | 🔋BAT: 78% | PWR: +20W | NET: ↓82.2K ↑58.9K
```
## Screenshots
<div align="center">
<img src="screenshots/demo.gif" alt="Demo">
</div>
## Features
- **Live monitoring** — CPU usage, RAM, CPU temperature, GPU metrics (when available), battery status, power draw, network speed, disk I/O, fan speeds
- **Display modes** — Text, Icons, Icons + Text, or None (values only) for the panel view
- **Custom icons** — Pick any icon from your installed theme for each metric
- **Font customization** — Choose any system font and size
- **Configurable** — Toggle each metric, adjust refresh rate, tune colors, organized in 4 settings tabs
- **Minimal footprint** — Native KDE KSysGuard sensors + QML, no heavy dependencies or excessive subprocesses
- **Click to expand** — Detailed popup view with all stats
## Requirements
- KDE Plasma 6.0+
## Installation
### KDE Store (Recommended)
Install directly from the KDE Store:
👉 **[Get KVitals on the KDE Store](https://www.pling.com/p/2347917/)**
Or from within KDE Plasma:
1. Right-click on the panel → **Add Widgets...**
2. Click **Get New Widgets...** → **Download New Plasma Widgets...**
3. Search for **"KVitals"**
4. Click **Install**
---
### Quick Install (curl)
```bash
curl -fsSL https://github.com/yassine20011/kvitals/releases/latest/download/install-remote.sh | bash
```
### Quick Install (wget)
```bash
wget -qO- https://github.com/yassine20011/kvitals/releases/latest/download/install-remote.sh | bash
```
### Manual Install
```bash
git clone https://github.com/yassine20011/kvitals.git
cd kvitals
bash install.sh
```
Then restart Plasma and add the widget:
```bash
plasmashell --replace &
```
1. Right-click on the panel → **Add Widgets...**
2. Search for **KVitals**
3. Drag it onto your panel
## Configuration
Right-click the widget → **Configure KVitals...** to access settings in four tabs:
- **General** — Display mode, layout, icon size, font, update interval
- **Metrics** — Toggle CPU, RAM, Temperature, GPU, Battery, Power, Network, Disk, Fan
- **Icons** — Customize icons for each metric from your theme
- **Colors** — Set custom font colors and optional threshold-based metric colors
See the [full configuration reference](docs/configuration.md) for details.
## Uninstall
```bash
rm -rf ~/.local/share/plasma/plasmoids/org.kde.plasma.kvitals
```
Then restart Plasma: `plasmashell --replace &`
## Documentation
- [Installation](docs/installation.md)
- [Configuration](docs/configuration.md)
- [Architecture](docs/architecture.md)
- [Contributing](docs/contributing.md)
- [Troubleshooting](docs/troubleshooting.md)
## License
By contributing, you agree that your contributions will be licensed under the [GPL-3.0 License](LICENSE).
@@ -0,0 +1,78 @@
# KVitals Roadmap
This roadmap outlines planned features and improvements. It is not a strict commitment—priorities may shift based on community feedback and contributions.
Have a suggestion? Open an issue or start a discussion on GitHub.
---
## Currently Supported Metrics
- CPU Usage
- CPU Temperature
- CPU Frequency
- RAM Usage
- GPU (Usage, VRAM, Temperature) — with multi-GPU and custom labels
- Battery & Power Consumption
- Network Speed (Download/Upload)
- Disk I/O (Read/Write rates)
- Disk Temperature (highest across all NVMe/SATA drives)
---
## Currently Supported UX Features
- Custom metric order (drag to reorder)
- Per-metric compact panel visibility toggle
- Metric grouping (merge CPU+Temp, Battery+Power, split GPU)
- Threshold-based coloring (warning/critical per metric)
- Custom font color
- Display modes: Text, Icons, Icons+Text
- Horizontal / Vertical layout
- **Unit Preferences** (°C/°F, Bytes/Bits)
---
## Planned
### New Metrics
#### KSystemStats Sensors
These sensors are exposed by `ksystemstats` and are planned for future releases:
- **Disk Usage** — Used/free space per partition via `disk/all/usedPercent` or per-disk breakdown
- **CPU Load Averages** — 1, 5, and 15-minute averages via `cpu/loadaverages/*`
- **Swap Usage** — Used/total swap memory via `memory/swap/*`
- **GPU Frequency & Power** — Core frequency and power draw via `gpu/<device>/coreFrequency` and `gpu/<device>/power`
- **Battery Health** — Degradation percentage via `power/<device>/health`
- **System Uptime** — Via `os/system/uptime`
#### External Sensors (lmsensors)
These require `lmsensors` to be installed and configured:
- **Fan Speed** — CPU fan RPM (where available)
### UX & Configuration
- **Per-metric custom label** — Let users rename metric labels (e.g. "CPU" → "Processor")
- **Tooltip customization** — Choose which metrics appear in the hover tooltip
- **Click action** — Configure what happens when clicking the widget (e.g. open System Monitor)
---
## Under Consideration
These are ideas being evaluated — no commitment yet:
- **Per-core view** — Individual core usage/temperature in the popup
- **Pressure metrics (PSI)** — CPU/IO/Memory pressure via Linux PSI interface
- **Wayland multi-screen** — Better handling across multiple monitors
- **Tray icon mode** — Minimal system tray alternative to panel widget
---
## Not Planned
- Graphs or charts in the compact panel (out of scope for a panel widget)
@@ -0,0 +1,81 @@
# Security Policy
## Official Distribution Channels
KVitals is distributed through the following **official channels**:
### 1. **KDE Store** (Recommended)
- **URL**: https://www.pling.com/p/2347917/
- **Installation**: Via KDE Plasma widget installer (Right-click panel → Add Widgets → Download New Plasma Widgets)
- **Verification**: Installed directly from the official KDE Plasma store
### 2. **GitHub Releases**
- **URL**: https://github.com/yassine20011/kvitals/releases
- **Installation**: `curl` or `wget` scripts from official releases
- **Verification**: Source code available for review at https://github.com/yassine20011/kvitals
### 3. **Git Clone** (Source)
- **Repository**: https://github.com/yassine20011/kvitals.git
- **Installation**: `bash install.sh` from cloned repository
- **Verification**: Full source code transparency; review commits and tags
## Community-Maintained Packages
### **AUR**
- **Package**: `plasma6-applets-kvitals-git`
- **Status**: Community-maintained package, not officially maintained by the KVitals project.
- **Verification**: Check the AUR package maintainer; review PKGBUILD for any modifications
## What to Avoid
⚠️ **Avoid installing KVitals from**:
- Unofficial forks or repackaged versions not listed above
- Third-party websites or app stores not listed above
- Modified or patched versions from unknown sources
If you encounter a suspicious KVitals package or fork, please report it to me via GitHub.
## Reporting Security Vulnerabilities
If you discover a security vulnerability in KVitals, **do not** open a public GitHub issue. Instead:
### Recommended: GitHub Security Advisory
1. Go to https://github.com/yassine20011/kvitals/security/advisories
2. Click **Report a vulnerability**
3. Provide details about the vulnerability
This allows for responsible disclosure and coordinated patching before public disclosure.
### Alternative: Direct Contact
For sensitive issues, use the email fallback below rather than a public GitHub comment or issue.
### What to Include
- Clear description of the vulnerability
- Steps to reproduce (if applicable)
- Potential impact or severity
- Suggested fix (if you have one)
**Please allow reasonable time for investigation and coordinated disclosure before public disclosure.**
## Code Verification
KVitals is written in **QML** (Qt Markup Language) and distributed as open source without bundled compiled binaries. To verify authenticity:
1. Clone the official repository:
```bash
git clone https://github.com/yassine20011/kvitals.git
```
2. Review the source code:
- All widget logic is in `contents/ui/` (human-readable QML)
- Configuration is in `contents/config/`
- No obfuscated or minified code
3. Install from your reviewed source:
```bash
bash install.sh
```
## Questions or Concerns?
For security-related questions or concerns, please use the GitHub Security Advisory flow first. If you need a direct fallback, contact me by email at [Yassine.amjad001@gmail.com](mailto:Yassine.amjad001@gmail.com).
@@ -0,0 +1,26 @@
import QtQuick 2.0
import org.kde.plasma.configuration 2.0
ConfigModel {
ConfigCategory {
name: i18n("General")
icon: "configure"
source: "configGeneral.qml"
}
ConfigCategory {
name: i18n("Metrics")
icon: "view-statistics"
source: "configMetrics.qml"
}
ConfigCategory {
name: i18n("Icons")
icon: "preferences-desktop-icons"
source: "configIcons.qml"
}
ConfigCategory {
name: i18n("Colors")
icon: "color-management"
source: "configColors.qml"
}
}
@@ -0,0 +1,209 @@
<?xml version="1.0" encoding="UTF-8"?>
<kcfg xmlns="http://www.kde.org/standards/kcfg/1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.kde.org/standards/kcfg/1.0 http://www.kde.org/standards/kcfg/1.0/kcfg.xsd">
<kcfgfile name=""/>
<group name="General">
<entry name="showCpu" type="Bool">
<default>true</default>
</entry>
<entry name="showCpuFreq" type="Bool">
<default>false</default>
</entry>
<entry name="showRam" type="Bool">
<default>true</default>
</entry>
<entry name="showTemp" type="Bool">
<default>true</default>
</entry>
<entry name="showGpu" type="Bool">
<default>true</default>
</entry>
<entry name="showBattery" type="Bool">
<default>true</default>
</entry>
<entry name="showPower" type="Bool">
<default>true</default>
</entry>
<entry name="showNetwork" type="Bool">
<default>true</default>
</entry>
<entry name="showDisk" type="Bool">
<default>false</default>
</entry>
<entry name="showFan" type="Bool">
<default>false</default>
</entry>
<entry name="compactShowCpu" type="Bool">
<default>true</default>
</entry>
<entry name="compactShowRam" type="Bool">
<default>true</default>
</entry>
<entry name="compactShowTemp" type="Bool">
<default>true</default>
</entry>
<entry name="compactShowGpu" type="Bool">
<default>true</default>
</entry>
<entry name="compactShowBattery" type="Bool">
<default>true</default>
</entry>
<entry name="compactShowPower" type="Bool">
<default>true</default>
</entry>
<entry name="compactShowNetwork" type="Bool">
<default>true</default>
</entry>
<entry name="compactShowDisk" type="Bool">
<default>false</default>
</entry>
<entry name="compactShowFan" type="Bool">
<default>false</default>
</entry>
<entry name="networkInterface" type="String">
<default>auto</default>
</entry>
<entry name="batteryDevice" type="String">
<default>auto</default>
</entry>
<entry name="gpuSelection" type="String">
<default></default>
</entry>
<entry name="gpuLabels" type="String">
<default></default>
</entry>
<entry name="displayMode" type="String">
<default>text</default>
</entry>
<entry name="layoutType" type="String">
<default>horizontal</default>
</entry>
<entry name="mergeCpuTemp" type="Bool">
<default>false</default>
</entry>
<entry name="mergeCpuFreq" type="Bool">
<default>false</default>
</entry>
<entry name="mergeBatPwr" type="Bool">
<default>false</default>
</entry>
<entry name="splitGpu" type="Bool">
<default>false</default>
</entry>
<entry name="gpuMetrics" type="String">
<default></default>
</entry>
<entry name="iconSize" type="Int">
<default>12</default>
</entry>
<entry name="cpuIcon" type="String">
<default>cpu</default>
</entry>
<entry name="ramIcon" type="String">
<default>memory</default>
</entry>
<entry name="tempIcon" type="String">
<default>temperature-normal</default>
</entry>
<entry name="gpuIcon" type="String">
<default>video-card</default>
</entry>
<entry name="batteryIcon" type="String">
<default>battery-good</default>
</entry>
<entry name="powerIcon" type="String">
<default>battery-charging-60</default>
</entry>
<entry name="networkIcon" type="String">
<default>network-wireless</default>
</entry>
<entry name="diskIcon" type="String">
<default>drive-harddisk</default>
</entry>
<entry name="fanIcon" type="String">
<default>fan</default>
</entry>
<entry name="fontFamily" type="String">
<default>monospace</default>
</entry>
<entry name="fontSize" type="Int">
<default>0</default>
</entry>
<entry name="fontBold" type="Bool">
<default>false</default>
</entry>
<entry name="metricOrder" type="String">
<default>cpu,ram,temp,gpu,bat,pwr,net,disk,fan</default>
</entry>
<entry name="updateInterval" type="Int">
<default>2000</default>
</entry>
<entry name="useCustomColors" type="Bool">
<default>false</default>
</entry>
<entry name="fontColor" type="String">
<default></default>
</entry>
<entry name="enableThresholdColors" type="Bool">
<default>false</default>
</entry>
<entry name="warningColor" type="String">
<default>#e5a50a</default>
</entry>
<entry name="criticalColor" type="String">
<default>#da4453</default>
</entry>
<entry name="cpuWarningThreshold" type="Int">
<default>70</default>
</entry>
<entry name="cpuCriticalThreshold" type="Int">
<default>90</default>
</entry>
<entry name="tempWarningThreshold" type="Int">
<default>60</default>
</entry>
<entry name="tempCriticalThreshold" type="Int">
<default>85</default>
</entry>
<entry name="ramWarningThreshold" type="Int">
<default>70</default>
</entry>
<entry name="ramCriticalThreshold" type="Int">
<default>90</default>
</entry>
<entry name="gpuWarningThreshold" type="Int">
<default>70</default>
</entry>
<entry name="gpuCriticalThreshold" type="Int">
<default>90</default>
</entry>
<entry name="gpuTempWarningThreshold" type="Int">
<default>60</default>
</entry>
<entry name="gpuTempCriticalThreshold" type="Int">
<default>85</default>
</entry>
<entry name="batteryWarningThreshold" type="Int">
<default>30</default>
</entry>
<entry name="batteryCriticalThreshold" type="Int">
<default>15</default>
</entry>
<entry name="diskTempWarningThreshold" type="Int">
<default>45</default>
</entry>
<entry name="diskTempCriticalThreshold" type="Int">
<default>60</default>
</entry>
<entry name="tempUnit" type="String">
<default>C</default>
</entry>
<entry name="networkUnit" type="String">
<default>bytes</default>
</entry>
<entry name="fanUnit" type="String">
<default>rpm</default>
</entry>
</group>
</kcfg>
@@ -0,0 +1,211 @@
import QtQuick
import QtQuick.Layouts
import org.kde.plasma.components as PlasmaComponents
import org.kde.kirigami as Kirigami
RowLayout {
id: compactRow
spacing: Kirigami.Units.smallSpacing
required property var metricsModel
required property bool useIcons
required property bool useText
required property int effectiveFontSize
required property string fontFamily
required property bool fontBold
required property int iconSize
required property color baseTextColor
required property string layoutType
readonly property bool isVertical: layoutType === "vertical"
signal toggleExpanded()
TapHandler {
onTapped: compactRow.toggleExpanded()
}
// Shared segments renderer
component SegmentsRow: Row {
required property var segments
spacing: 2
Repeater {
model: segments
delegate: Row {
required property var modelData
required property int index
spacing: 2
PlasmaComponents.Label {
visible: index > 0
text: "·"
font.pixelSize: compactRow.effectiveFontSize
font.family: compactRow.fontFamily
font.bold: compactRow.fontBold
color: compactRow.baseTextColor
opacity: 0.5
}
PlasmaComponents.Label {
text: modelData.value
font.pixelSize: compactRow.effectiveFontSize
font.family: compactRow.fontFamily
font.bold: compactRow.fontBold
color: modelData.color
}
}
}
}
Repeater {
model: compactRow.metricsModel
delegate: Item {
required property var modelData
required property int index
implicitWidth: loader.implicitWidth
implicitHeight: loader.implicitHeight
Loader {
id: loader
anchors.fill: parent
sourceComponent: compactRow.isVertical ? verticalDelegate : horizontalDelegate
property var itemData: modelData
property int itemIndex: index
}
}
}
// ── Horizontal delegate (unchanged behaviour) ──────────────────────────
Component {
id: horizontalDelegate
RowLayout {
spacing: 2
Layout.fillHeight: true
PlasmaComponents.Label {
visible: itemIndex > 0 && !itemData.hideSeparator
text: "|"
font.pixelSize: compactRow.effectiveFontSize
font.family: compactRow.fontFamily
color: compactRow.baseTextColor
opacity: 0.4
Layout.alignment: Qt.AlignVCenter
}
Kirigami.Icon {
visible: compactRow.useIcons
source: itemData.icon
isMask: true
Layout.preferredWidth: compactRow.iconSize
Layout.preferredHeight: compactRow.iconSize
Layout.alignment: Qt.AlignVCenter
}
PlasmaComponents.Label {
visible: compactRow.useText
text: itemData.label
font.pixelSize: compactRow.effectiveFontSize
font.family: compactRow.fontFamily
color: compactRow.baseTextColor
Layout.alignment: Qt.AlignVCenter
}
PlasmaComponents.Label {
visible: !itemData.segments
text: itemData.value || ""
font.pixelSize: compactRow.effectiveFontSize
font.family: compactRow.fontFamily
font.bold: compactRow.fontBold
color: itemData.color || compactRow.baseTextColor
Layout.alignment: Qt.AlignVCenter
}
SegmentsRow {
visible: !!itemData.segments
segments: itemData.segments || []
Layout.alignment: Qt.AlignVCenter
}
}
}
// ── Vertical delegate (value on top, icon+label below) ─────────────────
Component {
id: verticalDelegate
RowLayout {
spacing: Kirigami.Units.smallSpacing
Layout.fillHeight: true
// Thin line separator between metrics
Rectangle {
visible: itemIndex > 0 && !itemData.hideSeparator
width: 1
Layout.fillHeight: true
color: compactRow.baseTextColor
opacity: 0.2
}
ColumnLayout {
spacing: 1
Layout.alignment: Qt.AlignVCenter
// Top: value(s)
RowLayout {
spacing: 0
Layout.alignment: Qt.AlignHCenter
PlasmaComponents.Label {
visible: !itemData.segments
text: itemData.value || ""
font.pixelSize: compactRow.effectiveFontSize
font.family: compactRow.fontFamily
font.bold: compactRow.fontBold
color: itemData.color || compactRow.baseTextColor
horizontalAlignment: Text.AlignHCenter
}
SegmentsRow {
visible: !!itemData.segments
segments: itemData.segments || []
Layout.alignment: Qt.AlignHCenter
}
}
// Bottom: icon + label
RowLayout {
visible: compactRow.useIcons || compactRow.useText
spacing: 2
Layout.alignment: Qt.AlignHCenter
Kirigami.Icon {
visible: compactRow.useIcons
source: itemData.icon
isMask: true
Layout.preferredWidth: Math.round(compactRow.iconSize * 0.85)
Layout.preferredHeight: Math.round(compactRow.iconSize * 0.85)
Layout.alignment: Qt.AlignVCenter
}
PlasmaComponents.Label {
visible: compactRow.useText
text: {
var lbl = itemData.label || "";
return lbl.endsWith(":") ? lbl.slice(0, -1) : lbl;
}
font.pixelSize: Math.max(8, compactRow.effectiveFontSize - 2)
font.family: compactRow.fontFamily
color: compactRow.baseTextColor
opacity: 0.65
Layout.alignment: Qt.AlignVCenter
}
}
}
}
}
}
@@ -0,0 +1,48 @@
import QtQuick
import QtQuick.Layouts
import org.kde.plasma.components as PlasmaComponents
import org.kde.kirigami as Kirigami
ColumnLayout {
id: fullView
spacing: Kirigami.Units.smallSpacing
Layout.preferredWidth: Kirigami.Units.gridUnit * 18
Layout.preferredHeight: Kirigami.Units.gridUnit * 12
required property var metricsModel
required property color baseTextColor
required property bool fontBold
PlasmaComponents.Label {
text: "KVitals"
font.bold: true // intentional: title always bold for visual hierarchy
font.pixelSize: Kirigami.Theme.defaultFont.pixelSize * 1.2
Layout.alignment: Qt.AlignHCenter
Layout.bottomMargin: Kirigami.Units.smallSpacing
}
Repeater {
model: fullView.metricsModel
delegate: RowLayout {
required property var modelData
Layout.fillWidth: true
Layout.leftMargin: Kirigami.Units.largeSpacing
Layout.rightMargin: Kirigami.Units.largeSpacing
PlasmaComponents.Label {
text: modelData.label
color: fullView.baseTextColor
opacity: 0.7
Layout.fillWidth: true
}
PlasmaComponents.Label {
text: modelData.value
font.bold: fullView.fontBold
color: modelData.color
horizontalAlignment: Text.AlignRight
}
}
}
}
@@ -0,0 +1,425 @@
import QtQuick 2.0
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import Qt.labs.platform 1.0 as Platform
import org.kde.kirigami 2.5 as Kirigami
import org.kde.kcmutils as KCM
import "./sensors"
KCM.SimpleKCM {
id: colorsPage
property alias cfg_useCustomColors: useCustomColorsCheck.checked
property string cfg_fontColor
property alias cfg_enableThresholdColors: enableThresholdCheck.checked
property string cfg_warningColor: "#e5a50a"
property string cfg_criticalColor: "#da4453"
property alias cfg_cpuWarningThreshold: cpuWarnSlider.value
property alias cfg_cpuCriticalThreshold: cpuCritSlider.value
property alias cfg_tempWarningThreshold: tempWarnSlider.value
property alias cfg_tempCriticalThreshold: tempCritSlider.value
property alias cfg_ramWarningThreshold: ramWarnSlider.value
property alias cfg_ramCriticalThreshold: ramCritSlider.value
property alias cfg_gpuWarningThreshold: gpuWarnSlider.value
property alias cfg_gpuCriticalThreshold: gpuCritSlider.value
property alias cfg_gpuTempWarningThreshold: gpuTempWarnSlider.value
property alias cfg_gpuTempCriticalThreshold: gpuTempCritSlider.value
property alias cfg_batteryWarningThreshold: batWarnSlider.value
property alias cfg_batteryCriticalThreshold: batCritSlider.value
property alias cfg_diskTempWarningThreshold: diskTempWarnSlider.value
property alias cfg_diskTempCriticalThreshold: diskTempCritSlider.value
readonly property string defaultWarningColor: "#e5a50a"
readonly property string defaultCriticalColor: "#da4453"
property string cfg_tempUnit: "C"
function isRgbHex(value) {
return /^#[0-9A-Fa-f]{6}$/.test(value)
}
function colorToRgbHex(colorValue) {
if (!colorValue || colorValue.r === undefined || colorValue.g === undefined || colorValue.b === undefined) {
return ""
}
function channelToHex(channel) {
const value = Math.max(0, Math.min(255, Math.round(channel * 255)))
return value.toString(16).padStart(2, "0")
}
return "#" + channelToHex(colorValue.r) + channelToHex(colorValue.g) + channelToHex(colorValue.b)
}
function openColorDialog(dialog, value, fallbackColor) {
const initialColor = isRgbHex(value) ? value : fallbackColor
dialog.color = initialColor
dialog.currentColor = initialColor
dialog.open()
}
Kirigami.FormLayout {
// === Section: Custom Font Color ===
Kirigami.Separator {
Kirigami.FormData.isSection: true
Kirigami.FormData.label: i18n("Font Color")
}
CheckBox {
id: useCustomColorsCheck
Kirigami.FormData.label: i18n("Use custom font color:")
}
RowLayout {
Kirigami.FormData.label: i18n("Color:")
enabled: cfg_useCustomColors
spacing: Kirigami.Units.smallSpacing
Button {
id: fontColorButton
text: ""
padding: 0
implicitWidth: Kirigami.Units.gridUnit * 2
implicitHeight: Kirigami.Units.gridUnit * 1.5
onClicked: colorsPage.openColorDialog(fontColorDialog, cfg_fontColor, Kirigami.Theme.textColor)
background: Rectangle {
radius: 4
border.width: 1
border.color: fontColorButton.visualFocus ? Kirigami.Theme.highlightColor : Qt.rgba(1, 1, 1, 0.15)
color: "transparent"
Rectangle {
anchors.fill: parent
anchors.margins: 2
radius: 3
color: colorsPage.isRgbHex(cfg_fontColor) ? cfg_fontColor : Kirigami.Theme.textColor
}
}
}
Platform.ColorDialog {
id: fontColorDialog
title: i18n("Choose Font Color")
parentWindow: colorsPage.Window.window
onAccepted: {
const hex = colorsPage.colorToRgbHex(color)
if (!hex) {
return
}
if (hex !== fontColorField.text) {
fontColorField.text = hex
}
cfg_fontColor = hex
}
}
TextField {
id: fontColorField
placeholderText: "#ffffff"
text: cfg_fontColor
maximumLength: 7
Layout.preferredWidth: 100
onTextChanged: {
if (/^#[0-9A-Fa-f]{6}$/.test(text))
cfg_fontColor = text
}
}
Button {
text: i18n("Reset")
icon.name: "edit-undo"
onClicked: { fontColorField.text = ""; cfg_fontColor = "" }
}
}
// === Section: Threshold Colors ===
Kirigami.Separator {
Kirigami.FormData.isSection: true
Kirigami.FormData.label: i18n("Threshold Colors")
}
CheckBox {
id: enableThresholdCheck
Kirigami.FormData.label: i18n("Enable threshold coloring:")
}
RowLayout {
Kirigami.FormData.label: i18n("Warning color:")
enabled: cfg_enableThresholdColors
spacing: Kirigami.Units.smallSpacing
Button {
id: warningColorButton
text: ""
padding: 0
implicitWidth: Kirigami.Units.gridUnit * 2
implicitHeight: Kirigami.Units.gridUnit * 1.5
onClicked: colorsPage.openColorDialog(warningColorDialog, cfg_warningColor, colorsPage.defaultWarningColor)
background: Rectangle {
radius: 4
border.width: 1
border.color: warningColorButton.visualFocus ? Kirigami.Theme.highlightColor : Qt.rgba(1, 1, 1, 0.15)
color: "transparent"
Rectangle {
anchors.fill: parent
anchors.margins: 2
radius: 3
color: colorsPage.isRgbHex(cfg_warningColor) ? cfg_warningColor : colorsPage.defaultWarningColor
}
}
}
Platform.ColorDialog {
id: warningColorDialog
title: i18n("Choose Warning Color")
parentWindow: colorsPage.Window.window
onAccepted: {
const hex = colorsPage.colorToRgbHex(color)
if (!hex) {
return
}
if (hex !== warningColorField.text) {
warningColorField.text = hex
}
cfg_warningColor = hex
}
}
TextField {
id: warningColorField
text: cfg_warningColor
maximumLength: 7
Layout.preferredWidth: 100
onTextChanged: {
if (/^#[0-9A-Fa-f]{6}$/.test(text))
cfg_warningColor = text
}
}
}
RowLayout {
Kirigami.FormData.label: i18n("Critical color:")
enabled: cfg_enableThresholdColors
spacing: Kirigami.Units.smallSpacing
Button {
id: criticalColorButton
text: ""
padding: 0
implicitWidth: Kirigami.Units.gridUnit * 2
implicitHeight: Kirigami.Units.gridUnit * 1.5
onClicked: colorsPage.openColorDialog(criticalColorDialog, cfg_criticalColor, colorsPage.defaultCriticalColor)
background: Rectangle {
radius: 4
border.width: 1
border.color: criticalColorButton.visualFocus ? Kirigami.Theme.highlightColor : Qt.rgba(1, 1, 1, 0.15)
color: "transparent"
Rectangle {
anchors.fill: parent
anchors.margins: 2
radius: 3
color: colorsPage.isRgbHex(cfg_criticalColor) ? cfg_criticalColor : colorsPage.defaultCriticalColor
}
}
}
Platform.ColorDialog {
id: criticalColorDialog
title: i18n("Choose Critical Color")
parentWindow: colorsPage.Window.window
onAccepted: {
const hex = colorsPage.colorToRgbHex(color)
if (!hex) {
return
}
if (hex !== criticalColorField.text) {
criticalColorField.text = hex
}
cfg_criticalColor = hex
}
}
TextField {
id: criticalColorField
text: cfg_criticalColor
maximumLength: 7
Layout.preferredWidth: 100
onTextChanged: {
if (/^#[0-9A-Fa-f]{6}$/.test(text))
cfg_criticalColor = text
}
}
}
// === Section: Thresholds Grid ===
Kirigami.Separator {
Kirigami.FormData.isSection: true
Kirigami.FormData.label: i18n("Thresholds")
visible: cfg_enableThresholdColors
}
GridLayout {
visible: cfg_enableThresholdColors
columns: 4
columnSpacing: Kirigami.Units.largeSpacing
rowSpacing: Kirigami.Units.smallSpacing
Layout.fillWidth: true
// --- Header ---
Label { text: "" }
Label { text: i18n("Warning"); font.bold: true; horizontalAlignment: Text.AlignHCenter; Layout.fillWidth: true }
Label { text: i18n("Critical"); font.bold: true; horizontalAlignment: Text.AlignHCenter; Layout.fillWidth: true }
Label { text: "" }
// --- CPU Usage ---
Label { text: i18n("CPU Usage") }
RowLayout {
Layout.fillWidth: true
Slider { id: cpuWarnSlider; from: 10; to: 100; stepSize: 5; value: 70; Layout.fillWidth: true }
Label { text: Math.round(cpuWarnSlider.value) + "%"; Layout.preferredWidth: 40 }
}
RowLayout {
Layout.fillWidth: true
Slider { id: cpuCritSlider; from: 10; to: 100; stepSize: 5; value: 90; Layout.fillWidth: true }
Label { text: Math.round(cpuCritSlider.value) + "%"; Layout.preferredWidth: 40 }
}
Rectangle { Layout.preferredWidth: 10; Layout.preferredHeight: 10; radius: 5; color: cpuWarnSlider.value >= cpuCritSlider.value ? cfg_criticalColor : "transparent" }
// --- CPU Temperature ---
Label { text: i18n("CPU Temp") }
RowLayout {
Layout.fillWidth: true
Slider { id: tempWarnSlider; from: 30; to: 110; stepSize: 5; value: 60; Layout.fillWidth: true }
Label { text: Utils.formatTemp(tempWarnSlider.value, cfg_tempUnit); Layout.preferredWidth: 40 }
}
RowLayout {
Layout.fillWidth: true
Slider { id: tempCritSlider; from: 30; to: 110; stepSize: 5; value: 85; Layout.fillWidth: true }
Label { text: Utils.formatTemp(tempCritSlider.value, cfg_tempUnit); Layout.preferredWidth: 40 }
}
Rectangle { Layout.preferredWidth: 10; Layout.preferredHeight: 10; radius: 5; color: tempWarnSlider.value >= tempCritSlider.value ? cfg_criticalColor : "transparent" }
// --- RAM Usage ---
Label { text: i18n("RAM Usage") }
RowLayout {
Layout.fillWidth: true
Slider { id: ramWarnSlider; from: 10; to: 100; stepSize: 5; value: 70; Layout.fillWidth: true }
Label { text: Math.round(ramWarnSlider.value) + "%"; Layout.preferredWidth: 40 }
}
RowLayout {
Layout.fillWidth: true
Slider { id: ramCritSlider; from: 10; to: 100; stepSize: 5; value: 90; Layout.fillWidth: true }
Label { text: Math.round(ramCritSlider.value) + "%"; Layout.preferredWidth: 40 }
}
Rectangle { Layout.preferredWidth: 10; Layout.preferredHeight: 10; radius: 5; color: ramWarnSlider.value >= ramCritSlider.value ? cfg_criticalColor : "transparent" }
// --- GPU Usage ---
Label { text: i18n("GPU Usage") }
RowLayout {
Layout.fillWidth: true
Slider { id: gpuWarnSlider; from: 10; to: 100; stepSize: 5; value: 70; Layout.fillWidth: true }
Label { text: Math.round(gpuWarnSlider.value) + "%"; Layout.preferredWidth: 40 }
}
RowLayout {
Layout.fillWidth: true
Slider { id: gpuCritSlider; from: 10; to: 100; stepSize: 5; value: 90; Layout.fillWidth: true }
Label { text: Math.round(gpuCritSlider.value) + "%"; Layout.preferredWidth: 40 }
}
Rectangle { Layout.preferredWidth: 10; Layout.preferredHeight: 10; radius: 5; color: gpuWarnSlider.value >= gpuCritSlider.value ? cfg_criticalColor : "transparent" }
// --- GPU Temperature ---
Label { text: i18n("GPU Temp") }
RowLayout {
Layout.fillWidth: true
Slider { id: gpuTempWarnSlider; from: 30; to: 110; stepSize: 5; value: 60; Layout.fillWidth: true }
Label { text: Utils.formatTemp(gpuTempWarnSlider.value, cfg_tempUnit); Layout.preferredWidth: 40 }
}
RowLayout {
Layout.fillWidth: true
Slider { id: gpuTempCritSlider; from: 30; to: 110; stepSize: 5; value: 85; Layout.fillWidth: true }
Label { text: Utils.formatTemp(gpuTempCritSlider.value, cfg_tempUnit); Layout.preferredWidth: 40 }
}
Rectangle { Layout.preferredWidth: 10; Layout.preferredHeight: 10; radius: 5; color: gpuTempWarnSlider.value >= gpuTempCritSlider.value ? cfg_criticalColor : "transparent" }
// --- Battery (inverted) ---
Label { text: i18n("Battery ↓") }
RowLayout {
Layout.fillWidth: true
Slider { id: batWarnSlider; from: 5; to: 60; stepSize: 5; value: 30; Layout.fillWidth: true }
Label { text: Math.round(batWarnSlider.value) + "%"; Layout.preferredWidth: 40 }
}
RowLayout {
Layout.fillWidth: true
Slider { id: batCritSlider; from: 5; to: 60; stepSize: 5; value: 15; Layout.fillWidth: true }
Label { text: Math.round(batCritSlider.value) + "%"; Layout.preferredWidth: 40 }
}
Rectangle { Layout.preferredWidth: 10; Layout.preferredHeight: 10; radius: 5; color: batWarnSlider.value <= batCritSlider.value ? cfg_criticalColor : "transparent" }
// --- Disk Temperature ---
Label { text: i18n("Disk Temp") }
RowLayout {
Layout.fillWidth: true
Slider { id: diskTempWarnSlider; from: 30; to: 80; stepSize: 5; value: 45; Layout.fillWidth: true }
Label { text: Utils.formatTemp(diskTempWarnSlider.value, cfg_tempUnit); Layout.preferredWidth: 40 }
}
RowLayout {
Layout.fillWidth: true
Slider { id: diskTempCritSlider; from: 30; to: 80; stepSize: 5; value: 60; Layout.fillWidth: true }
Label { text: Utils.formatTemp(diskTempCritSlider.value, cfg_tempUnit); Layout.preferredWidth: 40 }
}
Rectangle { Layout.preferredWidth: 10; Layout.preferredHeight: 10; radius: 5; color: diskTempWarnSlider.value >= diskTempCritSlider.value ? cfg_criticalColor : "transparent" }
}
Label {
visible: cfg_enableThresholdColors
text: i18n("Battery uses inverted thresholds — warning/critical trigger below the set values.\nA red dot means warning ≥ critical (invalid config).")
opacity: 0.6
font.italic: true
wrapMode: Text.WordWrap
Layout.fillWidth: true
}
// --- Reset ---
Kirigami.Separator {
Kirigami.FormData.isSection: true
}
Button {
icon.name: "edit-undo"
text: i18n("Reset all to defaults")
onClicked: {
useCustomColorsCheck.checked = false
fontColorField.text = ""
cfg_fontColor = ""
enableThresholdCheck.checked = false
warningColorField.text = colorsPage.defaultWarningColor
cfg_warningColor = colorsPage.defaultWarningColor
criticalColorField.text = colorsPage.defaultCriticalColor
cfg_criticalColor = colorsPage.defaultCriticalColor
cpuWarnSlider.value = 70; cpuCritSlider.value = 90
tempWarnSlider.value = 60; tempCritSlider.value = 85
ramWarnSlider.value = 70; ramCritSlider.value = 90
gpuWarnSlider.value = 70; gpuCritSlider.value = 90
gpuTempWarnSlider.value = 60; gpuTempCritSlider.value = 85
batWarnSlider.value = 30; batCritSlider.value = 15
diskTempWarnSlider.value = 45; diskTempCritSlider.value = 60
}
}
}
}
@@ -0,0 +1,154 @@
import QtQuick 2.0
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import org.kde.kirigami 2.5 as Kirigami
import org.kde.kcmutils as KCM
KCM.SimpleKCM {
id: configPage
property alias cfg_updateInterval: intervalSlider.value
property alias cfg_iconSize: iconSizeSlider.value
property alias cfg_fontSize: fontSizeSlider.value
property alias cfg_fontBold: fontBoldCheck.checked
property string cfg_displayMode: "text"
property string cfg_fontFamily: "monospace"
property string cfg_layoutType: "horizontal"
property string cfg_tempUnit: "C"
property string cfg_networkUnit: "bytes"
property string cfg_fanUnit: "rpm"
readonly property var displayModes: ["text", "icons", "icons+text", "none"]
readonly property var displayModeLabels: [i18n("Text"), i18n("Icons"), i18n("Icons + Text"), i18n("None")]
readonly property bool iconsEnabled: cfg_displayMode === "icons" || cfg_displayMode === "icons+text"
readonly property var layoutTypes: ["horizontal", "vertical"]
readonly property var layoutTypeLabels: [i18n("Horizontal"), i18n("Vertical")]
Kirigami.FormLayout {
ComboBox {
id: displayModeCombo
Kirigami.FormData.label: i18n("Display mode:")
model: configPage.displayModeLabels
currentIndex: {
var idx = configPage.displayModes.indexOf(cfg_displayMode);
return idx >= 0 ? idx : 0;
}
onActivated: {
cfg_displayMode = configPage.displayModes[currentIndex];
}
}
ComboBox {
id: layoutTypeCombo
Kirigami.FormData.label: i18n("Layout:")
model: configPage.layoutTypeLabels
currentIndex: {
var idx = configPage.layoutTypes.indexOf(cfg_layoutType);
return idx >= 0 ? idx : 0;
}
onActivated: {
cfg_layoutType = configPage.layoutTypes[currentIndex];
}
}
Slider {
id: iconSizeSlider
Kirigami.FormData.label: i18n("Icon size:")
from: 8
to: 24
stepSize: 2
value: 12
visible: configPage.iconsEnabled
}
Label {
text: iconSizeSlider.value + " px"
opacity: 0.7
visible: configPage.iconsEnabled
}
ComboBox {
id: fontFamilyCombo
Kirigami.FormData.label: i18n("Font:")
model: Qt.fontFamilies()
editable: true
currentIndex: {
var families = Qt.fontFamilies();
var idx = families.indexOf(cfg_fontFamily);
return idx >= 0 ? idx : 0;
}
onActivated: {
cfg_fontFamily = currentText;
}
onAccepted: {
cfg_fontFamily = editText;
}
popup.height: 300
}
Slider {
id: fontSizeSlider
Kirigami.FormData.label: i18n("Font size:")
from: 0
to: 24
stepSize: 1
value: 0
}
Label {
text: fontSizeSlider.value === 0 ? i18n("System default") : fontSizeSlider.value + " px"
opacity: 0.7
}
CheckBox {
id: fontBoldCheck
Kirigami.FormData.label: i18n("Bold font:")
text: i18n("Bold")
}
Slider {
id: intervalSlider
Kirigami.FormData.label: i18n("Update interval:")
from: 1000
to: 10000
stepSize: 500
value: 2000
}
Label {
text: (intervalSlider.value / 1000).toFixed(1) + " " + i18n("seconds")
opacity: 0.7
}
Kirigami.Separator {
Kirigami.FormData.isSection: true
Kirigami.FormData.label: i18n("Unit Preferences")
}
ComboBox {
id: tempUnitCombo
Kirigami.FormData.label: i18n("Temperature unit:")
model: [i18n("Celsius (°C)"), i18n("Fahrenheit (°F)")]
currentIndex: cfg_tempUnit === "F" ? 1 : 0
onActivated: cfg_tempUnit = (currentIndex === 1 ? "F" : "C")
}
ComboBox {
id: networkUnitCombo
Kirigami.FormData.label: i18n("Network/Disk I/O unit:")
model: [i18n("Bytes (KB, MB)"), i18n("Bits (Kb, Mb)")]
currentIndex: cfg_networkUnit === "bits" ? 1 : 0
onActivated: cfg_networkUnit = (currentIndex === 1 ? "bits" : "bytes")
}
ComboBox {
id: fanUnitCombo
Kirigami.FormData.label: i18n("Fan Speed unit:")
model: [i18n("RPM"), i18n("Percentage (%)")]
currentIndex: cfg_fanUnit === "percent" ? 1 : 0
onActivated: cfg_fanUnit = (currentIndex === 1 ? "percent" : "rpm")
}
}
}
@@ -0,0 +1,131 @@
import QtQuick 2.0
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.0
import org.kde.kirigami 2.5 as Kirigami
import org.kde.kcmutils as KCM
import org.kde.iconthemes as KIconThemes
KCM.SimpleKCM {
id: iconsPage
property string cfg_cpuIcon: "cpu"
property string cfg_ramIcon: "memory"
property string cfg_tempIcon: "temperature-normal"
property string cfg_gpuIcon: "video-card"
property string cfg_batteryIcon: "battery-good"
property string cfg_powerIcon: "battery-charging-60"
property string cfg_networkIcon: "network-wireless"
property string cfg_diskIcon: "drive-harddisk"
property string cfg_fanIcon: "fan"
KIconThemes.IconDialog {
id: cpuIconDialog
onIconNameChanged: if (iconName) cfg_cpuIcon = iconName
}
KIconThemes.IconDialog {
id: ramIconDialog
onIconNameChanged: if (iconName) cfg_ramIcon = iconName
}
KIconThemes.IconDialog {
id: tempIconDialog
onIconNameChanged: if (iconName) cfg_tempIcon = iconName
}
KIconThemes.IconDialog {
id: gpuIconDialog
onIconNameChanged: if (iconName) cfg_gpuIcon = iconName
}
KIconThemes.IconDialog {
id: batteryIconDialog
onIconNameChanged: if (iconName) cfg_batteryIcon = iconName
}
KIconThemes.IconDialog {
id: powerIconDialog
onIconNameChanged: if (iconName) cfg_powerIcon = iconName
}
KIconThemes.IconDialog {
id: networkIconDialog
onIconNameChanged: if (iconName) cfg_networkIcon = iconName
}
KIconThemes.IconDialog {
id: diskIconDialog
onIconNameChanged: if (iconName) cfg_diskIcon = iconName
}
KIconThemes.IconDialog {
id: fanIconDialog
onIconNameChanged: if (iconName) cfg_fanIcon = iconName
}
Kirigami.FormLayout {
RowLayout {
Kirigami.FormData.label: i18n("CPU:")
Kirigami.Icon { source: cfg_cpuIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: cpuIconDialog.open(); icon.name: "document-edit" }
}
RowLayout {
Kirigami.FormData.label: i18n("RAM:")
Kirigami.Icon { source: cfg_ramIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: ramIconDialog.open(); icon.name: "document-edit" }
}
RowLayout {
Kirigami.FormData.label: i18n("Temperature:")
Kirigami.Icon { source: cfg_tempIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: tempIconDialog.open(); icon.name: "document-edit" }
}
RowLayout {
Kirigami.FormData.label: i18n("GPU:")
Kirigami.Icon { source: cfg_gpuIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: gpuIconDialog.open(); icon.name: "document-edit" }
}
RowLayout {
Kirigami.FormData.label: i18n("Battery:")
Kirigami.Icon { source: cfg_batteryIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: batteryIconDialog.open(); icon.name: "document-edit" }
}
RowLayout {
Kirigami.FormData.label: i18n("Power:")
Kirigami.Icon { source: cfg_powerIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: powerIconDialog.open(); icon.name: "document-edit" }
}
RowLayout {
Kirigami.FormData.label: i18n("Network:")
Kirigami.Icon { source: cfg_networkIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: networkIconDialog.open(); icon.name: "document-edit" }
}
RowLayout {
Kirigami.FormData.label: i18n("Disk:")
Kirigami.Icon { source: cfg_diskIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: diskIconDialog.open(); icon.name: "document-edit" }
}
RowLayout {
Kirigami.FormData.label: i18n("Fan:")
Kirigami.Icon { source: cfg_fanIcon; isMask: true; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
Button { text: i18n("Change..."); onClicked: fanIconDialog.open(); icon.name: "document-edit" }
}
Button {
icon.name: "edit-undo"
text: i18n("Reset to defaults")
Kirigami.FormData.label: " "
onClicked: {
cfg_cpuIcon = "cpu";
cfg_ramIcon = "memory";
cfg_tempIcon = "temperature-normal";
cfg_gpuIcon = "video-card";
cfg_batteryIcon = "battery-good";
cfg_powerIcon = "battery-charging-60";
cfg_networkIcon = "network-wireless";
cfg_diskIcon = "drive-harddisk";
cfg_fanIcon = "fan";
}
}
}
}
@@ -0,0 +1,669 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import org.kde.kirigami as Kirigami
import org.kde.kcmutils as KCM
import org.kde.plasma.plasma5support as Plasma5Support
import org.kde.ksysguard.sensors as Sensors
import org.kde.kitemmodels as KItemModels
KCM.SimpleKCM {
id: metricsPage
// --- cfg_ bindings (must match main.xml keys exactly) ---
property bool cfg_showCpu
property bool cfg_showRam
property bool cfg_showTemp
property bool cfg_showGpu
property bool cfg_showBattery
property bool cfg_showPower
property bool cfg_showNetwork
property bool cfg_showDisk
property bool cfg_showFan
property bool cfg_compactShowCpu
property bool cfg_compactShowRam
property bool cfg_compactShowTemp
property bool cfg_compactShowGpu
property bool cfg_compactShowBattery
property bool cfg_compactShowPower
property bool cfg_compactShowNetwork
property bool cfg_compactShowDisk
property bool cfg_compactShowFan
property string cfg_networkInterface: "auto"
property string cfg_batteryDevice
property string cfg_gpuSelection: ""
property string cfg_gpuLabels: ""
property string cfg_metricOrder: "cpu,ram,temp,gpu,bat,pwr,net,disk"
property bool cfg_mergeCpuTemp: false
property bool cfg_mergeCpuFreq: false
property bool cfg_mergeBatPwr: false
property bool cfg_splitGpu: false
property string cfg_gpuMetrics: ""
property bool cfg_showCpuFreq: false
// --- GPU discovery via SensorTreeModel (pure metadata, no polling) ---
Sensors.SensorTreeModel { id: cfgSensorTree }
KItemModels.KDescendantsProxyModel { id: cfgFlatSensors; model: cfgSensorTree }
property var _liveDiscoveredGpus: []
Timer {
id: gpuRefreshDebounce
interval: 100
repeat: false
onTriggered: {
var found = [];
for (var row = 0; row < cfgFlatSensors.rowCount(); row++) {
var idx = cfgFlatSensors.index(row, 0);
var sensorId = cfgFlatSensors.data(idx, Sensors.SensorTreeModel.SensorId);
if (!sensorId || sensorId.length === 0) continue;
var match = sensorId.match(/^gpu\/(gpu\d+)\/usage$/);
if (!match) continue;
found.push({ id: match[1], name: "GPU " + (found.length + 1) });
}
if (JSON.stringify(found) !== JSON.stringify(_liveDiscoveredGpus))
_liveDiscoveredGpus = found;
}
}
function refreshConfigGpus() {
gpuRefreshDebounce.restart();
}
property bool _discoveryDirty: false
Timer {
id: discoveryTimer
interval: 500
repeat: false
running: _discoveryDirty
onTriggered: {
_discoveryDirty = false;
metricsPage.refreshConfigGpus();
}
}
Connections {
target: cfgFlatSensors
function onRowsInserted() { metricsPage._discoveryDirty = true; }
function onRowsRemoved() { metricsPage._discoveryDirty = true; }
function onModelReset() { metricsPage._discoveryDirty = true; }
function onDataChanged() { metricsPage._discoveryDirty = true; }
}
readonly property var discoveredGpus: {
if (_liveDiscoveredGpus.length > 0) return _liveDiscoveredGpus;
if (!cfg_gpuDiscovered) return [];
return cfg_gpuDiscovered.split(",").filter(function(s){ return s.indexOf(":") >= 0; }).map(function(s){
var parts = s.split(":");
return { id: parts[0], name: parts.slice(1).join(":") };
});
}
// --- Network interface discovery ---
property var ifaceList: ["auto"]
Plasma5Support.DataSource {
id: ifaceSource
engine: "executable"
connectedSources: ["ls /sys/class/net/"]
onNewData: function (source, data) {
if (data["exit code"] !== 0) return;
var raw = data["stdout"].trim();
if (raw.length === 0) return;
var ifaces = raw.split("\n").filter(function (name) {
return name !== "lo" && name.length > 0;
});
ifaces.unshift("auto");
metricsPage.ifaceList = ifaces;
}
}
// --- GPU label helpers ---
function parseGpuLabels(str) {
var result = {};
if (!str) return result;
str.split("|").forEach(function(pair) {
var sep = pair.indexOf(":");
if (sep > 0) result[pair.substring(0, sep)] = pair.substring(sep + 1);
});
return result;
}
function saveGpuLabel(gpuId, label) {
var labels = parseGpuLabels(cfg_gpuLabels);
var trimmed = (label || "").trim();
if (trimmed.length > 0) labels[gpuId] = trimmed;
else delete labels[gpuId];
var parts = [];
for (var id in labels) parts.push(id + ":" + labels[id]);
cfg_gpuLabels = parts.join("|");
}
// --- GPU sub-metric helpers ---
function parseGpuMetrics(str) {
var result = {};
if (!str) return result;
str.split("|").forEach(function(pair) {
var sep = pair.indexOf(":");
if (sep <= 0) return;
var id = pair.substring(0, sep);
var metrics = pair.substring(sep + 1).split(",").filter(function(m){
return m === "usage" || m === "vram" || m === "temp";
});
if (metrics.length > 0) result[id] = metrics;
});
return result;
}
function gpuMetricsFor(gpuId) {
var mm = parseGpuMetrics(cfg_gpuMetrics);
return (mm[gpuId] && mm[gpuId].length > 0) ? mm[gpuId] : ["usage", "vram", "temp"];
}
function saveGpuMetric(gpuId, metric, enable) {
var mm = parseGpuMetrics(cfg_gpuMetrics);
var current = mm[gpuId] ? mm[gpuId].slice() : ["usage", "vram", "temp"];
if (enable) {
if (current.indexOf(metric) < 0) current.push(metric);
} else {
if (current.length <= 1) return;
current = current.filter(function(m){ return m !== metric; });
}
var order = ["usage", "vram", "temp"];
current.sort(function(a, b){ return order.indexOf(a) - order.indexOf(b); });
if (current.length === 3) delete mm[gpuId];
else mm[gpuId] = current;
var parts = [];
for (var id in mm) parts.push(id + ":" + mm[id].join(","));
cfg_gpuMetrics = parts.join("|");
}
// --- Metric order helpers ---
readonly property var allKeys: ["cpu", "ram", "temp", "gpu", "bat", "pwr", "net", "disk", "fan"]
readonly property var metricMeta: ({
"cpu": { label: i18n("CPU usage"), icon: "cpu" },
"ram": { label: i18n("RAM usage"), icon: "memory" },
"temp": { label: i18n("CPU temperature"), icon: "temperature-normal" },
"gpu": { label: i18n("GPU metrics"), icon: "video-card" },
"bat": { label: i18n("Battery status"), icon: "battery-good" },
"pwr": { label: i18n("Power consumption"), icon: "battery-charging-60" },
"net": { label: i18n("Network speed"), icon: "network-wireless" },
"disk": { label: i18n("Disk I/O & temp"), icon: "drive-harddisk" },
"fan": { label: i18n("Fan speed"), icon: "fan" }
})
property var currentOrder: {
var keys = cfg_metricOrder.split(",").map(function(k){ return k.trim(); })
.filter(function(k){ return k.length > 0 && metricMeta[k] !== undefined; });
allKeys.forEach(function(k){ if (keys.indexOf(k) < 0) keys.push(k); });
return keys;
}
function isChecked(key) {
switch (key) {
case "cpu": return cfg_showCpu;
case "ram": return cfg_showRam;
case "temp": return cfg_showTemp;
case "gpu": return cfg_showGpu;
case "bat": return cfg_showBattery;
case "pwr": return cfg_showPower;
case "net": return cfg_showNetwork;
case "disk": return cfg_showDisk;
case "fan": return cfg_showFan;
}
return false;
}
function isCompactChecked(key) {
switch (key) {
case "cpu": return cfg_compactShowCpu;
case "ram": return cfg_compactShowRam;
case "temp": return cfg_compactShowTemp;
case "gpu": return cfg_compactShowGpu;
case "bat": return cfg_compactShowBattery;
case "pwr": return cfg_compactShowPower;
case "net": return cfg_compactShowNetwork;
case "disk": return cfg_compactShowDisk;
case "fan": return cfg_compactShowFan;
}
return false;
}
function setChecked(key, val) {
switch (key) {
case "cpu": cfg_showCpu = val; break;
case "ram": cfg_showRam = val; break;
case "temp": cfg_showTemp = val; break;
case "gpu": cfg_showGpu = val; break;
case "bat": cfg_showBattery = val; break;
case "pwr": cfg_showPower = val; break;
case "net": cfg_showNetwork = val; break;
case "disk": cfg_showDisk = val; break;
case "fan": cfg_showFan = val; break;
}
if (!val) {
if ((key === "cpu" || key === "temp") && cfg_mergeCpuTemp) cfg_mergeCpuTemp = false;
if ((key === "bat" || key === "pwr") && cfg_mergeBatPwr) cfg_mergeBatPwr = false;
if (key === "gpu" && cfg_splitGpu) cfg_splitGpu = false;
}
}
function setCompactChecked(key, val) {
switch (key) {
case "cpu": cfg_compactShowCpu = val; break;
case "ram": cfg_compactShowRam = val; break;
case "temp": cfg_compactShowTemp = val; break;
case "gpu": cfg_compactShowGpu = val; break;
case "bat": cfg_compactShowBattery = val; break;
case "pwr": cfg_compactShowPower = val; break;
case "net": cfg_compactShowNetwork = val; break;
case "disk": cfg_compactShowDisk = val; break;
case "fan": cfg_compactShowFan = val; break;
}
}
function moveMetric(fromIndex, toIndex) {
var keys = currentOrder.slice();
var item = keys.splice(fromIndex, 1)[0];
keys.splice(toIndex, 0, item);
cfg_metricOrder = keys.join(",");
}
// =========================================================================
// UI
// =========================================================================
// Prevent "ugly to correct" UI flash during initial layout calculations
property bool _isReady: false
Timer {
id: readyTimer
interval: 100
running: true
repeat: false
onTriggered: metricsPage._isReady = true
}
BusyIndicator {
anchors.centerIn: metricsPage
running: !metricsPage._isReady
visible: running
z: 999
}
Kirigami.FormLayout {
opacity: metricsPage._isReady ? 1 : 0
Behavior on opacity { NumberAnimation { duration: 150 } }
// ----- Section header -----
Kirigami.Separator {
Kirigami.FormData.isSection: true
Kirigami.FormData.label: i18n("Visibility & Order")
}
// Column headers row
RowLayout {
spacing: Kirigami.Units.smallSpacing
Label {
text: i18n("Metric (Full view)")
font.bold: true
opacity: 0.7
Layout.preferredWidth: Kirigami.Units.gridUnit * 14
}
Label {
text: i18n("Compact")
font.bold: true
opacity: 0.7
Layout.preferredWidth: Kirigami.Units.gridUnit * 4
horizontalAlignment: Text.AlignHCenter
}
Item { Layout.fillWidth: true }
}
// Metric rows
ColumnLayout {
spacing: 0
Layout.fillWidth: true
Repeater {
model: metricsPage.currentOrder
delegate: ColumnLayout {
id: metricDelegate
required property var modelData
required property int index
spacing: 0
Layout.fillWidth: true
// Hide metrics absorbed by a merge group
visible: !(modelData === "temp" && cfg_mergeCpuTemp && cfg_showCpu) &&
!(modelData === "pwr" && cfg_mergeBatPwr && cfg_showBattery)
// Resolved shorthands for readability inside this delegate
readonly property bool metricEnabled: metricsPage.isChecked(modelData)
readonly property string metricLabel: (metricsPage.metricMeta[modelData] || {}).label || modelData
readonly property string metricIcon: (metricsPage.metricMeta[modelData] || {}).icon || "help-about"
// ── Main row ──────────────────────────────────────────────
RowLayout {
Layout.fillWidth: true
spacing: Kirigami.Units.smallSpacing
// Metric toggle
CheckBox {
id: enabledCheck
text: metricDelegate.metricLabel
checked: metricDelegate.metricEnabled
onToggled: metricsPage.setChecked(modelData, checked)
Layout.preferredWidth: Kirigami.Units.gridUnit * 14
}
// Compact-view toggle
Item {
Layout.preferredWidth: Kirigami.Units.gridUnit * 4
Layout.minimumHeight: compactCheck.implicitHeight
CheckBox {
id: compactCheck
anchors.centerIn: parent
checked: metricsPage.isCompactChecked(modelData)
enabled: metricDelegate.metricEnabled
onToggled: metricsPage.setCompactChecked(modelData, checked)
// Accessible name for keyboard/screen-reader users
Accessible.name: i18n("Show %1 in compact panel", metricDelegate.metricLabel)
}
}
// Spacer
Item { Layout.fillWidth: true }
// Reorder buttons
Button {
icon.name: "arrow-up"
flat: true
enabled: index > 0
implicitWidth: Kirigami.Units.gridUnit * 2
implicitHeight: Kirigami.Units.gridUnit * 2
onClicked: metricsPage.moveMetric(index, index - 1)
ToolTip.text: i18n("Move up")
ToolTip.visible: hovered
ToolTip.delay: Kirigami.Units.toolTipDelay
}
Button {
icon.name: "arrow-down"
flat: true
enabled: index < metricsPage.currentOrder.length - 1
implicitWidth: Kirigami.Units.gridUnit * 2
implicitHeight: Kirigami.Units.gridUnit * 2
onClicked: metricsPage.moveMetric(index, index + 1)
ToolTip.text: i18n("Move down")
ToolTip.visible: hovered
ToolTip.delay: Kirigami.Units.toolTipDelay
}
}
// ── Inline per-metric settings (visible only when enabled) ──
// Each block is keyed to its metric so context is never lost.
// CPU settings
Loader {
active: modelData === "cpu" && metricDelegate.metricEnabled
visible: active
Layout.fillWidth: true
Layout.leftMargin: Kirigami.Units.gridUnit + Kirigami.Units.smallSpacing
Layout.topMargin: Kirigami.Units.smallSpacing
sourceComponent: ColumnLayout {
spacing: Kirigami.Units.smallSpacing
RowLayout {
spacing: Kirigami.Units.largeSpacing
CheckBox {
text: i18n("Show CPU frequency")
checked: cfg_showCpuFreq
onToggled: {
cfg_showCpuFreq = checked;
if (!checked) cfg_mergeCpuFreq = false;
}
}
CheckBox {
text: i18n("Merge frequency into compact view")
checked: cfg_mergeCpuFreq
enabled: cfg_showCpuFreq
onToggled: cfg_mergeCpuFreq = checked
}
}
CheckBox {
visible: cfg_showTemp
text: i18n("Show temperature next to usage (merge CPU & temp)")
checked: cfg_mergeCpuTemp
enabled: cfg_showTemp
onToggled: cfg_mergeCpuTemp = checked
}
}
}
// Network settings
Loader {
active: modelData === "net" && metricDelegate.metricEnabled
visible: active
Layout.fillWidth: true
Layout.leftMargin: Kirigami.Units.gridUnit + Kirigami.Units.smallSpacing
Layout.topMargin: Kirigami.Units.smallSpacing
sourceComponent: RowLayout {
spacing: Kirigami.Units.smallSpacing
Label { text: i18n("Interface:") }
ComboBox {
id: ifaceCombo
model: metricsPage.ifaceList
currentIndex: {
var idx = metricsPage.ifaceList.indexOf(cfg_networkInterface);
return idx >= 0 ? idx : 0;
}
onActivated: cfg_networkInterface = metricsPage.ifaceList[currentIndex]
implicitWidth: Kirigami.Units.gridUnit * 10
}
}
}
// Battery settings
Loader {
active: modelData === "bat" && metricDelegate.metricEnabled
visible: active
Layout.fillWidth: true
Layout.leftMargin: Kirigami.Units.gridUnit + Kirigami.Units.smallSpacing
Layout.topMargin: Kirigami.Units.smallSpacing
sourceComponent: ColumnLayout {
spacing: Kirigami.Units.smallSpacing
RowLayout {
spacing: Kirigami.Units.smallSpacing
Label { text: i18n("Device:") }
TextField {
id: batteryInput
text: cfg_batteryDevice === "auto" ? "" : cfg_batteryDevice
placeholderText: i18n("Leave empty for auto-detect (e.g. BAT0)")
implicitWidth: Kirigami.Units.gridUnit * 14
onTextEdited: {
var v = text.trim();
cfg_batteryDevice = v.length > 0 ? v : "auto";
}
}
}
CheckBox {
visible: cfg_showPower
text: i18n("Show power consumption next to battery level (merge battery & power)")
checked: cfg_mergeBatPwr
enabled: cfg_showPower
onToggled: cfg_mergeBatPwr = checked
}
}
}
// GPU settings
Loader {
active: modelData === "gpu" && metricDelegate.metricEnabled
visible: active
Layout.fillWidth: true
Layout.leftMargin: Kirigami.Units.gridUnit + Kirigami.Units.smallSpacing
Layout.topMargin: Kirigami.Units.smallSpacing
sourceComponent: ColumnLayout {
spacing: Kirigami.Units.smallSpacing
// Split GPU option
CheckBox {
text: i18n("Show usage, VRAM and temperature as separate entries (split GPU metrics)")
checked: cfg_splitGpu
onToggled: cfg_splitGpu = checked
}
// No GPU found yet (Loading state)
RowLayout {
visible: metricsPage.discoveredGpus.length === 0
spacing: Kirigami.Units.smallSpacing
BusyIndicator {
running: parent.visible
Layout.preferredWidth: Kirigami.Units.gridUnit
Layout.preferredHeight: Kirigami.Units.gridUnit
}
Label {
text: i18n("Discovering GPUs...")
opacity: 0.7
font.italic: true
}
}
// Hybrid GPU tip
Label {
visible: metricsPage.discoveredGpus.length > 1
text: i18n("Tip: on hybrid-GPU laptops, uncheck the discrete GPU to let it suspend and save power.")
opacity: 0.7
font.italic: true
wrapMode: Text.WordWrap
Layout.maximumWidth: Kirigami.Units.gridUnit * 24
}
// Per-GPU rows
Repeater {
id: gpuSelectorRepeater
model: metricsPage.discoveredGpus
delegate: ColumnLayout {
id: gpuDelegate
required property var modelData
spacing: Kirigami.Units.smallSpacing
Layout.fillWidth: true
Layout.leftMargin: Kirigami.Units.smallSpacing
property var _activeMetrics: metricsPage.gpuMetricsFor(modelData.id)
property bool _gpuEnabled: {
if (!cfg_gpuSelection || cfg_gpuSelection === "") return true;
if (cfg_gpuSelection === "none") return false;
return cfg_gpuSelection.split(",").indexOf(modelData.id) >= 0;
}
// GPU enable checkbox
CheckBox {
text: gpuDelegate.modelData.name
checked: gpuDelegate._gpuEnabled
onToggled: {
var ids;
if (!cfg_gpuSelection || cfg_gpuSelection === "") {
ids = gpuSelectorRepeater.model.map(function(g){ return g.id; });
} else if (cfg_gpuSelection === "none") {
ids = [];
} else {
ids = cfg_gpuSelection.split(",").filter(function(s){ return s.length > 0; });
}
if (checked) {
if (ids.indexOf(modelData.id) < 0) ids.push(modelData.id);
} else {
ids = ids.filter(function(id){ return id !== modelData.id; });
}
var allIds = gpuSelectorRepeater.model.map(function(g){ return g.id; });
var allSelected = allIds.every(function(id){ return ids.indexOf(id) >= 0; });
if (allSelected) cfg_gpuSelection = "";
else if (ids.length === 0) cfg_gpuSelection = "none";
else cfg_gpuSelection = ids.join(",");
}
}
// Label + sub-metrics (indented under GPU checkbox)
ColumnLayout {
enabled: gpuDelegate._gpuEnabled
opacity: gpuDelegate._gpuEnabled ? 1.0 : 0.4
spacing: Kirigami.Units.smallSpacing
Layout.leftMargin: Kirigami.Units.gridUnit + Kirigami.Units.smallSpacing
// Custom label
RowLayout {
spacing: Kirigami.Units.smallSpacing
Label { text: i18n("Label:"); opacity: 0.8 }
TextField {
implicitWidth: Kirigami.Units.gridUnit * 12
text: metricsPage.parseGpuLabels(cfg_gpuLabels)[gpuDelegate.modelData.id] || ""
placeholderText: gpuDelegate.modelData.name
onTextEdited: metricsPage.saveGpuLabel(gpuDelegate.modelData.id, text)
}
}
// Sub-metric toggles
RowLayout {
spacing: Kirigami.Units.largeSpacing
Label { text: i18n("Show:"); opacity: 0.8 }
CheckBox {
text: i18n("Usage")
checked: gpuDelegate._activeMetrics.indexOf("usage") >= 0
enabled: !(checked && gpuDelegate._activeMetrics.length <= 1)
onToggled: metricsPage.saveGpuMetric(gpuDelegate.modelData.id, "usage", checked)
}
CheckBox {
text: i18n("VRAM")
checked: gpuDelegate._activeMetrics.indexOf("vram") >= 0
enabled: !(checked && gpuDelegate._activeMetrics.length <= 1)
onToggled: metricsPage.saveGpuMetric(gpuDelegate.modelData.id, "vram", checked)
}
CheckBox {
text: i18n("Temperature")
checked: gpuDelegate._activeMetrics.indexOf("temp") >= 0
enabled: !(checked && gpuDelegate._activeMetrics.length <= 1)
onToggled: metricsPage.saveGpuMetric(gpuDelegate.modelData.id, "temp", checked)
}
}
}
}
}
}
}
// Thin divider between rows (not after the last visible one)
Rectangle {
visible: {
for (var i = index + 1; i < metricsPage.currentOrder.length; i++) {
var nextData = metricsPage.currentOrder[i];
var isHidden = (nextData === "temp" && cfg_mergeCpuTemp && cfg_showCpu) ||
(nextData === "pwr" && cfg_mergeBatPwr && cfg_showBattery);
if (!isHidden) return true;
}
return false;
}
Layout.fillWidth: true
height: 1
color: Kirigami.Theme.textColor
opacity: 0.08
Layout.topMargin: Kirigami.Units.smallSpacing
Layout.bottomMargin: Kirigami.Units.smallSpacing
}
}
}
}
}
}
@@ -0,0 +1,558 @@
import QtQuick
import QtQuick.Layouts
import org.kde.plasma.plasmoid
import org.kde.plasma.components as PlasmaComponents
import org.kde.kirigami as Kirigami
import "./sensors"
PlasmoidItem {
id: root
property bool _dbg: { console.warn("[KVitals] main.qml: constructing..."); return true; }
preferredRepresentation: compactRepresentation
// --- Configuration properties ---
property bool showCpu: Plasmoid.configuration.showCpu
property bool showRam: Plasmoid.configuration.showRam
property bool showTemp: Plasmoid.configuration.showTemp
property bool showGpu: Plasmoid.configuration.showGpu
property bool showBattery: Plasmoid.configuration.showBattery
property bool showPower: Plasmoid.configuration.showPower
property bool showNetwork: Plasmoid.configuration.showNetwork
property bool showDisk: Plasmoid.configuration.showDisk
property bool showFan: Plasmoid.configuration.showFan
property bool compactShowCpu: Plasmoid.configuration.compactShowCpu
property bool compactShowRam: Plasmoid.configuration.compactShowRam
property bool compactShowTemp: Plasmoid.configuration.compactShowTemp
property bool compactShowGpu: Plasmoid.configuration.compactShowGpu
property bool compactShowBattery: Plasmoid.configuration.compactShowBattery
property bool compactShowPower: Plasmoid.configuration.compactShowPower
property bool compactShowNetwork: Plasmoid.configuration.compactShowNetwork
property bool compactShowDisk: Plasmoid.configuration.compactShowDisk
property bool compactShowFan: Plasmoid.configuration.compactShowFan
property string networkInterface: Plasmoid.configuration.networkInterface
property string batteryDevice: Plasmoid.configuration.batteryDevice
property string gpuSelection: Plasmoid.configuration.gpuSelection
property string gpuLabels: Plasmoid.configuration.gpuLabels
property string displayMode: Plasmoid.configuration.displayMode
property string layoutType: Plasmoid.configuration.layoutType
property bool mergeCpuTemp: Plasmoid.configuration.mergeCpuTemp
property bool mergeCpuFreq: Plasmoid.configuration.mergeCpuFreq
property bool showCpuFreq: Plasmoid.configuration.showCpuFreq
property bool mergeBatPwr: Plasmoid.configuration.mergeBatPwr
property bool splitGpu: Plasmoid.configuration.splitGpu
property string gpuMetrics: Plasmoid.configuration.gpuMetrics
property int iconSize: Plasmoid.configuration.iconSize
property string cpuIcon: Plasmoid.configuration.cpuIcon
property string ramIcon: Plasmoid.configuration.ramIcon
property string tempIcon: Plasmoid.configuration.tempIcon
property string gpuIcon: Plasmoid.configuration.gpuIcon
property string batteryIcon: Plasmoid.configuration.batteryIcon
property string powerIcon: Plasmoid.configuration.powerIcon
property string networkIcon: Plasmoid.configuration.networkIcon
property string diskIcon: Plasmoid.configuration.diskIcon
property string fanIcon: Plasmoid.configuration.fanIcon
property string fontFamily: Plasmoid.configuration.fontFamily
property int fontSize: Plasmoid.configuration.fontSize
property bool fontBold: Plasmoid.configuration.fontBold
property int effectiveFontSize: fontSize > 0 ? fontSize : Kirigami.Theme.smallFont.pixelSize
property bool useIcons: displayMode === "icons" || displayMode === "icons+text"
property bool useText: displayMode === "text" || displayMode === "icons+text"
property string metricOrder: Plasmoid.configuration.metricOrder || "cpu,ram,temp,gpu,bat,pwr,net,disk"
property var orderedKeys: metricOrder.split(",").map(function (k) {
return k.trim();
})
property int updateInterval: Plasmoid.configuration.updateInterval || 2000
property string tempUnit: Plasmoid.configuration.tempUnit || "C"
property string networkUnit: Plasmoid.configuration.networkUnit || "bytes"
property string fanUnit: Plasmoid.configuration.fanUnit || "rpm"
// --- Color configuration properties ---
property bool useCustomColors: Plasmoid.configuration.useCustomColors
property string fontColor: Plasmoid.configuration.fontColor
property bool enableThresholdColors: Plasmoid.configuration.enableThresholdColors
property string warningColor: Plasmoid.configuration.warningColor || "#e5a50a"
property string criticalColor: Plasmoid.configuration.criticalColor || "#da4453"
property int cpuWarningThreshold: Plasmoid.configuration.cpuWarningThreshold
property int cpuCriticalThreshold: Plasmoid.configuration.cpuCriticalThreshold
property int tempWarningThreshold: Plasmoid.configuration.tempWarningThreshold
property int tempCriticalThreshold: Plasmoid.configuration.tempCriticalThreshold
property int ramWarningThreshold: Plasmoid.configuration.ramWarningThreshold
property int ramCriticalThreshold: Plasmoid.configuration.ramCriticalThreshold
property int gpuWarningThreshold: Plasmoid.configuration.gpuWarningThreshold
property int gpuCriticalThreshold: Plasmoid.configuration.gpuCriticalThreshold
property int gpuTempWarningThreshold: Plasmoid.configuration.gpuTempWarningThreshold
property int gpuTempCriticalThreshold: Plasmoid.configuration.gpuTempCriticalThreshold
property int batteryWarningThreshold: Plasmoid.configuration.batteryWarningThreshold
property int batteryCriticalThreshold: Plasmoid.configuration.batteryCriticalThreshold
property int diskTempWarningThreshold: Plasmoid.configuration.diskTempWarningThreshold
property int diskTempCriticalThreshold: Plasmoid.configuration.diskTempCriticalThreshold
// --- Computed base text color ---
property color baseTextColor: (useCustomColors && fontColor !== "") ? fontColor : Kirigami.Theme.textColor
// --- Pre-resolved per-metric colors (reactive properties) ---
property color cpuColor: enableThresholdColors
? Utils.resolveColor(cpu.cpuNumericValue, cpuWarningThreshold, cpuCriticalThreshold,
warningColor, criticalColor, baseTextColor, false)
: baseTextColor
property color tempColor: enableThresholdColors
? Utils.resolveColor(temp.tempNumericValue, tempWarningThreshold, tempCriticalThreshold,
warningColor, criticalColor, baseTextColor, false)
: baseTextColor
property color ramColor: enableThresholdColors
? Utils.resolveColor(memory.ramPercentage, ramWarningThreshold, ramCriticalThreshold,
warningColor, criticalColor, baseTextColor, false)
: baseTextColor
property color gpuColor: enableThresholdColors
? Utils.resolveColor(gpu.gpuUsageNumber, gpuWarningThreshold, gpuCriticalThreshold,
warningColor, criticalColor, baseTextColor, false)
: baseTextColor
property color gpuTempColor: enableThresholdColors
? Utils.resolveColor(gpu.gpuTempNumber, gpuTempWarningThreshold, gpuTempCriticalThreshold,
warningColor, criticalColor, baseTextColor, false)
: baseTextColor
property color batteryColor: enableThresholdColors
? Utils.resolveColor(battery.batNumericValue, batteryWarningThreshold, batteryCriticalThreshold,
warningColor, criticalColor, baseTextColor, true)
: baseTextColor
property color diskTempColor: enableThresholdColors
? Utils.resolveColor(disk.diskTempNumber, diskTempWarningThreshold, diskTempCriticalThreshold,
warningColor, criticalColor, baseTextColor, false)
: baseTextColor
// --- Deferred sensor loading ---
// Sensors are loaded AFTER the window attachment is complete to avoid
// triggering a SIGSEGV in KirigamiPlasmaStyle's PlasmaTheme::syncColors()
// during the recursive QQuickItemPrivate::refWindow() walk at boot.
// See: https://github.com/nicehash/KVitals/issues/42
property bool _sensorsReady: sensorLoader.status === Loader.Ready
property var cpu: _sensorsReady ? sensorLoader.item.cpu : _nullCpu
property var memory: _sensorsReady ? sensorLoader.item.memory : _nullMemory
property var temp: _sensorsReady ? sensorLoader.item.temp : _nullTemp
property var gpu: _sensorsReady ? sensorLoader.item.gpu : _nullGpu
property var battery: _sensorsReady ? sensorLoader.item.battery : _nullBattery
property var network: _sensorsReady ? sensorLoader.item.network : _nullNetwork
property var disk: _sensorsReady ? sensorLoader.item.disk : _nullDisk
property var fans: _sensorsReady ? sensorLoader.item.fans : _nullFans
// Safe defaults so bindings don't error before sensors load
QtObject {
id: _nullCpu
property string cpuValue: ""
property string cpuFreqValue: ""
property real cpuNumericValue: NaN
}
QtObject {
id: _nullMemory
property string ramValue: ""
property real ramPercentage: NaN
}
QtObject {
id: _nullTemp
property string tempValue: "--"
property real tempNumericValue: NaN
}
QtObject {
id: _nullGpu
property real gpuUsageNumber: NaN
property real gpuTempNumber: NaN
property string gpuValue: ""
property string gpuRamValue: ""
property string gpuTempValue: ""
property string gpuDisplayValue: ""
property bool hasGpuData: false
property bool hasGpuUsageData: false
property bool hasGpuVramData: false
property bool hasGpuTempData: false
property var gpuDataList: []
property var discoveredGpus: []
}
QtObject {
id: _nullBattery
property string batValue: ""
property string powerValue: ""
property real batNumericValue: NaN
}
QtObject {
id: _nullNetwork
property string netDownValue: "0"
property string netUpValue: "0"
}
QtObject {
id: _nullDisk
property string diskReadValue: "0"
property string diskWriteValue: "0"
property string diskTempValue: ""
property real diskTempNumber: NaN
}
QtObject {
id: _nullFans
property string fanValue: ""
property bool hasFanData: false
}
Loader {
id: sensorLoader
active: false
sourceComponent: Item {
property alias cpu: _cpu
property alias memory: _memory
property alias temp: _temp
property alias gpu: _gpu
property alias battery: _battery
property alias network: _network
property alias disk: _disk
property alias fans: _fans
CpuSensors {
id: _cpu
updateInterval: root.updateInterval
}
MemorySensors {
id: _memory
updateInterval: root.updateInterval
}
TempSensors {
id: _temp
updateInterval: root.updateInterval
tempUnit: root.tempUnit
}
GpuSensors {
id: _gpu
updateInterval: root.updateInterval
gpuSelection: root.gpuSelection
gpuLabels: root.gpuLabels
tempUnit: root.tempUnit
gpuMetrics: root.gpuMetrics
}
BatterySensors {
id: _battery
updateInterval: root.updateInterval
batteryDevice: root.batteryDevice || "auto"
}
NetworkSensors {
id: _network
updateInterval: root.updateInterval
networkInterface: root.networkInterface
networkUnit: root.networkUnit
}
DiskSensors {
id: _disk
updateInterval: root.updateInterval
enabled: root.showDisk
tempUnit: root.tempUnit
networkUnit: root.networkUnit
}
FanSensors {
id: _fans
updateInterval: root.updateInterval
fanUnit: root.fanUnit
}
}
}
// Activate the sensor loader after the initial refWindow() walk is complete.
// The SIGSEGV in PlasmaTheme::syncColors() happens synchronously during
// ShellCorona::load() → refWindow(), so deferring to the next event loop
// iteration (Timer interval: 0) guarantees we're past the dangerous window.
Timer {
id: sensorActivationTimer
interval: 0
repeat: false
onTriggered: {
console.warn("[KVitals] main.qml: deferred load — activating sensors...");
sensorLoader.active = true;
}
}
Component.onCompleted: {
console.warn("[KVitals] main.qml: ready. config: showCpu=" + showCpu + " showGpu=" + showGpu + " showBattery=" + showBattery + " showNetwork=" + showNetwork + " showDisk=" + showDisk);
sensorActivationTimer.start();
}
// --- Representations ---
compactRepresentation: CompactView {
metricsModel: {
var items = [];
for (var i = 0; i < root.orderedKeys.length; i++) {
var key = root.orderedKeys[i];
if (key === "cpu" && root.showCpu && root.compactShowCpu && cpu.cpuValue) {
if (root.mergeCpuTemp && root.showTemp && root.compactShowTemp && temp.tempValue && temp.tempValue !== "--") {
var segs = [{value: cpu.cpuValue, color: root.cpuColor},
{value: temp.tempValue, color: root.tempColor}];
if (root.mergeCpuFreq && root.showCpuFreq)
segs.push({value: cpu.cpuFreqValue, color: root.baseTextColor});
items.push({icon: root.cpuIcon, label: "CPU:", color: root.cpuColor, segments: segs});
} else if (root.mergeCpuFreq && root.showCpuFreq) {
items.push({
icon: root.cpuIcon, label: "CPU:", color: root.cpuColor,
segments: [
{value: cpu.cpuValue, color: root.cpuColor},
{value: cpu.cpuFreqValue, color: root.baseTextColor}
]
});
} else {
items.push({icon: root.cpuIcon, label: "CPU:", value: cpu.cpuValue, color: root.cpuColor});
}
} else if (key === "ram" && root.showRam && root.compactShowRam && memory.ramValue)
items.push({
icon: root.ramIcon, label: "RAM:", value: memory.ramValue,
color: root.ramColor
});
else if (key === "temp" && root.showTemp && root.compactShowTemp && temp.tempValue && temp.tempValue !== "--"
&& !(root.mergeCpuTemp && root.showCpu && root.compactShowCpu))
items.push({
icon: root.tempIcon, label: "TEMP:", value: temp.tempValue,
color: root.tempColor
});
else if (key === "gpu" && root.showGpu && root.compactShowGpu && gpu.hasGpuData) {
var multiGpu = gpu.gpuDataList.length > 1;
if (multiGpu) {
// Show each GPU as a separate entry
for (var g = 0; g < gpu.gpuDataList.length; g++) {
var gd = gpu.gpuDataList[g];
var label = (gd.name.length > 0 ? gd.name : gd.id) + ":";
if (root.splitGpu) {
if (gd.usage) items.push({icon: root.gpuIcon, label: label, value: gd.usage, color: root.gpuColor});
if (gd.vram) items.push({icon: root.gpuIcon, label: "VRAM:", value: gd.vram, color: root.baseTextColor});
if (gd.temp) items.push({icon: root.gpuIcon, label: "GTEMP:", value: gd.temp, color: root.gpuTempColor});
} else {
var segs2 = [];
if (gd.usage) segs2.push({value: gd.usage, color: root.gpuColor});
if (gd.vram) segs2.push({value: gd.vram, color: root.baseTextColor});
if (gd.temp) segs2.push({value: gd.temp, color: root.gpuTempColor});
if (segs2.length > 0)
items.push({icon: root.gpuIcon, label: label, segments: segs2, color: root.gpuColor});
}
}
} else if (root.splitGpu) {
if (gpu.hasGpuUsageData)
items.push({icon: root.gpuIcon, label: "GPU:", value: gpu.gpuValue, color: root.gpuColor});
if (gpu.hasGpuVramData)
items.push({
icon: root.gpuIcon,
label: "VRAM:",
value: gpu.gpuRamValue,
color: root.baseTextColor
});
if (gpu.hasGpuTempData)
items.push({
icon: root.gpuIcon,
label: "GTEMP:",
value: gpu.gpuTempValue,
color: root.gpuTempColor
});
} else {
var gpuSegs = [];
if (gpu.hasGpuUsageData)
gpuSegs.push({value: gpu.gpuValue, color: root.gpuColor});
if (gpu.hasGpuVramData)
gpuSegs.push({value: gpu.gpuRamValue, color: root.baseTextColor});
if (gpu.hasGpuTempData)
gpuSegs.push({value: gpu.gpuTempValue, color: root.gpuTempColor});
items.push({
icon: root.gpuIcon, label: "GPU:", segments: gpuSegs,
color: root.gpuColor
});
}
} else if (key === "bat" && root.showBattery && root.compactShowBattery && battery.batValue) {
if (root.mergeBatPwr && root.showPower && root.compactShowPower && battery.powerValue) {
items.push({
icon: root.batteryIcon, label: "BAT:",
color: root.batteryColor,
segments: [
{value: battery.batValue, color: root.batteryColor},
{value: battery.powerValue, color: root.baseTextColor}
]
});
} else {
items.push({
icon: root.batteryIcon, label: "BAT:", value: battery.batValue,
color: root.batteryColor
});
}
} else if (key === "pwr" && root.showPower && root.compactShowPower && battery.powerValue
&& !(root.mergeBatPwr && root.showBattery && root.compactShowBattery))
items.push({
icon: root.powerIcon, label: "PWR:", value: battery.powerValue,
color: root.baseTextColor
});
else if (key === "net" && root.showNetwork && root.compactShowNetwork)
items.push({
icon: root.networkIcon, label: "NET:",
value: "↓" + network.netDownValue + " ↑" + network.netUpValue,
color: root.baseTextColor
});
else if (key === "disk" && root.showDisk && root.compactShowDisk) {
var diskSegs = [{value: "↓" + disk.diskReadValue, color: root.baseTextColor},
{value: "↑" + disk.diskWriteValue, color: root.baseTextColor}];
if (disk.diskTempValue)
diskSegs.push({value: disk.diskTempValue, color: root.diskTempColor});
items.push({icon: root.diskIcon, label: "DSK:", segments: diskSegs, color: root.baseTextColor});
}
else if (key === "fan" && root.showFan && root.compactShowFan && fans.hasFanData) {
items.push({
icon: root.fanIcon, label: "FAN:", value: fans.fanValue,
color: root.baseTextColor
});
}
}
return items;
}
layoutType: root.layoutType
useIcons: root.useIcons
useText: root.useText
effectiveFontSize: root.effectiveFontSize
fontFamily: root.fontFamily
fontBold: root.fontBold
iconSize: root.iconSize
baseTextColor: root.baseTextColor
onToggleExpanded: root.expanded = !root.expanded
}
fullRepresentation: FullView {
baseTextColor: root.baseTextColor
fontBold: root.fontBold
metricsModel: {
var items = [];
for (var i = 0; i < root.orderedKeys.length; i++) {
var key = root.orderedKeys[i];
if (key === "cpu" && root.showCpu)
items.push({
label: "CPU Usage", value: cpu.cpuValue,
color: root.cpuColor
});
if (key === "cpu" && root.showCpu && root.showCpuFreq)
items.push({
label: "CPU Frequency", value: cpu.cpuFreqValue,
color: root.baseTextColor
});
else if (key === "ram" && root.showRam)
items.push({
label: "Memory", value: memory.ramValue,
color: root.ramColor
});
else if (key === "temp" && root.showTemp && temp.tempValue !== "--")
items.push({
label: "CPU Temp", value: temp.tempValue,
color: root.tempColor
});
else if (key === "gpu" && root.showGpu) {
if (gpu.gpuDataList.length > 1) {
for (var g = 0; g < gpu.gpuDataList.length; g++) {
var gd = gpu.gpuDataList[g];
var label = gd.name || gd.id;
if (gd.usage) items.push({label: label + " Usage", value: gd.usage, color: root.gpuColor});
if (gd.vram) items.push({label: label + " VRAM", value: gd.vram, color: root.baseTextColor});
if (gd.temp) items.push({label: label + " Temp", value: gd.temp, color: root.gpuTempColor});
}
} else {
if (gpu.hasGpuUsageData) items.push({
label: "GPU Usage", value: gpu.gpuValue,
color: root.gpuColor
});
if (gpu.hasGpuVramData) items.push({
label: "GPU VRAM", value: gpu.gpuRamValue,
color: root.baseTextColor
});
if (gpu.hasGpuTempData) items.push({
label: "GPU Temp", value: gpu.gpuTempValue,
color: root.gpuTempColor
});
}
} else if (key === "bat" && root.showBattery && battery.batValue)
items.push({
label: "Battery", value: battery.batValue,
color: root.batteryColor
});
else if (key === "pwr" && root.showPower && battery.powerValue)
items.push({
label: "Power", value: battery.powerValue,
color: root.baseTextColor
});
else if (key === "net" && root.showNetwork) {
items.push({label: "Network ↓", value: network.netDownValue, color: root.baseTextColor});
items.push({label: "Network ↑", value: network.netUpValue, color: root.baseTextColor});
}
else if (key === "disk" && root.showDisk) {
items.push({label: "Disk Read", value: disk.diskReadValue, color: root.baseTextColor});
items.push({label: "Disk Write", value: disk.diskWriteValue, color: root.baseTextColor});
if (disk.diskTempValue)
items.push({label: "Disk Temp", value: disk.diskTempValue, color: root.diskTempColor});
}
else if (key === "fan" && root.showFan && fans.hasFanData) {
items.push({label: "Fans", value: fans.fanValue, color: root.baseTextColor});
}
}
return items;
}
}
// --- Tooltip ---
toolTipMainText: "KVitals"
toolTipSubText: {
var parts = [];
for (var i = 0; i < root.orderedKeys.length; i++) {
var key = root.orderedKeys[i];
if (key === "cpu" && root.showCpu && cpu.cpuValue)
parts.push("CPU: " + cpu.cpuValue);
else if (key === "ram" && root.showRam && memory.ramValue)
parts.push("RAM: " + memory.ramValue);
else if (key === "temp" && root.showTemp && temp.tempValue && temp.tempValue !== "--")
parts.push("TEMP: " + temp.tempValue);
else if (key === "gpu" && root.showGpu && gpu.hasGpuData) {
if (gpu.gpuDataList.length > 1) {
for (var g = 0; g < gpu.gpuDataList.length; g++) {
var gd = gpu.gpuDataList[g];
var label = gd.name || gd.id;
var vals = [gd.usage, gd.vram, gd.temp].filter(function(v) { return v; });
if (vals.length > 0) parts.push(label + ": " + vals.join(" "));
}
} else {
if (gpu.hasGpuUsageData) parts.push("GPU: " + gpu.gpuValue);
if (gpu.hasGpuVramData) parts.push("VRAM: " + gpu.gpuRamValue);
if (gpu.hasGpuTempData) parts.push("GPU TEMP: " + gpu.gpuTempValue);
}
} else if (key === "bat" && root.showBattery && battery.batValue)
parts.push("BAT: " + battery.batValue);
else if (key === "pwr" && root.showPower && battery.powerValue)
parts.push("PWR: " + battery.powerValue);
else if (key === "net" && root.showNetwork)
parts.push("NET: ↓" + network.netDownValue + " ↑" + network.netUpValue);
else if (key === "disk" && root.showDisk) {
var dParts = ["↓" + disk.diskReadValue, "↑" + disk.diskWriteValue];
if (disk.diskTempValue) dParts.push(disk.diskTempValue);
parts.push("DSK: " + dParts.join(" "));
}
else if (key === "fan" && root.showFan && fans.hasFanData) {
parts.push("FAN: " + fans.fanValue);
}
}
return parts.join("\n");
}
}
@@ -0,0 +1,193 @@
import QtQuick
import org.kde.ksysguard.sensors as Sensors
import org.kde.plasma.plasma5support as Plasma5Support
Item {
id: root
property bool _dbg: { console.warn("[KVitals] BatterySensors: constructing..."); return true; }
property int updateInterval: 2000
property string batteryDevice: "auto"
readonly property real batNumericValue: {
if (batChargeSensor.status !== Sensors.Sensor.Ready)
return NaN;
return batChargeSensor.value;
}
readonly property string batValue: {
if (isNaN(batNumericValue)) return "";
return Math.round(batNumericValue) + "%";
}
readonly property string powerValue: {
if (batRateSensor.status !== Sensors.Sensor.Ready) return "";
var watts = Math.abs(batRateSensor.value);
if (watts < 0.01) return "0.0W";
var sign = batRateSensor.value > 0 ? "+" : "-";
return sign + watts.toFixed(1) + "W";
}
// --- Dynamic battery sensor discovery ---
property string discoveredBatId: ""
property string batChargeSensorId: {
var base = (batteryDevice && batteryDevice !== "auto") ? batteryDevice : discoveredBatId;
return base ? ("power/" + base + "/chargePercentage") : "";
}
property string batRateSensorId: {
var base = (batteryDevice && batteryDevice !== "auto") ? batteryDevice : discoveredBatId;
return base ? ("power/" + base + "/chargeRate") : "";
}
property var batteryCandidates: [
"battery_BAT0",
"battery_BAT1",
"battery_BAT2",
"battery_BATT",
"battery_BATT0"
]
property var stage1Probes: []
Component.onCompleted: {
console.warn("[KVitals] BatterySensors: ready. batteryDevice = " + batteryDevice);
if (batteryDevice && batteryDevice !== "auto")
return;
for (var i = 0; i < batteryCandidates.length; i++) {
var pre = "power/" + batteryCandidates[i] + "/chargePercentage";
var code = 'import org.kde.ksysguard.sensors as Sensors; Sensors.Sensor { sensorId: "' + pre + '"; updateRateLimit: 2000 }';
try {
var probe = Qt.createQmlObject(code, root, "probe_" + i);
stage1Probes.push({ candidate: batteryCandidates[i], probe: probe });
} catch(e) {
}
}
}
Timer {
id: stage1Timer
interval: 500
repeat: true
running: (!batteryDevice || batteryDevice === "auto") && !discoveredBatId
property int attempts: 0
onTriggered: {
attempts++;
console.warn("[KVitals] BatterySensors: probe attempt = " + attempts);
for (var i = 0; i < stage1Probes.length; i++) {
if (stage1Probes[i].probe && stage1Probes[i].probe.status === Sensors.Sensor.Ready) {
console.warn("[KVitals] BatterySensors: stage 1 found = " + stage1Probes[i].candidate);
persistDetectedBattery(stage1Probes[i].candidate);
running = false;
cleanupProbes();
return;
}
}
if (attempts >= 6) { // 3 seconds timeout
console.warn("[KVitals] BatterySensors: stage 1 timeout, starting qdbus fallback...");
running = false;
cleanupProbes();
// Stage 2: qdbus fallback
tryNextQdbus();
}
}
}
function cleanupProbes() {
for (var i = 0; i < stage1Probes.length; i++) {
if (stage1Probes[i].probe)
stage1Probes[i].probe.destroy();
}
stage1Probes = [];
}
function persistDetectedBattery(deviceId) {
discoveredBatId = deviceId;
}
function extractBatteryIds(stdout) {
if (!stdout)
return [];
var matches = stdout.match(/power\/[^\/"\s]+\/chargePercentage/g);
if (!matches)
return [];
var ids = [];
for (var i = 0; i < matches.length; i++) {
var parts = matches[i].split("/");
if (parts.length < 3)
continue;
if (ids.indexOf(parts[1]) === -1)
ids.push(parts[1]);
}
return ids;
}
// Stage 2: qdbus fallback
property var qdbusVariants: ["qdbus", "qdbus6", "qdbus-qt6", "qdbus-qt5"]
property int qdbusIndex: 0
Plasma5Support.DataSource {
id: qdbusDetector
engine: "executable"
property bool active: false
onNewData: function(sourceName, data) {
if (!active) return;
active = false;
disconnectSource(sourceName);
console.debug("[KVitals] BatterySensors: qdbus exit code = " + data["exit code"]);
if (data["exit code"] === 0) {
var stdoutStr = data["stdout"] ? data["stdout"].toString() : "";
var ids = extractBatteryIds(stdoutStr);
console.debug("[KVitals] BatterySensors: qdbus ids = " + JSON.stringify(ids));
if (ids.length === 1) {
persistDetectedBattery(ids[0]);
return;
}
if (ids.length > 1) {
console.warn("BatterySensors: multiple batteries found:", JSON.stringify(ids), "— using first:", ids[0]);
persistDetectedBattery(ids[0]);
return;
}
} else {
console.warn("[KVitals] BatterySensors: qdbus command failed.");
}
tryNextQdbus();
}
function run(variant) {
var cmd = variant + " --literal org.kde.ksystemstats1" +
" /org/kde/ksystemstats1" +
" org.kde.ksystemstats1.allSensors";
active = true;
connectSource(cmd);
}
}
function tryNextQdbus() {
if (qdbusIndex >= qdbusVariants.length) {
console.warn("[KVitals] BatterySensors: all detection methods exhausted; set batteryDevice manually.");
return;
}
var variant = qdbusVariants[qdbusIndex];
qdbusIndex++;
console.debug("[KVitals] BatterySensors: trying qdbus variant = " + variant);
qdbusDetector.run(variant);
}
Sensors.Sensor {
id: batChargeSensor
sensorId: root.batChargeSensorId
updateRateLimit: root.updateInterval > 5000 ? root.updateInterval : 5000
}
Sensors.Sensor {
id: batRateSensor
sensorId: root.batRateSensorId
updateRateLimit: root.updateInterval > 5000 ? root.updateInterval : 5000
}
}
@@ -0,0 +1,47 @@
import QtQuick
import org.kde.ksysguard.sensors as Sensors
Item {
id: root
property bool _dbg: { console.warn("[KVitals] CpuSensors: constructing..."); return true; }
property int updateInterval: 2000
readonly property real cpuNumericValue: {
if (cpuSensor.status !== Sensors.Sensor.Ready)
return NaN;
return cpuSensor.value;
}
readonly property string cpuValue: {
if (isNaN(cpuNumericValue))
return "...";
return Math.round(cpuNumericValue) + "%";
}
// Frequency in MHz from KSysGuard (unit type 302 = MHz); displays as GHz above 1000 MHz
readonly property string cpuFreqValue: {
if (freqSensor.status !== Sensors.Sensor.Ready || freqSensor.value == null)
return "...";
var mhz = freqSensor.value;
if (mhz >= 1000)
return (mhz / 1000).toFixed(2) + " GHz";
return Math.round(mhz) + " MHz";
}
Sensors.Sensor {
id: cpuSensor
sensorId: "cpu/all/usage"
updateRateLimit: root.updateInterval
}
Sensors.Sensor {
id: freqSensor
sensorId: "cpu/all/averageFrequency"
updateRateLimit: root.updateInterval
}
Component.onCompleted: {
console.warn("[KVitals] CpuSensors: ready.");
}
}
@@ -0,0 +1,113 @@
import QtQuick
import org.kde.ksysguard.sensors as Sensors
import org.kde.kitemmodels as KItemModels
Item {
id: root
property bool _dbg: { console.warn("[KVitals] DiskSensors: constructing..."); return true; }
property int updateInterval: 2000
property bool enabled: true
property string tempUnit: "C"
property string networkUnit: "bytes"
readonly property string diskReadValue: Utils.formatRate(diskReadSensor.status === Sensors.Sensor.Ready ? diskReadSensor.value : NaN, networkUnit)
readonly property string diskWriteValue: Utils.formatRate(diskWriteSensor.status === Sensors.Sensor.Ready ? diskWriteSensor.value : NaN, networkUnit)
// Highest temperature found across all discovered drive temp sensors
readonly property real diskTempNumber: _diskTempNum
readonly property string diskTempValue: isNaN(_diskTempNum) ? "" : Utils.formatTemp(_diskTempNum, tempUnit)
property real _diskTempNum: NaN
// I/O sensors
Sensors.Sensor {
id: diskReadSensor
sensorId: "disk/all/read"
updateRateLimit: root.updateInterval
enabled: root.enabled
}
Sensors.Sensor {
id: diskWriteSensor
sensorId: "disk/all/write"
updateRateLimit: root.updateInterval
enabled: root.enabled
}
// Matches lmsensors chips that are NVMe (nvme-pci-*) or SATA drivetemp
// (drivetemp-scsi-*) and picks temp1 (Composite) or temp2 (secondary sensor)
Sensors.SensorTreeModel { id: sensorTree }
KItemModels.KDescendantsProxyModel {
id: flatSensors
model: sensorTree
}
property var _tempSensorIds: []
function _refreshTempSensors() {
console.debug("[KVitals] DiskSensors: scan started. rows = " + flatSensors.rowCount());
var found = [];
for (var row = 0; row < flatSensors.rowCount(); row++) {
var idx = flatSensors.index(row, 0);
var sid = flatSensors.data(idx, Sensors.SensorTreeModel.SensorId);
if (!sid) continue;
if (/^lmsensors\/(nvme-pci-[^/]+|drivetemp-scsi-[^/]+)\/temp[12]$/.test(sid))
found.push(sid);
}
console.debug("[KVitals] DiskSensors: scan finished. found = " + JSON.stringify(found));
if (JSON.stringify(found) !== JSON.stringify(_tempSensorIds)) {
console.debug("[KVitals] DiskSensors: temp sensors updated. ids = " + JSON.stringify(found));
_tempSensorIds = found;
}
}
property bool _discoveryDirty: false
Timer {
id: discoveryTimer
interval: 500
repeat: false
running: _discoveryDirty
onTriggered: {
_discoveryDirty = false;
root._refreshTempSensors();
}
}
Connections {
target: flatSensors
function onRowsInserted() { root._discoveryDirty = true; }
function onRowsRemoved() { root._discoveryDirty = true; }
function onModelReset() { root._discoveryDirty = true; }
}
Component.onCompleted: {
console.warn("[KVitals] DiskSensors: ready.");
_refreshTempSensors();
}
// Poll discovered temp sensors
Sensors.SensorDataModel {
id: tempData
sensors: root._tempSensorIds
updateRateLimit: root.updateInterval
enabled: root._tempSensorIds.length > 0
onDataChanged: root._aggregateTemp()
onReadyChanged: { if (ready) root._aggregateTemp(); }
}
function _aggregateTemp() {
var max = NaN;
for (var i = 0; i < _tempSensorIds.length; i++) {
var col = tempData.column(_tempSensorIds[i]);
if (col < 0) continue;
var val = tempData.data(tempData.index(0, col), Sensors.SensorDataModel.Value);
if (typeof val !== "number" || isNaN(val) || val <= 0) continue;
if (isNaN(max) || val > max) max = val;
}
_diskTempNum = max;
}
}
@@ -0,0 +1,117 @@
import QtQuick
import org.kde.ksysguard.sensors as Sensors
import org.kde.kitemmodels as KItemModels
Item {
id: root
property int updateInterval: 2000
property string fanUnit: "rpm" // "rpm" or "percent"
readonly property var discoveredFans: _discovered
property var _discovered: []
readonly property string fanValue: _fanStr
readonly property bool hasFanData: _fanStr.length > 0
property string _fanStr: ""
// -------------------------------------------------------------------------
// Step 1: Discover available Fans via SensorTreeModel
// -------------------------------------------------------------------------
Sensors.SensorTreeModel {
id: sensorTree
}
KItemModels.KDescendantsProxyModel {
id: flatSensors
model: sensorTree
}
function refreshDiscovered() {
var found = [];
for (var row = 0; row < flatSensors.rowCount(); row++) {
var idx = flatSensors.index(row, 0);
var sensorId = flatSensors.data(idx, Sensors.SensorTreeModel.SensorId);
if (!sensorId || sensorId.length === 0) continue;
// Match any sensor that contains /fan and doesn't end with a non-digit (typically fan1, fan2, etc)
var match = sensorId.match(/^(lmsensors|cpu|gpu)\/.*\/fan\d+$/i);
if (!match) continue;
// Some names are like "cpu_fan", we can try to extract the last part or use the sensor Name
var name = flatSensors.data(idx, Qt.DisplayRole) || "Fan " + (found.length + 1);
found.push({ id: sensorId, name: name });
}
if (JSON.stringify(found) !== JSON.stringify(_discovered)) {
_discovered = found;
}
}
Connections {
target: flatSensors
function onRowsInserted() { root.refreshDiscovered(); }
function onRowsRemoved() { root.refreshDiscovered(); }
function onModelReset() { root.refreshDiscovered(); }
}
Component.onCompleted: refreshDiscovered()
// -------------------------------------------------------------------------
// Step 2: Poll discovered fans
// -------------------------------------------------------------------------
readonly property var _activeSensorIds: _discovered.map(function(f){ return f.id; })
Sensors.SensorDataModel {
id: fanData
sensors: root._activeSensorIds
updateRateLimit: root.updateInterval
enabled: root._activeSensorIds.length > 0
onDataChanged: root.aggregate()
onReadyChanged: { if (ready) root.aggregate(); }
}
function _modelValue(sensorId) {
var col = fanData.column(sensorId);
if (col < 0) return NaN;
var idx = fanData.index(0, col);
if (!idx.valid) return NaN;
var val = fanData.data(idx, Sensors.SensorDataModel.Value);
return (val === undefined || val === null) ? NaN : val;
}
function _modelMax(sensorId) {
var col = fanData.column(sensorId);
if (col < 0) return NaN;
var idx = fanData.index(0, col);
if (!idx.valid) return NaN;
var val = fanData.data(idx, Sensors.SensorDataModel.Maximum);
return (val === undefined || val === null) ? NaN : val;
}
function aggregate() {
var parts = [];
for (var i = 0; i < _discovered.length; i++) {
var f = _discovered[i];
var v = _modelValue(f.id);
if (isNaN(v) || v <= 0) continue; // Ignore 0 RPM or disconnected fans
var str = "";
if (fanUnit === "percent") {
var max = _modelMax(f.id);
if (isNaN(max) || max <= 0) {
continue;
}
var pct = Math.min(100, Math.round((v / max) * 100));
str = pct + "%";
} else {
str = Math.round(v) + " RPM";
}
parts.push(str);
}
_fanStr = parts.join(" ");
}
onFanUnitChanged: aggregate()
}
@@ -0,0 +1,270 @@
import QtQuick
import org.kde.ksysguard.sensors as Sensors
import org.kde.kitemmodels as KItemModels
Item {
id: root
property bool _dbg: { console.warn("[KVitals] GpuSensors: constructing..."); return true; }
property int updateInterval: 2000
// Comma-separated selected GPU IDs e.g. "gpu0,gpu1". Empty = all discovered.
property string gpuSelection: ""
// User-defined labels: "gpu0:My iGPU|gpu1:dGPU". Empty string = use default "GPU N" name.
property string gpuLabels: ""
// Temperature unit: "C" (default) or "F"
property string tempUnit: "C"
// Per-GPU sub-metric visibility: "gpu0:usage,vram|gpu1:usage,temp"
// Empty string (default) = all three sub-metrics enabled for every GPU.
property string gpuMetrics: ""
// List of { id: "gpu0", name: "GPU 1" } derived from SensorTreeModel (no polling)
readonly property var discoveredGpus: _discovered
property var _discovered: []
// Aggregated display (single-GPU compat)
readonly property real gpuUsageNumber: _usageNum
readonly property real gpuTempNumber: _tempNum
readonly property string gpuValue: _usageStr
readonly property string gpuRamValue: _vramStr
readonly property string gpuTempValue: _tempStr
readonly property string gpuDisplayValue:
[_usageStr, _vramStr, _tempStr].filter(function(v){return v;}).join(" ")
readonly property bool hasGpuData: gpuDisplayValue.length > 0
readonly property bool hasGpuUsageData: _usageStr.length > 0
readonly property bool hasGpuVramData: _vramStr.length > 0
readonly property bool hasGpuTempData: _tempStr.length > 0
// Per-GPU list for multi display: [{ id, name, usage, vram, temp, usageNumber, tempNumber }]
readonly property var gpuDataList: _dataList
property var _dataList: []
property real _usageNum: NaN
property real _tempNum: NaN
property string _usageStr: ""
property string _vramStr: ""
property string _tempStr: ""
// -------------------------------------------------------------------------
// Step 1: Discover available GPUs via SensorTreeModel (metadata only, no polling)
// -------------------------------------------------------------------------
Sensors.SensorTreeModel {
id: sensorTree
}
KItemModels.KDescendantsProxyModel {
id: flatSensors
model: sensorTree
}
// Parse "gpu0:Label A|gpu1:Label B" → { gpu0: "Label A", gpu1: "Label B" }
function parseGpuLabels(str) {
var result = {};
if (!str) return result;
var pairs = str.split("|");
for (var i = 0; i < pairs.length; i++) {
var sep = pairs[i].indexOf(":");
if (sep > 0)
result[pairs[i].substring(0, sep)] = pairs[i].substring(sep + 1);
}
return result;
}
// Parse "gpu0:usage,vram|gpu1:usage,temp" → { gpu0: ["usage","vram"], gpu1: ["usage","temp"] }
// Missing GPU or empty string → default all three enabled.
function parseGpuMetrics(str) {
var result = {};
if (!str) return result;
var pairs = str.split("|");
for (var i = 0; i < pairs.length; i++) {
var sep = pairs[i].indexOf(":");
if (sep <= 0) continue;
var id = pairs[i].substring(0, sep);
var metrics = pairs[i].substring(sep + 1).split(",")
.filter(function(m){ return m === "usage" || m === "vram" || m === "temp"; });
if (metrics.length > 0) result[id] = metrics;
}
return result;
}
// Return enabled sub-metric list for a specific GPU (["usage","vram","temp"] if unconfigured)
function gpuMetricsFor(gpuId, metricsMap) {
return (metricsMap[gpuId] && metricsMap[gpuId].length > 0)
? metricsMap[gpuId]
: ["usage", "vram", "temp"];
}
function refreshDiscovered() {
console.debug("[KVitals] GpuSensors: scan started. rows = " + flatSensors.rowCount());
var found = [];
for (var row = 0; row < flatSensors.rowCount(); row++) {
var idx = flatSensors.index(row, 0);
var sensorId = flatSensors.data(idx, Sensors.SensorTreeModel.SensorId);
if (!sensorId || sensorId.length === 0) continue;
var match = sensorId.match(/^gpu\/(gpu\d+)\/usage$/);
if (!match) continue;
found.push({ id: match[1], name: "GPU " + (found.length + 1) });
}
console.debug("[KVitals] GpuSensors: scan finished. found = " + JSON.stringify(found));
if (JSON.stringify(found) !== JSON.stringify(_discovered)) {
console.warn("[KVitals] GpuSensors: discovered GPUs updated = " + JSON.stringify(found));
_discovered = found;
if (typeof Plasmoid !== "undefined" && Plasmoid.configuration)
Plasmoid.configuration.gpuDiscovered =
found.map(function(g){ return g.id + ":" + g.name; }).join(",");
}
}
property bool _discoveryDirty: false
Timer {
id: discoveryTimer
interval: 500
repeat: false
running: _discoveryDirty
onTriggered: {
_discoveryDirty = false;
root.refreshDiscovered();
}
}
Connections {
target: flatSensors
function onRowsInserted() { root._discoveryDirty = true; }
function onRowsRemoved() { root._discoveryDirty = true; }
function onModelReset() { root._discoveryDirty = true; }
function onDataChanged() { root._discoveryDirty = true; }
}
Component.onCompleted: {
console.warn("[KVitals] GpuSensors: ready. selection=" + gpuSelection);
refreshDiscovered();
}
// -------------------------------------------------------------------------
// Step 2: Compute active sensor IDs — per GPU, only poll enabled sub-metrics
// -------------------------------------------------------------------------
readonly property var _activeIds: {
if (!gpuSelection || gpuSelection === "")
return _discovered.map(function(g){ return g.id; });
if (gpuSelection === "none")
return [];
return gpuSelection.split(",")
.map(function(s){ return s.trim(); })
.filter(function(s){ return s.length > 0; });
}
readonly property var _activeSensorIds: {
var ids = [];
var mm = parseGpuMetrics(gpuMetrics);
for (var i = 0; i < _activeIds.length; i++) {
var g = _activeIds[i];
var m = gpuMetricsFor(g, mm);
if (m.indexOf("usage") >= 0) ids.push("gpu/" + g + "/usage");
if (m.indexOf("vram") >= 0) {
ids.push("gpu/" + g + "/usedVram");
ids.push("gpu/" + g + "/totalVram");
}
if (m.indexOf("temp") >= 0) ids.push("gpu/" + g + "/temperature");
}
return ids;
}
// -------------------------------------------------------------------------
// Step 3: Single SensorDataModel — polls ONLY the selected sensors
// -------------------------------------------------------------------------
Sensors.SensorDataModel {
id: gpuData
sensors: root._activeSensorIds
updateRateLimit: root.updateInterval
enabled: root._activeSensorIds.length > 0
onDataChanged: root.aggregate()
onReadyChanged: { if (ready) root.aggregate(); }
}
// -------------------------------------------------------------------------
// Step 4: Aggregate values — label resolution: custom label > default name > "GPU N"
// -------------------------------------------------------------------------
function _modelValue(sensorId) {
var col = gpuData.column(sensorId);
if (col < 0) return NaN;
var idx = gpuData.index(0, col);
if (!idx.valid) return NaN;
var val = gpuData.data(idx, Sensors.SensorDataModel.Value);
return (val === undefined || val === null) ? NaN : val;
}
function aggregate() {
var ids = _activeIds;
var customLabels = parseGpuLabels(gpuLabels);
var mm = parseGpuMetrics(gpuMetrics);
var newList = [];
var totalUsage = 0, usageCount = 0;
var totalVramUsed = 0, totalVramTotal = 0, hasVram = false;
var maxTemp = NaN;
for (var i = 0; i < ids.length; i++) {
var g = ids[i];
var m = gpuMetricsFor(g, mm);
var showU = m.indexOf("usage") >= 0;
var showV = m.indexOf("vram") >= 0;
var showT = m.indexOf("temp") >= 0;
// Resolve display name: custom label > default name > fallback
var hwName = "GPU " + (i + 1);
for (var j = 0; j < _discovered.length; j++) {
if (_discovered[j].id === g) { hwName = _discovered[j].name; break; }
}
var name = customLabels[g] || hwName;
var uVal = showU ? _modelValue("gpu/" + g + "/usage") : NaN;
var vuVal = showV ? _modelValue("gpu/" + g + "/usedVram") : NaN;
var vtVal = showV ? _modelValue("gpu/" + g + "/totalVram") : NaN;
var tVal = showT ? _modelValue("gpu/" + g + "/temperature") : NaN;
var uStr = !isNaN(uVal) ? Math.round(uVal) + "%" : "";
var vStr = "";
if (!isNaN(vuVal) && !isNaN(vtVal) && vtVal > 0 && vuVal >= 0)
vStr = Utils.formatBytes(vuVal) + "/" + Utils.formatBytes(vtVal) + "G";
// tVal === 0 is ksystemstats' null sentinel for iGPU (no hwmon node)
var tStr = (!isNaN(tVal) && tVal > 0) ? Utils.formatTemp(tVal, tempUnit) : "";
newList.push({ id: g, name: name,
usage: uStr, vram: vStr, temp: tStr,
usageNumber: !isNaN(uVal) ? uVal : NaN,
tempNumber: (!isNaN(tVal) && tVal > 0) ? tVal : NaN });
if (!isNaN(uVal)) { totalUsage += uVal; usageCount++; }
if (!isNaN(vuVal) && !isNaN(vtVal) && vtVal > 0 && vuVal >= 0) {
totalVramUsed += vuVal;
totalVramTotal += vtVal;
hasVram = true;
}
if (!isNaN(tVal) && tVal > 0 && (isNaN(maxTemp) || tVal > maxTemp)) maxTemp = tVal;
}
_dataList = newList;
_usageNum = usageCount > 0 ? totalUsage / usageCount : NaN;
_usageStr = usageCount > 0 ? Math.round(_usageNum) + "%" : "";
_vramStr = (hasVram && totalVramTotal > 0)
? Utils.formatBytes(totalVramUsed) + "/" + Utils.formatBytes(totalVramTotal) + "G" : "";
_tempNum = !isNaN(maxTemp) ? maxTemp : NaN;
_tempStr = !isNaN(maxTemp) ? Utils.formatTemp(maxTemp, tempUnit) : "";
}
// Re-aggregate when gpuMetrics, labels, selection, or unit change
onGpuMetricsChanged: aggregate()
onGpuLabelsChanged: aggregate()
onGpuSelectionChanged: aggregate()
onTempUnitChanged: aggregate()
}
@@ -0,0 +1,38 @@
import QtQuick
import org.kde.ksysguard.sensors as Sensors
Item {
id: root
property bool _dbg: { console.warn("[KVitals] MemorySensors: constructing..."); return true; }
property int updateInterval: 2000
readonly property real ramPercentage: {
if (ramUsedSensor.status !== Sensors.Sensor.Ready || ramTotalSensor.status !== Sensors.Sensor.Ready)
return NaN;
if (ramTotalSensor.value <= 0) return NaN;
return (ramUsedSensor.value / ramTotalSensor.value) * 100;
}
readonly property string ramValue: {
if (isNaN(ramPercentage))
return "...";
return Utils.formatBytes(ramUsedSensor.value) + "/" + Utils.formatBytes(ramTotalSensor.value) + "G";
}
Sensors.Sensor {
id: ramUsedSensor
sensorId: "memory/physical/used"
updateRateLimit: root.updateInterval
}
Sensors.Sensor {
id: ramTotalSensor
sensorId: "memory/physical/total"
updateRateLimit: root.updateInterval
}
Component.onCompleted: {
console.warn("[KVitals] MemorySensors: ready.");
}
}
@@ -0,0 +1,43 @@
import QtQuick
import org.kde.ksysguard.sensors as Sensors
Item {
id: root
property bool _dbg: { console.warn("[KVitals] NetworkSensors: constructing..."); return true; }
property int updateInterval: 2000
property string networkInterface: "auto"
property string networkUnit: "bytes"
readonly property string netIfacePath: {
if (networkInterface === "" || networkInterface === "auto")
return "all";
return networkInterface;
}
readonly property string netDownValue: {
if (netDownSensor.status !== Sensors.Sensor.Ready) return "...";
return Utils.formatRate(netDownSensor.value, networkUnit);
}
readonly property string netUpValue: {
if (netUpSensor.status !== Sensors.Sensor.Ready) return "...";
return Utils.formatRate(netUpSensor.value, networkUnit);
}
Sensors.Sensor {
id: netDownSensor
sensorId: "network/" + root.netIfacePath + "/download"
updateRateLimit: root.updateInterval
}
Sensors.Sensor {
id: netUpSensor
sensorId: "network/" + root.netIfacePath + "/upload"
updateRateLimit: root.updateInterval
}
Component.onCompleted: {
console.warn("[KVitals] NetworkSensors: ready.");
}
}
@@ -0,0 +1,31 @@
import QtQuick
import org.kde.ksysguard.sensors as Sensors
Item {
id: root
property bool _dbg: { console.warn("[KVitals] TempSensors: constructing..."); return true; }
property int updateInterval: 2000
property string tempUnit: "C"
readonly property real tempNumericValue: {
if (tempSensor.status !== Sensors.Sensor.Ready)
return NaN;
return tempSensor.value;
}
readonly property string tempValue: {
if (isNaN(tempNumericValue)) return "--";
return Utils.formatTemp(tempNumericValue, tempUnit);
}
Sensors.Sensor {
id: tempSensor
sensorId: "cpu/all/averageTemperature"
updateRateLimit: root.updateInterval
}
Component.onCompleted: {
console.warn("[KVitals] TempSensors: ready.");
}
}
@@ -0,0 +1,99 @@
pragma Singleton
import QtQuick
import org.kde.ksysguard.sensors as Sensors
QtObject {
function formatBytes(bytes) {
if (typeof bytes !== "number" || isNaN(bytes))
return "...";
var gb = bytes / (1024 * 1024 * 1024);
return gb.toFixed(1);
}
// unit: "bytes" (default, KB/MB) or "bits" (Kb/Mb)
// Suffix convention: uppercase B = bytes, lowercase b = bits
function formatRate(bytesPerSec, unit) {
if (typeof bytesPerSec !== "number" || isNaN(bytesPerSec))
return "...";
if (unit === "bits") {
var bps = bytesPerSec * 8;
if (bps >= 1000000)
return (bps / 1000000).toFixed(1) + "Mb";
return Math.max(0, bps / 1000).toFixed(1) + "Kb";
}
var kbps = bytesPerSec / 1024;
if (kbps >= 1024)
return (kbps / 1024).toFixed(1) + "MB";
return Math.max(0, kbps).toFixed(1) + "KB";
}
// celsiusValue: raw °C number from sensor; unit: "C" or "F"
function formatTemp(celsiusValue, unit) {
if (typeof celsiusValue !== "number" || isNaN(celsiusValue))
return "";
if (unit === "F")
return Math.round(celsiusValue * 9 / 5 + 32) + "°F";
return Math.round(celsiusValue) + "°C";
}
function sensorValueOrNaN(sensor) {
if (!sensor || sensor.status !== Sensors.Sensor.Ready)
return NaN;
if (typeof sensor.value !== "number" || isNaN(sensor.value))
return NaN;
return sensor.value;
}
function firstReadyNumber(sensors, requirePositive) {
for (var i = 0; i < sensors.length; i++) {
var value = sensorValueOrNaN(sensors[i]);
if (isNaN(value))
continue;
if (requirePositive && value <= 0)
continue;
return value;
}
return NaN;
}
function maxReadyNumber(sensors, requirePositive) {
var maxValue = NaN;
for (var i = 0; i < sensors.length; i++) {
var value = sensorValueOrNaN(sensors[i]);
if (isNaN(value))
continue;
if (requirePositive && value <= 0)
continue;
if (isNaN(maxValue) || value > maxValue)
maxValue = value;
}
return maxValue;
}
function firstReadyVramPair(pairs) {
for (var i = 0; i < pairs.length; i++) {
var used = sensorValueOrNaN(pairs[i].used);
var total = sensorValueOrNaN(pairs[i].total);
if (isNaN(used) || isNaN(total))
continue;
if (total <= 0 || used < 0)
continue;
return { used: used, total: total };
}
return null;
}
function resolveColor(numericValue, warningThreshold, criticalThreshold,
warningColor, criticalColor, baseColor, inverted) {
if (isNaN(numericValue))
return baseColor;
if (inverted) {
if (numericValue <= criticalThreshold) return criticalColor;
if (numericValue <= warningThreshold) return warningColor;
} else {
if (numericValue >= criticalThreshold) return criticalColor;
if (numericValue >= warningThreshold) return warningColor;
}
return baseColor;
}
}
@@ -0,0 +1,10 @@
module sensors
singleton Utils 1.0 Utils.qml
CpuSensors 1.0 CpuSensors.qml
MemorySensors 1.0 MemorySensors.qml
TempSensors 1.0 TempSensors.qml
GpuSensors 1.0 GpuSensors.qml
BatterySensors 1.0 BatterySensors.qml
NetworkSensors 1.0 NetworkSensors.qml
DiskSensors 1.0 DiskSensors.qml
FanSensors 1.0 FanSensors.qml
@@ -0,0 +1,133 @@
# Architecture
KVitals is a KDE Plasma 6 widget (plasmoid) with a modular architecture connecting native **KSysGuard sensors** to a **QML UI** through dedicated sensor components.
## Data Flow
![KVitals Data Flow](dataflow.svg)
## Sensor Modules (`contents/ui/sensors/`)
Each system metric has its own QML component under `sensors/`. These components encapsulate all sensor subscriptions, data parsing, and value formatting for their metric.
| Module | Sensors | Exposed Properties |
|---|---|---|
| `CpuSensors.qml` | `cpu/all/usage` | `cpuValue` |
| `MemorySensors.qml` | `memory/physical/used`, `total` | `ramValue` |
| `TempSensors.qml` | `cpu/all/averageTemperature` | `tempValue` |
| `GpuSensors.qml` | `gpu/all/usage`, `totalVram`, `usedVram`, `temperature` | `gpuValue`, `gpuRamValue`, `gpuTempValue`, `gpuDisplayValue`, `hasGpuData` |
| `BatterySensors.qml` | `power/<device>/chargePercentage`, `chargeRate` | `batValue`, `powerValue` |
| `NetworkSensors.qml` | `network/<iface>/download`, `upload` | `netDownValue`, `netUpValue` |
A shared `Utils.qml` singleton provides formatting helpers (`formatBytes`, `formatRate`) and sensor-reading utilities (`sensorValueOrNaN`, `firstReadyNumber`, `maxReadyNumber`, `firstReadyVramPair`).
### Performance Benefits
1. **Zero Subprocesses**: No `bash`, `awk`, or `cat` commands are spawned.
2. **Stable File Descriptors**: No CLI pipes need to be kept open, eliminating Plasma 6 Wayland FD-exhaustion crashes.
3. **Low Latency**: The widget reads the exact same backend API as the official KDE System Monitor.
## Orchestrator (`main.qml`)
`main.qml` acts as a lightweight orchestrator:
1. **Reads configuration** from `Plasmoid.configuration`
2. **Instantiates sensor modules** with the configured `updateInterval`
3. **Builds metrics models** using the `orderedKeys` array (derived from the `metricOrder` config)
4. **Applies view-specific visibility rules** such as `compactShow*` settings and compact grouping
5. **Passes models** to `CompactView` and `FullView` for rendering
```
main.qml
├── CpuSensors { id: cpu }
├── MemorySensors { id: memory }
├── TempSensors { id: temp }
├── GpuSensors { id: gpu }
├── BatterySensors { id: battery }
├── NetworkSensors { id: network }
├── compactRepresentation: CompactView { metricsModel: ... }
└── fullRepresentation: FullView { metricsModel: ... }
```
## Views
### CompactView (Panel)
A `RowLayout` with a `Repeater` that renders each compact-visible metric as:
- **Icon** (optional, via `Kirigami.Icon` with `isMask: true`)
- **Label** (optional, e.g., "CPU:")
- **Value** (always shown, e.g., "26%")
- **Separator** (`|` between metrics)
Visibility of icons/labels is controlled by the `displayMode` property. Metric inclusion is controlled by both the metric-level `show*` settings and the compact-panel `compactShow*` settings, allowing a metric to remain visible in the popup/tooltip while being hidden from the panel.
The compact panel also supports horizontal and vertical delegates through the `layoutType` setting.
!!! tip
Icons use `isMask: true` to render as monochrome, matching the panel's text color regardless of the icon theme.
### FullView (Popup)
A `ColumnLayout` with a `Repeater` showing a detailed row per enabled metric with label and bold value, displayed when clicking the widget.
### Tooltip
Multi-line text showing all enabled metrics, displayed on hover. Compact-panel visibility settings do not filter the tooltip.
## Configuration System
```
config/main.xml ← Config schema (entry names, types, defaults)
config/config.qml ← Tab registration (General, Metrics, Icons, Colors)
ui/configGeneral.qml ← General tab (display mode, layout, font, interval)
ui/configMetrics.qml ← Metrics tab (show/hide toggles, compact panel visibility, metric order, grouping, network interface, battery device)
ui/configIcons.qml ← Icons tab (per-metric icon picker)
ui/configColors.qml ← Colors tab (font color, warning/critical colors, thresholds)
```
All config values are accessed in `main.qml` via `Plasmoid.configuration.<key>`.
!!! tip "Adding a New Sensor"
1. Create `contents/ui/sensors/NewSensor.qml` exposing formatted value properties
2. Register it in `sensors/qmldir`
3. Instantiate it in `main.qml`
4. Add it to the `orderedKeys` loop in compact/full/tooltip builders
5. Add `show*` and `compactShow*` config entries in `main.xml`
6. Add the metric and compact panel checkboxes in `configMetrics.qml`
## Project Structure
```
kvitals/
├── metadata.json # Plasmoid metadata (name, version, id)
├── install.sh # Local install script
├── install-remote.sh # Remote install (curl/wget)
├── CHANGELOG.md # Version history
├── docs/ # Documentation
│ ├── installation.md
│ ├── configuration.md
│ ├── architecture.md
│ ├── contributing.md
│ └── troubleshooting.md
└── contents/
├── config/
│ ├── config.qml # Tab registration
│ └── main.xml # Config schema
└── ui/
├── main.qml # Widget orchestrator
├── CompactView.qml # Panel representation
├── FullView.qml # Popup representation
├── configGeneral.qml # General settings tab
├── configMetrics.qml # Metrics settings tab
├── configIcons.qml # Icons settings tab
├── configColors.qml # Colors settings tab
└── sensors/ # Sensor modules
├── qmldir # QML module definition
├── CpuSensors.qml # CPU usage
├── MemorySensors.qml # RAM usage
├── TempSensors.qml # CPU temperature
├── GpuSensors.qml # GPU usage, VRAM, temp
├── BatterySensors.qml # Battery & power
├── NetworkSensors.qml # Network speed
└── Utils.qml # Shared formatting helpers
```
@@ -0,0 +1,250 @@
# Changelog
All notable changes to KVitals will be documented in this file.
## [2.10.1] - 2026-06-29
### Fixed
- **Plasmashell Boot Crashes**: Resolved a critical race condition that caused `plasmashell` to enter a crash loop during system boot. Sensor module loading is now deferred until after window attachment is fully complete, preventing the `KirigamiPlasmaStyle` SIGSEGV (#49).
## [2.10.0] - 2026-06-27
### Added
- **Fan Speed Monitoring** (`Metrics` settings): A new standalone "Fan" metric that dynamically discovers and reports fan speeds (including GPU and CPU fans) directly from the system (#47).
- Automatically identifies fans through `SensorTreeModel`.
- Supports RPM and Percentage display units (configurable in `General` settings).
- Fully integrates with compact panel, full popup, and tooltip views.
- Safely handles fans that do not report a maximum RPM by omitting them from percentage-based aggregations to prevent misleading data.
- **Display Mode 'None'** (`General` settings): A new display mode that completely hides the metric labels and icons, showing only the raw values to save space (#47).
- **Config UI Redesign** (`Metrics` settings): The metrics configuration page has been overhauled for better UX, with inline contextual settings (e.g. CPU, GPU, Network options expand directly under their respective metrics) and debounced sensor discovery to eliminate UI freezes on load (#48).
## [2.9.0] - 2026-06-19
### Added
- **Per-GPU Sub-metric Visibility** (`Metrics` settings — GPU Selection): Each GPU entry now has independent **Usage**, **VRAM**, and **Temperature** toggles, letting you show only the metrics you care about without disabling the GPU entirely (#44).
- Toggling a sub-metric off immediately stops polling those sensors — no unnecessary kernel data fetched.
- A **minimum-one** guard prevents all three sub-metrics from being deselected at once (the last checked box is disabled), keeping at least one value visible per GPU.
- Sub-metric checkboxes are automatically disabled when the parent GPU is deselected, matching visual state to functional reality.
- Storage format uses a compact pipe-separated string (`gpu0:usage,vram|gpu1:usage,temp`). GPUs using all defaults are omitted, keeping the config short. Empty string (default) = all three enabled for every GPU — fully backwards-compatible with existing configs.
## [2.8.1] - 2026-05-23
### Fixed
- **Installation via KDE Store leaving stale widget state** (`install-remote.sh`): Users who first installed via the KDE Store (or an older `install-remote.sh`) and then upgraded manually could end up with a mismatched `kpackage/generic/` registration. This caused settings like **Show in compact panel** to silently not apply, because KDE resolves widget configuration from the kpackage path, not the plasmoids path. The remote install script now mirrors the local `install.sh` behaviour exactly: it removes any previous entry under `~/.local/share/kpackage/generic/<id>` (including stale symlinks), creates the install directory under `~/.local/share/plasma/plasmoids/`, and creates a fresh symlink at the kpackage path pointing to it.
## [2.8.0] - 2026-05-22
### Added
- **Disk I/O & Temperature** (`Metrics` settings — Disk I/O & Temp): New metric showing real-time disk read/write rates and the highest drive temperature across all NVMe and SATA drives. Displayed as `DSK: ↓2.1MB ↑76KB · 42°C` in the compact panel (#36).
- Drive temperatures are discovered dynamically via `SensorTreeModel` + `lmsensors` (supports `nvme-pci-*` and `drivetemp-scsi-*` chips) — zero polling overhead when the metric is disabled.
- Dedicated **Disk Temp** threshold sliders added to the Colors settings page (default: warning 45°C, critical 60°C).
- **Unit Preferences** (`General` settings — Unit Preferences section): Choose display units globally across all metrics (#37).
- **Temperature**: Celsius (°C, default) or Fahrenheit (°F). Applies to CPU temp, GPU temp, and Disk temp everywhere — panel, popup, and tooltip.
- **Network / Disk I/O**: Bytes (KB/MB, default) or Bits (Kb/Mb). Applies to Network and Disk I/O rates. Suffix convention follows industry standard: uppercase `B` = bytes, lowercase `b` = bits.
- Threshold slider labels in the Colors settings page update live to reflect the chosen temperature unit (stored values remain in °C for correct sensor comparison).
## [2.7.0] - 2026-05-15
### Added
- **Multi-GPU Support** (`Metrics` settings — GPU Selection): On systems with more than one GPU, each GPU is now listed individually as a separate metric in both the compact panel and the full popup view (#22). Works automatically — no configuration needed on single-GPU machines.
- Each GPU is detected dynamically via `SensorTreeModel` metadata; no persistent subscriptions run during discovery.
- The GPU Selection section in settings shows all discovered GPUs with independent enable/disable checkboxes.
- **GPU Custom Labels** (`Metrics` settings — GPU Selection): On multi-GPU systems, each GPU entry in the panel shows a customizable label. Type a name in the **Label** field (e.g. `iGPU`, `dGPU`) to override the default `GPU 1` / `GPU 2` identifiers. Leave it empty to keep the default numbering.
- **Hybrid GPU power hint**: When two or more GPUs are detected, a contextual note appears in the GPU Selection section explaining that unchecking the discrete GPU prevents KVitals from polling it, allowing it to suspend when idle.
### Fixed
- **Unintended dGPU Wakeup** on hybrid GPU laptops (Intel/AMD + NVIDIA setups using `supergfxctl` / `asusctl`): The previous implementation used permanent `Sensors.Sensor` subscriptions for up to 6 hardcoded GPU slots. These subscriptions polled every GPU continuously, preventing the dGPU from entering its suspended/power-save state even when it was idle (#26).
- **New architecture**: Discovery uses `SensorTreeModel` + `KDescendantsProxyModel` (pure metadata query, no value subscriptions). Data polling uses a single `SensorDataModel` constrained strictly to the GPUs the user has selected.
- **Result**: Deselecting a GPU in settings stops all polling for that GPU immediately. On hybrid setups, unchecking the dGPU allows it to fully suspend.
- **Note**: If the dGPU remains active even after unchecking it in KVitals, the cause is likely unrelated — some Xwayland applications keep the GPU awake independently of any sensor polling. This is a system/compositor-level behavior outside the scope of KVitals.
## [2.6.0] - 2026-05-10
### Added
- **Compact Panel Visibility** (`Metrics` settings): Each metric now has an independent "Show in compact panel" toggle, allowing metrics to appear in the full popup view but stay hidden from the panel bar (#29, thanks @keiishu). Disabling a metric preserves its compact visibility state for when it is re-enabled.
- **CPU Frequency** (`Metrics` settings): Display the average CPU frequency in the widget. Auto-formats as GHz (≥ 1000 MHz) or MHz (#33).
- **Merge into CPU** (compact view): Appends frequency as a second segment next to CPU usage (`CPU: 34% · 3.20 GHz`). Compatible with Merge CPU & Temp — all three values appear as segments.
- **Full view sub-item**: When enabled, CPU Frequency appears as a dedicated row directly under CPU Usage in the popup.
- **Bold Font** (`General` settings): Toggle bold styling for all metric value labels across compact and full views (#30). Defaults to off.
### Fixed
- Inconsistent font weight across metrics in vertical layout: RAM and Network values (rendered via `SegmentsRow`) were always bold while CPU/GPU were not. All value labels now follow the new Bold Font setting uniformly.
## [2.5.0] - 2026-04-30
### Added
- **Layout Type** (`General` settings): Choose between **Horizontal** (default, unchanged) and **Vertical** layout for the compact panel view. In vertical mode, the metric value is displayed on top with the label/icon dimmed below — ideal for tall panels or icon-only display (#11).
- **Metric Grouping** (`Metrics` settings — Grouping section):
- **Merge CPU & Temp**: Combines CPU temperature as a second value next to CPU usage (`CPU: 45% · 62°C`), using the same segment display as GPU. The CPU Temperature entry is hidden from the metric order list while merged.
- **Merge Battery & Power**: Combines power consumption as a second value next to battery level (`BAT: 87% · 12.4W`). Power Consumption entry is hidden from the metric order list while merged.
- **Split GPU Metrics**: Optionally break GPU usage, VRAM and temperature into separate panel entries instead of the default grouped display (default: grouped).
### Changed
- Metric order list now hides absorbed metrics when grouping is active (e.g. "CPU Temperature" disappears when "Merge CPU & Temp" is enabled), keeping the list clean and non-redundant.
- `CompactView` refactored to use a `Loader`-based delegate system, enabling runtime layout switching without widget reload.
### Fixed
- `Unable to assign [undefined] to QColor` runtime error when CPU+Temp or Battery+Power merge was enabled — missing top-level `color` field on segmented metric objects.
- Defensive `|| baseTextColor` fallback added to all value label color bindings in `CompactView`.
## [2.4.0] - 2026-04-01
### Added
- **Custom Font Color**: Override the widget font color to match your panel theme (#20). Configurable via the new **Colors** settings tab.
- **Threshold-Based Coloring**: Metric values dynamically change color when they exceed configurable warning/critical thresholds (#12). Supported metrics:
- CPU usage (default: warning 70%, critical 90%)
- CPU temperature (default: warning 60°C, critical 85°C)
- RAM usage (default: warning 70%, critical 90%)
- GPU usage (default: warning 70%, critical 90%)
- GPU temperature (default: warning 60°C, critical 85°C)
- Battery level (inverted: warning below 30%, critical below 15%)
- **Colors Config Tab**: New settings page with color pickers for font/warning/critical colors and per-metric threshold sliders.
- Sensor modules now expose raw numeric values (`cpuNumericValue`, `tempNumericValue`, `ramPercentage`, `batNumericValue`) for threshold comparison.
- `Utils.resolveColor()` function for flexible threshold-triggered color resolution.
### Fixed
- Fixed the Colors tab color picker turning white after selecting a color; it now uses a stable native platform color dialog and preserves the selected swatch correctly.
### Notes
- Network and Power metrics are excluded from threshold coloring (no meaningful universal threshold).
- Both features are **opt-in** — disabled by default. Existing users are unaffected.
## [2.3.0] - 2026-03-13
### Changed
- **Sensor Module Architecture**: Extracted all sensor logic from `main.qml` into dedicated QML components under `contents/ui/sensors/`:
- `CpuSensors.qml` — CPU usage monitoring
- `MemorySensors.qml` — RAM usage monitoring
- `TempSensors.qml` — CPU temperature monitoring
- `GpuSensors.qml` — GPU usage, VRAM, and temperature monitoring
- `BatterySensors.qml` — Battery and power monitoring with auto-detection
- `NetworkSensors.qml` — Network download/upload speed monitoring
- `Utils.qml` — Shared formatting helpers (byte formatting, rate formatting)
- **View Separation**: Extracted compact and full representations into `CompactView.qml` and `FullView.qml`.
- **Reduced `main.qml`**: From ~700 lines to ~140 lines — now acts purely as an orchestrator.
### Notes
- No user-facing or configuration changes. The widget behaves identically to v2.2.1.
- This refactor improves maintainability and makes it easier to add new sensor types in the future.
## [2.2.1] - 2026-03-07
### Fixed
- **Battery Detection Hotfix**: Replaced `SensorTreeModel` with a crash-free **Two-Stage Hybrid Detection** system (#14):
- **Stage 1 (Silent Probe)**: Silently probes common battery paths (`BAT0`, `BAT1`, `BATT`, etc.) for instant detection without running any subprocesses.
- **Stage 2 (Fallback)**: If no standard battery is found, falls back to a single `qdbus` query to list all sensors, completely avoiding `PlasmaCore.DataSource` file descriptor leaks. Includes a manual config fallback if `qdbus` is unavailable.
## [2.2.0] - 2026-03-05
### Added
- **Custom Metric Order**: Added a new configuration option to arrange metrics (CPU, RAM, GPU, etc.) individually in whatever order you prefer (#7).
- **Dynamic Battery Detection**: Replaced hardcoded `BAT0`/`BAT1` sensors with dynamic `SensorTreeModel` discovery. The widget will now automatically find any battery your system has (BAT0, BATT, CMB0, macsmc-battery, etc.) (#14).
## [2.1.1] - 2026-03-03
### Fixed
- Fixed a "Detected anchors on an item that is managed by a layout" QML warning spanning the journal log caused by a `MouseArea` anchoring inside a `RowLayout` (#13).
## [2.1.0] - 2026-03-01
### Added
- **GPU Metrics Support**: Added VRAM usage and GPU temperature monitoring to the widget.
- GPU data is retrieved natively using KDE KSysGuard sensors (`org.kde.ksysguard.sensors`).
## [2.0.0] - 2026-02-27
### Changed
- **Major Architecture Overhaul**: Replaced the previous `sys-stats.sh` backend with native KDE KSysGuard sensors (`org.kde.ksysguard.sensors`).
- Completely eliminates "file descriptor leak" crashes (Issue #8) and improves overall performance by relying directly on the `ksystemstats` D-Bus daemon instead of constantly spawning bash processes.
- Automatic fallback for battery monitoring (BAT0 and BAT1) logic implemented directly in QML.
## [1.4.1] - 2026-02-24
### Fixed
- RAM usage showing empty on non-English locales — `free` translates its `Mem:` header based on locale, causing the parser to match nothing
- Switched RAM data source from `free -b` to `/proc/meminfo` (locale-independent, faster, more accurate)
## [1.4.0] - 2026-02-22
### Added
- **Display mode setting** — choose between Text, Icons, or Icons + Text for the panel
- **Custom icon picker** — select icons from your installed theme for each metric (via KDE's native icon picker)
- **Icon size slider** — adjust icon size (8–24px) when using icon mode
- **Font customization** — choose any system font and font size for the panel text
- **Settings tabs** — split configuration into General, Metrics, and Icons tabs
- **Reset to defaults** button on the Icons tab
- **CHANGELOG.md** — version history
- **Documentation** — MkDocs site with installation, configuration, architecture, contributing, and troubleshooting guides
## [1.3.0] - 2026-02-16
### Added
- Power consumption tracking (via `/sys/class/power_supply/`) — contributed by [@Pijuli](https://github.com/Pijuli)
### Fixed
- ShellCheck warnings from power consumption PR (SC2034, SC2155)
## [1.2.1] - 2026-02-16
### Fixed
- AMD CPU temperature detection — added `k10temp`, `zenpower`, `zenergy`, `amdgpu` to thermal_zone and hwmon detection
- lm-sensors fallback now matches AMD `Tccd1` label
- Reordered temperature fallback tiers to prioritize CPU-specific sources over generic thermal zones
## [1.2.0] - 2026-02-13
### Added
- Auto-detect network interface via `ip route` with manual override in settings
- Network interface selector in widget configuration
### Fixed
- ShellCheck warnings (SC2010, SC2155)
## [1.1.0] - 2026-02-12
### Changed
- Modularized `sys-stats.sh` into functions
- Enhanced CPU temperature detection with 4-tier fallback (thermal_zone → hwmon → lm-sensors → generic)
## [1.0.0] - 2026-02-12
### Added
- Initial release
- CPU usage (delta-based from `/proc/stat`)
- RAM usage (from `/proc/meminfo`)
- CPU temperature (multi-source detection)
- Battery status with emoji indicators
- Network speed (delta-based from `/proc/net/dev`)
- Configurable update interval
- Toggle visibility per metric
@@ -0,0 +1,156 @@
# Configuration
Right-click the widget → **Configure KVitals...** to open the settings dialog. Settings are organized into four tabs.
## General Tab
| Setting | Description | Default |
|---------------------|--------------------------------------------------------------------------------|--------------------|
| **Display mode** | How metrics are shown in the panel | Text |
| **Layout** | Compact panel layout direction | Horizontal |
| **Icon size** | Icon dimensions in pixels (only visible when using icons) | 12 px |
| **Font** | Font family for all panel text (searchable dropdown of system fonts, editable) | monospace |
| **Font size** | Text size in pixels. `0` uses the system default | 0 (system default) |
| **Update interval** | How often stats are refreshed | 2.0 seconds |
### Display Modes
| Mode | Description |
|------------------|---------------------------------------------------------------|
| **Text** | Labels + values: `CPU: 26% \| RAM: 8.8/39.0G` |
| **Icons** | Icons + values only: `🖥 26% \| 🧠 8.8/39.0G` |
| **Icons + Text** | Icons + labels + values: `🖥 CPU: 26% \| 🧠 RAM: 8.8/39.0G` |
!!! tip "Saving Panel Space"
**Icons** mode is the most compact — great for small panels or when you have many metrics enabled.
### Layout Types
| Layout | Description |
|----------------|--------------------------------------------------------------|
| **Horizontal** | Shows each compact metric in a single row, separated by `\|` |
| **Vertical** | Stacks the value above the icon |
## Metrics Tab
| Setting | Description | Default |
|---------------------------|-----------------------------------------------------------------------------------|--------------------------------------|
| **Metric Order** | Use the up/down buttons to rearrange metrics in the panel | CPU, RAM, Temp, GPU, Bat, Power, Net |
| **Metric enable toggles** | Enables or disables each metric | On |
| **Show in compact panel** | Controls whether each enabled metric appears in the panel representation | On |
| **Network interface** | Select network interface (`auto` or manual) | auto |
| **Battery device** | Leave empty for automatic battery detection, or enter a sensor device id manually | auto |
### Supported Metrics
| Metric | Compact Label | Description |
|-----------------------|---------------|-----------------------------------------------------|
| **CPU Usage** | `CPU:` | CPU utilization percentage |
| **RAM Usage** | `RAM:` | Used/total memory |
| **CPU Temperature** | `TEMP:` | CPU temperature in °C |
| **GPU Metrics** | `GPU:` / `<name>:` | GPU usage %, VRAM used/total, and GPU temperature. On multi-GPU systems, each selected GPU appears as a separate labeled entry. |
| **Battery Status** | `BAT:` | Battery percentage |
| **Power Consumption** | `PWR:` | Power draw in watts |
| **Network Speed** | `NET:` | Download/upload speeds |
### Compact Panel Visibility
Each metric has two visibility controls:
| Control | Effect |
|---------------------------|-----------------------------------------------------------------------------------------------------------------------------|
| **Metric checkbox** | Enables the metric globally. |
| **Show in compact panel** | Hides or shows the metric in the panel widget. The metric remains available in the dropdown menu and tooltip while enabled. |
Use this when you still want to track a metric in the tooltip or dropdown but want to hide it from the panel to save
space.
### Grouping
| Setting | Description | Default |
|---------------------------|-----------------------------------------------------------------------------------------------------------|---------|
| **Merge CPU & Temp** | Shows CPU temperature as a second value next to CPU usage in the widget | Off |
| **Merge Battery & Power** | Shows power consumption as a second value next to battery level in the widget | Off |
| **Split GPU metrics** | Shows GPU usage, VRAM, and GPU temperature as separate compact panel entries instead of one grouped entry | Off |
Merged compact rows only absorb the second metric when both metrics are enabled and selected for the compact panel.
### Network Interface
When set to `auto`, the widget natively aggregates the traffic across all active network connections using KDE's
`network/all` sensor. This handles VPN routing and switching networks automatically.
You can manually select a specific interface (e.g., `wlan0`, `enp3s0`) from the dropdown if you only want to monitor a
single device.
!!! note
The manual interface list is populated dynamically from `/sys/class/net/`.
### GPU Selection
When the **GPU Metrics** metric is enabled, a **GPU Selection** section appears listing every GPU detected on your
system. GPUs are discovered dynamically via the KDE sensor tree — no polling is required during discovery.
| Control | Description |
|------------------|-----------------------------------------------------------------------------------------------|
| **Checkbox** | Enable or disable monitoring for each individual GPU |
| **Label field** | Override the display name for a GPU. Leave empty to use the name reported by ksystemstats. |
**Label resolution order**: custom label → ksystemstats-provided name (e.g. `GPU 1`) → `GPU N` fallback.
!!! tip "Hybrid GPU Laptops (Intel/AMD + NVIDIA)"
On hybrid setups using tools such as `supergfxctl` or `asusctl`, KVitals will only poll the GPUs whose
checkboxes are ticked. **Unchecking the discrete GPU** stops all polling for it, allowing it to enter its
suspended/power-save state when idle.
## Icons Tab
Each metric has its own icon that can be customized:
| Metric | Default Icon | Icon Name |
|-------------|--------------|-----------------------|
| CPU | 🖥 | `cpu` |
| RAM | 🧠 | `memory` |
| Temperature | 🌡 | `temperature-normal` |
| GPU | GPU | `video-card` |
| Battery | 🔋 | `battery-good` |
| Power | ⚡ | `battery-charging-60` |
| Network | 📶 | `network-wireless` |
Click **"Change..."** to open KDE's native icon picker, which lets you browse and search all icons from your installed
icon theme (Breeze, Papirus, Tela, etc.).
Click **"Reset to defaults"** to restore all icons to their default values.
!!! note "Monochrome Rendering"
Icons are rendered with `isMask: true`, meaning they adopt the panel's text color (monochrome). This ensures
visibility on both light and dark panels.
!!! tip "Finding Icons"
The icon picker shows all icons from your installed theme. Use the search bar to find icons by name — try keywords
like "chip", "thermometer", "download", or "lightning".
## Colors Tab
| Setting | Description | Default |
|-------------------------------|--------------------------------------------------------------|-------------------------|
| **Use custom font color** | Overrides the widget text color with a custom color | Off |
| **Color** | Font color as a picked or typed `#RRGGBB` value | Plasma theme text color |
| **Enable threshold coloring** | Changes color of supported metric values based on thresholds | Off |
| **Warning color** | Color used when a warning threshold is reached | `#e5a50a` |
| **Critical color** | Color used when a critical threshold is reached | `#da4453` |
Threshold coloring supports CPU usage, CPU temperature, RAM usage, GPU usage, GPU temperature, and battery level.
| Metric | Default warning color | Default critical color |
|-----------------|-----------------------|------------------------|
| CPU usage | 70% | 90% |
| CPU temperature | 60°C | 85°C |
| RAM usage | 70% | 90% |
| GPU usage | 70% | 90% |
| GPU temperature | 60°C | 85°C |
| Battery level | 30% | 15% |
!!! note "Battery Thresholds"
Battery thresholds are inverted: warning and critical states trigger when the battery level falls _below_ the
configured values.
@@ -0,0 +1,86 @@
# Contributing
Thanks for your interest in contributing to KVitals!
## Getting Started
1. Fork the repository
2. Clone your fork:
```bash
git clone https://github.com/<your-username>/kvitals.git
cd kvitals
```
3. Install locally for development:
```bash
bash install.sh
```
## Development Workflow
### Making Changes
1. Edit files in the project directory
2. Reinstall and test:
```bash
bash install.sh
kquitapp6 plasmashell && kstart plasmashell &
```
3. Check for QML errors:
```bash
journalctl -b --no-pager | grep kvitals
```
!!! tip "Fast Iteration"
You don't always need to restart plasmashell. For config-only changes, just reopen the settings dialog. For QML changes, a restart is required.
### Adding a New Metric
1. **Sensors** — Find the relevant `org.kde.ksysguard.sensors` sensor ID using `kstatsviewer`
2. **Settings** — Add `show*` and `compactShow*` entries to `contents/config/main.xml`
3. **Configuration UI** — Add the metric and compact visibility checkboxes to `configMetrics.qml`
4. **Icons** — Add an icon picker to `configIcons.qml`
5. **UI** — Add property bindings and model entries in `main.qml`
!!! note
Don't forget to add a default icon name for the new metric in `configIcons.qml`'s reset button handler.
### Adding a New Setting
1. Add the entry to `contents/config/main.xml` with a default value
2. Add the UI control to the appropriate config tab (`configGeneral.qml`, `configMetrics.qml`, `configIcons.qml`, or `configColors.qml`)
3. Bind the value in `main.qml` via `Plasmoid.configuration.<key>`
## Pull Requests
1. Create a feature branch: `git checkout -b feat/my-feature`
2. Make your changes and test locally
3. Ensure ShellCheck passes
4. Push and open a PR against `master`
!!! tip "Commit Messages"
Use conventional commits for clear history:
- `feat:` — New feature
- `fix:` — Bug fix
- `chore:` — Maintenance
- `docs:` — Documentation
## Code Style
- **QML** — Follow KDE's QML conventions, use `Kirigami` components where possible
- **Commits** — Use conventional commits: `feat:`, `fix:`, `chore:`, `docs:`
## Reporting Issues
When filing a bug report, please include:
- KDE Plasma version (`plasmashell --version`)
- Linux distribution and version
- Whether you're using Intel or AMD CPU
- Relevant journal output (`journalctl -b | grep kvitals`)
!!! note "Debugging Output"
To capture detailed logs for a bug report:
```bash
journalctl -b --no-pager | grep -i "kvitals\|sys-state" > kvitals-debug.log
```
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 32 KiB

@@ -0,0 +1,30 @@
# KVitals
A lightweight KDE Plasma 6 panel widget that displays live system vitals directly in your top bar.
```
CPU: 26% | RAM: 8.8/39.0G | TEMP: 96°C | 🔋BAT: 78% | PWR: +20W | NET: ↓82.2K ↑58.9K
```
## Features
- **Live monitoring** — CPU, RAM, temperature, GPU, battery, power, network
- **Display modes** — Text, Icons, or Icons + Text
- **Custom icons** — Pick any icon from your installed KDE theme
- **Font customization** — Choose any system font and size
- **Settings tabs** — General, Metrics, Icons, and Colors
- **Minimal footprint** — Native KSysGuard integration + QML, no heavy dependencies
## Quick Start
```bash
git clone https://github.com/yassine20011/kvitals.git
cd kvitals && bash install.sh
```
Then right-click your panel → **Add Widgets** → search **KVitals**.
## Links
- [GitHub Repository](https://github.com/yassine20011/kvitals)
- [KDE Store](https://www.pling.com/p/2347917/)
@@ -0,0 +1,58 @@
# Installation
## KDE Store (Recommended)
Install directly from the KDE Store:
👉 **[Get KVitals on the KDE Store](https://www.pling.com/p/2347917/)**
Or from within KDE Plasma:
1. Right-click on the panel → **Add Widgets...**
2. Click **Get New Widgets...** → **Download New Plasma Widgets...**
3. Search for **"KVitals"**
4. Click **Install**
## Quick Install (curl)
```bash
curl -fsSL https://github.com/yassine20011/kvitals/releases/latest/download/install-remote.sh | bash
```
## Quick Install (wget)
```bash
wget -qO- https://github.com/yassine20011/kvitals/releases/latest/download/install-remote.sh | bash
```
## Manual Install
```bash
git clone https://github.com/yassine20011/kvitals.git
cd kvitals
bash install.sh
```
Then add the widget:
1. Right-click on the panel → **Add Widgets...**
2. Search for **KVitals**
3. Drag it onto your panel
!!! note "Restart Required"
You may need to restart Plasma for the widget to appear:
```bash
plasmashell --replace &
```
## Requirements
- KDE Plasma 6.0+
## Uninstall
```bash
rm -rf ~/.local/share/plasma/plasmoids/org.kde.plasma.kvitals
plasmashell --replace &
```
!!! warning
This permanently removes the widget and all its configuration. Your settings will not be preserved.
@@ -0,0 +1,39 @@
# As a condition of accessing this website, the website operator
# explicitly GRANTS permission for the following content signals:
# search: building a search index and providing search results
# ai-input: inputting content into one or more AI models
# ai-train: training or fine-tuning AI models.
# BEGIN Content Signals
User-agent: *
Content-Signal: search=yes,ai-input=yes,ai-train=yes
Allow: /
# END Content Signals
# Explicitly welcoming popular AI scrapers and search bots
User-agent: Amazonbot
Allow: /
User-agent: Applebot-Extended
Allow: /
User-agent: Bytespider
Allow: /
User-agent: CCBot
Allow: /
User-agent: ClaudeBot
Allow: /
User-agent: Google-Extended
Allow: /
User-agent: GPTBot
Allow: /
User-agent: meta-externalagent
Allow: /
Sitemap: https://kvitals.dev/sitemap.xml
@@ -0,0 +1,141 @@
# Troubleshooting
## Temperature Shows "--"
**Cause:** The widget couldn't find a temperature source on your system.
**Fix:** Check which thermal sources are available:
```bash
# Check thermal zones
cat /sys/class/thermal/thermal_zone*/type 2>/dev/null
# Check hwmon
for d in /sys/class/hwmon/hwmon*/; do
echo "$(cat "$d/name" 2>/dev/null): $d"
done
# Check lm-sensors
sensors 2>/dev/null | head -20
```
!!! tip "AMD Systems"
If you're on AMD, make sure `k10temp` or `zenpower` kernel module is loaded:
```bash
sudo modprobe k10temp
```
To load it automatically on boot, add `k10temp` to `/etc/modules-load.d/k10temp.conf`.
## RAM Shows Empty (versions ≤ 1.4.0)
**Cause:** On versions before 1.4.1, RAM was read by parsing the `free` command, which translates its output headers (e.g. `Mem:`) based on your system locale. Non-English locales caused the parser to match nothing.
**Fix:** Update to KVitals 1.4.1+, which reads directly from `/proc/meminfo` (always English, locale-independent).
## Battery/Power Shows Nothing
**Cause:** No battery detected (e.g., desktop systems without a battery or UPS).
**Behavior in KVitals (v2.2.0+):** The widget uses KDE's native `SensorTreeModel` to dynamically scan your system's hardware tree for any connected battery (including `BAT0`, `BAT1`, `BATT`, `CMB0`, `macsmc-battery`, etc.). If nothing shows up, it means the KDE `ksystemstats` daemon cannot find a battery API on your machine.
!!! note
This is expected behavior on desktop systems. Disable battery and power metrics in **Settings → Metrics** tab to hide the empty entries.
## Network Speed Shows 0
**Cause:** Wrong network interface selected.
**Fix:**
1. Open **Settings → Metrics** and ensure the network interface is set to `auto`.
2. If you want to monitor a specific connection, select it from the dropdown list.
!!! tip
If you use multiple connections (WiFi + Ethernet), set the interface manually to the one you want to monitor.
## GPU Shows Only Usage (or Missing VRAM/Temp)
**Cause:** GPU sensor availability depends on your driver/backend. Some systems expose only usage, while VRAM or temperature sensors are missing or report no data.
**Behavior in KVitals:** The widget now shows only the GPU fields that are available on your system (no placeholder `...` / `--` for unsupported GPU sub-metrics).
**Fix/Debug:** List GPU sensor IDs reported by Plasma KSystemStats:
```bash
qdbus --literal org.kde.ksystemstats1 /org/kde/ksystemstats1 org.kde.ksystemstats1.allSensors \
| rg -o '"gpu/[^"]+"' | tr -d '"' | sort -u
```
Then test a specific sensor value:
```bash
qdbus --literal org.kde.ksystemstats1 /org/kde/ksystemstats1 org.kde.ksystemstats1.sensorData gpu/all/usage
```
!!! tip
On multi-GPU systems, per-GPU sensors such as `gpu/gpu1/*` may exist even when aggregate sensors are partial.
## Metric Shows in Popup But Not Panel
**Cause:** The metric is enabled, but its **Show in compact panel** checkbox is disabled in the Metrics settings.
**Fix:**
1. Open **Settings → Metrics**.
2. Find the metric in the order list.
3. Enable **Show in compact panel** under that metric.
!!! note
Compact grouping also depends on compact visibility. For example, **Merge CPU & Temp** only shows temperature next to CPU when both metrics are enabled and selected for the compact panel.
## Widget Shows "KVitals" or "..."
**Cause:** The KSysGuard daemon hasn't returned sensor data yet.
**Fix:** Wait a few seconds for the data to populate. If it still doesn't, try restarting the `plasma-ksystemstats` service:
```bash
systemctl --user restart plasma-ksystemstats.service
```
## Icons Not Visible on Panel
**Cause:** Icons are rendered with `isMask: true` (monochrome). If your panel background is the same color as the text color, icons may be invisible.
!!! tip
Try switching to a different Plasma theme, or adjust the panel opacity. You can also switch to **Text** display mode if icons aren't working well with your theme.
## Settings Dialog Shows Warnings in Journal
!!! note "Harmless Warnings"
You may see `cfg_*Default` warnings in the journal. These are harmless Plasma 6 KCM warnings about default property injection and **do not affect functionality**.
## Widget Not Appearing After Install
**Fix:**
1. Restart plasmashell:
```bash
kquitapp6 plasmashell && kstart plasmashell &
```
2. If still missing, check the install path:
```bash
ls ~/.local/share/plasma/plasmoids/org.kde.plasma.kvitals/
```
!!! warning
If the directory doesn't exist, the install failed. Re-run `bash install.sh` from the project directory.
## Custom Font Not Applying
**Cause:** The font name might not match exactly.
**Fix:**
1. Check available fonts: `fc-list | grep -i "font-name"`
2. In settings, use the exact family name from the dropdown
3. Font size `0` means "use system default" — set a specific value if needed
!!! tip
The font dropdown is searchable — start typing the font name to filter the list. You can also type a custom font name directly.
@@ -0,0 +1,51 @@
#!/usr/bin/env bash
set -euo pipefail
REPO="yassine20011/kvitals"
PLASMOID_ID="org.kde.plasma.kvitals"
DEST_DIR="$HOME/.local/share/plasma/plasmoids/$PLASMOID_ID"
KPACKAGE_DIR="$HOME/.local/share/kpackage/generic/$PLASMOID_ID"
TMP_DIR=$(mktemp -d)
cleanup() { rm -rf "$TMP_DIR"; }
trap cleanup EXIT
echo "⚡ Installing KVitals..."
# Download and extract
# Clone repository
if ! command -v git &>/dev/null; then
echo "❌ Error: git is required"
exit 1
fi
echo " Cloning repository..."
git clone --depth 1 "https://github.com/$REPO.git" "$TMP_DIR/kvitals"
SRC_DIR="$TMP_DIR/kvitals"
# Remove old installation
for dir in "$DEST_DIR" "$KPACKAGE_DIR"; do
if [[ -d "$dir" ]] || [[ -L "$dir" ]]; then
echo " Removing previous installation from $dir..."
rm -rf "$dir"
fi
done
# Install
mkdir -p "$DEST_DIR"
cp "$SRC_DIR/metadata.json" "$DEST_DIR/"
cp -r "$SRC_DIR/contents" "$DEST_DIR/"
mkdir -p "$(dirname "$KPACKAGE_DIR")"
ln -s "$DEST_DIR" "$KPACKAGE_DIR"
echo ""
echo "✅ KVitals installed to: $DEST_DIR"
echo ""
echo "Next steps:"
echo " 1. Restart Plasma: plasmashell --replace &"
echo " 2. Right-click panel → Add Widgets → search 'KVitals'"
echo " 3. Drag it onto your panel"
echo ""
echo "To uninstall: rm -rf $DEST_DIR $KPACKAGE_DIR"
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
set -euo pipefail
PLASMOID_ID="org.kde.plasma.kvitals"
SRC_DIR="$(cd "$(dirname "$0")" && pwd)"
DEST_DIR="$HOME/.local/share/plasma/plasmoids/$PLASMOID_ID"
KPACKAGE_DIR="$HOME/.local/share/kpackage/generic/$PLASMOID_ID"
echo "Installing KVitals plasmoid..."
# Remove old installation if present
for dir in "$DEST_DIR" "$KPACKAGE_DIR"; do
if [[ -d "$dir" ]] || [[ -L "$dir" ]]; then
echo " Removing previous installation from $dir..."
rm -rf "$dir"
fi
done
# Install to primary location
mkdir -p "$DEST_DIR"
cp -r "$SRC_DIR/metadata.json" "$DEST_DIR/"
cp -r "$SRC_DIR/contents" "$DEST_DIR/"
mkdir -p "$(dirname "$KPACKAGE_DIR")"
ln -s "$DEST_DIR" "$KPACKAGE_DIR"
echo ""
echo "✅ Installed to: $DEST_DIR"
echo ""
echo "Next steps:"
echo " 1. Right-click on your KDE top panel"
echo " 2. Click 'Add Widgets...'"
echo " 3. Search for 'KVitals'"
echo " 4. Drag it onto your panel"
echo ""
echo "To uninstall: rm -rf $DEST_DIR $KPACKAGE_DIR"
@@ -0,0 +1,21 @@
{
"KPlugin": {
"Id": "org.kde.plasma.kvitals",
"Name": "KVitals",
"Description": "Live system vitals in the panel: CPU, RAM, Temp, GPU, Battery, Network, Disk, Fan",
"Icon": "utilities-system-monitor",
"Category": "System Information",
"Authors": [
{
"Name": "Yassine Amjad",
"Email": "yassine.amjad001@gmail.com"
}
],
"Website": "https://github.com/yassine20011/kvitals",
"BugReportUrl": "https://github.com/yassine20011/kvitals/issues",
"Version": "2.10.1",
"License": "GPL-3.0"
},
"KPackageStructure": "Plasma/Applet",
"X-Plasma-API-Minimum-Version": "6.0"
}
@@ -0,0 +1,82 @@
site_name: KVitals
site_description: A lightweight KDE Plasma 6 panel widget for live system vitals
site_url: https://kvitals.dev/
repo_url: https://github.com/yassine20011/kvitals
repo_name: yassine20011/kvitals
theme:
name: material
palette:
- scheme: slate
primary: deep purple
accent: pink
toggle:
icon: material/brightness-7
name: Switch to light mode
- scheme: default
primary: deep purple
accent: pink
toggle:
icon: material/brightness-4
name: Switch to dark mode
features:
- navigation.instant
- navigation.tabs
- navigation.sections
- navigation.top
- search.highlight
- search.suggest
- content.code.copy
icon:
repo: fontawesome/brands/github
markdown_extensions:
- admonition
- pymdownx.details
- pymdownx.superfences
- pymdownx.highlight:
anchor_linenums: true
- pymdownx.inlinehilite
- pymdownx.tabbed:
alternate_style: true
- tables
- attr_list
- md_in_html
- toc:
permalink: true
nav:
- Home: index.md
- Installation: installation.md
- Configuration: configuration.md
- Architecture: architecture.md
- Contributing: contributing.md
- Troubleshooting: troubleshooting.md
- Changelog: changelog.md
extra:
social:
- icon: fontawesome/brands/github
link: https://github.com/yassine20011
plugins:
- search
- llmstxt:
markdown_description: >
KVitals is a lightweight KDE Plasma 6 panel widget that displays live
system vitals including CPU usage, memory usage, CPU temperature,
GPU metrics, battery status, power draw, and network upload/download
speeds directly in your panel. It uses native KDE KSysGuard sensors and
is fully configurable through a settings UI.
full_output: llms-full.txt
sections:
Getting started:
- index.md: Overview and features of KVitals
- installation.md: How to install KVitals on KDE Plasma 6
- configuration.md: Widget settings and customization options
Technical reference:
- architecture.md: System architecture, data flow, and component design
- troubleshooting.md: Common issues and solutions
Community:
- contributing.md: How to contribute to the project
- changelog.md: Version history and release notes
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -e
PLASMOID_NAME="org.kde.plasma.kvitals"
VERSION=$(grep '"Version"' metadata.json | cut -d '"' -f 4)
FILENAME="${PLASMOID_NAME}-v${VERSION}.plasmoid"
echo "📦 Packaging $PLASMOID_NAME version $VERSION..."
# A .plasmoid file is just a ZIP archive containing the package files
# We exclude the git directory, install scripts, and screenshots
zip -r "$FILENAME" \
metadata.json \
contents \
LICENSE \
README.md \
-x "*.git*" \
-x "install.sh" \
-x "install-remote.sh" \
-x "package.sh" \
-x "*.DS_Store"
echo "✅ Created package: $FILENAME"
Binary file not shown.

After

Width:  |  Height:  |  Size: 974 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 KiB

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 3 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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,110 @@
# Window Title Reborn - for KDE Plasma 6.6+
<!-- <img src="screenshots/icon.png" alt="Window Title Reborn logo" width="88px" /> -->
A clean, customizable KDE Plasma panel widget that shows the active window's title and icon.
See it on the KDE Store: https://store.kde.org/p/2350022
## Features
- **Shows the active window's title and icon** with rich text and HTML substitution support
- **5 widget length modes**: Contents, Fixed, Maximum, Minimum, and Min + Max
- **Horizontal text alignment** and **hide when unavailable** options
- **Configurable appearance**: Font formatting, spacing, and icon choices
- **App name substitutions** via customizable regex matching
- **Behavior options**: Show on maximize only, scroll tasks, middle-click close, and double-click maximize/minimize
## Screenshots
![Window Title Reborn Preview](screenshots/preview.png)
![Config — Appearance](screenshots/config-appearance.png)
![Config — Behavior](screenshots/config-behavior.png)
![Config — Substitutions](screenshots/config-substitutions.png)
## Requirements
- KDE Plasma 6.6+
- KDE Frameworks 6
- Qt 6.x
## Installation
### Option 1: Install from Plasma widgets (recommended)
1. Open panel edit mode and choose **Add/Manage Widgets**.
2. Click **Get New…** → **Download New Plasma Widgets**.
3. Search for **"Window Title Reborn"**.
4. Click **Install** and add the widget to your panel.
### Option 2: Install from KDE Store download
1. Go to https://store.kde.org/p/2350022
2. Open the **Files** tab and download the *Window Title Reborn* `.plasmoid` file (if applicable).
3. In Plasma, open **Add/Manage Widgets** → **Get New…** → **Install Widget From Local File**.
4. Select the downloaded `.plasmoid` file and complete the installation.
### Option 3: Install from source with kpackagetool6
```bash
git clone https://github.com/ShrekBytes/window-title-reborn.git
cd window-title-reborn
kpackagetool6 -t Plasma/Applet -i .
```
Restart plasmashell:
```bash
systemctl --user restart plasma-plasmashell
```
or log out and log back in.
### Upgrading an existing kpackagetool6 installation
From inside the project directory:
```bash
kpackagetool6 -t Plasma/Applet -u .
```
Then restart plasmashell again:
```bash
systemctl --user restart plasma-plasmashell
```
or log out and log back in.
### Uninstalling existing kpackagetool6 installation
```bash
kpackagetool6 -t Plasma/Applet -r org.kde.plasma.windowtitlereborn
```
## Text Substitutions
| Substitution | Replaced With |
|:------------:|----------------------|
| `%a` | Application Name |
| `%w` | Window Title |
| `%q` | Activity Name |
| `<b>…</b>` | Bold text |
| `<i>…</i>` | Italic text |
| `<br>` / `<p>` | New line |
## Acknowledgements
- Based on [plasma6-window-title-applet](https://github.com/dhruv8sh/plasma6-window-title-applet) by **Dhruvesh Surolia**
- [applet-window-title](https://github.com/psifidotos/applet-window-title) by **Psifidotos**
## License
Licensed under the [**GNU General Public License v3.0**](LICENSE)

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