Add glassMxrph shell sources

Initial commit of the Quickshell desktop suite: bar, dock, launcher,
settings, Control Center, dashboard, OSD, lock screen, desktop widgets,
plugin host with the vendored Noctalia/Omarchy compatibility layer,
helpers, packaging, tests and phase documentation.

Includes the optimization work so far: usage widgets and dashboard
gauges no longer animate continuously, desktop widgets pause while
covered, system controls stop flickering on background polls, dock app
matching uses an indexed catalog, and workspace ghosts are created only
for occupied slots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mxandClaude Opus 5.5 committed 2026-10-07 22:36:17 +02:00
commit 99e64a7713
433 files changed
+57792

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

+63
View File
@@ -0,0 +1,63 @@
import QtQuick
import QtQuick.Shapes
import Quickshell
import Quickshell.Wayland
import "../components"
import "../core"
import "../services"
import "../theme"
// Quickshell selects the concrete PanelWindow implementation at runtime.
// qmllint disable uncreatable-type
PanelWindow {
// qmllint enable uncreatable-type
id: root
required property var modelData
screen: modelData
anchors { top: true; left: true; right: true }
readonly property int outerMargin: BarDrawers.margin
// The window reaches below the bar (input is masked to the bar) so the
// HyprGlass layer edge is not on the bar's bottom edge, where drawers join.
implicitHeight: BarDrawers.bottom + BarDrawers.overhang
mask: Region { item: panel }
color: Theme.transparent
exclusionMode: ExclusionMode.Ignore
WlrLayershell.namespace: "glassMxrph-bar"
Component.onCompleted: TrayService.registerBar(root)
Component.onDestruction: TrayService.unregisterBar(root)
GlassPanel {
id: panel
x: root.outerMargin; y: root.outerMargin
width: root.width - 2 * root.outerMargin
height: BarDrawers.height
radius: BarDrawers.radius
border.width: 0
ModuleRow { position: "left"; barScreen: root.screen; anchors.left: parent.left; anchors.leftMargin: 6; anchors.verticalCenter: parent.verticalCenter }
ModuleRow { position: "center"; barScreen: root.screen; anchors.centerIn: parent }
ModuleRow { position: "right"; barScreen: root.screen; anchors.right: parent.right; anchors.rightMargin: 6; anchors.verticalCenter: parent.verticalCenter }
}
// Outline with openings where drawers hang from the bar.
Shape {
id: outline
x: panel.x
y: panel.y
width: panel.width
height: panel.height
preferredRendererType: Shape.CurveRenderer
readonly property var gaps: BarDrawers.gapsFor(root.screen ? root.screen.name : "").map(g => [g.x0 - panel.x, g.x1 - panel.x]).sort((a, b) => b[0] - a[0])
ShapePath {
fillColor: "transparent"
strokeColor: Theme.border
strokeWidth: 1
PathSvg {
path: {
const W = panel.width - 1, H = panel.height - 0.5, r = Math.max(0, panel.radius - 0.5), o = 0.5;
let d = `M ${r + o} ${o} L ${W - r} ${o} A ${r} ${r} 0 0 1 ${W} ${r + o} L ${W} ${H - r} A ${r} ${r} 0 0 1 ${W - r} ${H}`;
// Bottom edge right to left, skipping each drawer's span.
for (const g of outline.gaps)
d += ` L ${Math.min(W - r, Math.max(r, g[1]))} ${H} M ${Math.max(r, Math.min(W - r, g[0]))} ${H}`;
return d + ` L ${r + o} ${H} A ${r} ${r} 0 0 1 ${o} ${H - r} L ${o} ${r + o} A ${r} ${r} 0 0 1 ${r + o} ${o}`;
}
}
}
}
}
+278
View File
@@ -0,0 +1,278 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Wayland
import Quickshell.Widgets
import "../components"
import "../core"
import "../theme"
// Bar hover popout. HyprGlass shapes glass from the layer box, so the surface is
// sized to the card and its geometry animates to morph between anchors.
// qmllint disable uncreatable-type
PanelWindow {
// qmllint enable uncreatable-type
id: root
readonly property Item anchorItem: PopoutState.anchor
readonly property var anchorWindow: anchorItem ? anchorItem.QsWindow.window : null
readonly property string kind: PopoutState.kind
// The hovered window's Wayland toplevel; falls back to the focused one.
readonly property var toplevel: PopoutState.payload || ToplevelManager.activeToplevel
// Anchors may name a wider placement item (the tray pill, the window list)
// so the drawer stays put while the pointer moves between its entries.
readonly property var anchorObject: anchorItem
readonly property Item placementItem: anchorObject ? (anchorObject.placement || anchorObject) : null
readonly property point anchorPoint: placementItem && anchorWindow ? placementItem.mapToItem(anchorWindow.contentItem, 0, 0) : Qt.point(0, 0)
readonly property real availableWidth: screen ? screen.width : 1280
readonly property real targetWidth: Math.ceil(root.kind === "window" ? windowCard.implicitWidth : tip.implicitWidth)
readonly property real targetHeight: Math.ceil(root.kind === "window" ? windowCard.implicitHeight : tip.implicitHeight)
readonly property real targetX: BarDrawers.clampX(anchorPoint.x + (placementItem ? placementItem.width / 2 : 0), targetWidth + 2 * BarDrawers.ear, availableWidth)
// Morph only while the drawer is out; a cold open grows in place.
readonly property bool morph: drawer.progress > 0.05 && Theme.duration > 0
property real animX: targetX
property real animW: targetWidth
property real animH: targetHeight
Behavior on animX {
enabled: root.morph
NumberAnimation {
duration: Theme.duration * 1.4
easing.type: Easing.BezierSpline
easing.bezierCurve: [0.2, 0, 0, 1, 1, 1]
}
}
Behavior on animW {
enabled: root.morph
NumberAnimation {
duration: Theme.duration * 1.4
easing.type: Easing.BezierSpline
easing.bezierCurve: [0.2, 0, 0, 1, 1, 1]
}
}
Behavior on animH {
enabled: root.morph
NumberAnimation {
duration: Theme.duration * 1.4
easing.type: Easing.BezierSpline
easing.bezierCurve: [0.2, 0, 0, 1, 1, 1]
}
}
screen: anchorWindow ? anchorWindow.screen : null
anchors {
top: true
left: true
}
// The layer starts at the screen top so the bar join is inside its box.
// Quickshell 0.3.1 qmllint cannot resolve the exported Margins value type.
// qmllint disable unqualified unresolved-type
margins.left: Math.round(animX)
// qmllint enable unqualified unresolved-type
implicitWidth: Math.max(40, Math.round(drawer.width))
implicitHeight: Math.max(30, Math.round(BarDrawers.bottom + animH))
mask: Region {
item: drawer.body
}
exclusionMode: ExclusionMode.Ignore
color: Theme.transparent
readonly property bool active: PopoutState.open || drawer.shown
visible: active
WlrLayershell.namespace: "glassMxrph-popout"
WlrLayershell.layer: WlrLayer.Overlay
WlrLayershell.keyboardFocus: WlrKeyboardFocus.None
Component.onCompleted: PopoutState.window = root
Component.onDestruction: if (PopoutState.window === root)
PopoutState.window = null
BarDrawer {
id: drawer
objectName: "barPopoutSurface"
y: BarDrawers.bottom
open: PopoutState.open
contentWidth: Math.round(root.animW)
contentHeight: Math.round(root.animH)
drawerId: "popout"
screenName: root.screen ? root.screen.name : ""
screenX: root.animX
onHoveredChanged: PopoutState.setPopoutHovered(hovered)
Text {
id: tip
anchors.centerIn: parent
padding: 10
leftPadding: 14
rightPadding: 14
text: PopoutState.text
color: Theme.text
font.pixelSize: 12
opacity: root.kind === "tooltip" ? 1 : 0
visible: opacity > 0
Behavior on opacity {
NumberAnimation {
duration: Theme.duration / 2
}
}
}
Column {
id: windowCard
objectName: "windowPreview"
anchors.horizontalCenter: parent.horizontalCenter
anchors.top: parent.top
padding: 12
spacing: 10
opacity: (root.kind === "window" ? 1 : 0) * contentFade
visible: opacity > 0
Behavior on opacity {
NumberAnimation {
duration: Theme.duration / 2
}
}
Connections {
target: root
function onToplevelChanged() {
if (root.kind === "window" && Theme.duration > 0)
swap.restart();
}
}
NumberAnimation {
id: swap
target: windowCard
property: "contentFade"
from: 0.35
to: 1
duration: Theme.duration
easing.type: Easing.OutCubic
}
property real contentFade: 1
readonly property var entry: root.toplevel && root.toplevel.appId ? DesktopEntries.heuristicLookup(root.toplevel.appId) : null
// Fixed size: hovering between windows swaps the content, not the pane.
readonly property real previewWidth: 480
Row {
spacing: 10
width: windowCard.previewWidth
IconImage {
id: appIcon
anchors.verticalCenter: parent.verticalCenter
implicitSize: 32
source: windowCard.entry && windowCard.entry.icon ? Quickshell.iconPath(windowCard.entry.icon, true) : ""
visible: source.toString() !== ""
// Synchronous on purpose: Quickshell's icon provider loads QPixmaps,
// which crash when built off the GUI thread (Quickshell 0.3.1).
}
Column {
anchors.verticalCenter: parent.verticalCenter
width: parent.width - (appIcon.visible ? appIcon.width + parent.spacing : 0) - actions.width - parent.spacing
Text {
width: parent.width
text: root.toplevel ? root.toplevel.title || "Untitled" : ""
color: Theme.text
font.pixelSize: 13
font.weight: Font.DemiBold
elide: Text.ElideRight
}
Text {
width: parent.width
text: windowCard.entry && windowCard.entry.name ? windowCard.entry.name + " · " + root.toplevel.appId : root.toplevel ? root.toplevel.appId : ""
color: Theme.textSecondary
font.pixelSize: 11
elide: Text.ElideRight
}
}
Row {
id: actions
anchors.verticalCenter: parent.verticalCenter
spacing: 4
WindowAction {
objectName: "previewMaximize"
glyph: root.toplevel && root.toplevel.maximized ? "󰘕" : "󰘖"
fallback: "□"
label: "Maximize"
onActivated: root.toplevel.maximized = !root.toplevel.maximized
}
WindowAction {
objectName: "previewFullscreen"
glyph: "󰊓"
fallback: "⤢"
label: "Fullscreen"
onActivated: root.toplevel.fullscreen = !root.toplevel.fullscreen
}
WindowAction {
objectName: "previewClose"
glyph: "󰅖"
fallback: "×"
label: "Close window"
danger: true
onActivated: {
PopoutState.close();
root.toplevel.close();
}
}
}
}
ClippingRectangle {
id: frame
width: windowCard.previewWidth
height: 270
radius: Math.max(8, Theme.radius * 0.55)
color: Theme.surfaceVariant
border.width: 1
border.color: Theme.hairline
ScreencopyView {
id: preview
// Letterboxed into the fixed frame, keeping the window's aspect.
readonly property real aspect: sourceSize.width > 0 && sourceSize.height > 0 ? sourceSize.width / sourceSize.height : 16 / 9
anchors.centerIn: parent
width: Math.min(parent.width, parent.height * aspect)
height: width / aspect
captureSource: root.kind === "window" && root.active && root.toplevel ? root.toplevel : null
live: root.active && root.kind === "window"
constraintSize: Qt.size(windowCard.previewWidth * 2, 540)
opacity: hasContent ? 1 : 0
Behavior on opacity {
NumberAnimation {
duration: Theme.duration
}
}
}
Text {
anchors.centerIn: parent
visible: !preview.hasContent
text: "Preview unavailable"
color: Theme.textSecondary
font.pixelSize: 12
}
}
}
}
component WindowAction: Rectangle {
id: action
property string glyph
property string fallback
property string label
property bool danger: false
signal activated
implicitWidth: 26
implicitHeight: 26
radius: 13
color: hover.hovered ? (danger ? Qt.alpha("#ff5f57", 0.85) : Theme.hover) : Theme.surfaceVariant
border.width: 1
border.color: Theme.hairline
Behavior on color {
ColorAnimation {
duration: Theme.duration / 2
}
}
Text {
anchors.centerIn: parent
text: Icons.available ? action.glyph : action.fallback
font.family: Icons.available ? Icons.family : ""
font.pixelSize: 13
color: Theme.text
}
HoverHandler {
id: hover
cursorShape: Qt.PointingHandCursor
}
TapHandler {
onTapped: if (root.toplevel)
action.activated()
}
Accessible.role: Accessible.Button
Accessible.name: label
}
}
+14
View File
@@ -0,0 +1,14 @@
import QtQuick
import "../core"
Loader {
required property string moduleId
property var barScreen
// The module's layout entry ({id, position, enabled, options}).
property var entry: ({})
source: ModuleRegistry.source(moduleId)
onLoaded: {
if (item && "metric" in item) item.metric = moduleId;
if (item && "barScreen" in item) item.barScreen = Qt.binding(() => barScreen);
if (item && "entry" in item) item.entry = Qt.binding(() => entry);
}
}
+13
View File
@@ -0,0 +1,13 @@
pragma ComponentBehavior: Bound
import QtQuick
import "../core"
Row {
id: root
required property string position
property var barScreen
spacing: 8
Repeater {
model: BarLayout.modulesFor(root.barScreen ? root.barScreen.name : "").filter(m => m.enabled && m.position === root.position)
ModuleLoader { required property var modelData; moduleId: modelData.id; barScreen: root.barScreen; entry: modelData }
}
}
@@ -0,0 +1,227 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell
import Quickshell.Hyprland
import Quickshell.Widgets
import "../../components"
import "../../core"
import "../../services"
import "../../theme"
// Programs on the focused workspace, left to right. Hover one for a live
// preview, click to focus it, middle-click to close it.
GlassPill {
id: root
objectName: "activeWindowPill"
property var barScreen
// Layout entry; options come from the cog in Settings → Bar.
property var entry: ({
id: "activeWindow"
})
readonly property string transition: ModuleRegistry.option(entry, "transition")
readonly property string labels: ModuleRegistry.option(entry, "labels")
readonly property string collapse: ModuleRegistry.option(entry, "collapse")
readonly property int labelWidth: ({
short: 90,
medium: 150,
long: 230
})[ModuleRegistry.option(entry, "labelWidth")] || 150
readonly property bool previews: ModuleRegistry.option(entry, "preview") !== "off"
readonly property int workspace: Hyprland.focusedWorkspace ? Hyprland.focusedWorkspace.id : 0
// Workspace switches replace the whole list: animate it as one, in the
// switch direction, instead of popping each pill in.
property int previousWorkspace: workspace
property real slideFrom: 0
property bool switching: false
onWorkspaceChanged: {
slideFrom = workspace > previousWorkspace ? 1 : -1;
previousWorkspace = workspace;
switching = true;
settle.restart();
if (transition === "fade" || transition === "slide")
switchAnim.restart();
}
Timer {
id: settle
interval: Theme.duration + 50
onTriggered: root.switching = false
}
ParallelAnimation {
id: switchAnim
NumberAnimation {
target: row
property: "opacity"
from: 0
to: 1
duration: Theme.duration * 1.2
easing.type: Easing.OutCubic
}
NumberAnimation {
target: slide
property: "x"
from: root.transition === "slide" ? 14 * root.slideFrom * Math.max(0.3, Theme.intensity) : 0
to: 0
duration: Theme.duration * 1.4
easing.type: Easing.OutCubic
}
}
// Left to right by Hyprland's last known position. Positions are not
// refreshed here: Hyprland.refreshToplevels() can crash Quickshell 0.3.1
// (HyprlandToplevel::updateFromObject), so windows without one go last.
// Read windows only after startup: bindings on Hyprland toplevels during
// Quickshell's initial window parse make its startup crash far likelier.
property bool armed: false
Timer {
interval: 1500
running: true
onTriggered: root.armed = true
}
readonly property var windows: !armed ? [] : HyprlandService.windows.filter(w => w.workspace === root.workspace && !!w.handle).sort((a, b) => root.order(a) - root.order(b))
function order(w) {
return w.width > 0 ? w.x * 10000 + w.y : 1e12 + HyprlandService.windows.indexOf(w);
}
// Crowded workspaces show the unfocused programs as icons only.
readonly property bool compact: labels === "icons" || labels === "focused" || (collapse !== "never" && windows.length > Number(collapse))
function pretty(id) {
const last = String(id || "").split(".").pop().replace(/[-_]+/g, " ");
return last ? last.charAt(0).toUpperCase() + last.slice(1) : "Window";
}
implicitHeight: ModuleRegistry.pillHeight
implicitWidth: (windows.length ? row.implicitWidth : empty.implicitWidth) + 8
Behavior on implicitWidth {
enabled: root.transition !== "none"
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
clip: true
Text {
id: empty
anchors.centerIn: parent
visible: root.windows.length === 0
leftPadding: 12
rightPadding: 12
text: "Desktop"
color: Theme.textSecondary
font.pixelSize: 13
}
Row {
id: row
anchors.centerIn: parent
spacing: 2
transform: Translate {
id: slide
}
// Single new windows pop in; a workspace switch uses switchAnim.
add: Transition {
enabled: root.transition !== "none" && (root.transition === "pop" || !root.switching)
NumberAnimation {
properties: "opacity,scale"
from: 0
to: 1
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
move: Transition {
enabled: root.transition !== "none"
NumberAnimation {
properties: "x"
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
Repeater {
model: ScriptModel {
values: root.windows
objectProp: "address"
}
Rectangle {
id: item
required property var modelData
required property int index
readonly property var toplevel: modelData.handle
// Previews hang under the whole list so the pane stays put.
readonly property Item placement: root
readonly property var entry: modelData.appId ? DesktopEntries.heuristicLookup(modelData.appId) : null
readonly property string name: entry && entry.name ? entry.name : root.pretty(modelData.appId || modelData.title)
readonly property bool focused: !!toplevel && toplevel.activated
readonly property bool previewing: PopoutState.open && PopoutState.anchor === item
readonly property bool labelled: root.labels !== "icons" && (!root.compact || focused)
objectName: "windowItem-" + index
implicitHeight: ModuleRegistry.pillHeight - 6
implicitWidth: content.implicitWidth + 16
radius: height / 2
color: previewing ? Qt.alpha(Theme.accent, 0.28) : focused ? Qt.alpha(Theme.text, 0.13) : hover.hovered ? Theme.hover : Theme.transparent
Behavior on color {
ColorAnimation {
duration: Theme.duration / 2
}
}
Behavior on implicitWidth {
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
Row {
id: content
anchors.centerIn: parent
spacing: 7
IconImage {
id: icon
anchors.verticalCenter: parent.verticalCenter
implicitSize: Math.round(ModuleRegistry.pillHeight * 0.5)
source: item.entry && item.entry.icon ? Quickshell.iconPath(item.entry.icon, true) : Quickshell.iconPath("application-x-executable", true)
// Synchronous on purpose: Quickshell's icon provider loads QPixmaps,
// which crash when built off the GUI thread (Quickshell 0.3.1).
}
Text {
anchors.verticalCenter: parent.verticalCenter
visible: item.labelled
width: Math.min(implicitWidth, root.labelWidth)
text: item.name
color: item.focused ? Theme.text : Theme.textSecondary
font.pixelSize: 13
font.weight: item.focused ? Font.DemiBold : Font.Normal
elide: Text.ElideRight
}
}
// Focused-window underline.
Rectangle {
anchors.bottom: parent.bottom
anchors.horizontalCenter: parent.horizontalCenter
width: item.focused ? 14 : 0
height: 2
radius: 1
color: Theme.accentVivid
Behavior on width {
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
}
HoverHandler {
id: hover
cursorShape: Qt.PointingHandCursor
onHoveredChanged: hovered ? PopoutState.hover(item, root.previews ? "window" : "tooltip", item.modelData.title || item.name, item.toplevel) : PopoutState.unhover(item)
}
TapHandler {
acceptedButtons: Qt.LeftButton
onTapped: {
PopoutState.close();
HyprlandService.focusWindow(item.modelData.address);
}
}
TapHandler {
acceptedButtons: Qt.MiddleButton
onTapped: HyprlandService.closeWindow(item.modelData.address)
}
Accessible.role: Accessible.Button
Accessible.name: item.name + (item.focused ? ", focused" : "")
}
}
}
}
+83
View File
@@ -0,0 +1,83 @@
pragma ComponentBehavior: Bound
import QtQuick
import "../../components"
import "../../core"
import "../../services"
import "../../theme"
// Cava audio visualizer in the bar. Click opens the dashboard's Media tab,
// right-click the Media settings. Cava only runs while something plays.
GlassPill {
id: root
objectName: "cavaPill"
readonly property var options: ConfigService.ready ? ConfigService.data.bar.cava : ({
bars: 12,
style: "bars",
hideWhenIdle: true
})
readonly property bool mirror: options.style === "mirror"
readonly property bool shown: !CavaService.failed && (MediaService.playing || !options.hideWhenIdle)
readonly property int barWidth: 3
readonly property int gap: 2
implicitHeight: ModuleRegistry.pillHeight
implicitWidth: shown ? options.bars * barWidth + (options.bars - 1) * gap + 22 : 0
visible: implicitWidth > 0.5
opacity: shown ? 1 : 0
clip: true
Behavior on implicitWidth {
NumberAnimation {
duration: Theme.duration * 1.4
easing.type: Easing.OutCubic
}
}
Behavior on opacity {
NumberAnimation {
duration: Theme.duration
}
}
Component.onCompleted: CavaService.widgetConsumers++
Component.onDestruction: CavaService.widgetConsumers--
// Cava emits 24 bands; each pill bar averages its share of them.
function level(index) {
const all = CavaService.bars, n = options.bars, from = Math.floor(index * all.length / n), to = Math.max(from + 1, Math.floor((index + 1) * all.length / n));
let sum = 0;
for (let i = from; i < to; i++)
sum += all[i] || 0;
return sum / (to - from);
}
Row {
anchors.centerIn: parent
height: parent.height - 12
spacing: root.gap
Repeater {
model: root.options.bars
Rectangle {
required property int index
readonly property real value: MediaService.playing ? Math.min(1, root.level(index)) : 0
width: root.barWidth
radius: width / 2
height: Math.max(width, parent.height * value)
y: root.mirror ? (parent.height - height) / 2 : parent.height - height
color: Theme.accentVivid
opacity: 0.55 + 0.45 * value
Behavior on height {
NumberAnimation {
duration: 80
}
}
}
}
}
TapHandler {
acceptedButtons: Qt.LeftButton
onTapped: ShellState.toggleDashboard("media")
}
TapHandler {
acceptedButtons: Qt.RightButton
onTapped: ShellState.openSettings("media")
}
HoverHandler {
cursorShape: Qt.PointingHandCursor
}
Accessible.name: "Audio visualizer"
}
+31
View File
@@ -0,0 +1,31 @@
import QtQuick
import Quickshell
import "../../components"
import "../../theme"
import "../../services"
import "../../core"
GlassPill {
id: root
readonly property var options: ConfigService.data.bar.clock
width: label.implicitWidth + 30
height: ModuleRegistry.pillHeight
SystemClock {
id: clock
precision: root.options.showSeconds ? SystemClock.Seconds : SystemClock.Minutes
}
Text {
id: label
anchors.centerIn: parent
text: Qt.formatDateTime(clock.date, (root.options.showDate ? "ddd, d MMM " : "") + (root.options.use24Hour ? "HH:mm" : "h:mm") + (root.options.showSeconds ? ":ss" : "") + (root.options.use24Hour ? "" : " AP"))
color: Theme.text
font.pixelSize: 13
}
// Clicking the clock opens the dashboard (Settings → Dashboard).
MouseArea {
anchors.fill: parent
enabled: ConfigService.ready && ConfigService.data.dashboard.enabled && ConfigService.data.dashboard.openFromClock
cursorShape: enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
onClicked: ShellState.toggleDashboard("")
}
}
+35
View File
@@ -0,0 +1,35 @@
import QtQuick
import "../../components"
import "../../services"
import "../../core"
GlassButton {
property string metric: "cpu"
implicitHeight: ModuleRegistry.pillHeight
Component.onCompleted: MetricsService.consumers++
Component.onDestruction: MetricsService.consumers--
text: {
switch (metric) {
case "cpu":
return "CPU " + MetricsService.value(MetricsService.cpu.percent, "%");
case "cpuTemperature":
return "CPU " + MetricsService.value(MetricsService.cpu.temperature, "°C");
case "gpu":
return "GPU " + MetricsService.value(MetricsService.gpu.percent, "%");
case "gpuTemperature":
return "GPU " + MetricsService.value(MetricsService.gpu.temperature, "°C");
case "ram":
return "RAM " + MetricsService.value(MetricsService.ram.percent, "%");
case "storage":
return "Disk " + MetricsService.value((MetricsService.snapshot.storage || [
{}
])[0]?.percent, "%");
default:
return "↓ " + MetricsService.bytes(MetricsService.network.download) + "/s ↑ " + MetricsService.bytes(MetricsService.network.upload) + "/s";
}
}
readonly property bool network: metric === "networkThroughput"
accented: network && ShellState.controlCenterOpen
onClicked: network ? ShellState.toggleControlCenter() : ShellState.openSettings("metrics")
Accessible.name: text
}
@@ -0,0 +1,36 @@
import QtQuick
import QtQuick.Layouts
import "../../components"
import "../../services"
import "../../core"
import "../../theme"
GlassPill {
implicitWidth: content.implicitWidth + 12
implicitHeight: ModuleRegistry.pillHeight
RowLayout {
id: content
anchors.centerIn: parent
spacing: 3
GlassButton {
implicitWidth: ModuleRegistry.pillHeight - 4
implicitHeight: ModuleRegistry.pillHeight - 4
text: MediaService.playing ? "Ⅱ" : "▶"
enabled: !!MediaService.player && MediaService.player.canTogglePlaying && MediaService.player.canControl
onClicked: MediaService.toggle()
Accessible.name: "Toggle playback"
}
GlassButton {
implicitWidth: 160
implicitHeight: ModuleRegistry.pillHeight - 4
contentItem: Text {
text: MediaService.title
color: Theme.text
elide: Text.ElideRight
verticalAlignment: Text.AlignVCenter
}
onClicked: ShellState.openSettings("media")
Accessible.name: "Media settings"
}
}
}
+120
View File
@@ -0,0 +1,120 @@
import QtQuick
import Quickshell
import "../../components"
import "../../core"
import "../../services"
import "../../theme"
import "../../compat/omarchy/Ui" as OmarchyUi
// Hosts an installed plugin's bar widget inside glassMxrph's own pill, so it
// sits in the bar like any built-in module (size, glass, spacing, per-screen
// layouts, cog options). The widget gets a PluginBarApi whose colors, font and
// size come from the glassMxrph theme; tooltips use the shared hover popout.
GlassPill {
id: root
property var barScreen
property var entry: ({})
readonly property string pluginId: entry.id ? String(entry.id).slice("plugin:".length) : ""
readonly property bool noctalia: PluginService.ecosystem(pluginId) === "noctalia"
readonly property string source: PluginService.entryUrl(pluginId, "bar-widget")
readonly property var settings: PluginService.widgetSettings(pluginId, entry.options)
readonly property Item widget: loader.item as Item
// Not widget.visible: that reads false while this pill is still hidden.
// Omarchy widgets report emptiness through hasVisualContent instead.
readonly property var widgetObject: loader.item
readonly property bool shown: !!widget && (noctalia || widgetObject.hasVisualContent !== false) && widget.implicitWidth > 0
implicitHeight: ModuleRegistry.pillHeight
implicitWidth: shown ? Math.ceil(widget.implicitWidth) + 8 : 0
visible: implicitWidth > 0
Behavior on implicitWidth {
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
OmarchyUi.PluginBarApi {
id: api
pluginId: root.pluginId
moduleName: root.pluginId
shell: root.pluginId ? PluginService.shellFor(root.pluginId) : null
foreground: Theme.text
barForeground: Theme.text
background: Qt.alpha(Theme.surface, Theme.glassOpacity)
urgent: Theme.urgent
fontFamily: fontProbe.font.family
position: "top"
vertical: false
barSize: ModuleRegistry.pillHeight
transparent: true
foregroundAnimationEnabled: Theme.duration > 0
activePopout: PluginService.activePopout
layoutConfig: root.settings
// Like Omarchy's bar: only a hovered widget shows its tooltip (plugins
// also call this whenever their data refreshes).
_showTooltip: (target, text) => {
if (text && target && target.tooltipHovered !== false)
PopoutState.hover(target, "tooltip", text);
}
_hideTooltip: target => PopoutState.unhover(target)
_requestPopout: owner => PluginService.requestPopout(owner)
_releasePopout: owner => PluginService.releasePopout(owner)
_switchPanelFrom: (owner, direction) => false
_targetBelongsToWindow: (target, window) => !!target && !!target.QsWindow && target.QsWindow.window === window
_moduleWidgets: id => PluginService.widgets[id] || []
_run: command => Quickshell.execDetached(Array.isArray(command) ? command : ["sh", "-c", String(command)])
}
// The default UI font, which glassMxrph's own text uses.
Text {
id: fontProbe
visible: false
}
// Noctalia widgets get their pluginApi at creation, as in Noctalia, so their
// first bindings already see it.
onSourceChanged: load()
Component.onCompleted: load()
function load() {
if (!source) {
loader.source = "";
return;
}
if (!noctalia) {
loader.source = source;
return;
}
loader.setSource(source, {
pluginApi: PluginService.noctaliaApi(pluginId),
screen: barScreen,
widgetId: pluginId,
section: entry.position || "right",
sectionWidgetIndex: 0,
sectionWidgetsCount: 1
});
}
Loader {
id: loader
anchors.centerIn: parent
height: parent.height
onLoaded: {
if (root.noctalia) {
// Noctalia v4 bar widget contract.
const napi = PluginService.noctaliaApi(root.pluginId);
if ("screen" in item)
item.screen = Qt.binding(() => root.barScreen);
if (napi)
napi.barWidget = item;
} else {
if ("bar" in item)
item.bar = api;
if ("moduleName" in item)
item.moduleName = root.pluginId;
if ("settings" in item)
item.settings = Qt.binding(() => root.settings);
}
PluginService.registerWidget(root.pluginId, item);
}
}
Component.onDestruction: if (loader.item)
PluginService.unregisterWidget(pluginId, loader.item)
}
+12
View File
@@ -0,0 +1,12 @@
import QtQuick
import "../../components"
import "../../core"
import "../../theme"
GlassIconButton {
text: "⚙"
implicitWidth: ModuleRegistry.pillHeight
implicitHeight: ModuleRegistry.pillHeight
onClicked: ShellState.toggleSettings()
rotation: ShellState.settingsOpen ? 60 * Theme.intensity : 0
Behavior on rotation { NumberAnimation { duration: Theme.duration; easing.type: Easing.OutCubic } }
}
+18
View File
@@ -0,0 +1,18 @@
import QtQuick
import "../../components"
import "../../core"
import "../../services"
GlassButton {
id: root
property var barScreen
Component.onCompleted: ShellState.systemPills = ShellState.systemPills.concat([root])
Component.onDestruction: ShellState.systemPills = ShellState.systemPills.filter(p => p !== root)
objectName: "systemPill"
readonly property bool volumeInBar: BarLayout.modulesFor(barScreen ? barScreen.name : "").some(m => m.id === "volume" && m.enabled)
implicitHeight: ModuleRegistry.pillHeight
text: volumeInBar ? "☷" : "☷ " + (AudioService.sink && AudioService.sink.audio ? (AudioService.sink.audio.muted ? "Muted" : Math.round(AudioService.sink.audio.volume * 100) + "%") : "System")
accented: ShellState.controlCenterOpen
onClicked: ShellState.toggleControlCenter()
Accessible.name: "Control Center"
}
+25
View File
@@ -0,0 +1,25 @@
pragma ComponentBehavior: Bound
import QtQuick
import "../../components"
import "../../services"
import "../../menus"
import "../../core"
Item {
id: root
property var barScreen
readonly property bool shown: TrayService.options.enabled && TrayService.items.length > 0
implicitWidth: shown ? row.implicitWidth + 12 : 0
implicitHeight: shown ? ModuleRegistry.pillHeight : 0
visible: shown
// The whole pill is hover space: gaps between icons keep a hover menu open.
readonly property bool hovered: hover.hovered
HoverHandler { id: hover }
GlassPill { anchors.fill: parent; visible: TrayService.options.background === "pill" }
Row {
id: row; anchors.centerIn: parent; spacing: TrayService.options.spacing
Repeater {
model: root.shown ? TrayService.items : []
TrayIcon { required property var modelData; trayItem: modelData; barScreen: root.barScreen; group: root }
}
}
}
+70
View File
@@ -0,0 +1,70 @@
import QtQuick
import "../../components"
import "../../core"
import "../../services"
import "../../theme"
// Output volume: scroll to adjust, click to mute, right-click for audio settings.
GlassButton {
id: root
objectName: "volumePill"
readonly property var audio: AudioService.sink ? AudioService.sink.audio : null
readonly property bool muted: !!audio && audio.muted
readonly property real level: audio ? audio.volume : 0
readonly property int step: ConfigService.ready ? ConfigService.data.osd.step : 5
readonly property string glyph: !audio ? "󰖁" : muted || level === 0 ? "󰖁" : level < 0.34 ? "󰕿" : level < 0.67 ? "󰖀" : "󰕾"
enabled: !!audio
accented: false
implicitHeight: ModuleRegistry.pillHeight
// Width comes from the texts directly; the value reserves room for "100%"
// so the pill does not jitter while scrolling.
TextMetrics {
id: widest
font: value.font
text: "100%"
}
contentItem: Item {
implicitWidth: icon.implicitWidth + 6 + valueWidth
implicitHeight: Math.max(icon.implicitHeight, value.implicitHeight)
readonly property real valueWidth: Math.max(widest.advanceWidth, value.implicitWidth)
Text {
id: icon
anchors.left: parent.left
anchors.verticalCenter: parent.verticalCenter
text: Icons.available ? root.glyph : (root.muted ? "×" : "♪")
font.family: Icons.available ? Icons.family : ""
font.pixelSize: 15
color: root.muted ? Theme.urgent : Theme.text
}
Text {
id: value
anchors.left: icon.right
anchors.leftMargin: 6
anchors.verticalCenter: parent.verticalCenter
text: !root.audio ? "—" : root.muted ? "Off" : Math.round(root.level * 100) + "%"
font.pixelSize: 13
font.features: {
"tnum": 1
}
color: root.muted ? Theme.urgent : Theme.text
}
}
implicitWidth: icon.implicitWidth + 6 + Math.max(widest.advanceWidth, value.implicitWidth) + 28
onClicked: AudioService.mute(false)
WheelHandler {
acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
onWheel: event => {
if (!root.audio)
return;
const delta = (event.angleDelta.y || -event.angleDelta.x) > 0 ? 1 : -1;
if (delta > 0)
root.audio.muted = false;
AudioService.volume(false, root.level + delta * root.step / 100);
}
}
TapHandler {
acceptedButtons: Qt.RightButton
onTapped: ShellState.openSettings("audio")
}
Accessible.name: "Volume " + (muted ? "muted" : Math.round(level * 100) + "%")
}
+281
View File
@@ -0,0 +1,281 @@
pragma ComponentBehavior: Bound
import QtQuick
import Quickshell.Hyprland
import "../../components"
import "../../theme"
import "../../services"
import "../../core"
// Workspace switcher. Styles (bar.workspaces.style): numbers, roman numerals,
// dots (filled = occupied, ring = empty) and pacman (after Serpantinum: pellets
// for empty workspaces, ghosts for occupied ones, Pac-Man on the active one).
GlassPill {
id: root
property var barScreen
// Every bar follows the globally focused workspace, whichever monitor it is on.
readonly property int activeId: Hyprland.focusedWorkspace ? Hyprland.focusedWorkspace.id : 0
// Workspaces shown on other monitors get a faint outline.
readonly property var visibleIds: Hyprland.monitors.values.map(m => m.activeWorkspace ? m.activeWorkspace.id : 0).filter(id => id > 0 && id !== activeId)
readonly property int count: ConfigService.data.bar.workspaces.count
readonly property string style: ConfigService.data.bar.workspaces.style || "numbers"
readonly property bool pacman: style === "pacman"
readonly property real pacmanScale: 0.95
readonly property int slotWidth: style === "roman" ? 38 : style === "dots" ? 22 : style === "pacman" ? 24 : 32
readonly property int slotHeight: height - 6
readonly property int activeIndex: activeId >= 1 && activeId <= count ? activeId - 1 : -1
width: count * slotWidth + 8
height: ModuleRegistry.pillHeight
function roman(value) {
const numerals = [[10, "X"], [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]];
let result = "";
for (const [n, symbol] of numerals)
while (value >= n) {
result += symbol;
value -= n;
}
return result;
}
Repeater {
model: root.pacman ? [] : root.visibleIds.filter(id => id <= root.count)
Rectangle {
required property int modelData
x: 4 + (modelData - 1) * root.slotWidth
y: 3
width: root.slotWidth
height: root.slotHeight
radius: height / 2
color: Qt.alpha(Theme.accent, 0.18)
border.width: 1
border.color: Qt.alpha(Theme.accent, 0.6)
}
}
// Sliding accent highlight (all styles except pacman, whose actor marks the active slot).
Rectangle {
visible: !root.pacman && root.activeIndex >= 0
x: 4 + Math.max(0, root.activeIndex) * root.slotWidth
y: 3
width: root.slotWidth
height: root.slotHeight
radius: height / 2
color: Theme.accent
Behavior on x {
NumberAnimation {
duration: Theme.duration
easing.type: Easing.OutCubic
}
}
}
Row {
x: 4
y: 3
Repeater {
model: root.count
Item {
id: slot
required property int index
readonly property var workspace: Hyprland.workspaces.values.find(w => w.id === index + 1) || null
readonly property bool active: root.activeIndex === index
readonly property bool occupied: !!workspace && workspace.toplevels.values.length > 0
readonly property bool urgent: !!workspace && workspace.urgent
width: root.slotWidth
height: root.slotHeight
// Numbers and roman numerals
Text {
visible: root.style === "numbers" || root.style === "roman"
anchors.centerIn: parent
anchors.verticalCenterOffset: slot.occupied && !slot.active ? -2 : 0
text: root.style === "roman" ? root.roman(slot.index + 1) : slot.index + 1
font.pixelSize: root.style === "roman" ? 11 : 12
font.weight: root.style === "roman" ? Font.DemiBold : Font.Normal
font.letterSpacing: root.style === "roman" ? 0.5 : 0
color: slot.urgent ? Theme.urgent : slot.active ? Theme.accentText : Theme.text
opacity: slot.active || slot.occupied ? 1 : 0.5
}
Rectangle {
visible: (root.style === "numbers" || root.style === "roman") && slot.occupied && !slot.active
anchors.bottom: parent.bottom
anchors.bottomMargin: 1
anchors.horizontalCenter: parent.horizontalCenter
width: 3
height: 3
radius: 2
color: Theme.text
}
// Dots: filled when occupied, ring when empty
Rectangle {
visible: root.style === "dots"
anchors.centerIn: parent
width: slot.active ? 9 : 8
height: width
radius: width / 2
color: slot.active ? Theme.accentText : slot.urgent ? Theme.urgent : slot.occupied ? Theme.text : Theme.transparent
border.width: slot.occupied || slot.active ? 0 : 1.5
border.color: slot.urgent ? Theme.urgent : Qt.alpha(Theme.text, 0.6)
Behavior on width {
NumberAnimation {
duration: Theme.duration / 2
}
}
}
// Pacman: pellets (every second one a power pellet) and ghosts
Rectangle {
visible: root.pacman && !slot.occupied
anchors.centerIn: parent
width: Math.round((slot.index % 2 === 1 ? 9 : 6) * root.pacmanScale)
height: width
radius: width / 2
color: slot.urgent ? Theme.urgent : Qt.alpha(Theme.text, 0.75)
scale: slot.active ? 0 : pelletArea.containsMouse ? 1.25 : 1
Behavior on scale {
NumberAnimation {
duration: 180
easing.type: Easing.OutBack
}
}
}
// Created only for occupied slots in pacman style: each Canvas holds
// its own 2D context and texture.
Loader {
active: root.pacman && slot.occupied
anchors.centerIn: parent
sourceComponent: Canvas {
id: ghost
width: Math.round(16 * root.pacmanScale)
height: Math.round(17 * root.pacmanScale)
scale: slot.active ? 0 : pelletArea.containsMouse ? 1.15 : 1
Behavior on scale {
NumberAnimation {
duration: 220
easing.type: Easing.OutBack
}
}
// Pupils look towards Pac-Man.
readonly property real look: root.activeIndex > slot.index ? 1 : root.activeIndex < slot.index && root.activeIndex >= 0 ? -1 : 0
readonly property color body: slot.urgent ? Theme.urgent : Theme.textSecondary
onLookChanged: requestPaint()
onBodyChanged: requestPaint()
onVisibleChanged: if (visible)
requestPaint()
Component.onCompleted: requestPaint()
onPaint: {
const ctx = getContext("2d");
ctx.reset();
const w = width - 2, h = height - 2, r = w / 2, x0 = 1, y0 = 1;
const bottom = y0 + h, wave = h * 0.14;
ctx.beginPath();
ctx.moveTo(x0, y0 + r);
ctx.arc(x0 + r, y0 + r, r, Math.PI, 0, false);
ctx.lineTo(x0 + w, bottom);
ctx.quadraticCurveTo(x0 + w * 5 / 6, bottom - wave, x0 + w * 2 / 3, bottom);
ctx.quadraticCurveTo(x0 + w / 2, bottom - wave, x0 + w / 3, bottom);
ctx.quadraticCurveTo(x0 + w / 6, bottom - wave, x0, bottom);
ctx.closePath();
ctx.fillStyle = body;
ctx.fill();
const eye = w * 0.17, ex1 = x0 + w * 0.32, ex2 = x0 + w * 0.68, ey = y0 + r * 0.95;
ctx.beginPath();
ctx.arc(ex1, ey, eye, 0, 2 * Math.PI);
ctx.arc(ex2, ey, eye, 0, 2 * Math.PI);
ctx.fillStyle = "#ffffff";
ctx.fill();
const shift = look * eye * 0.35;
ctx.beginPath();
ctx.arc(ex1 + shift, ey, eye * 0.55, 0, 2 * Math.PI);
ctx.arc(ex2 + shift, ey, eye * 0.55, 0, 2 * Math.PI);
ctx.fillStyle = "#11111b";
ctx.fill();
}
}
}
MouseArea {
id: pelletArea
anchors.fill: parent
hoverEnabled: root.pacman
cursorShape: Qt.PointingHandCursor
onClicked: Hyprland.dispatch("workspace " + (slot.index + 1))
}
}
}
}
// Pac-Man glides to the active workspace, chomps, and faces its direction of travel.
Canvas {
id: pac
property int previous: root.activeIndex
property bool facingLeft: false
property real mouth: 0.18
visible: root.pacman && root.activeIndex >= 0
width: Math.round(20 * root.pacmanScale)
height: width
y: 3 + (root.slotHeight - height) / 2
x: 4 + Math.max(0, root.activeIndex) * root.slotWidth + (root.slotWidth - width) / 2
Behavior on x {
NumberAnimation {
duration: Math.max(Theme.duration, 1) * 1.4
easing.type: Easing.OutQuint
}
}
transform: Scale {
origin.x: pac.width / 2
xScale: pac.facingLeft ? -1 : 1
}
Connections {
target: root
function onActiveIndexChanged() {
if (root.activeIndex < pac.previous)
pac.facingLeft = true;
else if (root.activeIndex > pac.previous)
pac.facingLeft = false;
pac.previous = root.activeIndex;
if (Theme.intensity > 0)
chomp.restart();
}
}
SequentialAnimation {
id: chomp
loops: 3
NumberAnimation {
target: pac
property: "mouth"
to: 0.02
duration: 80
easing.type: Easing.InOutQuad
}
NumberAnimation {
target: pac
property: "mouth"
to: 0.18
duration: 80
easing.type: Easing.InOutQuad
}
}
readonly property color body: Theme.accentVivid
onMouthChanged: requestPaint()
onBodyChanged: requestPaint()
onVisibleChanged: if (visible)
requestPaint()
Component.onCompleted: requestPaint()
onPaint: {
const ctx = getContext("2d");
ctx.reset();
const r = width / 2, m = mouth * Math.PI;
ctx.beginPath();
ctx.moveTo(r, r);
ctx.arc(r, r, r - 0.5, m, 2 * Math.PI - m, false);
ctx.closePath();
ctx.fillStyle = body;
ctx.fill();
ctx.beginPath();
ctx.arc(r + r * 0.12, r - r * 0.46, Math.max(1.5, r * 0.14), 0, 2 * Math.PI);
ctx.fillStyle = "#11111b";
ctx.fill();
}
}
}
@@ -0,0 +1,16 @@
Tabler Licenses - Detailed Usage Rights and Guidelines
This is a legal agreement between you, the Purchaser, and Tabler. Purchasing or downloading of any Tabler product (Tabler Admin Template, Tabler Icons, Tabler Emails, Tabler Illustrations), constitutes your acceptance of the terms of this license, Tabler terms of service and Tabler private policy.
Tabler Admin Template and Tabler Icons License*
Tabler Admin Template and Tabler Icons are available under MIT License.
Copyright (c) 2018-2025 Tabler
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
See more at Tabler Admin Template MIT License See more at Tabler Icons MIT License
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,120 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../theme" as G
// glassMxrph replacement for Noctalia's Color singleton. Same Material-style
// roles and helpers, but every role comes from the glassMxrph theme (glass
// tint, accent, text), so Noctalia plugins render in the glassMxrph look.
// Noctalia's colors.json is not read.
Singleton {
id: root
property bool reloadColors: false
property bool skipTransition: false
property bool isTransitioning: false
function scheduleExternalColorReload() {
}
function startTransition() {
}
property color mPrimary: G.Theme.accent
property color mOnPrimary: G.Theme.accentText
property color mSecondary: G.Theme.accentVivid
property color mOnSecondary: G.Theme.accentText
property color mTertiary: G.Theme.accentVivid
property color mOnTertiary: G.Theme.accentText
property color mError: G.Theme.urgent
property color mOnError: "#000000"
// Panels and cards: the shell's glass tint; widgets sit on surfaceVariant.
property color mSurface: G.Theme.surface
property color mOnSurface: G.Theme.text
property color mSurfaceVariant: G.Theme.surfaceVariant
property color mOnSurfaceVariant: G.Theme.textSecondary
property color mOutline: G.Theme.border
property color mShadow: "#000000"
// Noctalia hovers with a solid accent; glassMxrph uses a soft highlight.
property color mHover: Qt.alpha(G.Theme.text, 0.12)
property color mOnHover: G.Theme.text
function resolveColorKey(key) {
switch (key) {
case "primary":
return root.mPrimary;
case "secondary":
return root.mSecondary;
case "tertiary":
return root.mTertiary;
case "error":
return root.mError;
default:
return root.mOnSurface;
}
}
function resolveOnColorKey(key) {
switch (key) {
case "primary":
return root.mOnPrimary;
case "secondary":
return root.mOnSecondary;
case "tertiary":
return root.mOnTertiary;
case "error":
return root.mOnError;
default:
return root.mSurface;
}
}
function resolveColorKeyOptional(key) {
switch (key) {
case "primary":
return root.mPrimary;
case "secondary":
return root.mSecondary;
case "tertiary":
return root.mTertiary;
case "error":
return root.mError;
default:
return "transparent";
}
}
// glassMxrph is dark-only; panels follow the shell's glass opacity.
function adaptiveOpacity(baseOpacity) {
return baseOpacity;
}
function smartAlpha(baseColor, minAlpha = 0.4) {
return Qt.alpha(baseColor, Math.max(minAlpha, Math.min(baseColor.a, G.Theme.glassOpacity)));
}
readonly property var colorKeyModel: [
{
"key": "none",
"name": "None"
},
{
"key": "primary",
"name": "Primary"
},
{
"key": "secondary",
"name": "Secondary"
},
{
"key": "tertiary",
"name": "Tertiary"
},
{
"key": "error",
"name": "Error"
}
]
}
@@ -0,0 +1,883 @@
pragma Singleton
import QtQuick
import Quickshell
Singleton {
id: root
// Public API
function go(search, targets, options) {
return _go(search, targets, options);
}
function single(search, target) {
return _single(search, target);
}
function highlight(result, open, close) {
if (open === undefined)
open = '<b>';
if (close === undefined)
close = '</b>';
return _highlight(result, open, close);
}
function prepare(target) {
return _prepare(target);
}
function cleanup() {
return _cleanup();
}
// Internal implementation
readonly property var _INFINITY: Infinity
readonly property var _NEGATIVE_INFINITY: -Infinity
readonly property var _NULL: null
property var _noResults: {
let r = [];
r.total = 0;
return r;
}
property var _noTarget: _prepare('')
property var _preparedCache: new Map()
property var _preparedSearchCache: new Map()
property var _matchesSimple: []
property var _matchesStrict: []
property var _nextBeginningIndexesChanges: []
property var _keysSpacesBestScores: []
property var _allowPartialMatchScores: []
property var _tmpTargets: []
property var _tmpResults: []
property var _q: _fastpriorityqueue()
function _fastpriorityqueue() {
var e = [], o = 0, a = {};
var v = function (r) {
for (var a = 0, vc = e[a], c = 1; c < o; ) {
var s = c + 1;
a = c;
if (s < o && e[s]._score < e[c]._score)
a = s;
e[a - 1 >> 1] = e[a];
c = 1 + (a << 1);
}
for (var f = a - 1 >> 1; a > 0 && vc._score < e[f]._score; f = (a = f) - 1 >> 1)
e[a] = e[f];
e[a] = vc;
};
a.add = function (r) {
var ac = o;
e[o++] = r;
for (var vc = ac - 1 >> 1; ac > 0 && r._score < e[vc]._score; vc = (ac = vc) - 1 >> 1)
e[ac] = e[vc];
e[ac] = r;
};
a.poll = function () {
if (o !== 0) {
var ac = e[0];
e[0] = e[--o];
v();
return ac;
}
};
a.peek = function () {
if (o !== 0)
return e[0];
};
a.replaceTop = function (r) {
e[0] = r;
v();
};
return a;
}
function _createResult() {
return {
target: '',
obj: _NULL,
_score: _NEGATIVE_INFINITY,
_indexes: [],
_targetLower: '',
_targetLowerCodes: _NULL,
_nextBeginningIndexes: _NULL,
_bitflags: 0,
get indexes() {
return this._indexes.slice(0, this._indexes.len).sort((a, b) => a - b);
},
set indexes(idx) {
this._indexes = idx;
},
highlight: function (open, close) {
return root._highlight(this, open, close);
},
get score() {
return root._normalizeScore(this._score);
},
set score(s) {
this._score = root._denormalizeScore(s);
}
};
}
function _createKeysResult(len) {
var arr = new Array(len);
arr._score = _NEGATIVE_INFINITY;
arr.obj = _NULL;
Object.defineProperty(arr, 'score', {
get: function () {
return root._normalizeScore(this._score);
},
set: function (s) {
this._score = root._denormalizeScore(s);
}
});
return arr;
}
function _new_result(target, options) {
var result = _createResult();
result.target = target;
result.obj = options.obj ?? _NULL;
result._score = options._score ?? _NEGATIVE_INFINITY;
result._indexes = options._indexes ?? [];
result._targetLower = options._targetLower ?? '';
result._targetLowerCodes = options._targetLowerCodes ?? _NULL;
result._nextBeginningIndexes = options._nextBeginningIndexes ?? _NULL;
result._bitflags = options._bitflags ?? 0;
return result;
}
function _normalizeScore(score) {
if (score === _NEGATIVE_INFINITY)
return 0;
if (score > 1)
return score;
return Math.E ** (((-score + 1) ** 0.04307 - 1) * -2);
}
function _denormalizeScore(normalizedScore) {
if (normalizedScore === 0)
return _NEGATIVE_INFINITY;
if (normalizedScore > 1)
return normalizedScore;
return 1 - Math.pow((Math.log(normalizedScore) / -2 + 1), 1 / 0.04307);
}
function _remove_accents(str) {
return str.replace(/\p{Script=Latin}+/gu, match => match.normalize('NFD')).replace(/[\u0300-\u036f]/g, '');
}
function _prepareLowerInfo(str) {
str = _remove_accents(str);
var strLen = str.length;
var lower = str.toLowerCase();
var lowerCodes = [];
var bitflags = 0;
var containsSpace = false;
for (var i = 0; i < strLen; ++i) {
var lowerCode = lowerCodes[i] = lower.charCodeAt(i);
if (lowerCode === 32) {
containsSpace = true;
continue;
}
var bit = lowerCode >= 97 && lowerCode <= 122 ? lowerCode - 97 : lowerCode >= 48 && lowerCode <= 57 ? 26 : lowerCode <= 127 ? 30 : 31;
bitflags |= 1 << bit;
}
return {
lowerCodes: lowerCodes,
bitflags: bitflags,
containsSpace: containsSpace,
_lower: lower
};
}
function _prepareBeginningIndexes(target) {
var targetLen = target.length;
var beginningIndexes = [];
var beginningIndexesLen = 0;
var wasUpper = false;
var wasAlphanum = false;
for (var i = 0; i < targetLen; ++i) {
var targetCode = target.charCodeAt(i);
var isUpper = targetCode >= 65 && targetCode <= 90;
var isAlphanum = isUpper || targetCode >= 97 && targetCode <= 122 || targetCode >= 48 && targetCode <= 57;
var isBeginning = isUpper && !wasUpper || !wasAlphanum || !isAlphanum;
wasUpper = isUpper;
wasAlphanum = isAlphanum;
if (isBeginning)
beginningIndexes[beginningIndexesLen++] = i;
}
return beginningIndexes;
}
function _prepareNextBeginningIndexes(target) {
target = _remove_accents(target);
var targetLen = target.length;
var beginningIndexes = _prepareBeginningIndexes(target);
var nextBeginningIndexes = [];
var lastIsBeginning = beginningIndexes[0];
var lastIsBeginningI = 0;
for (var i = 0; i < targetLen; ++i) {
if (lastIsBeginning > i) {
nextBeginningIndexes[i] = lastIsBeginning;
} else {
lastIsBeginning = beginningIndexes[++lastIsBeginningI];
nextBeginningIndexes[i] = lastIsBeginning === undefined ? targetLen : lastIsBeginning;
}
}
return nextBeginningIndexes;
}
function _prepareSearch(search) {
if (typeof search === 'number')
search = '' + search;
else if (typeof search !== 'string')
search = '';
search = search.trim();
var info = _prepareLowerInfo(search);
var spaceSearches = [];
if (info.containsSpace) {
var searches = search.split(/\s+/);
searches = [...new Set(searches)];
for (var i = 0; i < searches.length; i++) {
if (searches[i] === '')
continue;
var _info = _prepareLowerInfo(searches[i]);
spaceSearches.push({
lowerCodes: _info.lowerCodes,
_lower: searches[i].toLowerCase(),
containsSpace: false
});
}
}
return {
lowerCodes: info.lowerCodes,
_lower: info._lower,
containsSpace: info.containsSpace,
bitflags: info.bitflags,
spaceSearches: spaceSearches
};
}
function _prepare(target) {
if (typeof target === 'number')
target = '' + target;
else if (typeof target !== 'string')
target = '';
var info = _prepareLowerInfo(target);
return _new_result(target, {
_targetLower: info._lower,
_targetLowerCodes: info.lowerCodes,
_bitflags: info.bitflags
});
}
function _cleanup() {
_preparedCache.clear();
_preparedSearchCache.clear();
}
function _isPrepared(x) {
return typeof x === 'object' && typeof x._bitflags === 'number';
}
function _getPrepared(target) {
if (target.length > 999)
return _prepare(target);
var targetPrepared = _preparedCache.get(target);
if (targetPrepared !== undefined)
return targetPrepared;
targetPrepared = _prepare(target);
_preparedCache.set(target, targetPrepared);
return targetPrepared;
}
function _getPreparedSearch(search) {
if (search.length > 999)
return _prepareSearch(search);
var searchPrepared = _preparedSearchCache.get(search);
if (searchPrepared !== undefined)
return searchPrepared;
searchPrepared = _prepareSearch(search);
_preparedSearchCache.set(search, searchPrepared);
return searchPrepared;
}
function _getValue(obj, prop) {
var tmp = obj[prop];
if (tmp !== undefined)
return tmp;
if (typeof prop === 'function')
return prop(obj);
var segs = prop;
if (!Array.isArray(prop))
segs = prop.split('.');
var len = segs.length;
var i = -1;
while (obj && (++i < len))
obj = obj[segs[i]];
return obj;
}
function _single(search, target) {
if (!search || !target)
return _NULL;
var preparedSearch = _getPreparedSearch(search);
if (!_isPrepared(target))
target = _getPrepared(target);
var searchBitflags = preparedSearch.bitflags;
if ((searchBitflags & target._bitflags) !== searchBitflags)
return _NULL;
return _algorithm(preparedSearch, target);
}
function _highlight(result, open, close) {
if (open === undefined)
open = '<b>';
if (close === undefined)
close = '</b>';
var callback = typeof open === 'function' ? open : undefined;
var target = result.target;
var targetLen = target.length;
var indexes = result.indexes;
var highlighted = '';
var matchI = 0;
var indexesI = 0;
var opened = false;
var parts = [];
for (var i = 0; i < targetLen; ++i) {
var ch = target[i];
if (indexes[indexesI] === i) {
++indexesI;
if (!opened) {
opened = true;
if (callback) {
parts.push(highlighted);
highlighted = '';
} else {
highlighted += open;
}
}
if (indexesI === indexes.length) {
if (callback) {
highlighted += ch;
parts.push(callback(highlighted, matchI++));
highlighted = '';
parts.push(target.substr(i + 1));
} else {
highlighted += ch + close + target.substr(i + 1);
}
break;
}
} else {
if (opened) {
opened = false;
if (callback) {
parts.push(callback(highlighted, matchI++));
highlighted = '';
} else {
highlighted += close;
}
}
}
highlighted += ch;
}
return callback ? parts : highlighted;
}
function _all(targets, options) {
var results = [];
results.total = targets.length;
var limit = options?.limit || _INFINITY;
if (options?.key) {
for (var i = 0; i < targets.length; i++) {
var obj = targets[i];
var target = _getValue(obj, options.key);
if (target == _NULL)
continue;
if (!_isPrepared(target))
target = _getPrepared(target);
var result = _new_result(target.target, {
_score: target._score,
obj: obj
});
results.push(result);
if (results.length >= limit)
return results;
}
} else if (options?.keys) {
for (var i = 0; i < targets.length; i++) {
var obj = targets[i];
var objResults = _createKeysResult(options.keys.length);
for (var keyI = options.keys.length - 1; keyI >= 0; --keyI) {
var target = _getValue(obj, options.keys[keyI]);
if (!target) {
objResults[keyI] = _noTarget;
continue;
}
if (!_isPrepared(target))
target = _getPrepared(target);
target._score = _NEGATIVE_INFINITY;
target._indexes.len = 0;
objResults[keyI] = target;
}
objResults.obj = obj;
objResults._score = _NEGATIVE_INFINITY;
results.push(objResults);
if (results.length >= limit)
return results;
}
} else {
for (var i = 0; i < targets.length; i++) {
var target = targets[i];
if (target == _NULL)
continue;
if (!_isPrepared(target))
target = _getPrepared(target);
target._score = _NEGATIVE_INFINITY;
target._indexes.len = 0;
results.push(target);
if (results.length >= limit)
return results;
}
}
return results;
}
function _algorithm(preparedSearch, prepared, allowSpaces, allowPartialMatch) {
if (allowSpaces === undefined)
allowSpaces = false;
if (allowPartialMatch === undefined)
allowPartialMatch = false;
if (allowSpaces === false && preparedSearch.containsSpace)
return _algorithmSpaces(preparedSearch, prepared, allowPartialMatch);
var searchLower = preparedSearch._lower;
var searchLowerCodes = preparedSearch.lowerCodes;
var searchLowerCode = searchLowerCodes[0];
var targetLowerCodes = prepared._targetLowerCodes;
var searchLen = searchLowerCodes.length;
var targetLen = targetLowerCodes.length;
var searchI = 0;
var targetI = 0;
var matchesSimpleLen = 0;
for (; ; ) {
var isMatch = searchLowerCode === targetLowerCodes[targetI];
if (isMatch) {
_matchesSimple[matchesSimpleLen++] = targetI;
++searchI;
if (searchI === searchLen)
break;
searchLowerCode = searchLowerCodes[searchI];
}
++targetI;
if (targetI >= targetLen)
return _NULL;
}
searchI = 0;
var successStrict = false;
var matchesStrictLen = 0;
var nextBeginningIndexes = prepared._nextBeginningIndexes;
if (nextBeginningIndexes === _NULL)
nextBeginningIndexes = prepared._nextBeginningIndexes = _prepareNextBeginningIndexes(prepared.target);
targetI = _matchesSimple[0] === 0 ? 0 : nextBeginningIndexes[_matchesSimple[0] - 1];
var backtrackCount = 0;
if (targetI !== targetLen)
for (; ; ) {
if (targetI >= targetLen) {
if (searchI <= 0)
break;
++backtrackCount;
if (backtrackCount > 200)
break;
--searchI;
var lastMatch = _matchesStrict[--matchesStrictLen];
targetI = nextBeginningIndexes[lastMatch];
} else {
var isMatch = searchLowerCodes[searchI] === targetLowerCodes[targetI];
if (isMatch) {
_matchesStrict[matchesStrictLen++] = targetI;
++searchI;
if (searchI === searchLen) {
successStrict = true;
break;
}
++targetI;
} else {
targetI = nextBeginningIndexes[targetI];
}
}
}
var substringIndex = searchLen <= 1 ? -1 : prepared._targetLower.indexOf(searchLower, _matchesSimple[0]);
var isSubstring = !!~substringIndex;
var isSubstringBeginning = !isSubstring ? false : substringIndex === 0 || prepared._nextBeginningIndexes[substringIndex - 1] === substringIndex;
if (isSubstring && !isSubstringBeginning) {
for (var i = 0; i < nextBeginningIndexes.length; i = nextBeginningIndexes[i]) {
if (i <= substringIndex)
continue;
for (var s = 0; s < searchLen; s++)
if (searchLowerCodes[s] !== prepared._targetLowerCodes[i + s])
break;
if (s === searchLen) {
substringIndex = i;
isSubstringBeginning = true;
break;
}
}
}
var calculateScore = function (matches) {
var score = 0;
var extraMatchGroupCount = 0;
for (var i = 1; i < searchLen; ++i) {
if (matches[i] - matches[i - 1] !== 1) {
score -= matches[i];
++extraMatchGroupCount;
}
}
var unmatchedDistance = matches[searchLen - 1] - matches[0] - (searchLen - 1);
score -= (12 + unmatchedDistance) * extraMatchGroupCount;
if (matches[0] !== 0)
score -= matches[0] * matches[0] * 0.2;
if (!successStrict) {
score *= 1000;
} else {
var uniqueBeginningIndexes = 1;
for (var i = nextBeginningIndexes[0]; i < targetLen; i = nextBeginningIndexes[i])
++uniqueBeginningIndexes;
if (uniqueBeginningIndexes > 24)
score *= (uniqueBeginningIndexes - 24) * 10;
}
score -= (targetLen - searchLen) / 2;
if (isSubstring)
score /= 1 + searchLen * searchLen * 1;
if (isSubstringBeginning)
score /= 1 + searchLen * searchLen * 1;
score -= (targetLen - searchLen) / 2;
return score;
};
var matchesBest, score;
if (!successStrict) {
if (isSubstring)
for (var i = 0; i < searchLen; ++i)
_matchesSimple[i] = substringIndex + i;
matchesBest = _matchesSimple;
score = calculateScore(matchesBest);
} else {
if (isSubstringBeginning) {
for (var i = 0; i < searchLen; ++i)
_matchesSimple[i] = substringIndex + i;
matchesBest = _matchesSimple;
score = calculateScore(_matchesSimple);
} else {
matchesBest = _matchesStrict;
score = calculateScore(_matchesStrict);
}
}
prepared._score = score;
for (var i = 0; i < searchLen; ++i)
prepared._indexes[i] = matchesBest[i];
prepared._indexes.len = searchLen;
var result = _createResult();
result.target = prepared.target;
result._score = prepared._score;
result._indexes = prepared._indexes;
return result;
}
function _algorithmSpaces(preparedSearch, target, allowPartialMatch) {
var seen_indexes = new Set();
var score = 0;
var result = _NULL;
var first_seen_index_last_search = 0;
var searches = preparedSearch.spaceSearches;
var searchesLen = searches.length;
var changeslen = 0;
var resetNextBeginningIndexes = function () {
for (let i = changeslen - 1; i >= 0; i--)
target._nextBeginningIndexes[_nextBeginningIndexesChanges[i * 2 + 0]] = _nextBeginningIndexesChanges[i * 2 + 1];
};
var hasAtLeast1Match = false;
for (var i = 0; i < searchesLen; ++i) {
_allowPartialMatchScores[i] = _NEGATIVE_INFINITY;
var search = searches[i];
result = _algorithm(search, target);
if (allowPartialMatch) {
if (result === _NULL)
continue;
hasAtLeast1Match = true;
} else {
if (result === _NULL) {
resetNextBeginningIndexes();
return _NULL;
}
}
var isTheLastSearch = i === searchesLen - 1;
if (!isTheLastSearch) {
var indexes = result._indexes;
var indexesIsConsecutiveSubstring = true;
for (let j = 0; j < indexes.len - 1; j++) {
if (indexes[j + 1] - indexes[j] !== 1) {
indexesIsConsecutiveSubstring = false;
break;
}
}
if (indexesIsConsecutiveSubstring) {
var newBeginningIndex = indexes[indexes.len - 1] + 1;
var toReplace = target._nextBeginningIndexes[newBeginningIndex - 1];
for (let j = newBeginningIndex - 1; j >= 0; j--) {
if (toReplace !== target._nextBeginningIndexes[j])
break;
target._nextBeginningIndexes[j] = newBeginningIndex;
_nextBeginningIndexesChanges[changeslen * 2 + 0] = j;
_nextBeginningIndexesChanges[changeslen * 2 + 1] = toReplace;
changeslen++;
}
}
}
score += result._score / searchesLen;
_allowPartialMatchScores[i] = result._score / searchesLen;
if (result._indexes[0] < first_seen_index_last_search) {
score -= (first_seen_index_last_search - result._indexes[0]) * 2;
}
first_seen_index_last_search = result._indexes[0];
for (var j = 0; j < result._indexes.len; ++j)
seen_indexes.add(result._indexes[j]);
}
if (allowPartialMatch && !hasAtLeast1Match)
return _NULL;
resetNextBeginningIndexes();
var allowSpacesResult = _algorithm(preparedSearch, target, true);
if (allowSpacesResult !== _NULL && allowSpacesResult._score > score) {
if (allowPartialMatch) {
for (var i = 0; i < searchesLen; ++i) {
_allowPartialMatchScores[i] = allowSpacesResult._score / searchesLen;
}
}
return allowSpacesResult;
}
if (allowPartialMatch)
result = target;
result._score = score;
var idx = 0;
for (let index of seen_indexes)
result._indexes[idx++] = index;
result._indexes.len = idx;
return result;
}
function _go(search, targets, options) {
if (!search)
return options?.all ? _all(targets, options) : _noResults;
var preparedSearch = _getPreparedSearch(search);
var searchBitflags = preparedSearch.bitflags;
var containsSpace = preparedSearch.containsSpace;
var threshold = _denormalizeScore(options?.threshold ?? 0.35);
var limit = options?.limit || _INFINITY;
var resultsLen = 0;
var limitedCount = 0;
var targetsLen = targets.length;
function push_result(result) {
if (resultsLen < limit) {
_q.add(result);
++resultsLen;
} else {
++limitedCount;
if (result._score > _q.peek()._score)
_q.replaceTop(result);
}
}
if (options?.key) {
var key = options.key;
for (var i = 0; i < targetsLen; ++i) {
var obj = targets[i];
var target = _getValue(obj, key);
if (!target)
continue;
if (!_isPrepared(target))
target = _getPrepared(target);
if ((searchBitflags & target._bitflags) !== searchBitflags)
continue;
var result = _algorithm(preparedSearch, target);
if (result === _NULL)
continue;
if (result._score < threshold)
continue;
result.obj = obj;
push_result(result);
}
} else if (options?.keys) {
var keys = options.keys;
var keysLen = keys.length;
outer: for (var i = 0; i < targetsLen; ++i) {
var obj = targets[i];
var keysBitflags = 0;
for (var keyI = 0; keyI < keysLen; ++keyI) {
var key = keys[keyI];
var target = _getValue(obj, key);
if (!target) {
_tmpTargets[keyI] = _noTarget;
continue;
}
if (!_isPrepared(target))
target = _getPrepared(target);
_tmpTargets[keyI] = target;
keysBitflags |= target._bitflags;
}
if ((searchBitflags & keysBitflags) !== searchBitflags)
continue;
if (containsSpace)
for (let j = 0; j < preparedSearch.spaceSearches.length; j++)
_keysSpacesBestScores[j] = _NEGATIVE_INFINITY;
for (var keyI = 0; keyI < keysLen; ++keyI) {
target = _tmpTargets[keyI];
if (target === _noTarget) {
_tmpResults[keyI] = _noTarget;
continue;
}
_tmpResults[keyI] = _algorithm(preparedSearch, target, false, containsSpace);
if (_tmpResults[keyI] === _NULL) {
_tmpResults[keyI] = _noTarget;
continue;
}
if (containsSpace)
for (let j = 0; j < preparedSearch.spaceSearches.length; j++) {
if (_allowPartialMatchScores[j] > -1000) {
if (_keysSpacesBestScores[j] > _NEGATIVE_INFINITY) {
var tmp = (_keysSpacesBestScores[j] + _allowPartialMatchScores[j]) / 4;
if (tmp > _keysSpacesBestScores[j])
_keysSpacesBestScores[j] = tmp;
}
}
if (_allowPartialMatchScores[j] > _keysSpacesBestScores[j])
_keysSpacesBestScores[j] = _allowPartialMatchScores[j];
}
}
if (containsSpace) {
for (let j = 0; j < preparedSearch.spaceSearches.length; j++)
if (_keysSpacesBestScores[j] === _NEGATIVE_INFINITY)
continue outer;
} else {
var hasAtLeast1Match = false;
for (let j = 0; j < keysLen; j++)
if (_tmpResults[j]._score !== _NEGATIVE_INFINITY) {
hasAtLeast1Match = true;
break;
}
if (!hasAtLeast1Match)
continue;
}
var objResults = _createKeysResult(keysLen);
for (let j = 0; j < keysLen; j++)
objResults[j] = _tmpResults[j];
var score;
if (containsSpace) {
score = 0;
for (let j = 0; j < preparedSearch.spaceSearches.length; j++)
score += _keysSpacesBestScores[j];
} else {
score = _NEGATIVE_INFINITY;
for (let j = 0; j < keysLen; j++) {
var res = objResults[j];
if (res._score > -1000) {
if (score > _NEGATIVE_INFINITY) {
var tmp = (score + res._score) / 4;
if (tmp > score)
score = tmp;
}
}
if (res._score > score)
score = res._score;
}
}
objResults.obj = obj;
objResults._score = score;
if (options?.scoreFn) {
score = options.scoreFn(objResults);
if (!score)
continue;
score = _denormalizeScore(score);
objResults._score = score;
}
if (score < threshold)
continue;
push_result(objResults);
}
} else {
for (var i = 0; i < targetsLen; ++i) {
var target = targets[i];
if (!target)
continue;
if (!_isPrepared(target))
target = _getPrepared(target);
if ((searchBitflags & target._bitflags) !== searchBitflags)
continue;
var result = _algorithm(preparedSearch, target);
if (result === _NULL)
continue;
if (result._score < threshold)
continue;
push_result(result);
}
}
if (resultsLen === 0)
return _noResults;
var results = new Array(resultsLen);
for (var i = resultsLen - 1; i >= 0; --i)
results[i] = _q.poll();
results.total = resultsLen + limitedCount;
return results;
}
}
+375
View File
@@ -0,0 +1,375 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import qs.compat.noctalia.Commons
Singleton {
id: root
property bool isLoaded: false
property string langCode: ""
property var locale: Qt.locale()
property string systemDetectedLangCode: ""
property string fullLocaleCode: "" // Preserves regional locale variants
property var translations: ({})
property var fallbackTranslations: ({})
// Static list of available translations — update when adding/removing translation files
property var availableLanguages: ["en", "en-GB", "cs", "de", "es", "fr", "hu", "it", "ja", "ko-KR", "ku", "nl", "nn-HN", "nn-NO", "pl", "pt", "ru", "sv", "tr", "uk-UA", "vi", "zh-CN", "zh-TW"]
// Default date format per language (used by lock screen, etc.)
readonly property var dateFormats: ({
"cs": "dddd d. MMMM",
"de": "dddd, d. MMMM",
"en": "dddd, MMMM d",
"es": "dddd, d 'de' MMMM",
"fr": "dddd d MMMM",
"hu": "MMMM d., dddd",
"it": "dddd d MMMM",
"ja": "yyyy年M月d日 dddd",
"ko": "yyyy년 M월 d일 dddd",
"ku": "dddd, dê MMMM",
"nl": "dddd d MMMM",
"nn": "dddd d. MMMM",
"pl": "dddd, d MMMM",
"pt": "dddd, d 'de' MMMM",
"ro": "dddd, d MMMM",
"ru": "dddd, d MMMM",
"sv": "dddd d MMMM",
"tr": "dddd, d MMMM",
"uk": "dddd, d MMMM",
"vi": "dddd, d 'tháng' M",
"zh": "yyyy年M月d日 dddd"
})
// Signals for reactive updates
signal languageChanged(string newLanguage)
signal translationsLoaded
// FileView to load translation files
property FileView translationFile: FileView {
id: fileView
printErrors: false
watchChanges: true
onFileChanged: reload()
onLoaded: {
try {
var data = JSON.parse(text());
root.translations = data;
Logger.i("I18n", `Loaded translations for "${root.langCode}"`);
root.isLoaded = true;
root.translationsLoaded();
// Load English fallback for non-English languages (only after main file succeeds)
if (root.langCode !== "en") {
fallbackFileView.path = `file://${Quickshell.shellDir}/compat/noctalia/Assets/Translations/en.json`;
}
} catch (e) {
Logger.e("I18n", `Failed to parse translation file: ${e}`);
setLanguage("en");
}
}
onLoadFailed: function (error) {
if (root.langCode === "en") {
Logger.e("I18n", `Failed to load English translation file: ${error}`);
// English also failed - still emit signal to unblock startup
root.isLoaded = true;
root.translationsLoaded();
return;
}
// Qt.callLater is needed because FileView doesn't re-trigger when path
// is changed inside its own onLoadFailed handler
var strippedCode = stripScript(root.langCode);
if (strippedCode !== root.langCode) {
Logger.d("I18n", `Translation file for "${root.langCode}" not found, trying "${strippedCode}"`);
root.langCode = strippedCode;
Qt.callLater(loadTranslations);
} else {
// Try language-only code (e.g. "zh-CN" → "zh")
var shortCode = root.langCode.substring(0, 2);
if (shortCode !== root.langCode) {
Logger.d("I18n", `Translation file for "${root.langCode}" not found, trying "${shortCode}"`);
root.langCode = shortCode;
Qt.callLater(loadTranslations);
} else {
Logger.w("I18n", `Translation file for "${root.langCode}" not found, falling back to English`);
root.langCode = "en";
root.fullLocaleCode = "en";
root.locale = Qt.locale("en");
Qt.callLater(loadTranslations);
}
}
}
}
// FileView to load fallback translation files
property FileView fallbackTranslationFile: FileView {
id: fallbackFileView
watchChanges: true
onFileChanged: reload()
onLoaded: {
try {
var data = JSON.parse(text());
root.fallbackTranslations = data;
Logger.d("I18n", `Loaded english fallback translations`);
} catch (e) {
Logger.e("I18n", `Failed to parse fallback translation file: ${e}`);
}
}
onLoadFailed: function (error) {
Logger.e("I18n", `Failed to load fallback translation file: ${error}`);
}
}
// Correct language when settings finish loading from disk (or user changes it)
Connections {
target: Settings.data.general
function onLanguageChanged() {
var userLang = Settings.data.general.language;
if (userLang !== "" && userLang !== root.langCode && availableLanguages.includes(userLang)) {
Logger.i("I18n", `Applying user language preference: "${userLang}"`);
setLanguage(userLang);
} else if (userLang === "" && root.systemDetectedLangCode !== "" && root.systemDetectedLangCode !== root.langCode) {
Logger.i("I18n", `Language reset to default, reverting to system language: "${root.systemDetectedLangCode}"`);
setLanguage(root.systemDetectedLangCode);
}
}
}
Component.onCompleted: {
Logger.i("I18n", "Service started");
var lang = determineFastLanguage();
langCode = lang.code;
fullLocaleCode = lang.fullLocale;
locale = Qt.locale(lang.fullLocale);
systemDetectedLangCode = lang.code;
Logger.i("I18n", `Loading "${lang.code}" (locale: "${lang.fullLocale}")`);
loadTranslations();
}
// Strip 4-letter script subtag from a BCP 47 tag (e.g. "fr-Latn-FR" → "fr-FR")
function stripScript(tag) {
var parts = tag.split("-");
var result = [];
for (var i = 0; i < parts.length; i++) {
if (parts[i].length === 4 && /^[A-Za-z]{4}$/.test(parts[i])) {
continue;
}
result.push(parts[i]);
}
return result.join("-");
}
// Determine the best language match against availableLanguages
function determineFastLanguage() {
// User preference from Settings (defaults to "" if not yet loaded from disk)
var userLang = Settings.data.general.language;
if (userLang !== "" && availableLanguages.includes(userLang)) {
return {
code: userLang,
fullLocale: userLang
};
}
// Match system locale against available translations
for (var i = 0; i < Qt.locale().uiLanguages.length; i++) {
var fullLang = Qt.locale().uiLanguages[i];
// Exact match (e.g. "zh-CN")
if (availableLanguages.includes(fullLang)) {
return {
code: fullLang,
fullLocale: fullLang
};
}
// Script-stripped match (e.g. "zh-Hans-CN" → "zh-CN")
var stripped = stripScript(fullLang);
if (stripped !== fullLang && availableLanguages.includes(stripped)) {
return {
code: stripped,
fullLocale: fullLang
};
}
// Language-only match (e.g. "fr-FR" → "fr")
var short_ = fullLang.substring(0, 2);
if (availableLanguages.includes(short_)) {
return {
code: short_,
fullLocale: fullLang
};
}
}
return {
code: "en",
fullLocale: "en"
};
}
function dateFormat() {
var lang = langCode.split("-")[0];
return dateFormats[lang] || "dddd, d MMMM";
}
// -------------------------------------------
function setLanguage(newLangCode, fullLocale) {
if (typeof fullLocale === "undefined") {
fullLocale = newLangCode;
}
if (newLangCode !== langCode && availableLanguages.includes(newLangCode)) {
langCode = newLangCode;
fullLocaleCode = fullLocale;
locale = Qt.locale(fullLocale);
Logger.i("I18n", `Language set to "${langCode}" with locale "${fullLocale}"`);
languageChanged(langCode);
loadTranslations();
} else if (!availableLanguages.includes(newLangCode)) {
Logger.w("I18n", `Language "${newLangCode}" is not available`);
}
}
// -------------------------------------------
function loadTranslations() {
if (langCode === "")
return;
const filePath = `file://${Quickshell.shellDir}/compat/noctalia/Assets/Translations/${langCode}.json`;
fileView.path = filePath;
isLoaded = false;
}
// -------------------------------------------
// Check if a translation exists
function hasTranslation(key) {
if (!isLoaded)
return false;
const keys = key.split(".");
var value = translations;
for (var i = 0; i < keys.length; i++) {
if (value && typeof value === "object" && keys[i] in value) {
value = value[keys[i]];
} else {
return false;
}
}
return typeof value === "string";
}
// -------------------------------------------
// Get all translation keys (useful for debugging)
function getAllKeys(obj, prefix) {
if (typeof obj === "undefined")
obj = translations;
if (typeof prefix === "undefined")
prefix = "";
var keys = [];
for (var key in (obj || {})) {
const value = obj[key];
const fullKey = prefix ? `${prefix}.${key}` : key;
if (typeof value === "object" && value !== null) {
keys = keys.concat(getAllKeys(value, fullKey));
} else if (typeof value === "string") {
keys.push(fullKey);
}
}
return keys;
}
// -------------------------------------------
// Reload translations (useful for development)
function reload() {
Logger.d("I18n", "Reloading translations");
loadTranslations();
}
// -------------------------------------------
// Main translation function
function tr(key, interpolations) {
if (typeof interpolations === "undefined")
interpolations = {};
if (!isLoaded) {
//Logger.d("I18n", "Translations not loaded yet")
return key;
}
// Navigate nested keys (e.g., "menu.file.open")
const keys = key.split(".");
// Look-up translation in the active language
var value = translations;
var notFound = false;
for (var i = 0; i < keys.length; i++) {
if (value && typeof value === "object" && keys[i] in value) {
value = value[keys[i]];
} else {
Logger.d("I18n", `Translation key "${key}" not found at part "${keys[i]}"`);
Logger.d("I18n", `Available keys: ${Object.keys(value || {}).join(", ")}`);
notFound = true;
break;
}
}
// Fallback to english if not found
if (notFound && availableLanguages.includes("en") && langCode !== "en") {
value = fallbackTranslations;
for (var i = 0; i < keys.length; i++) {
if (value && typeof value === "object" && keys[i] in value) {
value = value[keys[i]];
} else {
// Indicate this key does not even exists in the english fallback
return `!!${key}!!`;
}
}
} else if (notFound) {
// No fallback available
return `!!${key}!!`;
}
if (typeof value !== "string") {
Logger.d("I18n", `Translation key "${key}" is not a string`);
return key;
}
// Handle interpolations (e.g., "Hello {name}!")
var result = value;
for (var placeholder in interpolations) {
const regex = new RegExp(`\\{${placeholder}\\}`, 'g');
result = result.replace(regex, interpolations[placeholder]);
}
return result;
}
// -------------------------------------------
// Plural translation function
function trp(key, count, interpolations) {
if (typeof interpolations === "undefined") {
interpolations = {};
}
// Use key for singular, key-plural for plural
const realKey = count === 1 ? key : `${key}-plural`;
// Merge interpolations with count
var finalInterpolations = {
"count": count
};
for (var prop in interpolations) {
finalInterpolations[prop] = interpolations[prop];
}
return tr(realKey, finalInterpolations);
}
}
@@ -0,0 +1,85 @@
pragma Singleton
import QtQuick
import QtQuick.Controls
import Quickshell
import qs.compat.noctalia.Commons
Singleton {
id: root
// Expose the font family name for easy access
readonly property string fontFamily: currentFontLoader ? currentFontLoader.name : ""
readonly property string defaultIcon: IconsTabler.defaultIcon
readonly property var icons: IconsTabler.icons
readonly property var aliases: IconsTabler.aliases
readonly property string fontPath: "/compat/noctalia/Assets/Fonts/tabler/noctalia-tabler-icons.ttf"
// Current active font loader
property FontLoader currentFontLoader: null
property int fontVersion: 0
// Create a unique cache-busting path
readonly property string cacheBustingPath: Quickshell.shellDir + fontPath + "?v=" + fontVersion + "&t=" + Date.now()
// Signal emitted when font is reloaded
signal fontReloaded
Component.onCompleted: {
Logger.i("Icons", "Service started");
loadFontWithCacheBusting();
}
Connections {
target: Quickshell
function onReloadCompleted() {
Logger.d("Icons", "Quickshell reload completed - forcing font reload");
reloadFont();
}
}
// ---------------------------------------
function get(iconName) {
// Check in aliases first
if (aliases[iconName] !== undefined) {
iconName = aliases[iconName];
}
// Find the appropriate codepoint
return icons[iconName];
}
function loadFontWithCacheBusting() {
Logger.d("Icons", "Loading font with cache busting");
// Destroy old loader first
if (currentFontLoader) {
currentFontLoader.destroy();
currentFontLoader = null;
}
// Create new loader with cache-busting URL
currentFontLoader = Qt.createQmlObject(`
import QtQuick
FontLoader {
source: "${cacheBustingPath}"
}
`, root, "dynamicFontLoader_" + fontVersion);
// Connect to the new loader's status changes
currentFontLoader.statusChanged.connect(function () {
if (currentFontLoader.status === FontLoader.Ready) {
Logger.d("Icons", "Font loaded successfully:", currentFontLoader.name, "(version " + fontVersion + ")");
fontReloaded();
} else if (currentFontLoader.status === FontLoader.Error) {
Logger.e("Icons", "Font failed to load (version " + fontVersion + ")");
}
});
}
function reloadFont() {
Logger.d("Icons", "Forcing font reload...");
fontVersion++;
loadFontWithCacheBusting();
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,201 @@
pragma Singleton
import QtQuick
QtObject {
function getKeybindString(event) {
let keyStr = "";
if (event.modifiers & Qt.ControlModifier)
keyStr += "Ctrl+";
if (event.modifiers & Qt.AltModifier)
keyStr += "Alt+";
if (event.modifiers & Qt.ShiftModifier)
keyStr += "Shift+";
let keyName = "";
let rawText = event.text;
if (event.key >= Qt.Key_A && event.key <= Qt.Key_Z || event.key >= Qt.Key_0 && event.key <= Qt.Key_9) {
keyName = String.fromCharCode(event.key);
} else if (event.key >= Qt.Key_F1 && event.key <= Qt.Key_F12) {
keyName = "F" + (event.key - Qt.Key_F1 + 1);
} else if (rawText && rawText.length > 0 && rawText.charCodeAt(0) > 31 && rawText.charCodeAt(0) !== 127) {
keyName = rawText.toUpperCase();
if (event.modifiers & Qt.ShiftModifier) {
const shiftMap = {
"!": "1",
"\"": "2",
"§": "3",
"$": "4",
"%": "5",
"&": "6",
"/": "7",
"(": "8",
")": "9",
"=": "0",
"@": "2",
"#": "3",
"^": "6",
"*": "8"
};
if (shiftMap[keyName]) {
keyName = shiftMap[keyName];
}
}
} else {
switch (event.key) {
case Qt.Key_Escape:
keyName = "Esc";
break;
case Qt.Key_Space:
keyName = "Space";
break;
case Qt.Key_Return:
keyName = "Return";
break;
case Qt.Key_Enter:
keyName = "Enter";
break;
case Qt.Key_Tab:
keyName = "Tab";
break;
case Qt.Key_Backspace:
keyName = "Backspace";
break;
case Qt.Key_Delete:
keyName = "Del";
break;
case Qt.Key_Insert:
keyName = "Ins";
break;
case Qt.Key_Home:
keyName = "Home";
break;
case Qt.Key_End:
keyName = "End";
break;
case Qt.Key_PageUp:
keyName = "PgUp";
break;
case Qt.Key_PageDown:
keyName = "PgDn";
break;
case Qt.Key_Left:
keyName = "Left";
break;
case Qt.Key_Right:
keyName = "Right";
break;
case Qt.Key_Up:
keyName = "Up";
break;
case Qt.Key_Down:
keyName = "Down";
break;
case Qt.Key_BracketLeft:
keyName = "[";
break;
case Qt.Key_BracketRight:
keyName = "]";
break;
case Qt.Key_Backslash:
keyName = "\\";
break;
case Qt.Key_Slash:
keyName = "/";
break;
case Qt.Key_QuoteLeft:
case Qt.Key_AsciiTilde:
case Qt.Key_Dead_Grave:
keyName = "`";
break;
}
}
if (!keyName)
return "";
return keyStr + keyName;
}
function checkKey(event, settingName, settings) {
// Accept both simplified names ("remove") and full property names ("keyRemove")
// so callers are less error-prone.
var normalized = String(settingName || "");
if (!normalized)
return false;
var propName = normalized.startsWith("key") ? normalized : ("key" + normalized.charAt(0).toUpperCase() + normalized.slice(1));
var boundKeys = settings.data.general.keybinds[propName];
if (!boundKeys || boundKeys.length === 0)
return false;
var eventString = getKeybindString(event);
for (var i = 0; i < boundKeys.length; i++) {
if (boundKeys[i] === eventString)
return true;
}
return false;
}
/**
* Check if a keybind string conflicts with any other existing keybinds.
* @param {string} keyStr - The keybind string to check (e.g., "Ctrl+A").
* @param {string} currentPath - The settings path of the keybind being edited (to skip checking itself).
* @param {object} data - The settings data object (from Settings.data).
* @returns {string|null} - The name of the conflicting action, or null if no conflict.
*/
function getKeybindConflict(keyStr, currentPath, data) {
if (!keyStr || !data)
return null;
const searchKey = String(keyStr).trim().toLowerCase();
// 1. Check navigation keybinds
const navKeybinds = data.general ? data.general.keybinds : null;
const navMap = {
"keyUp": "Navigation: Up",
"keyDown": "Navigation: Down",
"keyLeft": "Navigation: Left",
"keyRight": "Navigation: Right",
"keyEnter": "Navigation: Enter",
"keyEscape": "Navigation: Escape"
};
if (navKeybinds) {
for (const prop in navMap) {
const fullPath = "general.keybinds." + prop;
if (fullPath === currentPath)
continue;
const boundKeys = navKeybinds[prop];
if (boundKeys && boundKeys.length !== undefined) {
for (let i = 0; i < boundKeys.length; i++) {
if (String(boundKeys[i]).trim().toLowerCase() === searchKey) {
return navMap[prop];
}
}
}
}
}
// 2. Check session menu power options
const sessionMenu = data.sessionMenu;
if (sessionMenu && sessionMenu.powerOptions) {
const powerOptions = sessionMenu.powerOptions;
for (let i = 0; i < powerOptions.length; i++) {
const entry = powerOptions[i];
const fullPath = "sessionMenu.powerOptions[" + i + "].keybind";
if (fullPath === currentPath)
continue;
if (entry.keybind && String(entry.keybind).trim().toLowerCase() === searchKey) {
// Capitalize action name
const actionName = entry.action ? entry.action.charAt(0).toUpperCase() + entry.action.slice(1) : "Unknown";
return "Session Menu: " + actionName;
}
}
}
return null;
}
}
@@ -0,0 +1,69 @@
pragma Singleton
import Quickshell
import qs.compat.noctalia.Commons
Singleton {
id: root
function _formatMessage(...args) {
var t = Time.getFormattedTimestamp();
if (args.length > 1) {
const maxLength = 14;
var module = args.shift().substring(0, maxLength).padStart(maxLength, " ");
return `\x1b[36m[${t}]\x1b[0m \x1b[35m${module}\x1b[0m ` + args.join(" ");
} else {
return `[\x1b[36m[${t}]\x1b[0m ` + args.join(" ");
}
}
function _getStackTrace() {
try {
throw new Error("Stack trace");
} catch (e) {
return e.stack;
}
}
// Debug log (only when Settings.isDebug is true)
function d(...args) {
if (Settings?.isDebug) {
var msg = _formatMessage(...args);
console.debug(msg);
}
}
// Info log (always visible)
function i(...args) {
var msg = _formatMessage(...args);
console.info(msg);
}
// Warning log (always visible)
function w(...args) {
var msg = _formatMessage(...args);
console.warn(msg);
}
// Error log (always visible)
function e(...args) {
var msg = _formatMessage(...args);
console.error(msg);
}
function callStack() {
var stack = _getStackTrace();
Logger.i("Debug", "--------------------------");
Logger.i("Debug", "Current call stack");
// Split the stack into lines and log each one
var stackLines = stack.split('\n');
for (var i = 0; i < stackLines.length; i++) {
var line = stackLines[i].trim(); // Remove leading/trailing whitespace
if (line.length > 0) {
// Only log non-empty lines
Logger.i("Debug", `- ${line}`);
}
}
Logger.i("Debug", "--------------------------");
}
}
@@ -0,0 +1,23 @@
import QtQuick
QtObject {
id: root
// Migrate from version < 27 to version 27
// Converts settingsPanelAttachToBar boolean to settingsPanelMode string
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v27");
// Check rawJson for old property (adapter doesn't expose removed properties)
if (rawJson?.ui?.settingsPanelAttachToBar !== undefined) {
if (rawJson.ui.settingsPanelAttachToBar === true) {
adapter.ui.settingsPanelMode = "attached";
} else {
adapter.ui.settingsPanelMode = "centered";
}
logger.i("Settings", "Migrated settingsPanelAttachToBar to settingsPanelMode: " + adapter.ui.settingsPanelMode);
}
return true;
}
}
@@ -0,0 +1,37 @@
import QtQuick
QtObject {
id: root
// Migrate TaskbarGrouped widgets to Workspace with showApplications: true
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v28");
// Check bar widgets in all sections
const sections = ["left", "center", "right"];
for (const section of sections) {
if (!rawJson?.bar?.widgets?.[section])
continue;
const widgets = rawJson.bar.widgets[section];
for (let i = 0; i < widgets.length; i++) {
if (widgets[i].id === "TaskbarGrouped") {
// Convert TaskbarGrouped to Workspace with showApplications
const oldWidget = widgets[i];
adapter.bar.widgets[section][i] = {
id: "Workspace",
showApplications: true,
labelMode: oldWidget.labelMode || "index",
hideUnoccupied: oldWidget.hideUnoccupied || false,
showLabelsOnlyWhenOccupied: oldWidget.showLabelsOnlyWhenOccupied ?? true,
colorizeIcons: oldWidget.colorizeIcons || false
};
logger.i("Settings", "Migrated TaskbarGrouped to Workspace in " + section + " section");
}
}
}
return true;
}
}
@@ -0,0 +1,18 @@
import QtQuick
QtObject {
id: root
// Migrate systemMonitor.enableNvidiaGpu to systemMonitor.enableDgpuMonitoring
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v32");
// Check rawJson for old property (adapter doesn't expose removed properties)
if (rawJson?.systemMonitor?.enableNvidiaGpu !== undefined) {
adapter.systemMonitor.enableDgpuMonitoring = rawJson.systemMonitor.enableNvidiaGpu;
logger.i("Settings", "Migrated systemMonitor.enableNvidiaGpu to enableDgpuMonitoring: " + adapter.systemMonitor.enableDgpuMonitoring);
}
return true;
}
}
@@ -0,0 +1,26 @@
import QtQuick
QtObject {
id: root
// Migrate wallpaper.randomEnabled to wallpaper.wallpaperChangeMode
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v33");
if (rawJson?.wallpaper?.randomEnabled !== undefined) {
// We'll keep randomEnabled for backward compatibility but set wallpaperChangeMode
if (rawJson.wallpaper.randomEnabled === true) {
adapter.wallpaper.wallpaperChangeMode = "random";
logger.i("Settings", "Migrated wallpaper.randomEnabled=true to wallpaperChangeMode=random");
} else {
adapter.wallpaper.wallpaperChangeMode = "random";
logger.i("Settings", "Set wallpaperChangeMode=random (randomEnabled was false)");
}
} else {
adapter.wallpaper.wallpaperChangeMode = "random";
logger.i("Settings", "Set default wallpaperChangeMode=random");
}
return true;
}
}
@@ -0,0 +1,20 @@
import QtQuick
QtObject {
id: root
// Migrate bar.transparent to bar.backgroundOpacity + bar.useSeparateOpacity
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v35");
if (rawJson?.bar?.transparent !== undefined) {
if (rawJson.bar.transparent === true) {
adapter.bar.backgroundOpacity = 0;
adapter.bar.useSeparateOpacity = true;
logger.i("Settings", "Migrated bar.transparent=true to backgroundOpacity=0, useSeparateOpacity=true");
}
}
return true;
}
}
@@ -0,0 +1,29 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
// Clear legacy emoji usage cache to adopt new format
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v36");
const usagePath = Settings.cacheDir + "emoji_usage.json";
if (!usagePath.endsWith("emoji_usage.json")) {
logger.w("Settings", "Skipping emoji usage cleanup due to unexpected path: " + usagePath);
return true;
}
try {
// Ensure dir exists then remove the file
Quickshell.execDetached(["sh", "-c", `mkdir -p "${Settings.cacheDir}" && rm -f -- "${usagePath}"`]);
logger.i("Settings", "Cleared legacy emoji usage file at: " + usagePath);
} catch (e) {
logger.w("Settings", "Failed to clear emoji usage cache: " + e);
}
return true;
}
}
@@ -0,0 +1,79 @@
import QtQuick
QtObject {
id: root
// Rename WiFi widgets/shortcuts to Network
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v37 (WiFi → Network)");
let changed = false;
function migrateArray(contextName, rawArr, adapterArr, setItem) {
if (!adapterArr)
return;
const len = adapterArr.length;
for (let i = 0; i < len; i++) {
// Prefer raw item if present, otherwise use adapter item
const item = rawArr && rawArr[i] !== undefined ? rawArr[i] : adapterArr[i];
if (item === undefined || item === null)
continue;
// Case 1: simple string entries
if (typeof item === "string") {
if (item === "WiFi") {
setItem(i, "Network");
changed = true;
logger.i("Settings", `Migrated ${contextName}[${i}] from WiFi to Network (string entry)`);
}
continue;
}
// Case 2: object entries with id
let id = item.id !== undefined ? item.id : (item.widgetId !== undefined ? item.widgetId : undefined);
if (id === "WiFi") {
var newObj = {};
for (var key in item)
newObj[key] = item[key];
if (newObj.id !== undefined)
newObj.id = "Network";
if (newObj.widgetId !== undefined && newObj.id === undefined)
newObj.widgetId = "Network"; // fallback if older schema used widgetId
setItem(i, newObj);
changed = true;
logger.i("Settings", `Migrated ${contextName}[${i}] from WiFi to Network (object entry)`);
}
}
}
// --- Bar widgets: left/center/right
const sections = ["left", "center", "right"];
for (const section of sections) {
const rawArr = rawJson?.bar?.widgets?.[section];
const adapterArr = adapter?.bar?.widgets?.[section];
migrateArray(`bar.widgets.${section}`, rawArr, adapterArr, function (i, v) {
adapter.bar.widgets[section][i] = v;
});
}
// --- Control Center shortcuts: left/right
const rawLeft = rawJson?.controlCenter?.shortcuts?.left;
const adLeft = adapter?.controlCenter?.shortcuts?.left;
migrateArray("controlCenter.shortcuts.left", rawLeft, adLeft, function (i, v) {
adapter.controlCenter.shortcuts.left[i] = v;
});
const rawRight = rawJson?.controlCenter?.shortcuts?.right;
const adRight = adapter?.controlCenter?.shortcuts?.right;
migrateArray("controlCenter.shortcuts.right", rawRight, adRight, function (i, v) {
adapter.controlCenter.shortcuts.right[i] = v;
});
if (!changed) {
logger.i("Settings", "No WiFi widget IDs found to migrate; leaving settings unchanged");
}
return true;
}
}
@@ -0,0 +1,27 @@
import QtQuick
import qs.compat.noctalia.Commons
QtObject {
function migrate(adapter, logger, rawJson) {
logger.i("Migration38", "Migrating bar margins from percentages to integers");
// Use rawJson to read original values, adapter to write new values (following migration patterns)
const rawVertical = rawJson?.bar?.marginVertical;
const rawHorizontal = rawJson?.bar?.marginHorizontal;
// Only migrate if values exist and are percentages (<= 1.0)
if (rawVertical !== undefined && typeof rawVertical === 'number' && rawVertical <= 1.0) {
const marginXL = 18; // Standard value of Style.marginXL
adapter.bar.marginVertical = Math.round(rawVertical * marginXL);
logger.d("Migration38", "Converted marginVertical from " + rawVertical + " to " + adapter.bar.marginVertical + "px");
}
if (rawHorizontal !== undefined && typeof rawHorizontal === 'number' && rawHorizontal <= 1.0) {
const marginXL = 18; // Standard value of Style.marginXL
adapter.bar.marginHorizontal = Math.round(rawHorizontal * marginXL);
logger.d("Migration38", "Converted marginHorizontal from " + rawHorizontal + " to " + adapter.bar.marginHorizontal + "px");
}
return true;
}
}
@@ -0,0 +1,43 @@
import QtQuick
QtObject {
id: root
// List of all template IDs that existed as booleans in the old format
readonly property var templateIds: ["gtk", "qt", "kcolorscheme", "alacritty", "kitty", "ghostty", "foot", "wezterm", "fuzzel", "discord", "pywalfox", "vicinae", "walker", "code", "spicetify", "telegram", "cava", "yazi", "emacs", "niri", "hyprland", "mango", "zed", "helix", "zenBrowser"]
function migrate(adapter, logger, rawJson) {
logger.i("Migration39", "Migrating templates from boolean format to activeTemplates array");
// Check if old format exists (any boolean template property)
const oldTemplates = rawJson?.templates;
if (!oldTemplates) {
logger.d("Migration39", "No templates section found, skipping migration");
return true;
}
// Check if already migrated (has activeTemplates array)
if (Array.isArray(oldTemplates.activeTemplates)) {
logger.d("Migration39", "Already has activeTemplates array, skipping migration");
return true;
}
// Build the new activeTemplates array from old boolean values
const activeTemplates = [];
for (const templateId of templateIds) {
if (oldTemplates[templateId] === true) {
activeTemplates.push({
"id": templateId,
"enabled": true
});
logger.d("Migration40", "Migrated enabled template: " + templateId);
}
}
// Write the new format
adapter.templates.activeTemplates = activeTemplates;
logger.i("Migration40", "Migrated " + activeTemplates.length + " templates to new array format");
return true;
}
}
@@ -0,0 +1,28 @@
import QtQuick
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration42", "Migrating randomEnabled to automationEnabled");
const wallpaper = rawJson?.wallpaper;
if (!wallpaper) {
logger.d("Migration42", "No wallpaper section found, skipping migration");
return true;
}
// Check if already migrated (has automationEnabled)
if (wallpaper.automationEnabled !== undefined) {
logger.d("Migration42", "Already has automationEnabled, skipping migration");
return true;
}
// Migrate randomEnabled to automationEnabled
const oldValue = wallpaper.randomEnabled ?? false;
adapter.wallpaper.automationEnabled = oldValue;
logger.i("Migration42", "Migrated randomEnabled=" + oldValue + " to automationEnabled=" + oldValue);
return true;
}
}
@@ -0,0 +1,29 @@
import QtQuick
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration43", "Migrating recursiveSearch to viewMode");
const wallpaper = rawJson?.wallpaper;
if (!wallpaper) {
logger.d("Migration43", "No wallpaper section found, skipping migration");
return true;
}
// Check if already migrated (has viewMode)
if (wallpaper.viewMode !== undefined) {
logger.d("Migration43", "Already has viewMode, skipping migration");
return true;
}
// Migrate recursiveSearch to viewMode
const oldValue = wallpaper.recursiveSearch ?? false;
const newValue = oldValue ? "recursive" : "single";
adapter.wallpaper.viewMode = newValue;
logger.i("Migration43", "Migrated recursiveSearch=" + oldValue + " to viewMode=" + newValue);
return true;
}
}
@@ -0,0 +1,35 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration44", "Updating PAM pam/password.conf");
const configDir = Settings.configDir;
const pamConfigDir = configDir + "pam";
const pamConfigFile = pamConfigDir + "/password.conf";
const pamConfigDirEsc = pamConfigDir.replace(/'/g, "'\\''");
const pamConfigFileEsc = pamConfigFile.replace(/'/g, "'\\''");
// Ensure directory exists
Quickshell.execDetached(["mkdir", "-p", pamConfigDir]);
// Generate the PAM config file content (updated version)
var configContent = "auth sufficient pam_fprintd.so timeout=-1\n";
configContent += "auth sufficient /run/current-system/sw/lib/security/pam_fprintd.so timeout=-1 # for NixOS\n";
configContent += "auth required pam_unix.so\n";
// Write the config file using heredoc
var script = `cat > '${pamConfigFileEsc}' << 'EOF'\n`;
script += configContent;
script += "EOF\n";
Quickshell.execDetached(["sh", "-c", script]);
logger.d("Migration44", "PAM config file updated at:", pamConfigFile);
return true;
}
}
@@ -0,0 +1,18 @@
import QtQuick
QtObject {
/**
* Migration 45: Migrate 'floating' bar setting to 'barType'
*/
function migrate(adapter, logger, rawJson) {
logger.i("Migration45", "Migrating bar settings...");
if (rawJson?.bar?.floating) {
adapter.bar.barType = "floating";
} else {
adapter.bar.barType = "simple";
}
return true;
}
}
@@ -0,0 +1,21 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration46", "Removing legacy PAM configuration file");
const configDir = Settings.configDir;
const pamConfigDir = configDir + "pam";
// Remove the entire pam directory if it exists
const script = `rm -rf '${pamConfigDir}'`;
Quickshell.execDetached(["sh", "-c", script]);
logger.d("Migration46", "Cleaned up legacy PAM config");
return true;
}
}
@@ -0,0 +1,18 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Migration47", "Removing network_stats.json cache");
const networkStatsFile = Settings.cacheDir + "network_stats.json";
Quickshell.execDetached(["rm", "-f", networkStatsFile]);
logger.d("Migration47", "Removed network_stats.json");
return true;
}
}
@@ -0,0 +1,22 @@
import QtQuick
QtObject {
id: root
// Migrate battery thresholds from notifications to systemMonitor
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v48");
if (rawJson?.notifications?.batteryWarningThreshold !== undefined) {
adapter.systemMonitor.batteryWarningThreshold = rawJson.notifications.batteryWarningThreshold;
logger.i("Settings", "Migrated notifications.batteryWarningThreshold to systemMonitor: " + adapter.systemMonitor.batteryWarningThreshold);
}
if (rawJson?.notifications?.batteryCriticalThreshold !== undefined) {
adapter.systemMonitor.batteryCriticalThreshold = rawJson.notifications.batteryCriticalThreshold;
logger.i("Settings", "Migrated notifications.batteryCriticalThreshold to systemMonitor: " + adapter.systemMonitor.batteryCriticalThreshold);
}
return true;
}
}
@@ -0,0 +1,17 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
// Remove old launcher_app_usage.json (usage tracking moved to ShellState)
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v49");
Quickshell.execDetached(["rm", "-f", Settings.cacheDir + "launcher_app_usage.json"]);
logger.i("Settings", "Removed old launcher_app_usage.json");
return true;
}
}
@@ -0,0 +1,24 @@
import QtQuick
QtObject {
id: root
// Migrate keybinds from single strings to arrays of strings
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v50");
const keybinds = rawJson?.general?.keybinds;
if (!keybinds)
return true;
const keys = ["keyUp", "keyDown", "keyLeft", "keyRight", "keyEnter", "keyEscape"];
for (const key of keys) {
if (keybinds[key] !== undefined && typeof keybinds[key] === "string") {
adapter.general.keybinds[key] = [keybinds[key]];
logger.i("Settings", "Migrated keybinds." + key + " from string to array: [" + keybinds[key] + "]");
}
}
return true;
}
}
@@ -0,0 +1,39 @@
import QtQuick
QtObject {
id: root
// Add default keybinds (1-6) to session menu power options if none are defined
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v53");
const powerOptions = rawJson?.sessionMenu?.powerOptions;
if (!powerOptions || !Array.isArray(powerOptions))
return true;
// Check if any power option has a keybind defined
const hasAnyKeybind = powerOptions.some(opt => opt.keybind && opt.keybind !== "");
if (hasAnyKeybind)
return true;
// No keybinds defined — apply defaults matching the action order
const defaultKeybinds = {
"lock": "1",
"suspend": "2",
"hibernate": "3",
"reboot": "4",
"logout": "5",
"shutdown": "6"
};
for (let i = 0; i < powerOptions.length; i++) {
const action = powerOptions[i].action;
if (defaultKeybinds[action]) {
adapter.sessionMenu.powerOptions[i].keybind = defaultKeybinds[action];
logger.i("Settings", "Set keybind '" + defaultKeybinds[action] + "' for session menu action: " + action);
}
}
return true;
}
}
@@ -0,0 +1,28 @@
import QtQuick
QtObject {
id: root
// Add numpad Enter as a second default keybind for keyEnter
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v54");
const keybinds = rawJson?.general?.keybinds;
if (!keybinds)
return true;
const keyEnter = keybinds.keyEnter;
if (!keyEnter || !Array.isArray(keyEnter))
return true;
// Only add "Enter" if the first entry is "Return" and "Enter" isn't already present
if (keyEnter[0] === "Return" && !keyEnter.includes("Enter")) {
var updated = Array.from(keyEnter);
updated.splice(1, 0, "Enter");
adapter.general.keybinds.keyEnter = updated;
logger.i("Settings", "Added 'Enter' (numpad) as second default keybind for keyEnter");
}
return true;
}
}
@@ -0,0 +1,22 @@
import QtQuick
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v55");
// Check if the old setting exists
if (rawJson.controlCenter && rawJson.controlCenter.openAtMouseOnBarRightClick !== undefined) {
if (!rawJson.bar)
rawJson.bar = {};
rawJson.bar.rightClickFollowMouse = rawJson.controlCenter.openAtMouseOnBarRightClick;
delete rawJson.controlCenter.openAtMouseOnBarRightClick;
logger.i("Settings", "Successfully moved openAtMouseOnBarRightClick to bar.rightClickFollowMouse");
}
return true;
}
}
@@ -0,0 +1,21 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v56 (Color Scheme Migration)");
const scriptPath = Quickshell.shellDir + "/Scripts/python/src/theming/migrate-colorschemes.py";
const configDir = Settings.configDir;
logger.i("Settings", `Running color scheme migration script: ${scriptPath} with configDir: ${configDir}`);
// Run the migration script detached
Quickshell.execDetached(["python3", scriptPath, configDir]);
return true;
}
}
@@ -0,0 +1,16 @@
import QtQuick
QtObject {
id: root
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v57 (cavaFrameRate -> spectrumFrameRate)");
if (rawJson && rawJson.audio && rawJson.audio.cavaFrameRate !== undefined) {
adapter.audio.spectrumFrameRate = rawJson.audio.cavaFrameRate;
logger.i("Settings", "Migrated cavaFrameRate:", rawJson.audio.cavaFrameRate, "-> spectrumFrameRate");
}
return true;
}
}
@@ -0,0 +1,14 @@
import QtQuick
QtObject {
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v58 (dock.dockType: static -> attached)");
if (rawJson && rawJson.dock && rawJson.dock.dockType === "static") {
adapter.dock.dockType = "attached";
logger.i("Settings", "Migrated dock.dockType: static -> attached");
}
return true;
}
}
@@ -0,0 +1,25 @@
import QtQuick
QtObject {
function migrate(adapter, logger, rawJson) {
logger.i("Settings", "Migrating settings to v59 (wallpaper.transitionType: string -> array)");
if (rawJson && rawJson.wallpaper && typeof rawJson.wallpaper.transitionType === "string") {
var oldValue = rawJson.wallpaper.transitionType;
var newValue;
if (oldValue === "random") {
newValue = ["fade", "disc", "stripes", "wipe", "pixelate", "honeycomb"];
} else if (oldValue === "none") {
newValue = [];
} else {
newValue = [oldValue];
}
adapter.wallpaper.transitionType = newValue;
logger.i("Settings", "Migrated wallpaper.transitionType:", oldValue, "->", JSON.stringify(newValue));
}
return true;
}
}
@@ -0,0 +1,63 @@
pragma Singleton
import QtQuick
QtObject {
id: root
// Map of version number to migration component
readonly property var migrations: ({
27: migration27Component,
28: migration28Component,
32: migration32Component,
33: migration33Component,
35: migration35Component,
36: migration36Component,
37: migration37Component,
38: migration38Component,
40: migration40Component,
42: migration42Component,
43: migration43Component,
44: migration44Component,
45: migration45Component,
46: migration46Component,
47: migration47Component,
48: migration48Component,
49: migration49Component,
50: migration50Component,
53: migration53Component,
54: migration54Component,
55: migration55Component,
56: migration56Component,
57: migration57Component,
58: migration58Component,
59: migration59Component
})
// Migration components
property Component migration27Component: Migration27 {}
property Component migration28Component: Migration28 {}
property Component migration32Component: Migration32 {}
property Component migration33Component: Migration33 {}
property Component migration35Component: Migration35 {}
property Component migration36Component: Migration36 {}
property Component migration37Component: Migration37 {}
property Component migration38Component: Migration38 {}
property Component migration40Component: Migration40 {}
property Component migration42Component: Migration42 {}
property Component migration43Component: Migration43 {}
property Component migration44Component: Migration44 {}
property Component migration45Component: Migration45 {}
property Component migration46Component: Migration46 {}
property Component migration47Component: Migration47 {}
property Component migration48Component: Migration48 {}
property Component migration49Component: Migration49 {}
property Component migration50Component: Migration50 {}
property Component migration53Component: Migration53 {}
property Component migration54Component: Migration54 {}
property Component migration55Component: Migration55 {}
property Component migration56Component: Migration56 {}
property Component migration57Component: Migration57 {}
property Component migration58Component: Migration58 {}
property Component migration59Component: Migration59 {}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,287 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import "../Helpers/QtObj2JS.js" as QtObj2JS
import qs.compat.noctalia.Services.Power
import qs.compat.noctalia.Services.System
import qs.compat.noctalia.Services.UI
// Centralized shell state management for small cache files
Singleton {
id: root
property string stateFile: ""
property bool isLoaded: false
// State properties for different services
readonly property alias data: adapter
// Signals for state changes
signal displayStateChanged
signal notificationsStateChanged
signal changelogStateChanged
signal colorSchemesListChanged
Component.onCompleted: {
// Setup state file path (needs Settings to be available)
Qt.callLater(() => {
if (typeof Settings !== 'undefined' && Settings.cacheDir) {
stateFile = Settings.cacheDir + "shell-state.json";
stateFileView.path = stateFile;
}
});
}
// FileView for shell state
FileView {
id: stateFileView
printErrors: false
watchChanges: false
adapter: JsonAdapter {
id: adapter
// CompositorService: display scales
property var display: ({})
// NotificationService: notification state
property var notificationsState: ({
lastSeenTs: 0
})
// UpdateService: changelog state
property var changelogState: ({
lastSeenVersion: ""
})
// SchemeDownloader: color schemes list
property var colorSchemesList: ({
schemes: [],
timestamp: 0
})
// UI state: settings panel, etc.
property var ui: ({
settingsSidebarExpanded: true
})
// Telemetry state
property var telemetry: ({
instanceId: ""
})
// Launcher app usage counts
property var launcherUsage: ({})
}
onLoaded: {
root.isLoaded = true;
Logger.d("ShellState", "Loaded state file");
}
onLoadFailed: error => {
if (error === 2) {
// File doesn't exist, will be created on first write
root.isLoaded = true;
Logger.d("ShellState", "State file doesn't exist, will create on first write");
} else {
Logger.e("ShellState", "Failed to load state file:", error);
root.isLoaded = true;
}
}
}
// Launcher usage
function getLauncherUsageCount(key) {
const m = adapter.launcherUsage;
if (!m)
return 0;
const v = m[key];
return typeof v === 'number' && isFinite(v) ? v : 0;
}
function recordLauncherUsage(key) {
let counts = Object.assign({}, adapter.launcherUsage || {});
counts[key] = getLauncherUsageCount(key) + 1;
adapter.launcherUsage = counts;
save();
}
// Migrate usage from one key to another, merging counts in a single save
function migrateLauncherUsage(fromKey, toKey) {
let counts = Object.assign({}, adapter.launcherUsage || {});
const fromCount = typeof counts[fromKey] === 'number' && isFinite(counts[fromKey]) ? counts[fromKey] : 0;
const toCount = typeof counts[toKey] === 'number' && isFinite(counts[toKey]) ? counts[toKey] : 0;
counts[toKey] = toCount + fromCount;
delete counts[fromKey];
adapter.launcherUsage = counts;
save();
}
// Debounced save timer
Timer {
id: saveTimer
interval: 500
onTriggered: performSave()
}
property bool saveQueued: false
function save() {
saveQueued = true;
saveTimer.restart();
}
function performSave() {
if (!saveQueued || !stateFile) {
return;
}
saveQueued = false;
try {
// Ensure cache directory exists
Quickshell.execDetached(["mkdir", "-p", Settings.cacheDir]);
Qt.callLater(() => {
try {
stateFileView.writeAdapter();
Logger.d("ShellState", "Saved state file");
} catch (writeError) {
Logger.e("ShellState", "Failed to write state file:", writeError);
}
});
} catch (error) {
Logger.e("ShellState", "Failed to save state:", error);
}
}
// Convenience functions for each service
// Display state (CompositorService)
function setDisplay(displayData) {
adapter.display = displayData;
save();
displayStateChanged();
}
function getDisplay() {
return adapter.display || {};
}
// Notifications state (NotificationService)
function setNotificationsState(stateData) {
adapter.notificationsState = stateData;
save();
notificationsStateChanged();
}
function getNotificationsState() {
return adapter.notificationsState || {
lastSeenTs: 0
};
}
// Changelog state (UpdateService)
function setChangelogState(stateData) {
adapter.changelogState = stateData;
save();
changelogStateChanged();
}
function getChangelogState() {
return adapter.changelogState || {
lastSeenVersion: ""
};
}
// Color schemes list (SchemeDownloader)
function setColorSchemesList(listData) {
adapter.colorSchemesList = listData;
save();
colorSchemesListChanged();
}
function getColorSchemesList() {
return adapter.colorSchemesList || {
schemes: [],
timestamp: 0
};
}
// UI state
function setUiState(stateData) {
adapter.ui = stateData;
save();
}
function getUiState() {
return adapter.ui || {
settingsSidebarExpanded: true
};
}
function setSettingsSidebarExpanded(expanded) {
let uiState = getUiState();
uiState.settingsSidebarExpanded = expanded;
setUiState(uiState);
}
function getSettingsSidebarExpanded() {
return getUiState().settingsSidebarExpanded !== false; // default to true
}
// Telemetry state
function setTelemetryState(stateData) {
adapter.telemetry = stateData;
save();
}
function getTelemetryState() {
return adapter.telemetry || {
instanceId: ""
};
}
function getTelemetryInstanceId() {
return getTelemetryState().instanceId || "";
}
function setTelemetryInstanceId(instanceId) {
let state = getTelemetryState();
state.instanceId = instanceId;
setTelemetryState(state);
}
// -----------------------------------------------------
function buildStateSnapshot() {
try {
const settingsData = QtObj2JS.qtObjectToPlainObject(Settings.data);
const shellStateData = ShellState?.data ? QtObj2JS.qtObjectToPlainObject(ShellState.data) || {} : {};
return {
settings: settingsData,
state: {
doNotDisturb: NotificationService.doNotDisturb,
noctaliaPerformanceMode: PowerProfileService.noctaliaPerformanceMode,
barVisible: BarService.isVisible,
openedPanel: PanelService.openedPanel?.objectName || "",
lockScreenActive: PanelService.lockScreen?.active || false,
wallpapers: WallpaperService.getWallpapersEffectiveMap(),
desktopWidgetsEditMode: DesktopWidgetRegistry.editMode || false,
// -------------
display: shellStateData.display || {},
notificationsState: shellStateData.notificationsState || {},
changelogState: shellStateData.changelogState || {},
colorSchemesList: shellStateData.colorSchemesList || {},
ui: shellStateData.ui || {}
}
};
} catch (error) {
Logger.e("Settings", "Failed to build state snapshot:", error);
return null;
}
}
}
@@ -0,0 +1,203 @@
pragma Singleton
import QtQuick
import Quickshell
import qs.compat.noctalia.Services.Power
import "../../../theme" as G
import "../../../core" as Core
Singleton {
id: root
// glassMxrph: radii, bar sizes, animation and panel opacity follow the
// glassMxrph theme so Noctalia plugins match the shell.
readonly property real glassRadiusRatio: G.Theme.radius / 20
readonly property real glassBarHeight: Core.BarDrawers.height
readonly property real glassCapsuleHeight: Core.ModuleRegistry.pillHeight
// Font size
readonly property real fontSizeXXS: 8
readonly property real fontSizeXS: 9
readonly property real fontSizeS: 10
readonly property real fontSizeM: 11
readonly property real fontSizeL: 13
readonly property real fontSizeXL: 16
readonly property real fontSizeXXL: 18
readonly property real fontSizeXXXL: 24
// Font weight
readonly property int fontWeightRegular: 400
readonly property int fontWeightMedium: 500
readonly property int fontWeightSemiBold: 600
readonly property int fontWeightBold: 700
// Container Radii: major layout sections (sidebars, cards, content panels)
readonly property int radiusXXXS: Math.round(3 * root.glassRadiusRatio)
readonly property int radiusXXS: Math.round(4 * root.glassRadiusRatio)
readonly property int radiusXS: Math.round(8 * root.glassRadiusRatio)
readonly property int radiusS: Math.round(12 * root.glassRadiusRatio)
readonly property int radiusM: Math.round(16 * root.glassRadiusRatio)
readonly property int radiusL: Math.round(20 * root.glassRadiusRatio)
// Input radii: interactive elements (buttons, toggles, text fields)
readonly property int iRadiusXXXS: Math.round(3 * root.glassRadiusRatio)
readonly property int iRadiusXXS: Math.round(4 * root.glassRadiusRatio)
readonly property int iRadiusXS: Math.round(8 * root.glassRadiusRatio)
readonly property int iRadiusS: Math.round(12 * root.glassRadiusRatio)
readonly property int iRadiusM: Math.round(16 * root.glassRadiusRatio)
readonly property int iRadiusL: Math.round(20 * root.glassRadiusRatio)
readonly property int screenRadius: Math.round(20 * Settings.data.general.screenRadiusRatio)
// Border
readonly property int borderS: Math.max(1, Math.round(1 * uiScaleRatio))
readonly property int borderM: Math.max(1, Math.round(2 * uiScaleRatio))
readonly property int borderL: Math.max(1, Math.round(3 * uiScaleRatio))
// Margins (for margins and spacing)
readonly property int marginXXXS: Math.round(1 * uiScaleRatio)
readonly property int marginXXS: Math.round(2 * uiScaleRatio)
readonly property int marginXS: Math.round(4 * uiScaleRatio)
readonly property int marginS: Math.round(6 * uiScaleRatio)
readonly property int marginM: Math.round(9 * uiScaleRatio)
readonly property int marginL: Math.round(13 * uiScaleRatio)
readonly property int marginXL: Math.round(18 * uiScaleRatio)
// Double margins, for proper container sizing only (e.g. height: id.implicitHeight + Style.margin2M)
readonly property int margin2XXXS: marginXXXS * 2
readonly property int margin2XXS: marginXXS * 2
readonly property int margin2XS: marginXS * 2
readonly property int margin2S: marginS * 2
readonly property int margin2M: marginM * 2
readonly property int margin2L: marginL * 2
readonly property int margin2XL: marginXL * 2
// Opacity
readonly property real opacityNone: 0.0
readonly property real opacityLight: 0.25
readonly property real opacityMedium: 0.5
readonly property real opacityHeavy: 0.75
readonly property real opacityAlmost: 0.95
readonly property real opacityFull: 1.0
readonly property real effectivePanelOpacity: G.Theme.glassOpacity
readonly property real effectiveBarOpacity: G.Theme.glassOpacity
// Shadows
readonly property real shadowOpacity: 0.85
readonly property real shadowBlur: 1.0
readonly property int shadowBlurMax: 22
readonly property real shadowHorizontalOffset: Settings.data.general.shadowOffsetX
readonly property real shadowVerticalOffset: Settings.data.general.shadowOffsetY
// Animation duration (ms)
readonly property int animationFaster: Math.round(G.Theme.duration * 0.35)
readonly property int animationFast: Math.round(G.Theme.duration * 0.7)
readonly property int animationNormal: Math.round(G.Theme.duration * 1.3)
readonly property int animationSlow: Math.round(G.Theme.duration * 2)
readonly property int animationSlowest: Math.round(G.Theme.duration * 3.3)
// Delays
readonly property int tooltipDelay: 300
readonly property int tooltipDelayLong: 1200
readonly property int pillDelay: 500
// Widgets base size
readonly property real baseWidgetSize: 33
readonly property real sliderWidth: 200
readonly property real uiScaleRatio: 1.0
// Bar Height
readonly property real barHeight: glassBarHeight
readonly property real capsuleHeight: glassCapsuleHeight
readonly property real _barBaseFontSize: 12
readonly property real barFontSize: 12
readonly property color capsuleColor: "transparent"
readonly property color capsuleBorderColor: "transparent"
readonly property int capsuleBorderWidth: 0
readonly property color boxBorderColor: Color.mOutline
// Pixel-perfect utility for centering content without subpixel positioning
function pixelAlignCenter(containerSize, contentSize) {
return Math.round((containerSize - contentSize) / 2);
}
// Ensures a number is always odd (rounds down to nearest odd)
function toOdd(n) {
return Math.floor(n / 2) * 2 + 1;
}
// Ensures a number is always even (rounds down to nearest even)
function toEven(n) {
return Math.floor(n / 2) * 2;
}
// Get bar height for a specific density and orientation
function getBarHeightForDensity(density, isVertical) {
let h;
switch (density) {
case "mini":
h = isVertical ? 23 : 21;
break;
case "compact":
h = isVertical ? 27 : 25;
break;
case "comfortable":
h = isVertical ? 39 : 37;
break;
case "spacious":
h = isVertical ? 49 : 47;
break;
default:
case "default":
h = isVertical ? 33 : 31;
}
return toOdd(h);
}
// Get capsule height for a specific density and bar height
function getCapsuleHeightForDensity(density, barHeight) {
let h;
switch (density) {
case "mini":
h = Math.round(barHeight * 0.90);
break;
case "compact":
h = Math.round(barHeight * 0.85);
break;
case "comfortable":
h = Math.round(barHeight * 0.75);
break;
case "spacious":
h = Math.round(barHeight * 0.65);
break;
default:
h = Math.round(barHeight * 0.82);
break;
}
return toOdd(h);
}
// Get bar font size for a specific bar height, capsule height, and orientation
function getBarFontSizeForDensity(barHeight, capsuleHeight, isVertical) {
const baseFontSize = Math.max(1, (barHeight / capsuleHeight) * Style.fontSizeXXS);
return isVertical ? baseFontSize * 0.9 * Settings.data.bar.fontScale : baseFontSize * Settings.data.bar.fontScale;
}
// Convenience functions for per-screen bar sizing
function getBarHeightForScreen(screenName) {
return glassBarHeight;
}
function getCapsuleHeightForScreen(screenName) {
return glassCapsuleHeight;
}
function getBarFontSizeForScreen(screenName) {
return barFontSize;
}
}
@@ -0,0 +1,289 @@
pragma Singleton
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
Singleton {
id: root
property real scoreThreshold: 0.2
// Manual overrides for tricky apps
property var substitutions: ({
"code-url-handler": "visual-studio-code",
"Code": "visual-studio-code",
"gnome-tweaks": "org.gnome.tweaks",
"pavucontrol-qt": "pavucontrol",
"wps": "wps-office2019-kprometheus",
"wpsoffice": "wps-office2019-kprometheus",
"footclient": "foot"
})
// Dynamic fixups
property var regexSubstitutions: [
{
"regex": /^steam_app_(\d+)$/,
"replace": "steam_icon_$1"
},
{
"regex": /Minecraft.*/,
"replace": "minecraft-launcher"
},
{
"regex": /.*polkit.*/,
"replace": "system-lock-screen"
},
{
"regex": /gcr.prompter/,
"replace": "system-lock-screen"
}
]
property list<DesktopEntry> entryList: []
property var preppedNames: []
property var preppedIcons: []
property var preppedIds: []
Component.onCompleted: refreshEntries()
Connections {
target: DesktopEntries.applications
function onValuesChanged() {
refreshEntries();
}
}
function refreshEntries() {
if (typeof DesktopEntries === 'undefined')
return;
const values = Array.from(DesktopEntries.applications.values);
if (values) {
entryList = values.sort((a, b) => a.name.localeCompare(b.name));
updatePreppedData();
}
}
function updatePreppedData() {
if (typeof FuzzySort === 'undefined')
return;
const list = Array.from(entryList);
preppedNames = list.map(a => ({
name: FuzzySort.prepare(`${a.name} `),
entry: a
}));
preppedIcons = list.map(a => ({
name: FuzzySort.prepare(`${a.icon} `),
entry: a
}));
preppedIds = list.map(a => ({
name: FuzzySort.prepare(`${a.id} `),
entry: a
}));
}
function iconForAppId(appId, fallbackName) {
const fallback = fallbackName || "application-x-executable";
if (!appId)
return iconFromName(fallback, fallback);
const entry = findAppEntry(appId);
if (entry) {
return iconFromName(entry.icon, fallback);
}
return iconFromName(appId, fallback);
}
// Robust lookup strategy
function findAppEntry(str) {
if (!str || str.length === 0)
return null;
let result = null;
if (result = checkHeuristic(str))
return result;
if (result = checkSubstitutions(str))
return result;
if (result = checkRegex(str))
return result;
if (result = checkSimpleTransforms(str))
return result;
if (result = checkFuzzySearch(str))
return result;
if (result = checkCleanMatch(str))
return result;
return null;
}
function iconFromName(iconName, fallbackName) {
const fallback = fallbackName || "application-x-executable";
try {
if (iconName && typeof Quickshell !== 'undefined' && Quickshell.iconPath) {
const p = Quickshell.iconPath(iconName, fallback);
if (p && p !== "")
return p;
}
} catch (e) {}
try {
return Quickshell.iconPath ? (Quickshell.iconPath(fallback, true) || "") : "";
} catch (e2) {
return "";
}
}
function distroLogoPath() {
try {
return (typeof OSInfo !== 'undefined' && OSInfo.distroIconPath) ? OSInfo.distroIconPath : "";
} catch (e) {
return "";
}
}
// --- Lookup Helpers ---
function checkHeuristic(str) {
if (typeof DesktopEntries !== 'undefined' && DesktopEntries.heuristicLookup) {
const entry = DesktopEntries.heuristicLookup(str);
if (entry)
return entry;
}
return null;
}
function checkSubstitutions(str) {
let effectiveStr = substitutions[str];
if (!effectiveStr)
effectiveStr = substitutions[str.toLowerCase()];
if (effectiveStr && effectiveStr !== str) {
return findAppEntry(effectiveStr);
}
return null;
}
function checkRegex(str) {
for (let i = 0; i < regexSubstitutions.length; i++) {
const sub = regexSubstitutions[i];
const replaced = str.replace(sub.regex, sub.replace);
if (replaced !== str) {
return findAppEntry(replaced);
}
}
return null;
}
function checkSimpleTransforms(str) {
if (typeof DesktopEntries === 'undefined' || !DesktopEntries.byId)
return null;
const lower = str.toLowerCase();
const variants = [str, lower, getFromReverseDomain(str), getFromReverseDomain(str)?.toLowerCase(), normalizeWithHyphens(str), str.replace(/_/g, '-').toLowerCase(), str.replace(/-/g, '_').toLowerCase()];
for (let i = 0; i < variants.length; i++) {
const variant = variants[i];
if (variant) {
const entry = DesktopEntries.byId(variant);
if (entry)
return entry;
}
}
return null;
}
function checkFuzzySearch(str) {
if (typeof FuzzySort === 'undefined')
return null;
// Check filenames (IDs) first
if (preppedIds.length > 0) {
let results = fuzzyQuery(str, preppedIds);
if (results.length === 0) {
const underscored = str.replace(/-/g, '_').toLowerCase();
if (underscored !== str)
results = fuzzyQuery(underscored, preppedIds);
}
if (results.length > 0)
return results[0];
}
// Then icons
if (preppedIcons.length > 0) {
const results = fuzzyQuery(str, preppedIcons);
if (results.length > 0)
return results[0];
}
// Then names
if (preppedNames.length > 0) {
const results = fuzzyQuery(str, preppedNames);
if (results.length > 0)
return results[0];
}
return null;
}
function checkCleanMatch(str) {
if (!str || str.length <= 3)
return null;
if (typeof DesktopEntries === 'undefined' || !DesktopEntries.byId)
return null;
// Aggressive fallback: strip all separators
const cleanStr = str.toLowerCase().replace(/[\.\-_]/g, '');
const list = Array.from(entryList);
for (let i = 0; i < list.length; i++) {
const entry = list[i];
const cleanId = (entry.id || "").toLowerCase().replace(/[\.\-_]/g, '');
if (cleanId.includes(cleanStr) || cleanStr.includes(cleanId)) {
return entry;
}
}
return null;
}
function fuzzyQuery(search, preppedData) {
if (!search || !preppedData || preppedData.length === 0)
return [];
return FuzzySort.go(search, preppedData, {
all: true,
key: "name"
}).map(r => r.obj.entry);
}
function iconExists(iconName) {
if (!iconName || iconName.length === 0)
return false;
if (iconName.startsWith("/"))
return true;
const path = Quickshell.iconPath(iconName, true);
return path && path.length > 0 && !path.includes("image-missing");
}
function getFromReverseDomain(str) {
if (!str)
return "";
return str.split('.').slice(-1)[0];
}
function normalizeWithHyphens(str) {
if (!str)
return "";
return str.toLowerCase().replace(/\s+/g, "-");
}
// Deprecated shim
function guessIcon(str) {
const entry = findAppEntry(str);
return entry ? entry.icon : "image-missing";
}
}
+232
View File
@@ -0,0 +1,232 @@
pragma Singleton
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.System
Singleton {
id: root
// Current date
property var now: new Date()
// Unix timestamp of the last update
property real _lastUpdateTs: Date.now()
// Signal emitted when a significant time jump is detected (e.g. system resume)
signal resumed
// Returns a Unix Timestamp (in seconds)
readonly property int timestamp: {
return Math.floor(root.now / 1000);
}
// Timer state (for countdown/stopwatch)
property bool timerRunning: false
property bool timerStopwatchMode: false
property int timerRemainingSeconds: 0
property int timerTotalSeconds: 0
property int timerElapsedSeconds: 0
property bool timerSoundPlaying: false
property int timerStartTimestamp: 0 // Unix timestamp when timer was started
property int timerPausedAt: 0 // Value when paused (for resuming)
Timer {
id: updateTimer
interval: 1000
repeat: true
running: true
triggeredOnStart: false
onTriggered: {
var newTime = new Date();
var currentTs = newTime.getTime();
// Detect time jump (e.g. system resume) - threshold: 5 seconds
if (currentTs - root._lastUpdateTs > 5000) {
Logger.i("Time", "Time jump detected (" + Math.round((currentTs - root._lastUpdateTs) / 1000) + "s) - likely system resume");
root.resumed();
}
root._lastUpdateTs = currentTs;
root.now = newTime;
// Update timer if running
if (root.timerRunning && root.timerStartTimestamp > 0) {
const elapsedSinceStart = root.timestamp - root.timerStartTimestamp;
if (root.timerStopwatchMode) {
root.timerElapsedSeconds = root.timerPausedAt + elapsedSinceStart;
} else {
root.timerRemainingSeconds = root.timerTotalSeconds - elapsedSinceStart;
if (root.timerRemainingSeconds <= 0) {
root.timerOnFinished();
}
}
}
// Adjust next interval to sync with the start of the next second
var msIntoSecond = newTime.getMilliseconds();
if (msIntoSecond > 100) {
// If we're more than 100ms into the second, adjust for next time
updateTimer.interval = 1000 - msIntoSecond + 10; // +10ms buffer
updateTimer.restart();
} else {
updateTimer.interval = 1000;
}
}
}
Component.onCompleted: {
// Start by syncing to the next second boundary
var now = new Date();
var msUntilNextSecond = 1000 - now.getMilliseconds();
updateTimer.interval = msUntilNextSecond + 10; // +10ms buffer
updateTimer.restart();
}
// Formats a Date object into a YYYYMMDD-HHMMSS string.
function getFormattedTimestamp(date) {
if (!date) {
date = new Date();
}
const year = date.getFullYear();
// getMonth() is zero-based, so we add 1
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}${month}${day}-${hours}${minutes}${seconds}`;
}
// Format an easy to read approximate duration ex: 4h 32m
// Used to display the time remaining on the Battery widget, computer uptime, etc..
function formatVagueHumanReadableDuration(totalSeconds) {
if (typeof totalSeconds !== 'number' || totalSeconds < 0) {
return '0s';
}
// Floor the input to handle decimal seconds
totalSeconds = Math.floor(totalSeconds);
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor((totalSeconds % 86400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
const parts = [];
if (days)
parts.push(`${days}d`);
if (hours)
parts.push(`${hours}h`);
if (minutes)
parts.push(`${minutes}m`);
// Only show seconds if no hours and no minutes
if (!hours && !minutes) {
parts.push(`${seconds}s`);
}
return parts.join(' ');
}
// Format a date into
function formatRelativeTime(date) {
if (!date)
return "";
const diff = Date.now() - date.getTime();
if (diff < 60000)
return I18n.tr("notifications.time.now");
if (diff < 120000)
return I18n.tr("notifications.time.diff-m");
if (diff < 3600000)
return I18n.tr("notifications.time.diff-mm", {
"diff": Math.floor(diff / 60000)
});
if (diff < 7200000)
return I18n.tr("notifications.time.diff-h");
if (diff < 86400000)
return I18n.tr("notifications.time.diff-hh", {
"diff": Math.floor(diff / 3600000)
});
if (diff < 172800000)
return I18n.tr("notifications.time.diff-d");
return I18n.tr("notifications.time.diff-dd", {
"diff": Math.floor(diff / 86400000)
});
}
// Timer functions
function timerStart() {
if (root.timerStopwatchMode) {
root.timerRunning = true;
root.timerStartTimestamp = root.timestamp;
root.timerPausedAt = root.timerElapsedSeconds;
} else {
if (root.timerRemainingSeconds <= 0) {
return;
}
root.timerRunning = true;
root.timerTotalSeconds = root.timerRemainingSeconds;
root.timerStartTimestamp = root.timestamp;
root.timerPausedAt = 0;
}
}
function timerPause() {
if (root.timerRunning) {
// Calculate and set remainingSeconds BEFORE changing timerRunning
// This ensures the UI sees the correct value when it reacts to timerRunning changing
if (root.timerStopwatchMode) {
root.timerPausedAt = root.timerElapsedSeconds;
} else {
// Calculate remaining seconds at the exact moment of pause
// Use current time directly to avoid stale timestamp issues
const currentTimestamp = Math.floor(Date.now() / 1000);
const elapsedSinceStart = currentTimestamp - root.timerStartTimestamp;
const currentRemaining = root.timerTotalSeconds - elapsedSinceStart;
root.timerPausedAt = Math.max(0, currentRemaining);
// CRITICAL: Update timerRemainingSeconds to the paused value BEFORE changing timerRunning
// This ensures UI sees correct value when it reacts to timerRunning change
root.timerRemainingSeconds = root.timerPausedAt;
}
}
root.timerRunning = false;
root.timerStartTimestamp = 0;
// Stop any repeating notification sound when pausing
SoundService.stopSound("alarm-beep.wav");
root.timerSoundPlaying = false;
}
function timerReset() {
root.timerRunning = false;
root.timerStartTimestamp = 0;
if (root.timerStopwatchMode) {
root.timerElapsedSeconds = 0;
root.timerPausedAt = 0;
} else {
root.timerRemainingSeconds = 0;
root.timerTotalSeconds = 0;
root.timerPausedAt = 0;
}
// Stop any repeating notification sound
SoundService.stopSound("alarm-beep.wav");
root.timerSoundPlaying = false;
}
function timerOnFinished() {
root.timerRunning = false;
root.timerRemainingSeconds = 0;
// Play notification sound with repeat at lower volume
root.timerSoundPlaying = true;
SoundService.playSound("alarm-beep.wav", {
repeat: true,
volume: 0.3
});
}
}
@@ -0,0 +1,161 @@
// AdvancedMath.js - Lightweight math library for Noctalia Calculator
// Provides advanced mathematical functions beyond basic arithmetic
// Helper function to convert degrees to radians
function toRadians(degrees) {
return degrees * (Math.PI / 180);
}
// Helper function to convert radians to degrees
function toDegrees(radians) {
return radians * (180 / Math.PI);
}
// Constants
var constants = {
PI: Math.PI,
E: Math.E,
LN2: Math.LN2,
LN10: Math.LN10,
LOG2E: Math.LOG2E,
LOG10E: Math.LOG10E,
SQRT1_2: Math.SQRT1_2,
SQRT2: Math.SQRT2
};
// Safe evaluation function that handles advanced math
function evaluate(expression) {
try {
// Fixes decimal arithmetic
var cleanExpr = expression.replace(/\s+/g, '').toLowerCase();
// Allows numbers (including decimals), basic operators, and explicitly permitted math terms only
var safeRegex = /^(\d*\.?\d+|[+\-*/()^%,]|sin|cos|tan|asin|acos|atan|atan2|sinh|cosh|tanh|asinh|acosh|atanh|log|ln|exp|pow|sqrt|cbrt|abs|floor|ceil|round|trunc|min|max|random|pi|e|sind|cosd|tand)+$/;
if (!safeRegex.test(cleanExpr)) {
throw new Error("Invalid characters or unauthorized functions in expression");
}
// Replace mathematical constants (Original Structure)
var processed = cleanExpr
.replace(/\bpi\b/gi, Math.PI)
.replace(/\be\b/gi, Math.E);
// Replace function calls with Math object equivalents
processed = processed
// Trigonometric functions
.replace(/\bsin\s*\(/g, 'Math.sin(')
.replace(/\bcos\s*\(/g, 'Math.cos(')
.replace(/\btan\s*\(/g, 'Math.tan(')
.replace(/\basin\s*\(/g, 'Math.asin(')
.replace(/\bacos\s*\(/g, 'Math.acos(')
.replace(/\batan\s*\(/g, 'Math.atan(')
.replace(/\batan2\s*\(/g, 'Math.atan2(')
// Hyperbolic functions
.replace(/\bsinh\s*\(/g, 'Math.sinh(')
.replace(/\bcosh\s*\(/g, 'Math.cosh(')
.replace(/\btanh\s*\(/g, 'Math.tanh(')
.replace(/\basinh\s*\(/g, 'Math.asinh(')
.replace(/\bacosh\s*\(/g, 'Math.acosh(')
.replace(/\batanh\s*\(/g, 'Math.atanh(')
// Logarithmic and exponential functions
.replace(/\blog\s*\(/g, 'Math.log10(')
.replace(/\bln\s*\(/g, 'Math.log(')
.replace(/\bexp\s*\(/g, 'Math.exp(')
.replace(/\bpow\s*\(/g, 'Math.pow(')
// Root functions
.replace(/\bsqrt\s*\(/g, 'Math.sqrt(')
.replace(/\bcbrt\s*\(/g, 'Math.cbrt(')
// Rounding and absolute
.replace(/\babs\s*\(/g, 'Math.abs(')
.replace(/\bfloor\s*\(/g, 'Math.floor(')
.replace(/\bceil\s*\(/g, 'Math.ceil(')
.replace(/\bround\s*\(/g, 'Math.round(')
.replace(/\btrunc\s*\(/g, 'Math.trunc(')
// Min/Max
.replace(/\bmin\s*\(/g, 'Math.min(')
.replace(/\bmax\s*\(/g, 'Math.max(')
// Random
.replace(/\brandom\s*\(\s*\)/g, 'Math.random()');
// Handle degree versions of trig functions
processed = processed
.replace(/\bsind\s*\(/g, '(function(x) { return Math.sin(' + (Math.PI / 180) + ' * x); })(')
.replace(/\bcosd\s*\(/g, '(function(x) { return Math.cos(' + (Math.PI / 180) + ' * x); })(')
.replace(/\btand\s*\(/g, '(function(x) { return Math.tan(' + (Math.PI / 180) + ' * x); })(');
// Handle ^ for exponentiation: convert 2^3 to Math.pow(2,3)
processed = processed.replace(/([\d.]+|\))\^([\d.]+|\([^)]*\))/g, 'Math.pow($1,$2)');
// Replacing eval() with a scoped function constructor
// This is safe because the strict whitelist guarantees only math reaches this point
var result = new Function('return ' + processed)();
if (!isFinite(result) || isNaN(result)) {
throw new Error("Invalid result");
}
return result;
} catch (error) {
throw new Error("Evaluation failed: " + error.message);
}
}
// Format result for display
function formatResult(result) {
if (Number.isInteger(result)) {
return result.toString();
}
// Handle very large or very small numbers
if (Math.abs(result) >= 1e15 || (Math.abs(result) < 1e-6 && result !== 0)) {
return result.toExponential(6);
}
// Normal decimal formatting
return parseFloat(result.toFixed(10)).toString();
}
// Get list of available functions for help
function getAvailableFunctions() {
return [
// Basic arithmetic: +, -, *, /, %, ^, ()
// Trigonometric functions
"sin(x), cos(x), tan(x) - trigonometric functions (radians)",
"sind(x), cosd(x), tand(x) - trigonometric functions (degrees)",
"asin(x), acos(x), atan(x) - inverse trigonometric",
"atan2(y, x) - two-argument arctangent",
// Hyperbolic functions
"sinh(x), cosh(x), tanh(x) - hyperbolic functions",
"asinh(x), acosh(x), atanh(x) - inverse hyperbolic",
// Logarithmic and exponential
"log(x) - base 10 logarithm",
"ln(x) - natural logarithm",
"exp(x) - e^x",
"pow(x, y) - x^y",
// Root functions
"sqrt(x) - square root",
"cbrt(x) - cube root",
// Rounding and absolute
"abs(x) - absolute value",
"floor(x), ceil(x), round(x), trunc(x)",
// Min/Max/Random
"min(a, b, ...), max(a, b, ...)",
"random() - random number 0-1",
// Constants
"pi, e - mathematical constants"
];
}
@@ -0,0 +1,127 @@
.pragma library
// Address helpers
var macFromDevice = (dev) => {
if (!dev) return "";
if (dev.address && dev.address.length > 0) return dev.address;
if (dev.nativePath && dev.nativePath.indexOf("/dev_") !== -1)
return dev.nativePath.split("dev_")[1].split("_").join(":");
return "";
};
var deviceKey = (dev) => {
if (!dev) return "";
if (dev.address && dev.address.length > 0) return dev.address.toUpperCase();
if (dev.nativePath && dev.nativePath.length > 0) return dev.nativePath;
if (dev.devicePath && dev.devicePath.length > 0) return dev.devicePath;
return (dev.name || dev.deviceName || "") + "|" + (dev.icon || "");
};
var dedupeDevices = (list) => {
if (!list || list.length === 0) return [];
var seen = ({});
var out = [];
for (var i = 0; i < list.length; ++i) {
var d = list[i];
if (!d) continue;
var k = deviceKey(d);
if (k && !seen[k]) { seen[k] = true; out.push(d); }
}
return out;
};
// RSSI parsing
var parseRssiOutput = (text) => {
try {
text = text || "";
var mParen = text.match(/\(\s*(-?\d+)\s*(?:d?b?m?)?\s*\)/i);
if (mParen && mParen.length > 1) return Number(mParen[1]);
var mDec = text.match(/RSSI:\s*(-?\d+)/i);
if (mDec && mDec.length > 1) return Number(mDec[1]);
var mHex = text.match(/RSSI:\s*0x([0-9a-fA-F]+)/i);
if (mHex && mHex.length > 1) {
var v = parseInt(mHex[1], 16);
if (v >= 0x80000000) v = v - 0x100000000; // 32-bit two's complement
else if (v >= 0x8000) v = v - 0x10000; // 16-bit
else if (v >= 0x80) v = v - 0x100; // 8-bit
return v;
}
} catch (e) {}
return null;
};
var dbmToPercent = (dbm) => {
if (dbm === null || dbm === undefined || isNaN(dbm)) return null;
// Clamp simple linear map roughly from -100..0 dBm to 0..100%
var pct = Math.round((Number(dbm) + 100) * 2);
if (isNaN(pct)) return null;
return Math.max(0, Math.min(100, pct));
};
// Signal helpers
var signalPercent = (device, cache, _version) => {
if (!device) return null;
try {
var addr = macFromDevice(device);
if (addr && cache && cache[addr] !== undefined) {
var cached = Number(cache[addr]) | 0;
return Math.max(0, Math.min(100, cached));
}
} catch (e) {}
var s = device && device.signalStrength;
if (s === undefined || s <= 0) return null;
var p = Number(s) | 0;
return Math.max(0, Math.min(100, p));
};
var signalIcon = (p) => {
if (p === null) return "antenna-bars-off";
if (p >= 80) return "antenna-bars-5";
if (p >= 60) return "antenna-bars-4";
if (p >= 40) return "antenna-bars-3";
if (p >= 20) return "antenna-bars-2";
return "antenna-bars-1";
};
// Icon mapping
var deviceIcon = (name, icon) => {
var s1 = String(name || "").toLowerCase();
var s2 = String(icon || "").toLowerCase();
// Prefer icon-based hints for display devices first to avoid "audio" catching TVs
var displayHints = ["display", "tv", "monitor", "projector", "screen", "chromecast", "cast"];
for (var dh = 0; dh < displayHints.length; dh++) {
if (s2.indexOf(displayHints[dh]) !== -1) return "bt-device-tv";
}
var tests = [
[["controller", "gamepad"], "bt-device-gamepad"],
[["microphone"], "bt-device-microphone"],
[["pod", "bud", "minor"], "bt-device-earbuds"],
[["headset", "arctis", "major"], "bt-device-headset"],
[["headphone"], "bt-device-headphones"],
[["mouse"], "bt-device-mouse"],
[["keyboard"], "bt-device-keyboard"],
[["watch"], "bt-device-watch"],
[["display", "tv", "monitor", "projector", "screen", "chromecast", "cast"], "bt-device-tv"],
[["speaker", "audio", "sound"], "bt-device-speaker"],
[["phone", "iphone", "android", "samsung"], "bt-device-phone"]
];
for (var i = 0; i < tests.length; i++) {
var keys = tests[i][0];
var out = tests[i][1];
for (var j = 0; j < keys.length; j++) {
var k = keys[j];
if (s1.indexOf(k) !== -1 || s2.indexOf(k) !== -1) return out;
}
}
return "bt-device-generic";
};
// Battery percent helper
var batteryPercent = (device) => {
if (!device || !device.batteryAvailable || device.battery === undefined) return null;
var val = Math.round(Number(device.battery) * 100);
if (isNaN(val)) return null;
return Math.max(0, Math.min(100, val));
};
@@ -0,0 +1,187 @@
var colors = [
// --- REDS ---
{ name: "MistyRose", color: "mistyrose" },
{ name: "LightPink", color: "lightpink" },
{ name: "Pink", color: "pink" },
{ name: "PaleVioletRed", color: "palevioletred" },
{ name: "Pink 500", color: "#E91E63" }, // Material
{ name: "HotPink", color: "hotpink" },
{ name: "DeepPink", color: "deeppink" },
{ name: "MediumVioletRed", color: "mediumvioletred" },
{ name: "LightSalmon", color: "lightsalmon" },
{ name: "Salmon", color: "salmon" },
{ name: "DarkSalmon", color: "darksalmon" },
{ name: "LightCoral", color: "lightcoral" },
{ name: "IndianRed", color: "indianred" },
{ name: "Alizarin", color: "#E74C3C" }, // Flat UI
{ name: "Red 500", color: "#F44336" }, // Material
{ name: "Crimson", color: "crimson" },
{ name: "Red", color: "red" },
{ name: "FireBrick", color: "firebrick" },
{ name: "DarkRed", color: "darkred" },
{ name: "Maroon", color: "maroon" },
{ name: "Brown", color: "brown" },
// --- ORANGES & BROWNS ---
{ name: "Coral", color: "coral" },
{ name: "Tomato", color: "tomato" },
{ name: "OrangeRed", color: "orangered" },
{ name: "Deep Orange 500", color: "#FF5722" }, // Material
{ name: "DarkOrange", color: "darkorange" },
{ name: "Carrot", color: "#E67E22" }, // Flat UI
{ name: "Orange 500", color: "#FF9800" }, // Material
{ name: "Orange", color: "orange" },
{ name: "SandyBrown", color: "sandybrown" },
{ name: "Peru", color: "peru" },
{ name: "Chocolate", color: "chocolate" },
{ name: "SaddleBrown", color: "saddlebrown" },
{ name: "Sienna", color: "sienna" },
{ name: "Brown 500", color: "#795548" }, // Material
// --- YELLOWS, BEIGES & GOLDS ---
{ name: "LightYellow", color: "lightyellow" },
{ name: "LemonChiffon", color: "lemonchiffon" },
{ name: "LightGoldenrodYellow", color: "lightgoldenrodyellow" },
{ name: "PapayaWhip", color: "papayawhip" },
{ name: "Moccasin", color: "moccasin" },
{ name: "PeachPuff", color: "peachpuff" },
{ name: "NavajoWhite", color: "navajowhite" },
{ name: "Wheat", color: "wheat" },
{ name: "BurlyWood", color: "burlywood" },
{ name: "Tan", color: "tan" },
{ name: "Bisque", color: "bisque" },
{ name: "BlanchedAlmond", color: "blanchedalmond" },
{ name: "Cornsilk", color: "cornsilk" },
{ name: "PaleGoldenrod", color: "palegoldenrod" },
{ name: "Khaki", color: "khaki" },
{ name: "DarkKhaki", color: "darkkhaki" },
{ name: "Goldenrod", color: "goldenrod" },
{ name: "DarkGoldenrod", color: "darkgoldenrod" },
{ name: "Sun Flower", color: "#F1C40F" }, // Flat UI
{ name: "Yellow 500", color: "#FFEB3B" }, // Material
{ name: "Yellow", color: "yellow" },
{ name: "Gold", color: "gold" },
{ name: "Amber 500", color: "#FFC107" }, // Material
// --- GREENS ---
{ name: "GreenYellow", color: "greenyellow" },
{ name: "Chartreuse", color: "chartreuse" },
{ name: "LawnGreen", color: "lawngreen" },
{ name: "Lime 500", color: "#CDDC39" }, // Material
{ name: "Lime", color: "lime" },
{ name: "LimeGreen", color: "limegreen" },
{ name: "PaleGreen", color: "palegreen" },
{ name: "LightGreen", color: "lightgreen" },
{ name: "Light Green 500", color: "#8BC34A" }, // Material
{ name: "MediumSpringGreen", color: "mediumspringgreen" },
{ name: "SpringGreen", color: "springgreen" },
{ name: "Emerald", color: "#2ECC71" }, // Flat UI
{ name: "Green 500", color: "#4CAF50" }, // Material
{ name: "MediumSeaGreen", color: "mediumseagreen" },
{ name: "SeaGreen", color: "seagreen" },
{ name: "ForestGreen", color: "forestgreen" },
{ name: "Green", color: "green" },
{ name: "DarkGreen", color: "darkgreen" },
{ name: "YellowGreen", color: "yellowgreen" },
{ name: "OliveDrab", color: "olivedrab" },
{ name: "Olive", color: "olive" },
{ name: "DarkOliveGreen", color: "darkolivegreen" },
// --- TEALS & CYANS ---
{ name: "MediumAquamarine", color: "mediumaquamarine" },
{ name: "DarkSeaGreen", color: "darkseagreen" },
{ name: "LightSeaGreen", color: "lightseagreen" },
{ name: "DarkCyan", color: "darkcyan" },
{ name: "Teal", color: "teal" },
{ name: "Turquoise", color: "#1ABC9C" }, // Flat UI
{ name: "LightCyan", color: "lightcyan" },
{ name: "PaleTurquoise", color: "paleturquoise" },
{ name: "Aquamarine", color: "aquamarine" },
{ name: "Turquoise", color: "turquoise" },
{ name: "MediumTurquoise", color: "mediumturquoise" },
{ name: "DarkTurquoise", color: "darkturquoise" },
{ name: "Aqua", color: "aqua" },
{ name: "Cyan", color: "cyan" },
{ name: "Cyan 500", color: "#00BCD4" }, // Material
{ name: "CadetBlue", color: "cadetblue" },
{ name: "Teal 500", color: "#009688" }, // Material
{ name: "DarkSlateGray", color: "darkslategray" },
// --- BLUES ---
{ name: "PowderBlue", color: "powderblue" },
{ name: "LightBlue", color: "lightblue" },
{ name: "SkyBlue", color: "skyblue" },
{ name: "LightSkyBlue", color: "lightskyblue" },
{ name: "Light Blue 500", color: "#03A9F4" }, // Material
{ name: "DeepSkyBlue", color: "deepskyblue" },
{ name: "DodgerBlue", color: "dodgerblue" },
{ name: "CornflowerBlue", color: "cornflowerblue" },
{ name: "Peter River", color: "#3498DB" }, // Flat UI
{ name: "Blue 500", color: "#2196F3" }, // Material
{ name: "SteelBlue", color: "steelblue" },
{ name: "LightSteelBlue", color: "lightsteelblue" },
{ name: "RoyalBlue", color: "royalblue" },
{ name: "Blue", color: "blue" },
{ name: "MediumBlue", color: "mediumblue" },
{ name: "Belize Hole", color: "#2980B9" }, // Flat UI
{ name: "DarkBlue", color: "darkblue" },
{ name: "Navy", color: "navy" },
{ name: "MidnightBlue", color: "midnightblue" },
{ name: "Midnight Blue", color: "#2C3E50" }, // Flat UI (Same name, different color)
{ name: "Indigo 500", color: "#3F51B5" }, // Material
{ name: "DarkSlateBlue", color: "darkslateblue" },
{ name: "MediumSlateBlue", color: "mediumslateblue" },
{ name: "SlateBlue", color: "slateblue" },
// --- PURPLES & MAGENTAS ---
{ name: "Lavender", color: "lavender" },
{ name: "Thistle", color: "thistle" },
{ name: "Plum", color: "plum" },
{ name: "Violet", color: "violet" },
{ name: "Orchid", color: "orchid" },
{ name: "Fuchsia", color: "fuchsia" },
{ name: "Magenta", color: "magenta" },
{ name: "MediumOrchid", color: "mediumorchid" },
{ name: "MediumPurple", color: "mediumpurple" },
{ name: "Amethyst", color: "#9B59B6" }, // Flat UI
{ name: "Purple 500", color: "#9C27B0" }, // Material
{ name: "BlueViolet", color: "blueviolet" },
{ name: "DarkViolet", color: "darkviolet" },
{ name: "DarkOrchid", color: "darkorchid" },
{ name: "DarkMagenta", color: "darkmagenta" },
{ name: "Purple", color: "purple" },
{ name: "Deep Purple 500", color: "#673AB7" }, // Material
{ name: "Indigo", color: "indigo" },
// --- NEUTRALS ---
{ name: "White", color: "white" },
{ name: "Snow", color: "snow" },
{ name: "HoneyDew", color: "honeydew" },
{ name: "MintCream", color: "mintcream" },
{ name: "Azure", color: "azure" },
{ name: "AliceBlue", color: "aliceblue" },
{ name: "GhostWhite", color: "ghostwhite" },
{ name: "WhiteSmoke", color: "whitesmoke" },
{ name: "Seashell", color: "seashell" },
{ name: "Beige", color: "beige" },
{ name: "OldLace", color: "oldlace" },
{ name: "FloralWhite", color: "floralwhite" },
{ name: "Ivory", color: "ivory" },
{ name: "AntiqueWhite", color: "antiquewhite" },
{ name: "Linen", color: "linen" },
{ name: "LavenderBlush", color: "lavenderblush" },
{ name: "Gainsboro", color: "gainsboro" },
{ name: "LightGray", color: "lightgray" },
{ name: "Silver", color: "silver" },
{ name: "DarkGray", color: "darkgray" },
{ name: "Gray", color: "gray" },
{ name: "Grey 500", color: "#9E9E9E" }, // Material
{ name: "Concrete", color: "#95A5A6" }, // Flat UI
{ name: "DimGray", color: "dimgray" },
{ name: "LightSlateGray", color: "lightslategray" },
{ name: "SlateGray", color: "slategray" },
{ name: "Asbestos", color: "#7F8C8D" }, // Flat UI
{ name: "Blue Grey 500", color: "#607D8B" }, // Material
{ name: "Wet Asphalt", color: "#34495E" }, // Flat UI
{ name: "Black", color: "black" }
]
@@ -0,0 +1,270 @@
// Convert hex color to HSL
function hexToHSL(hex) {
const rgb = hexToRgb(hex);
if (!rgb) return null;
return rgbToHsl(rgb.r, rgb.g, rgb.b);
}
// Convert HSL to hex color
function hslToHex(h, s, l) {
const rgb = hslToRgb(h, s, l);
return rgbToHex(rgb.r, rgb.g, rgb.b);
}
// Convert hex color to RGB
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : { r: 0, g: 0, b: 0 };
}
// Convert RGB to hex color
function rgbToHex(r, g, b) {
return "#" + [r, g, b].map(x => {
const hex = Math.round(Math.max(0, Math.min(255, x))).toString(16);
return hex.length === 1 ? "0" + hex : hex;
}).join("");
}
// Convert RGB to HSL
function rgbToHsl(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
}
return { h: h * 360, s: s * 100, l: l * 100 };
}
// Convert HSL to RGB
function hslToRgb(h, s, l) {
h /= 360;
s /= 100;
l /= 100;
let r, g, b;
if (s === 0) {
r = g = b = l;
} else {
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
}
// Convert RGB to HSV
function rgbToHsv(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max === 0 ? 0 : d / max;
if (max === min) {
h = 0;
} else {
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return { h: h * 360, s: s * 100, v: v * 100 };
}
// Convert HSV to RGB
function hsvToRgb(h, s, v) {
h /= 360;
s /= 100;
v /= 100;
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) };
}
// Calculate relative luminance (WCAG standard)
function getLuminance(hex) {
const rgb = hexToRgb(hex);
const [r, g, b] = [rgb.r, rgb.g, rgb.b].map(val => {
val /= 255;
return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
// Calculate contrast ratio between two colors
function getContrastRatio(hex1, hex2) {
const lum1 = getLuminance(hex1);
const lum2 = getLuminance(hex2);
const brightest = Math.max(lum1, lum2);
const darkest = Math.min(lum1, lum2);
return (brightest + 0.05) / (darkest + 0.05);
}
// Check if a color is considered "light"
function isLightColor(hex) {
return getLuminance(hex) > 0.5;
}
// Adjust color lightness
function adjustLightness(hex, amount) {
const hsl = hexToHSL(hex);
hsl.l = Math.max(0, Math.min(100, hsl.l + amount));
return hslToHex(hsl.h, hsl.s, hsl.l);
}
// Adjust color saturation
function adjustSaturation(hex, amount) {
const hsl = hexToHSL(hex);
hsl.s = Math.max(0, Math.min(100, hsl.s + amount));
return hslToHex(hsl.h, hsl.s, hsl.l);
}
// Adjust both lightness and saturation
function adjustLightnessAndSaturation(hex, lightnessAmount, saturationAmount) {
const hsl = hexToHSL(hex);
hsl.l = Math.max(0, Math.min(100, hsl.l + lightnessAmount));
hsl.s = Math.max(0, Math.min(100, hsl.s + saturationAmount));
return hslToHex(hsl.h, hsl.s, hsl.l);
}
// Generate "on" color with proper contrast (for text/icons)
function generateOnColor(baseColor, isDarkMode) {
const isBaseLight = isLightColor(baseColor);
// If base is light, we need dark text; if base is dark, we need light text
if (isBaseLight) {
// Try darker variants
let testColor = "#000000";
if (getContrastRatio(baseColor, testColor) >= 4.5) {
return testColor;
}
// Fallback to dark gray
return "#1c1b1f";
} else {
// Try lighter variants
let testColor = "#ffffff";
if (getContrastRatio(baseColor, testColor) >= 4.5) {
return testColor;
}
// Fallback to light gray
return "#e6e1e5";
}
}
// Generate container color (lighter in light mode, darker in dark mode)
function generateContainerColor(baseColor, isDarkMode) {
const rgb = hexToRgb(baseColor);
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
if (isDarkMode) {
// In dark mode, containers are darker and more saturated
hsl.l = Math.max(10, Math.min(30, hsl.l - 20));
hsl.s = Math.min(100, hsl.s + 10);
} else {
// In light mode, containers are lighter and less saturated
hsl.l = Math.min(90, Math.max(75, hsl.l + 30));
hsl.s = Math.max(0, hsl.s - 10);
}
const newRgb = hslToRgb(hsl.h, hsl.s, hsl.l);
return rgbToHex(newRgb.r, newRgb.g, newRgb.b);
}
// Generate surface variant colors
function generateSurfaceVariant(backgroundColor, step, isDarkMode) {
const rgb = hexToRgb(backgroundColor);
const hsl = rgbToHsl(rgb.r, rgb.g, rgb.b);
if (isDarkMode) {
// In dark mode, variants get progressively lighter
hsl.l = Math.min(100, hsl.l + (step * 3));
} else {
// In light mode, variants get progressively darker
hsl.l = Math.max(0, hsl.l - (step * 2));
}
const newRgb = hslToRgb(hsl.h, hsl.s, hsl.l);
return rgbToHex(newRgb.r, newRgb.g, newRgb.b);
}
@@ -0,0 +1,25 @@
// Helper function to stringify even if there are circular refs.
function stringify(obj, replacer, spaces, cycleReplacer) {
return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
}
function serializer(replacer, cycleReplacer) {
var stack = [], keys = []
if (cycleReplacer == null) cycleReplacer = function(key, value) {
if (stack[0] === value) return "[Circular ~]"
return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
}
return function(key, value) {
if (stack.length > 0) {
var thisPos = stack.indexOf(this)
~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
}
else stack.push(value)
return replacer == null ? value : replacer.call(this, key, value)
}
}
@@ -0,0 +1,114 @@
// -----------------------------------------------------
// Helper function to convert Qt objects to plain JavaScript objects
// Only used when generating settings-default.json
function qtObjectToPlainObject(obj) {
if (obj === null || obj === undefined) {
return obj;
}
// Handle primitive types
if (typeof obj !== "object") {
return obj;
}
// Handle native JavaScript arrays
if (Array.isArray(obj)) {
return obj.map((item) => qtObjectToPlainObject(item));
}
// Detect QML arrays FIRST (before color detection)
// QML arrays have a numeric length property and indexed properties
if (typeof obj.length === "number" && obj.length >= 0) {
// Check if it has indexed properties - be more flexible about detection
var hasIndexedProps = true;
var hasNumericKeys = false;
// Check if we have at least some numeric properties
for (var i = 0; i < obj.length; i++) {
if (obj.hasOwnProperty(i) || obj[i] !== undefined) {
hasNumericKeys = true;
break;
}
}
// If we have length > 0 and some numeric keys, treat as array
if (obj.length > 0 && hasNumericKeys) {
var arr = [];
for (var i = 0; i < obj.length; i++) {
// Use direct property access, handle undefined gracefully
var item = obj[i];
if (item !== undefined) {
arr.push(qtObjectToPlainObject(item));
}
}
return arr; // Return here to avoid processing as object
}
// Handle empty arrays (length = 0)
if (obj.length === 0) {
return [];
}
}
// Detect and convert QML color objects to hex strings
if (
typeof obj.r === "number" &&
typeof obj.g === "number" &&
typeof obj.b === "number" &&
typeof obj.a === "number" &&
typeof obj.valid === "boolean"
) {
// This looks like a QML color object
try {
// Try to get the string representation (should be hex like "#000000")
if (typeof obj.toString === "function") {
return obj.toString();
} else {
// Fallback: convert RGBA to hex manually
var r = Math.round(obj.r * 255);
var g = Math.round(obj.g * 255);
var b = Math.round(obj.b * 255);
var hex =
"#" +
r.toString(16).padStart(2, "0") +
g.toString(16).padStart(2, "0") +
b.toString(16).padStart(2, "0");
return hex;
}
} catch (e) {
// If conversion fails, fall through to regular object handling
}
}
// Handle regular objects
var plainObj = {};
// Get all property names, but filter out Qt-specific ones
var propertyNames = Object.getOwnPropertyNames(obj);
for (var i = 0; i < propertyNames.length; i++) {
var propName = propertyNames[i];
// Skip Qt-specific properties, functions, and array-like properties
if (
propName === "objectName" ||
propName === "objectNameChanged" ||
propName === "length" || // Skip length property
/^\d+$/.test(propName) || // Skip numeric keys (0, 1, 2, etc.)
propName.endsWith("Changed") ||
typeof obj[propName] === "function"
) {
continue;
}
try {
var value = obj[propName];
plainObj[propName] = qtObjectToPlainObject(value);
} catch (e) {
// Skip properties that can't be accessed
continue;
}
}
return plainObj;
}
@@ -0,0 +1,192 @@
function sha256(message) {
// SHA-256 constants
const K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// Initial hash values
let h0 = 0x6a09e667;
let h1 = 0xbb67ae85;
let h2 = 0x3c6ef372;
let h3 = 0xa54ff53a;
let h4 = 0x510e527f;
let h5 = 0x9b05688c;
let h6 = 0x1f83d9ab;
let h7 = 0x5be0cd19;
// Convert string to UTF-8 bytes manually
const msgBytes = stringToUtf8Bytes(message);
const msgLength = msgBytes.length;
const bitLength = msgLength * 8;
// Calculate padding
// Message + 1 bit (0x80) + padding zeros + 8 bytes for length = multiple of 64 bytes
const totalBitsNeeded = bitLength + 1 + 64; // message bits + padding bit + 64-bit length
const totalBytesNeeded = Math.ceil(totalBitsNeeded / 8);
const paddedLength = Math.ceil(totalBytesNeeded / 64) * 64; // Round up to multiple of 64
const paddedMsg = new Array(paddedLength).fill(0);
// Copy original message
for (let i = 0; i < msgLength; i++) {
paddedMsg[i] = msgBytes[i];
}
// Add padding bit (0x80 = 10000000 in binary)
paddedMsg[msgLength] = 0x80;
// Add length as 64-bit big-endian integer at the end
// JavaScript numbers are not precise enough for 64-bit integers, so we handle high/low separately
const highBits = Math.floor(bitLength / 0x100000000);
const lowBits = bitLength % 0x100000000;
// Write 64-bit length in big-endian format
paddedMsg[paddedLength - 8] = (highBits >>> 24) & 0xFF;
paddedMsg[paddedLength - 7] = (highBits >>> 16) & 0xFF;
paddedMsg[paddedLength - 6] = (highBits >>> 8) & 0xFF;
paddedMsg[paddedLength - 5] = highBits & 0xFF;
paddedMsg[paddedLength - 4] = (lowBits >>> 24) & 0xFF;
paddedMsg[paddedLength - 3] = (lowBits >>> 16) & 0xFF;
paddedMsg[paddedLength - 2] = (lowBits >>> 8) & 0xFF;
paddedMsg[paddedLength - 1] = lowBits & 0xFF;
// Process message in 512-bit (64-byte) chunks
for (let chunk = 0; chunk < paddedLength; chunk += 64) {
const w = new Array(64);
// Break chunk into sixteen 32-bit big-endian words
for (let i = 0; i < 16; i++) {
const offset = chunk + i * 4;
w[i] = (paddedMsg[offset] << 24) |
(paddedMsg[offset + 1] << 16) |
(paddedMsg[offset + 2] << 8) |
paddedMsg[offset + 3];
// Ensure unsigned 32-bit
w[i] = w[i] >>> 0;
}
// Extend the sixteen 32-bit words into sixty-four 32-bit words
for (let i = 16; i < 64; i++) {
const s0 = rightRotate(w[i - 15], 7) ^ rightRotate(w[i - 15], 18) ^ (w[i - 15] >>> 3);
const s1 = rightRotate(w[i - 2], 17) ^ rightRotate(w[i - 2], 19) ^ (w[i - 2] >>> 10);
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
}
// Initialize working variables for this chunk
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7;
// Main loop
for (let i = 0; i < 64; i++) {
const S1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25);
const ch = (e & f) ^ (~e & g);
const temp1 = (h + S1 + ch + K[i] + w[i]) >>> 0;
const S0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22);
const maj = (a & b) ^ (a & c) ^ (b & c);
const temp2 = (S0 + maj) >>> 0;
h = g;
g = f;
f = e;
e = (d + temp1) >>> 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) >>> 0;
}
// Add this chunk's hash to result so far
h0 = (h0 + a) >>> 0;
h1 = (h1 + b) >>> 0;
h2 = (h2 + c) >>> 0;
h3 = (h3 + d) >>> 0;
h4 = (h4 + e) >>> 0;
h5 = (h5 + f) >>> 0;
h6 = (h6 + g) >>> 0;
h7 = (h7 + h) >>> 0;
}
// Produce the final hash value as a hex string
return [h0, h1, h2, h3, h4, h5, h6, h7]
.map(h => h.toString(16).padStart(8, '0'))
.join('');
}
function stringToUtf8Bytes(str) {
const bytes = [];
for (let i = 0; i < str.length; i++) {
let code = str.charCodeAt(i);
if (code < 0x80) {
// 1-byte character (ASCII)
bytes.push(code);
} else if (code < 0x800) {
// 2-byte character
bytes.push(0xC0 | (code >> 6));
bytes.push(0x80 | (code & 0x3F));
} else if (code < 0xD800 || code > 0xDFFF) {
// 3-byte character (not surrogate)
bytes.push(0xE0 | (code >> 12));
bytes.push(0x80 | ((code >> 6) & 0x3F));
bytes.push(0x80 | (code & 0x3F));
} else {
// 4-byte character (surrogate pair)
i++; // Move to next character
const code2 = str.charCodeAt(i);
const codePoint = 0x10000 + (((code & 0x3FF) << 10) | (code2 & 0x3FF));
bytes.push(0xF0 | (codePoint >> 18));
bytes.push(0x80 | ((codePoint >> 12) & 0x3F));
bytes.push(0x80 | ((codePoint >> 6) & 0x3F));
bytes.push(0x80 | (codePoint & 0x3F));
}
}
return bytes;
}
function rightRotate(value, amount) {
return ((value >>> amount) | (value << (32 - amount))) >>> 0;
}
// Test function to verify implementation
// function testSHA256() {
// const tests = [
// {
// input: "",
// expected:
// "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
// },
// {
// input: "Hello World",
// expected:
// "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e",
// },
// {
// input: "abc",
// expected:
// "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
// },
// {
// input: "The quick brown fox jumps over the lazy dog",
// expected:
// "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592",
// },
// ];
// console.log("Running SHA-256 tests:");
// tests.forEach((test, i) => {
// const result = Crypto.sha256(test.input);
// const passed = result === test.expected;
// console.log(`Test ${i + 1}: ${passed ? "PASS" : "FAIL"}`);
// if (!passed) {
// console.log(` Input: "${test.input}"`);
// console.log(` Expected: ${test.expected}`);
// console.log(` Got: ${result}`);
// }
// });
// }
@@ -0,0 +1,103 @@
import QtQuick
import Quickshell
import Quickshell.Wayland
import "../../../components" as C
import "../../../core" as Core
import "../../../services" as GS
// Hosts a Noctalia v4 plugin's Panel.qml as a glassMxrph bar drawer: it grows
// out of the bar under the button that opened it, sized from the panel's
// contentPreferredWidth/Height. Escape or an outside click closes it.
PanelWindow {
id: root
required property var api
property url source: ""
readonly property bool open: !!api && !!api.panelOpenScreen
// Lets test drivers find this panel.
Component.onCompleted: GS.PluginService.panelWindows[api.pluginId] = root
// Keep the last screen while the drawer animates closed.
property var lastScreen: null
onOpenChanged: {
if (open)
lastScreen = api.panelOpenScreen;
else
GS.PluginService.releasePopout(api);
}
screen: open ? api.panelOpenScreen : lastScreen
readonly property Item anchorItem: api && api.panelAnchor ? api.panelAnchor : null
readonly property var anchorWindow: anchorItem && anchorItem.QsWindow ? anchorItem.QsWindow.window : null
readonly property bool fromBar: !!anchorWindow && GS.TrayService.barWindows.includes(anchorWindow)
readonly property real screenW: screen ? screen.width : 1920
readonly property real screenH: screen ? screen.height : 1080
readonly property real anchorCenter: {
root.open;
if (!fromBar)
return screenW / 2;
const p = anchorItem.mapToItem(anchorWindow.contentItem, anchorItem.width / 2, 0);
return p.x;
}
readonly property Item panel: loader.item
readonly property var panelObject: loader.item
readonly property real preferredWidth: panelObject && panelObject.contentPreferredWidth > 0 ? panelObject.contentPreferredWidth : 400
readonly property real preferredHeight: panelObject && panelObject.contentPreferredHeight > 0 ? panelObject.contentPreferredHeight : 320
readonly property real drawerX: Core.BarDrawers.clampX(anchorCenter, drawer.width, screenW)
anchors {
top: true
left: true
}
// qmllint disable unqualified unresolved-type
margins.left: root.drawerX
// qmllint enable unqualified unresolved-type
implicitWidth: Math.max(1, Math.round(drawer.width))
implicitHeight: Math.max(1, Math.round(Core.BarDrawers.bottom + drawer.contentHeight))
visible: open || drawer.shown
color: "transparent"
exclusionMode: ExclusionMode.Ignore
WlrLayershell.namespace: "glassMxrph-plugin-panel"
WlrLayershell.layer: WlrLayer.Overlay
WlrLayershell.keyboardFocus: open ? WlrKeyboardFocus.Exclusive : WlrKeyboardFocus.None
MouseArea {
x: -20000
y: -20000
width: 40000
height: 40000
enabled: root.open
onPressed: root.api.closePanel(null)
}
C.BarDrawer {
id: drawer
objectName: "noctaliaPanelSurface"
y: Core.BarDrawers.bottom
open: root.open
contentWidth: Math.min(root.preferredWidth, root.screenW - 2 * (Core.BarDrawers.margin + Core.BarDrawers.radius + ear))
contentHeight: Math.min(root.preferredHeight, root.screenH - Core.BarDrawers.bottom - 20)
drawerId: "noctalia-panel-" + (root.api ? root.api.pluginId : "")
screenName: root.screen ? root.screen.name : ""
screenX: root.drawerX
focus: root.open
Keys.onEscapePressed: root.api.closePanel(null)
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.AllButtons
}
Loader {
id: loader
anchors.fill: parent
active: root.open || drawer.shown
onActiveChanged: if (active)
setSource(root.source, {
pluginApi: root.api
})
onLoaded: {
if ("screen" in item)
item.screen = Qt.binding(() => root.screen);
}
}
}
}
@@ -0,0 +1,134 @@
import QtQuick
import Quickshell
import Quickshell.Io
// glassMxrph implementation of Noctalia v4's per-plugin `pluginApi`: same
// properties and functions (settings, translations, panel control), backed by
// glassMxrph. Settings persist to settings.json in the plugin's folder, like
// in Noctalia; panels open as glassMxrph bar drawers (see PluginService).
QtObject {
id: api
required property string pluginId
required property string pluginDir
property var manifest: ({})
property var pluginSettings: ({})
property var mainInstance: null
property var barWidget: null
property var desktopWidget: null
property var launcherProvider: null
property var controlCenterWidget: null
// The screen the panel is open on (null when closed), and the button it hangs from.
property var panelOpenScreen: null
property var panelAnchor: null
property var ipcHandlers: ({})
property var pluginTranslations: ({})
property var pluginFallbackTranslations: ({})
property string currentLanguage: (Qt.locale().name || "en").split("_")[0]
property int translationVersion: 0
// Host callbacks (set by glassMxrph's PluginService).
property var _currentScreen: null
property var _requestPanel: null
function nested(obj, path) {
let current = obj;
for (const key of String(path).split(".")) {
if (current === undefined || current === null)
return undefined;
current = current[key];
}
return current;
}
function saveSettings() {
settingsFile.setText(JSON.stringify(api.pluginSettings, null, 2));
api.pluginSettings = Object.assign({}, api.pluginSettings);
}
function openPanel(screen, buttonItem) {
api.panelAnchor = buttonItem || api.barWidget || null;
api.panelOpenScreen = screen || (api._currentScreen ? api._currentScreen() : Quickshell.screens[0]);
if (api._requestPanel)
api._requestPanel(api);
return true;
}
function closePanel(screen) {
if (!api.panelOpenScreen)
return false;
api.panelOpenScreen = null;
return true;
}
// Lets glassMxrph's popout coordinator close this panel like any other.
function close() {
api.closePanel(null);
}
function togglePanel(screen, buttonItem) {
if (api.panelOpenScreen && (!screen || screen === api.panelOpenScreen))
return api.closePanel(screen);
return api.openPanel(screen, buttonItem);
}
function openLauncher(screen) {
}
function closeLauncher(screen) {
}
function toggleLauncher(screen) {
}
function withCurrentScreen(callback) {
callback(api._currentScreen ? api._currentScreen() : Quickshell.screens[0]);
}
function tr(key, interpolations) {
let translation = api.nested(api.pluginTranslations, key);
if (typeof translation !== "string")
translation = api.nested(api.pluginFallbackTranslations, key);
if (typeof translation !== "string")
return "!!" + key + "!!";
for (const placeholder in (interpolations || {}))
translation = translation.replace(new RegExp("\\{" + placeholder + "\\}", "g"), interpolations[placeholder]);
return translation;
}
function trp(key, count, interpolations) {
return api.tr(count === 1 ? key : key + "-plural", Object.assign({
"count": count
}, interpolations || {}));
}
function hasTranslation(key) {
return api.nested(api.pluginTranslations, key) !== undefined || api.nested(api.pluginFallbackTranslations, key) !== undefined;
}
function parse(text) {
try {
return JSON.parse(text);
} catch (e) {
return {};
}
}
property FileView settingsFile: FileView {
path: api.pluginDir + "/settings.json"
blockLoading: true
printErrors: false
onLoaded: api.pluginSettings = Object.assign({}, (api.manifest.metadata && api.manifest.metadata.defaultSettings) || {}, api.parse(text()))
onLoadFailed: api.pluginSettings = Object.assign({}, (api.manifest.metadata && api.manifest.metadata.defaultSettings) || {})
}
property FileView languageFile: FileView {
path: api.pluginDir + "/i18n/" + api.currentLanguage + ".json"
blockLoading: true
printErrors: false
onLoaded: {
api.pluginTranslations = api.parse(text());
api.translationVersion++;
}
}
property FileView fallbackFile: FileView {
path: api.pluginDir + "/i18n/en.json"
blockLoading: true
printErrors: false
onLoaded: {
api.pluginFallbackTranslations = api.parse(text());
api.translationVersion++;
}
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 noctalia-dev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
import QtQuick
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Commons.Migrations
import qs.compat.noctalia.Modules.OSD
import qs.compat.noctalia.Services.Compositor
import qs.compat.noctalia.Services.Hardware
import qs.compat.noctalia.Services.Location
import qs.compat.noctalia.Services.Media
import qs.compat.noctalia.Services.Networking
import qs.compat.noctalia.Services.Noctalia
import qs.compat.noctalia.Services.Power
import qs.compat.noctalia.Services.System
import qs.compat.noctalia.Services.UI
import qs.compat.noctalia.Widgets
import qs.compat.noctalia.Widgets.AudioSpectrum
// Quickshell indexes qs.* modules from the shell's own import graph. Plugins
// live outside the shell folder, so this file pulls every Noctalia
// compatibility module into that graph for them. It renders nothing.
QtObject {
}
@@ -0,0 +1,11 @@
import QtQuick
// glassMxrph stub: Noctalia's Settings reads OSD.Type; glassMxrph has its own OSD.
QtObject {
enum Type {
Volume,
InputVolume,
Brightness,
LockKey
}
}
+14
View File
@@ -0,0 +1,14 @@
Noctalia v4 shell kit (Commons, Widgets, Helpers and selected Services),
vendored so Noctalia v4 plugins run inside glassMxrph.
Source: https://github.com/noctalia-dev/noctalia-shell (branch legacy-v4). MIT, see LICENSE.
Tabler icon font: Assets/Fonts/tabler (MIT, see tabler-icons-license.txt).
glassMxrph changes:
- Imports point at qs.compat.noctalia.* (Modules.qml registers them).
- Commons/Color.qml is replaced: Material roles come from the glassMxrph theme.
- Commons/Style.qml: radii, bar/capsule size, animation and opacity follow glassMxrph.
- Commons/Settings.qml stores its file in ~/.config/glassMxrph/noctalia-compat.
- Services/UI, Noctalia, Compositor, Networking, System/NotificationService and
Media/SpectrumService are small glassMxrph-backed stand-ins; Hardware/Battery,
Power/PowerProfile, Location, System/SystemStat and System/Sound are Noctalia's own.
- Host/ holds glassMxrph's pluginApi and the bar-drawer panel host.
@@ -0,0 +1,31 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Hyprland
// glassMxrph stand-in: glassMxrph runs on Hyprland.
Singleton {
readonly property bool isHyprland: true
readonly property bool isNiri: false
readonly property bool isSway: false
readonly property bool isMango: false
readonly property bool isLabwc: false
readonly property bool overviewActive: false
readonly property var workspaces: Hyprland.workspaces.values.map(w => ({
"id": w.id,
"idx": w.id,
"name": w.name,
"output": w.monitor ? w.monitor.name : "",
"isFocused": w.focused,
"isActive": w.active,
"isUrgent": w.urgent,
"isOccupied": w.toplevels.values.length > 0
}))
function getDisplayScale(screenName) {
const s = Quickshell.screens.find(x => x.name === screenName);
return s ? s.devicePixelRatio : 1;
}
function switchToWorkspace(workspace) {
Hyprland.dispatch("workspace " + (workspace && workspace.id !== undefined ? workspace.id : workspace));
}
}
@@ -0,0 +1,368 @@
pragma Singleton
import QtQml
import QtQuick
import Quickshell
import Quickshell.Io
import Quickshell.Services.UPower
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.Networking
import qs.compat.noctalia.Services.UI
Singleton {
id: root
readonly property var primaryDevice: _laptopBattery || _bluetoothBattery || null // Primary battery device (prioritizes laptop over Bluetooth)
readonly property real batteryPercentage: getPercentage(primaryDevice)
readonly property bool batteryCharging: isCharging(primaryDevice)
readonly property bool batteryPluggedIn: isPluggedIn(primaryDevice)
readonly property bool batteryReady: isDeviceReady(primaryDevice)
readonly property bool batteryPresent: isDevicePresent(primaryDevice)
readonly property real warningThreshold: Settings.data.systemMonitor.batteryWarningThreshold
readonly property real criticalThreshold: Settings.data.systemMonitor.batteryCriticalThreshold
readonly property string batteryIcon: getIcon(batteryPercentage, batteryCharging, batteryPluggedIn, batteryReady)
readonly property var laptopBatteries: UPower.devices.values.filter(d => d.isLaptopBattery).sort((x, y) => {
// Force DisplayDevice to the top
if (x.nativePath.includes("DisplayDevice"))
return -1;
if (y.nativePath.includes("DisplayDevice"))
return 1;
// Standard string comparison works for BAT0 vs BAT1
return x.nativePath.localeCompare(y.nativePath, undefined, {
numeric: true
});
})
readonly property var bluetoothBatteries: {
var list = [];
var btArray = BluetoothService.devices?.values || [];
for (var i = 0; i < btArray.length; i++) {
var btd = btArray[i];
if (btd && btd.connected && btd.batteryAvailable) {
list.push(btd);
}
}
return list;
}
readonly property var _laptopBattery: UPower.displayDevice.isPresent ? UPower.displayDevice : (laptopBatteries.length > 0 ? laptopBatteries[0] : null)
readonly property var _bluetoothBattery: bluetoothBatteries.length > 0 ? bluetoothBatteries[0] : null
property var deviceModel: {
var model = [
{
"key": "__default__",
"name": I18n.tr("bar.battery.device-default")
}
];
const devices = UPower.devices?.values || [];
for (let d of devices) {
if (!d || d.type === UPowerDeviceType.LinePower) {
continue;
}
model.push({
key: d.nativePath || "",
name: d.model || d.nativePath || I18n.tr("common.unknown")
});
}
return model;
}
property var _hasNotified: ({})
function findDevice(nativePath) {
if (!nativePath || nativePath === "__default__" || nativePath === "DisplayDevice") {
return _laptopBattery;
}
if (!UPower.devices) {
return null;
}
const devices = UPower.devices?.values || [];
for (let d of devices) {
if (d && d.nativePath === nativePath) {
if (d.type === UPowerDeviceType.LinePower) {
continue;
}
return d;
}
}
return null;
}
function isDevicePresent(device) {
if (!device) {
return false;
}
// Handle Bluetooth devices (identified by having batteryAvailable property)
if (device.batteryAvailable !== undefined) {
return device.connected === true;
}
// Handle UPower devices
if (device.type !== undefined) {
if (device.type === UPowerDeviceType.Battery && device.isPresent !== undefined) {
return device.isPresent === true;
}
// Fallback for non-battery UPower devices or if isPresent is missing
return device.ready && device.percentage !== undefined;
}
return false;
}
function isDeviceReady(device) {
if (!isDevicePresent(device)) {
return false;
}
if (device.batteryAvailable !== undefined) {
return device.battery !== undefined;
}
return device.ready && device.percentage !== undefined;
}
function getPercentage(device) {
if (!device) {
return -1;
}
if (device.batteryAvailable !== undefined) {
return Math.round((device.battery || 0) * 100);
}
return Math.round((device.percentage || 0) * 100);
}
function isCharging(device) {
if (!device || isBluetoothDevice(device)) {
// Tracking bluetooth devices can charge or not is a loop hole, none of my devices has it, even if it possible?!
return false; // Assuming not charging until someone/quickshell brings a way to do pretty unlikely.
}
if (device.state !== undefined) {
return device.state === UPowerDeviceState.Charging;
}
return false;
}
function isPluggedIn(device) {
if (!device || isBluetoothDevice(device)) {
// Tracking bluetooth devices can charge or not is a loop hole, none of my devices has it, even if it possible?!
return false; // Assuming not charging until someone/quickshell brings a way to do pretty unlikely.
}
if (device.state !== undefined) {
return device.state === UPowerDeviceState.FullyCharged || device.state === UPowerDeviceState.PendingCharge;
}
return false;
}
function isCriticalBattery(device) {
return (!isCharging(device) && !isPluggedIn(device)) && getPercentage(device) <= criticalThreshold;
}
function isLowBattery(device) {
return (!isCharging(device) && !isPluggedIn(device)) && getPercentage(device) <= warningThreshold && getPercentage(device) > criticalThreshold;
}
function isBluetoothDevice(device) {
if (!device) {
return false;
}
// Check for Quickshell Bluetooth device property
if (device.batteryAvailable !== undefined) {
return true;
}
// Check for UPower device path indicating it's a Bluetooth device
if (device.nativePath && (device.nativePath.includes("bluez") || device.nativePath.includes("bluetooth"))) {
return true;
}
return false;
}
function getDeviceName(device) {
if (!isDeviceReady(device)) {
return "";
}
if (!isBluetoothDevice(device) && device.isLaptopBattery) {
// If there is more than one battery explicitly name them
// Logger.e("BatteryDebug", "Available Battery count: " + laptopBatteries.length); // can be useful for debugging
if (laptopBatteries.length > 1 && device.nativePath) {
if (device.nativePath === "DisplayDevice") {
return I18n.tr("battery.all-batteries");
}
var match = device.nativePath.match(/(\d+)$/);
if (match) {
// In case of 2 batteries: bat0 => bat1 bat1 => bat2
return I18n.tr("common.battery") + " " + (parseInt(match[1]) + 1); // Append numbers
}
}
// Return Battery if there is only one
return I18n.tr("common.battery");
}
if (isBluetoothDevice(device) && device.name) {
return device.name;
}
if (device.model) {
return device.model;
}
return "";
}
function getIcon(percent, charging, pluggedIn, isReady) {
if (!isReady) {
return "battery-exclamation";
}
if (charging) {
return "battery-charging";
}
if (pluggedIn) {
return "battery-charging-2";
}
const icons = [
{
threshold: 86,
icon: "battery-4"
},
{
threshold: 56,
icon: "battery-3"
},
{
threshold: 31,
icon: "battery-2"
},
{
threshold: 11,
icon: "battery-1"
},
{
threshold: 0,
icon: "battery"
}
];
const match = icons.find(tier => percent >= tier.threshold);
return match ? match.icon : "battery-off"; // New fallback icon clearly represent if nothing is true here.
}
function getRateText(device) {
if (!device || device.changeRate === undefined) {
return "";
}
const rate = Math.abs(device.changeRate);
if (device.timeToFull > 0) {
return I18n.tr("battery.charging-rate", {
"rate": rate.toFixed(2)
});
} else if (device.timeToEmpty > 0) {
return I18n.tr("battery.discharging-rate", {
"rate": rate.toFixed(2)
});
}
}
function getTimeRemainingText(device) {
if (!isDeviceReady(device)) {
return I18n.tr("battery.no-battery-detected");
}
if (isPluggedIn(device)) {
return I18n.tr("battery.plugged-in");
} else if (device.timeToFull > 0) {
return I18n.tr("battery.time-until-full", {
"time": Time.formatVagueHumanReadableDuration(device.timeToFull)
});
} else if (device.timeToEmpty > 0) {
return I18n.tr("battery.time-left", {
"time": Time.formatVagueHumanReadableDuration(device.timeToEmpty)
});
}
return I18n.tr("common.idle");
}
function checkDevice(device) {
if (!device || !isDeviceReady(device)) {
return;
}
const percentage = getPercentage(device);
const charging = isCharging(device);
const pluggedIn = isPluggedIn(device);
const level = isLowBattery(device) ? "low" : (isCriticalBattery(device) ? "critical" : "");
var deviceKey = device.nativePath;
if (!_hasNotified[deviceKey]) {
_hasNotified[deviceKey] = {
low: false,
critical: false
};
}
if (charging || pluggedIn) {
_hasNotified[deviceKey].low = false;
_hasNotified[deviceKey].critical = false;
}
if (percentage > warningThreshold) {
_hasNotified[deviceKey].low = false;
_hasNotified[deviceKey].critical = false;
} else if (percentage > criticalThreshold) {
_hasNotified[deviceKey].critical = false;
}
if (level) {
if (!_hasNotified[deviceKey][level]) {
notify(device, level);
_hasNotified[deviceKey][level] = true;
}
}
}
function notify(device, level) {
if (!Settings.data.notifications.enableBatteryToast) {
return;
}
var name = getDeviceName(device);
var titleKey = level === "critical" ? "toast.battery.critical" : "toast.battery.low";
var descKey = level === "critical" ? "toast.battery.critical-desc" : "toast.battery.low-desc";
var title = I18n.tr(titleKey);
var desc = I18n.tr(descKey, {
"percent": getPercentage(device)
});
var icon = level === "critical" ? "battery-exclamation" : "battery-charging-2";
if (device == _bluetoothBattery && name) {
title = title + " " + name;
}
// Only 'showNotice' supports custom icons
ToastService.showNotice(title, desc, icon, 6000);
}
Instantiator {
model: deviceModel
delegate: Connections {
required property var modelData
property var device: findDevice(modelData.key)
target: device
function onPercentageChanged() {
if (device.isLaptopBattery && modelData.key !== "__default__") {
return;
}
checkDevice(device);
}
function onStateChanged() {
if (device.isLaptopBattery && modelData.key !== "__default__") {
return;
}
checkDevice(device);
}
}
}
}
@@ -0,0 +1,397 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Io
import qs.compat.noctalia.Commons
// Location and weather service with decoupled geocoding and weather fetching.
Singleton {
id: root
property string locationFile: Quickshell.env("NOCTALIA_WEATHER_FILE") || (Settings.cacheDir + "location.json")
property int weatherUpdateFrequency: 30 * 60
property bool isFetchingWeather: false
// Talia weather
readonly property int taliaMascotWeatherMonth: 3
readonly property int taliaMascotWeatherDay: 1
readonly property bool taliaWeatherMascotDayActive: {
const d = Time.now;
return d.getMonth() === root.taliaMascotWeatherMonth && d.getDate() === root.taliaMascotWeatherDay;
}
readonly property bool taliaWeatherMascotActive: taliaWeatherMascotDayActive || Settings.data.location.weatherTaliaMascotAlways
readonly property alias data: adapter
// True when the user has set a location name or enabled auto-locate
readonly property bool locationConfigured: Settings.data.location.name !== "" || Settings.data.location.autoLocate
// Stable UI properties - only updated when location is successfully geocoded
property bool coordinatesReady: false
property string stableLatitude: ""
property string stableLongitude: ""
property string stableName: ""
FileView {
id: locationFileView
path: locationFile
printErrors: false
onAdapterUpdated: saveTimer.start()
onLoaded: {
Logger.d("Location", "Loaded cached data");
if (adapter.latitude !== "" && adapter.longitude !== "" && adapter.weatherLastFetch > 0) {
root.stableLatitude = adapter.latitude;
root.stableLongitude = adapter.longitude;
root.stableName = adapter.name;
root.coordinatesReady = true;
Logger.i("Location", "Coordinates ready");
}
update();
}
onLoadFailed: function (error) {
update();
}
JsonAdapter {
id: adapter
property string latitude: ""
property string longitude: ""
property string name: ""
property int weatherLastFetch: 0
property var weather: null
}
}
// Formatted coordinates for UI display
readonly property string displayCoordinates: {
if (!root.coordinatesReady || root.stableLatitude === "" || root.stableLongitude === "") {
return "";
}
const lat = parseFloat(root.stableLatitude).toFixed(4);
const lon = parseFloat(root.stableLongitude).toFixed(4);
return `${lat}, ${lon}`;
}
// Auto-geolocate timer - periodically updates location via IP geolocation
Timer {
id: autoLocateTimer
interval: 30 * 60 * 1000
running: Settings.data.location.autoLocate
repeat: true
triggeredOnStart: true
onTriggered: root.geolocateAndApply()
}
// Update timer runs when weather is enabled or location-based scheduling is active
Timer {
id: updateTimer
interval: 20 * 1000
running: Settings.data.location.weatherEnabled || Settings.data.colorSchemes.schedulingMode == "location"
repeat: true
onTriggered: {
update();
}
}
Timer {
id: saveTimer
running: false
interval: 1000
onTriggered: locationFileView.writeAdapter()
}
function init() {
Logger.i("Location", "Service started");
}
function resetWeather() {
Logger.i("Location", "Resetting location and weather data");
root.coordinatesReady = false;
root.stableLatitude = "";
root.stableLongitude = "";
root.stableName = "";
adapter.latitude = "";
adapter.longitude = "";
adapter.name = "";
adapter.weatherLastFetch = 0;
adapter.weather = null;
isFetchingWeather = false;
update();
}
// Main update function - geocodes location if needed, then fetches weather if enabled
function update() {
updateLocation();
if (Settings.data.location.weatherEnabled) {
updateWeatherData();
}
}
// Runs independently of weather toggle
function updateLocation() {
const locationChanged = adapter.name !== Settings.data.location.name;
const needsGeocoding = (adapter.latitude === "") || (adapter.longitude === "") || locationChanged;
if (!needsGeocoding) {
return;
}
if (isFetchingWeather) {
return;
}
isFetchingWeather = true;
if (locationChanged) {
root.coordinatesReady = false;
Logger.d("Location", "Location changed from", adapter.name, "to", Settings.data.location.name);
}
geocodeLocation(Settings.data.location.name, function (latitude, longitude, name, country) {
adapter.name = Settings.data.location.name;
adapter.latitude = latitude.toString();
adapter.longitude = longitude.toString();
root.stableLatitude = adapter.latitude;
root.stableLongitude = adapter.longitude;
root.stableName = `${name}, ${country}`;
root.coordinatesReady = true;
isFetchingWeather = false;
Logger.i("Location", `Geocoded ${Settings.data.location.name}: ${root.stableLatitude}, ${root.stableLongitude}`);
if (locationChanged) {
adapter.weatherLastFetch = 0;
updateWeatherData();
}
}, errorCallback);
}
// Fetch weather data if enabled and coordinates are available
function updateWeatherData() {
if (!Settings.data.location.weatherEnabled) {
return;
}
if (isFetchingWeather) {
return;
}
if (adapter.latitude === "" || adapter.longitude === "") {
Logger.w("Location", "Cannot fetch weather without coordinates");
return;
}
const needsWeatherUpdate = (adapter.weatherLastFetch === "") || (adapter.weather === null) || (Time.timestamp >= adapter.weatherLastFetch + weatherUpdateFrequency);
if (needsWeatherUpdate) {
isFetchingWeather = true;
fetchWeatherData(adapter.latitude, adapter.longitude, errorCallback);
}
}
// Query geocoding API to convert location name to coordinates
function geocodeLocation(locationName, callback, errorCallback) {
if (locationName === "") {
isFetchingWeather = false;
return;
}
Logger.d("Location", "Geocoding location name");
var geoUrl = "https://api.noctalia.dev/geocode?city=" + encodeURIComponent(locationName);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
try {
var geoData = JSON.parse(xhr.responseText);
if (geoData.lat != null) {
callback(geoData.lat, geoData.lng, geoData.name, geoData.country);
} else {
errorCallback("Location", "could not resolve location name");
}
} catch (e) {
errorCallback("Location", "Failed to parse geocoding data: " + e);
}
} else {
errorCallback("Location", `Geocoding error: ${xhr.status} ${xhr.responseText}`);
}
}
};
xhr.open("GET", geoUrl);
xhr.send();
}
// Fetch weather data from Open-Meteo API
function fetchWeatherData(latitude, longitude, errorCallback) {
Logger.d("Location", "Fetching weather from api.open-meteo.com");
var url = "https://api.open-meteo.com/v1/forecast?latitude=" + latitude + "&longitude=" + longitude + "&current_weather=true&current=relativehumidity_2m,surface_pressure,is_day&daily=temperature_2m_max,temperature_2m_min,weathercode,sunset,sunrise&timezone=auto";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
try {
var weatherData = JSON.parse(xhr.responseText);
//console.log(JSON.stringify(weatherData))
// Save core data
data.weather = weatherData;
data.weatherLastFetch = Time.timestamp;
// Update stable display values only when complete and successful
root.stableLatitude = data.latitude = weatherData.latitude.toString();
root.stableLongitude = data.longitude = weatherData.longitude.toString();
root.coordinatesReady = true;
isFetchingWeather = false;
Logger.d("Location", "Cached weather to disk - stable coordinates updated");
} catch (e) {
errorCallback("Location", "Failed to parse weather data");
}
} else {
errorCallback("Location", `Weather error: ${xhr.status} ${xhr.responseText}`);
}
}
};
xhr.open("GET", url);
xhr.send();
}
// Geolocate via IP address using the Noctalia API
function geolocate(callback, errorCallback) {
Logger.d("Location", "Geolocating via IP");
var url = "https://api.noctalia.dev/geolocate";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
try {
var data = JSON.parse(xhr.responseText);
if (data.lat != null) {
callback(data.lat, data.lng, data.city, data.country);
} else {
errorCallback("Location", "Geolocate: no coordinates returned");
}
} catch (e) {
errorCallback("Location", "Failed to parse geolocate data: " + e);
}
} else {
errorCallback("Location", `Geolocate error: ${xhr.status} ${xhr.responseText}`);
}
}
};
xhr.open("GET", url);
xhr.send();
}
// Geolocate via IP and apply the result as the current location
function geolocateAndApply() {
if (isFetchingWeather) {
Logger.w("Location", "Geolocate skipped, fetch already in progress");
return;
}
geolocate(function (lat, lng, city, country) {
Logger.i("Location", "Geolocated to", city + ",", country + ":", lat + "," + lng);
const locationChanged = adapter.name !== city;
Settings.data.location.name = city;
adapter.name = city;
adapter.latitude = lat.toString();
adapter.longitude = lng.toString();
root.stableLatitude = adapter.latitude;
root.stableLongitude = adapter.longitude;
root.stableName = `${city}, ${country}`;
root.coordinatesReady = true;
if (locationChanged) {
adapter.weatherLastFetch = 0;
adapter.weather = null;
}
if (Settings.data.location.weatherEnabled) {
updateWeatherData();
}
}, errorCallback);
}
// --------------------------------
function errorCallback(module, message) {
Logger.w(module, message);
isFetchingWeather = false;
}
// --------------------------------
function weatherSymbolFromCode(code) {
var isDay = data.weather ? data.weather.current_weather.is_day : true;
if (code === 0)
return isDay ? "weather-sun" : "weather-moon";
if (code === 1 || code === 2)
return isDay ? "weather-cloud-sun" : "weather-moon-stars";
if (code === 3)
return "weather-cloud";
if (code >= 45 && code <= 48)
return "weather-cloud-haze";
if (code >= 51 && code <= 67)
return "weather-cloud-rain";
if (code >= 80 && code <= 82)
return "weather-cloud-rain";
if (code >= 71 && code <= 77)
return "weather-cloud-snow";
if (code >= 71 && code <= 77)
return "weather-cloud-snow";
if (code >= 85 && code <= 86)
return "weather-cloud-snow";
if (code >= 95 && code <= 99)
return "weather-cloud-lightning";
return "weather-cloud";
}
// --------------------------------
function taliaWeatherImageFromCode(code) {
var isDay = data.weather ? data.weather.current_weather.is_day : true;
if (code >= 40 && code <= 49)
return Quickshell.shellDir + "/Assets/Talia/TaliaDazed.png";
if (code >= 95 && code <= 99)
return Quickshell.shellDir + "/Assets/Talia/TaliaFear.png";
var wet = (code >= 51 && code <= 67) || (code >= 80 && code <= 82) || (code >= 71 && code <= 77) || (code >= 85 && code <= 86);
if (wet)
return Quickshell.shellDir + "/Assets/Talia/TaliaSob.png";
if ((code === 0 || code === 1 || code === 2) && isDay === false)
return Quickshell.shellDir + "/Assets/Talia/TaliaVampire.png";
if ((code === 0 && isDay === true) || code === 1 || code === 2)
return Quickshell.shellDir + "/Assets/Talia/TaliaParty.png";
return Quickshell.shellDir + "/Assets/Talia/TaliaBlank.png";
}
// --------------------------------
function weatherDescriptionFromCode(code) {
if (code === 0)
return "Clear sky";
if (code === 1)
return "Mainly clear";
if (code === 2)
return "Partly cloudy";
if (code === 3)
return "Overcast";
if (code === 45 || code === 48)
return "Fog";
if (code >= 51 && code <= 67)
return "Drizzle";
if (code >= 71 && code <= 77)
return "Snow";
if (code >= 80 && code <= 82)
return "Rain showers";
if (code >= 95 && code <= 99)
return "Thunderstorm";
return "Unknown";
}
// --------------------------------
function celsiusToFahrenheit(celsius) {
return 32 + celsius * 1.8;
}
}
@@ -0,0 +1,35 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../services" as GS
// glassMxrph stand-in: the audio spectrum comes from glassMxrph's Cava
// (Noctalia's PwAudioSpectrum is not in Quickshell 0.3.1).
Singleton {
id: root
property var _registeredComponents: ({})
readonly property int _registeredCount: Object.keys(_registeredComponents).length
readonly property var values: GS.CavaService.bars
readonly property bool isIdle: !GS.CavaService.wanted
property bool subscribed: false
on_RegisteredCountChanged: {
const want = _registeredCount > 0;
if (want !== subscribed) {
GS.CavaService.widgetConsumers += want ? 1 : -1;
subscribed = want;
}
}
function registerComponent(componentId) {
const next = Object.assign({}, _registeredComponents);
next[componentId] = true;
_registeredComponents = next;
}
function unregisterComponent(componentId) {
const next = Object.assign({}, _registeredComponents);
delete next[componentId];
_registeredComponents = next;
}
function isRegistered(componentId) {
return !!_registeredComponents[componentId];
}
}
@@ -0,0 +1,11 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Bluetooth
// glassMxrph stand-in: only what other compatibility services read.
Singleton {
readonly property var adapter: Bluetooth.defaultAdapter
readonly property var devices: Bluetooth.devices
readonly property bool enabled: !!adapter && adapter.enabled
}
@@ -0,0 +1,46 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../services" as GS
// glassMxrph stand-in: answers from glassMxrph's installed plugins.
Singleton {
readonly property string pluginsDir: (Quickshell.env("XDG_DATA_HOME") || Quickshell.env("HOME") + "/.local/share") + "/glassMxrph/plugins"
readonly property var pluginSources: []
function getPluginManifest(pluginId) {
const p = GS.PluginService.plugin(pluginId);
return p ? p.manifest : null;
}
function getPluginDir(pluginId) {
const p = GS.PluginService.plugin(pluginId);
return p ? p.dir : "";
}
function getAllInstalledPluginIds() {
return GS.PluginService.plugins.map(p => p.id);
}
function isPluginEnabled(pluginId) {
return GS.PluginService.isEnabled(pluginId);
}
function isMainSource(url) {
return true;
}
function getPluginSourceUrl(pluginId) {
const p = GS.PluginService.plugin(pluginId);
return p ? p.source : "";
}
function parseCompositeKey(key) {
return {
"pluginId": String(key),
"sourceHash": ""
};
}
function getSourceNameByHash(hash) {
return "";
}
function addPluginSource(name, url) {
}
function removePluginSource(url) {
}
function setSourceEnabled(url, enabled) {
}
}
@@ -0,0 +1,46 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../services" as GS
// glassMxrph stand-in: Noctalia plugins talk to glassMxrph's plugin service.
Singleton {
readonly property bool initialized: GS.PluginService.loaded
readonly property bool pluginsFullyLoaded: GS.PluginService.loaded
readonly property var availablePlugins: []
readonly property var pluginUpdates: ({})
readonly property int pluginUpdatesPending: 0
readonly property var installingPlugins: ({})
readonly property int activeFetches: 0
function getPluginAPI(pluginId) {
return GS.PluginService.noctaliaApi(pluginId);
}
function hasPluginError(pluginId) {
return false;
}
function getPluginError(pluginId) {
return "";
}
function enablePlugin(pluginId) {
GS.PluginService.setEnabled(pluginId, true);
}
function disablePlugin(pluginId) {
GS.PluginService.setEnabled(pluginId, false);
}
function uninstallPlugin(pluginId) {
GS.PluginService.remove(pluginId);
}
function installPlugin(plugin) {
}
function updatePlugin(pluginId) {
}
function checkForUpdates() {
}
function refreshAvailablePlugins() {
}
function isPluginHotReloadEnabled(pluginId) {
return false;
}
function togglePluginHotReload(pluginId) {
}
}
@@ -0,0 +1,132 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Services.UPower
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
Singleton {
id: root
readonly property var powerProfiles: PowerProfiles
readonly property bool available: powerProfiles && powerProfiles.hasPerformanceProfile
property int profile: powerProfiles ? powerProfiles.profile : PowerProfile.Balanced
// Not a power profile but a volatile property to quickly disable shadows, animations, etc..
property bool noctaliaPerformanceMode: false
function getName(p) {
if (!available)
return "Unknown";
const prof = (p !== undefined) ? p : profile;
switch (prof) {
case PowerProfile.Performance:
return "Performance";
case PowerProfile.Balanced:
return "Balanced";
case PowerProfile.PowerSaver:
return "Power saver";
default:
return "Unknown";
}
}
function getIcon(p) {
if (!available)
return "balanced";
const prof = (p !== undefined) ? p : profile;
switch (prof) {
case PowerProfile.Performance:
return "performance";
case PowerProfile.Balanced:
return "balanced";
case PowerProfile.PowerSaver:
return "powersaver";
default:
return "balanced";
}
}
function init() {
Logger.d("PowerProfileService", "Service started");
}
function setProfile(p) {
if (!available)
return;
try {
powerProfiles.profile = p;
} catch (e) {
Logger.e("PowerProfileService", "Failed to set profile:", e);
}
}
function cycleProfile() {
if (!available)
return;
const current = powerProfiles.profile;
if (current === PowerProfile.Performance)
setProfile(PowerProfile.PowerSaver);
else if (current === PowerProfile.Balanced)
setProfile(PowerProfile.Performance);
else if (current === PowerProfile.PowerSaver)
setProfile(PowerProfile.Balanced);
}
function cycleProfileReverse() {
if (!available)
return;
const current = powerProfiles.profile;
if (current === PowerProfile.Performance)
setProfile(PowerProfile.Balanced);
else if (current === PowerProfile.Balanced)
setProfile(PowerProfile.PowerSaver);
else if (current === PowerProfile.PowerSaver)
setProfile(PowerProfile.Performance);
}
function isDefault() {
if (!available)
return true;
return (profile === PowerProfile.Balanced);
}
Connections {
target: powerProfiles
function onProfileChanged() {
root.profile = powerProfiles.profile;
// Only show toast if we have a valid profile name (not "Unknown")
const profileName = root.getName();
if (profileName !== "Unknown") {
ToastService.showNotice(I18n.tr("toast.power-profile.profile-name", {
"profile": profileName
}), I18n.tr("toast.power-profile.changed"), profileName.toLowerCase().replace(" ", ""));
}
}
}
// Noctalia Performance Mode
// - Turning shadow off
// - Turning animation off
// - Do Not Disturb
function toggleNoctaliaPerformance() {
noctaliaPerformanceMode = !noctaliaPerformanceMode;
}
function setNoctaliaPerformance(value) {
noctaliaPerformanceMode = value;
}
onNoctaliaPerformanceModeChanged: {
if (noctaliaPerformanceMode) {
ToastService.showNotice(I18n.tr("toast.noctalia-performance.label"), I18n.tr("toast.noctalia-performance.enabled"), "rocket");
} else {
ToastService.showNotice(I18n.tr("toast.noctalia-performance.label"), I18n.tr("toast.noctalia-performance.disabled"), "rocket-off");
}
}
}
@@ -0,0 +1,8 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: notifications are handled outside the shell.
Singleton {
property bool doNotDisturb: false
}
@@ -0,0 +1,205 @@
pragma Singleton
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
Singleton {
id: root
// Map to track active sound players: resolvedPath -> MediaPlayer instance
property var activePlayers: ({})
// Check if QtMultimedia is available
property bool multimediaAvailable: false
// Container for dynamically created players
Item {
id: playersContainer
}
Component.onCompleted: {
// Test if QtMultimedia is available by trying to create a simple component
try {
var testComponent = Qt.createQmlObject(`
import QtQuick
import QtMultimedia
Item {}
`, root, "MultimediaTest");
if (testComponent) {
multimediaAvailable = true;
testComponent.destroy();
Logger.i("SoundService", "QtMultimedia found - sound playback enabled");
}
} catch (e) {
multimediaAvailable = false;
Logger.w("SoundService", "QtMultimedia not available - no audio will be played from noctalia-shell");
}
}
function resolvePath(soundPath) {
if (!soundPath || soundPath === "") {
return "";
}
let resolvedPath = soundPath;
// If it's just a filename (no path separators), assume it's in Assets/Sounds/
if (!soundPath.includes("/") && !soundPath.startsWith("file://")) {
resolvedPath = Quickshell.shellDir + "/Assets/Sounds/" + soundPath;
} else if (!soundPath.startsWith("/") && !soundPath.startsWith("file://")) {
// Relative path - assume it's relative to shellDir
resolvedPath = Quickshell.shellDir + "/" + soundPath;
} else if (soundPath.startsWith("file://")) {
resolvedPath = soundPath.substring(7); // Remove "file://" prefix
}
// Absolute paths are used as-is
return resolvedPath;
}
function playSound(soundPath, options) {
if (!soundPath || soundPath === "") {
Logger.w("SoundService", "No sound path provided");
return;
}
if (!multimediaAvailable) {
Logger.d("SoundService", "QtMultimedia not available, cannot play sound:", soundPath);
return;
}
const opts = options || {};
const volume = opts.volume !== undefined ? opts.volume : 1.0;
const fallback = opts.fallback !== undefined ? opts.fallback : false;
const repeat = opts.repeat !== undefined ? opts.repeat : false;
// Resolve path
const resolvedPath = resolvePath(soundPath);
// Stop any existing player for this path if it's looping
if (repeat && activePlayers[resolvedPath]) {
stopSound(soundPath);
}
// Create MediaPlayer instance dynamically with QtMultimedia import
const loopsValue = repeat ? "MediaPlayer.Infinite" : "1";
const escapedPath = resolvedPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
const playerQml = `
import QtQuick
import QtMultimedia
import Quickshell
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.System
MediaPlayer {
id: mediaPlayer
property string resolvedPath: "${escapedPath}"
property bool shouldFallback: ${fallback && !repeat}
property real soundVolume: ${Math.max(0, Math.min(1, volume))}
source: "file://${escapedPath}"
loops: ${loopsValue}
audioOutput: AudioOutput {
volume: soundVolume
}
onErrorOccurred: {
Logger.w("SoundService", "Error playing sound:", source, error, errorString);
if (shouldFallback) {
const fallbackPath = Quickshell.shellDir + "/Assets/Sounds/notification.mp3";
if (fallbackPath !== resolvedPath) {
SoundService.playSound(fallbackPath, {
volume: soundVolume,
fallback: false,
repeat: false
});
}
}
if (SoundService.activePlayers[resolvedPath]) {
delete SoundService.activePlayers[resolvedPath];
}
destroy();
}
onPlaybackStateChanged: function (state) {
if (state === MediaPlayer.StoppedState && loops === 1) {
if (SoundService.activePlayers[resolvedPath]) {
delete SoundService.activePlayers[resolvedPath];
}
destroy();
}
}
Component.onCompleted: {
play();
}
}
`;
try {
const player = Qt.createQmlObject(playerQml, playersContainer, "MediaPlayer_" + resolvedPath.replace(/[^a-zA-Z0-9]/g, "_"));
if (!player) {
Logger.w("SoundService", "Failed to create MediaPlayer for:", resolvedPath);
// Try fallback if requested
if (fallback && !repeat) {
const defaultSound = Quickshell.shellDir + "/Assets/Sounds/notification.mp3";
if (defaultSound !== resolvedPath) {
playSound(defaultSound, {
volume: volume,
fallback: false,
repeat: false
});
}
}
return;
}
// Store player in activePlayers map
activePlayers[resolvedPath] = player;
Logger.d("SoundService", "Playing sound:", resolvedPath, `(volume: ${Math.round(volume * 100)}%)`, repeat ? "(repeat)" : "");
} catch (e) {
Logger.w("SoundService", "Failed to create MediaPlayer:", e);
// Try fallback if requested
if (fallback && !repeat) {
const defaultSound = Quickshell.shellDir + "/Assets/Sounds/notification.mp3";
if (defaultSound !== resolvedPath) {
playSound(defaultSound, {
volume: volume,
fallback: false,
repeat: false
});
}
}
}
}
function stopSound(soundPath) {
if (!multimediaAvailable) {
// If multimedia isn't available, there are no active players to stop
return;
}
if (soundPath) {
// Resolve path the same way as playSound
const resolvedPath = resolvePath(soundPath);
// Stop and remove the player for this specific sound
if (activePlayers[resolvedPath]) {
const player = activePlayers[resolvedPath];
player.stop();
delete activePlayers[resolvedPath];
player.destroy();
Logger.d("SoundService", "Stopped sound:", resolvedPath);
}
} else {
// Stop all active players (typically used for repeating sounds)
const paths = Object.keys(activePlayers);
for (let i = 0; i < paths.length; i++) {
const path = paths[i];
const player = activePlayers[path];
player.stop();
player.destroy();
}
activePlayers = {};
Logger.d("SoundService", "Stopped all sounds");
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,22 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../core" as Core
import "../../../../services" as GS
// glassMxrph stand-in: the bar is glassMxrph's own top bar.
Singleton {
readonly property bool isVisible: true
property int widgetsRevision: 0
function getTooltipDirection(screenName) {
return "bottom";
}
function getPillDirection(widgetInstance) {
return !widgetInstance || widgetInstance.section !== "left";
}
// Plugin settings live in Settings → Plugins.
function openPluginSettings(screen, pluginManifest) {
GS.PluginService.focusedSettings = pluginManifest && pluginManifest.id ? pluginManifest.id : "";
Core.ShellState.openSettings("plugins");
}
}
@@ -0,0 +1,13 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia's built-in widget registry is not used.
Singleton {
property var widgets: ({})
property var widgetMetadata: ({})
property bool editMode: false
function hasWidget(id) {
return false;
}
}
@@ -0,0 +1,13 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia's built-in widget registry is not used.
Singleton {
property var widgets: ({})
property var widgetMetadata: ({})
property bool editMode: false
function hasWidget(id) {
return false;
}
}
@@ -0,0 +1,13 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia's built-in widget registry is not used.
Singleton {
property var widgets: ({})
property var widgetMetadata: ({})
property bool editMode: false
function hasWidget(id) {
return false;
}
}
@@ -0,0 +1,13 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia's built-in widget registry is not used.
Singleton {
property var widgets: ({})
property var widgetMetadata: ({})
property bool editMode: false
function hasWidget(id) {
return false;
}
}
@@ -0,0 +1,55 @@
pragma Singleton
import QtQuick
import Quickshell
import Quickshell.Hyprland
import "../../../../core" as Core
// glassMxrph stand-in: context menus open where the plugin asks and close on
// an outside click (Hyprland focus grab); launcher calls use glassMxrph's.
Singleton {
id: root
property var openedPanel: null
property var lockScreen: null
property bool isKeybindRecording: false
property var menu: null
function showContextMenu(contextMenu, anchorItem, screen, targetItem) {
if (!contextMenu || !anchorItem)
return;
closeContextMenu(screen);
menu = contextMenu;
contextMenu.openAtItem(anchorItem, screen, targetItem);
Qt.callLater(() => grab.active = !!root.menu);
}
function closeContextMenu(screen) {
grab.active = false;
if (menu && typeof menu.close === "function")
menu.close();
menu = null;
}
function getPopupMenuWindow(screen) {
return null;
}
function getPanel(name, screen) {
return null;
}
function isLauncherOpen() {
return Core.ShellState.launcherOpen;
}
function closeLauncher() {
Core.ShellState.launcherOpen = false;
}
function openLauncherWithSearch(text) {
Core.ShellState.openLauncher();
}
function setLauncherSearchText(text) {
}
function getLauncherSearchText() {
return "";
}
HyprlandFocusGrab {
id: grab
windows: root.menu ? [root.menu] : []
onCleared: root.closeContextMenu(null)
}
}
@@ -0,0 +1,24 @@
pragma Singleton
import QtQuick
import Quickshell
// glassMxrph stand-in: Noctalia toasts become desktop notifications.
Singleton {
function notify(urgency, title, description, duration) {
Quickshell.execDetached(["notify-send", "-a", "glassMxrph", "-u", urgency, "-t", String(duration || 4000), String(title || ""), String(description || "")]);
}
function showNotice(title, description = "", icon = "", duration = 3000, actionLabel = "", actionCallback = null) {
notify("low", title, description, duration);
}
function showInfo(title, description = "", icon = "", duration = 3000) {
notify("low", title, description, duration);
}
function showWarning(title, description = "", duration = 4000, actionLabel = "", actionCallback = null) {
notify("normal", title, description, duration);
}
function showError(title, description = "", duration = 6000, actionLabel = "", actionCallback = null) {
notify("critical", title, description, duration);
}
function dismissToast() {
}
}
@@ -0,0 +1,40 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../core" as Core
import "../../../../services" as GS
// glassMxrph stand-in: tooltips of bar widgets use the shell's hover popout
// (it hangs from the bar); tooltips elsewhere are not shown.
Singleton {
id: root
property var current: null
function inBar(target) {
const w = target && target.QsWindow ? target.QsWindow.window : null;
return !!w && GS.TrayService.barWindows.includes(w);
}
function show(target, content, direction, delay, fontFamily) {
if (!target || !content || !inBar(target))
return;
current = target;
Core.PopoutState.hover(target, "tooltip", String(content));
}
function hide(target) {
if (target && current !== target)
return;
if (current)
Core.PopoutState.unhover(current);
current = null;
}
function hideImmediately() {
current = null;
Core.PopoutState.close();
}
function updateContent(newContent) {
updateText(newContent);
}
function updateText(newText) {
if (current && Core.PopoutState.anchor === current)
Core.PopoutState.text = String(newText);
}
}
@@ -0,0 +1,29 @@
pragma Singleton
import QtQuick
import Quickshell
import "../../../../services" as GS
// glassMxrph stand-in for wallpaper queries.
Singleton {
readonly property bool isInitialized: true
readonly property var currentWallpapers: GS.ConfigService.ready ? GS.ConfigService.data.wallpaper.byMonitor : ({})
signal wallpaperProcessingComplete
function getWallpaper(screenName) {
return currentWallpapers[screenName] || "";
}
function getWallpapersEffectiveMap() {
return currentWallpapers;
}
function changeWallpaper(path, screenName) {
GS.WallpaperService.apply(path);
}
function isSolidColorPath(path) {
return String(path).startsWith("solid://");
}
function getSolidColor(path) {
return String(path).replace("solid://", "");
}
function getFillModeUniform() {
return 1;
}
}
@@ -0,0 +1,49 @@
import QtQuick
import qs.compat.noctalia.Commons
Item {
id: root
property color fillColor: Color.mPrimary
property color strokeColor: Color.mOnSurface
property int strokeWidth: 0
property var values: []
property bool vertical: false
property string barPosition: "top" // "top", "bottom", "left", "right"
property bool mirrored: true
// Minimum signal properties
property bool showMinimumSignal: false
property real minimumSignalValue: 0.01 // Default to 1% of height
// Pre compute horizontal mirroring
readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0
readonly property int totalBars: mirrored ? valuesCount * 2 : valuesCount
readonly property real barSlotSize: totalBars > 0 ? (vertical ? height : width) / totalBars : 0
readonly property bool highQuality: (Settings.data.audio.visualizerType === "low") ? false : true
Repeater {
model: root.totalBars
Rectangle {
property int valueIndex: root.mirrored ? (index < root.valuesCount ? root.valuesCount - 1 - index : index - root.valuesCount) : index
property real rawAmp: (root.values && root.values[valueIndex] !== undefined) ? root.values[valueIndex] : 0
property real amp: (root.showMinimumSignal && rawAmp === 0) ? root.minimumSignalValue : rawAmp
color: root.fillColor
border.color: root.strokeColor
border.width: root.strokeWidth
antialiasing: root.highQuality
smooth: root.highQuality
// Only update when value actually changes - reduces GPU load
width: vertical ? root.width * amp : root.barSlotSize * 0.5
height: vertical ? root.barSlotSize * 0.5 : root.height * amp
x: vertical ? (root.barPosition === "left" ? 0 : root.width - width) : index * root.barSlotSize + (root.barSlotSize * 0.25)
y: vertical ? index * root.barSlotSize + (root.barSlotSize * 0.25) : root.height - height
// Disable updates when invisible to save GPU
visible: root.visible
}
}
}
@@ -0,0 +1,51 @@
import QtQuick
import qs.compat.noctalia.Commons
Item {
id: root
property color fillColor: Color.mPrimary
property color strokeColor: Color.mOnSurface
property int strokeWidth: 0
property var values: []
property bool vertical: false
property bool mirrored: true
// Minimum signal properties
property bool showMinimumSignal: false
property real minimumSignalValue: 0.01 // Default to 1% of height
// Pre-compute mirroring
readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0
readonly property int totalBars: mirrored ? valuesCount * 2 : valuesCount
readonly property real barSlotSize: totalBars > 0 ? (vertical ? height : width) / totalBars : 0
readonly property bool highQuality: (Settings.data.audio.visualizerType === "low") ? false : true
readonly property real centerY: height / 2
readonly property real centerX: width / 2
Repeater {
model: root.totalBars
Rectangle {
property int valueIndex: root.mirrored ? (index < root.valuesCount ? root.valuesCount - 1 - index : index - root.valuesCount) : index
property real rawAmp: (root.values && root.values[valueIndex] !== undefined) ? root.values[valueIndex] : 0
property real amp: (root.showMinimumSignal && rawAmp === 0) ? root.minimumSignalValue : rawAmp
property real barSize: (vertical ? root.width : root.height) * amp
color: root.fillColor
border.color: root.strokeColor
border.width: root.strokeWidth
antialiasing: root.highQuality
smooth: root.highQuality
width: vertical ? barSize : root.barSlotSize * 0.8
height: vertical ? root.barSlotSize * 0.8 : barSize
x: vertical ? root.centerX - (barSize / 2) : index * root.barSlotSize + (root.barSlotSize * 0.25)
y: vertical ? index * root.barSlotSize + (root.barSlotSize * 0.25) : root.centerY - (barSize / 2)
// Disable updates when invisible to save GPU
visible: root.visible
}
}
}
@@ -0,0 +1,72 @@
import QtQuick
import Quickshell
import qs.compat.noctalia.Commons
Item {
id: root
property color fillColor: Color.mPrimary
property color strokeColor: Color.mOnSurface
property int strokeWidth: 0
property var values: []
property bool vertical: false
property bool mirrored: true
// Minimum signal properties
property bool showMinimumSignal: false
property real minimumSignalValue: 0.01 // Default to 1% of height
readonly property int valuesCount: (values && values.length !== undefined) ? values.length : 0
readonly property bool hasData: valuesCount >= 2
// Data texture: one pixel per value, R channel = amplitude
Item {
id: dataRow
width: Math.max(root.valuesCount, 4)
height: 1
Repeater {
model: dataRow.width
Rectangle {
required property int index
x: index
width: 1
height: 1
color: {
if (index >= root.valuesCount)
return Qt.rgba(0, 0, 0, 1);
var v = root.values[index];
if (v === undefined || v === null || !isFinite(v))
v = 0;
if (root.showMinimumSignal && v === 0)
v = root.minimumSignalValue;
return Qt.rgba(Math.max(0, Math.min(1, v)), 0, 0, 1);
}
}
}
}
ShaderEffectSource {
id: dataTex
sourceItem: dataRow
textureSize: Qt.size(dataRow.width, 1)
live: true
smooth: false
hideSource: true
}
ShaderEffect {
anchors.fill: parent
visible: root.hasData && root.width > 0 && root.height > 0
property variant dataSource: dataTex
property color fillColor: root.fillColor
property real count: root.valuesCount
property real texWidth: dataRow.width
property real vertical: root.vertical ? 1.0 : 0.0
property real mirrored: root.mirrored ? 1.0 : 0.0
fragmentShader: Qt.resolvedUrl(Quickshell.shellDir + "/Shaders/qsb/wave_spectrum.frag.qsb")
blending: true
}
}
@@ -0,0 +1,205 @@
import QtQuick
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Widgets
// Battery widget with Android 16 style rendering (horizontal or vertical)
Item {
id: root
// Data (must be provided by parent)
required property real percentage
required property bool charging
required property bool pluggedIn
required property bool ready
required property bool low
required property bool critical
// Sizing - baseSize controls overall scaleFactor for bar/panel usage
property real baseSize: Style.fontSizeM
// Styling - no hardcoded colors, only theme colors
property color baseColor: Color.mOnSurface
property color lowColor: Color.mError
property color chargingColor: Color.mPrimary
property color textColor: Color.mSurface
// Display options
property bool showPercentageText: true
property bool vertical: false
// Alternating state icon display (toggles between percentage and icon when charging)
property bool showStateIcon: false
onChargingChanged: {
if (!charging)
showStateIcon = false;
}
// Internal sizing calculations based on baseSize
readonly property real scaleFactor: baseSize / Style.fontSizeM
readonly property real bodyWidth: {
const min = Style.toOdd(22 * scaleFactor);
if (!showPercentageText) {
return min;
}
// increase length when showing 100%
if (percentage > 99) {
const max = Style.toOdd(30 * scaleFactor);
return max;
}
return min;
}
readonly property real bodyHeight: Style.toOdd(14 * scaleFactor)
readonly property real terminalWidth: Math.round(2.5 * scaleFactor)
readonly property real terminalHeight: Math.round(7 * scaleFactor)
readonly property real cornerRadius: Math.round(3 * scaleFactor)
// Total size is just body + terminal (no external icon)
readonly property real totalWidth: vertical ? bodyHeight : bodyWidth + terminalWidth
readonly property real totalHeight: vertical ? bodyWidth + terminalWidth : bodyHeight
// Determine active color based on state
readonly property color activeColor: {
if (!ready) {
return Qt.alpha(baseColor, Style.opacityMedium);
}
if (charging) {
return chargingColor;
}
if (low || critical) {
return lowColor;
}
return baseColor;
}
// Background color for empty portion (semi-transparent)
readonly property color emptyColor: Qt.alpha(baseColor, 0.66)
// State icon logic
readonly property string stateIcon: {
if (!ready)
return "x";
if (charging)
return "bolt-filled";
if (pluggedIn)
return "plug-filled";
return "";
}
// Animated percentage for smooth transitions
property real animatedPercentage: percentage
Behavior on animatedPercentage {
enabled: !Settings.data.general.animationDisabled
NumberAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
// Timer to alternate between percentage text and state icon when charging/plugged
Timer {
id: alternateTimer
interval: 4000
repeat: true
running: root.charging && root.showPercentageText
onTriggered: root.showStateIcon = !root.showStateIcon
}
implicitWidth: Math.round(totalWidth)
implicitHeight: Math.round(totalHeight)
Layout.maximumWidth: implicitWidth
Layout.maximumHeight: implicitHeight
// Battery body container
Item {
id: batteryBody
width: root.vertical ? root.bodyHeight : root.bodyWidth + root.terminalWidth
height: root.vertical ? root.bodyWidth + root.terminalWidth : root.bodyHeight
anchors.left: root.vertical ? undefined : parent.left
anchors.bottom: root.vertical ? parent.bottom : undefined
anchors.horizontalCenter: root.vertical ? parent.horizontalCenter : undefined
anchors.verticalCenter: root.vertical ? undefined : parent.verticalCenter
// Battery body background
Rectangle {
id: bodyBackground
y: root.vertical ? root.terminalWidth : 0
width: root.vertical ? root.bodyHeight : root.bodyWidth
height: root.vertical ? root.bodyWidth : root.bodyHeight
radius: root.cornerRadius
color: root.emptyColor
}
// Terminal cap
Rectangle {
x: root.vertical ? (root.bodyHeight - root.terminalHeight) / 2 : root.bodyWidth
y: root.vertical ? 0 : (root.bodyHeight - root.terminalHeight) / 2
width: root.vertical ? root.terminalHeight : root.terminalWidth
height: root.vertical ? root.terminalWidth : root.terminalHeight
radius: root.cornerRadius / 2
color: root.critical ? root.lowColor : root.emptyColor
}
// Fill level
Rectangle {
id: fillRect
visible: root.ready && (root.animatedPercentage > 0 || root.critical)
x: 0
y: root.vertical ? root.terminalWidth + root.bodyWidth * (1 - (root.critical ? 1 : root.animatedPercentage / 100)) : 0
width: root.vertical ? root.bodyHeight : root.bodyWidth * (root.critical ? 1 : root.animatedPercentage / 100)
height: root.vertical ? root.bodyWidth * (root.critical ? 1 : root.animatedPercentage / 100) : root.bodyHeight
radius: root.cornerRadius
color: root.activeColor
}
}
// Percentage text overlaid on battery center
NText {
id: percentageText
visible: opacity > 0
opacity: root.showPercentageText && root.ready && (root.charging ? !root.showStateIcon : !root.pluggedIn) ? 1 : 0
x: batteryBody.x + Style.pixelAlignCenter(bodyBackground.width, width)
y: batteryBody.y + bodyBackground.y + Style.pixelAlignCenter(bodyBackground.height, height)
font.family: Settings.data.ui.fontFixed
font.weight: Style.fontWeightBold
text: root.vertical ? String(Math.round(root.animatedPercentage)).split('').join('\n') : Math.round(root.animatedPercentage)
pointSize: root.baseSize * (root.vertical ? 0.82 : 0.82)
color: Qt.alpha(root.textColor, 0.75)
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
lineHeight: root.vertical ? 0.7 : 1.0
lineHeightMode: Text.ProportionalHeight
Behavior on opacity {
enabled: !Settings.data.general.animationDisabled
NumberAnimation {
duration: Style.animationFast
easing.type: Easing.InOutQuad
}
}
}
// State icon centered inside battery body (shown when alternating)
NIcon {
id: stateIconOverlay
visible: opacity > 0
opacity: !root.ready || (root.charging ? (root.showStateIcon || !root.showPercentageText) : root.pluggedIn) ? 1 : 0
x: batteryBody.x + Style.pixelAlignCenter(bodyBackground.width, width)
y: batteryBody.y + bodyBackground.y + Style.pixelAlignCenter(bodyBackground.height, height)
icon: root.stateIcon
pointSize: Style.toOdd(root.baseSize)
color: Qt.alpha(root.textColor, 0.75)
Behavior on opacity {
enabled: !Settings.data.general.animationDisabled
NumberAnimation {
duration: Style.animationFast
easing.type: Easing.InOutQuad
}
}
}
}
@@ -0,0 +1,30 @@
import QtQuick
import qs.compat.noctalia.Commons
// Rounded group container using the variant surface color.
// To be used in side panels and settings panes to group fields or buttons.
// Opacity is based on panelBackgroundOpacity but clamped to a minimum to avoid full transparency.
Item {
id: root
property color color: Color.mSurfaceVariant
property bool forceOpaque: false
property alias radius: bg.radius
property alias border: bg.border
Rectangle {
id: bg
anchors.fill: parent
radius: Style.radiusM
border.color: Style.boxBorderColor
border.width: Style.borderS
color: {
if (forceOpaque) {
return root.color;
}
return Color.smartAlpha(root.color);
}
}
}
@@ -0,0 +1,66 @@
import QtQuick
import qs.compat.noctalia.Commons
Item {
id: root
property bool running: true
property color color: Color.mPrimary
property int size: Style.baseWidgetSize
property int strokeWidth: Style.borderL
property int duration: Style.animationSlow * 2
implicitWidth: size
implicitHeight: size
onColorChanged: canvas.requestPaint()
// GPU-optimized spinner - draw once, rotate with GPU transform
Item {
id: spinner
anchors.fill: parent
// Static canvas - drawn ONCE, then cached
Canvas {
id: canvas
anchors.fill: parent
renderStrategy: Canvas.Cooperative // Better performance than Threaded for simple shapes
renderTarget: Canvas.FramebufferObject // GPU texture
// Enable layer caching - critical for performance!
layer.enabled: true
layer.smooth: true
Component.onCompleted: {
requestPaint();
}
onPaint: {
var ctx = getContext("2d");
ctx.reset();
var centerX = width / 2;
var centerY = height / 2;
var radius = Math.min(width, height) / 2 - strokeWidth / 2;
ctx.strokeStyle = root.color;
ctx.lineWidth = Math.max(1, root.strokeWidth);
ctx.lineCap = "round";
// Draw arc with gap (270 degrees = 3/4 of circle)
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + Math.PI * 1.5);
ctx.stroke();
}
}
// Smooth rotation animation - uses GPU transform, NO canvas repaints!
RotationAnimation on rotation {
running: root.running
from: 0
to: 360
duration: root.duration
loops: Animation.Infinite
}
}
}
@@ -0,0 +1,184 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
Item {
id: root
// Public properties
property string text: ""
property string icon: ""
property var tooltipText
property color backgroundColor: Color.mPrimary
property color textColor: Color.mOnPrimary
property color hoverColor: Color.mHover
property color textHoverColor: Color.mOnHover
property real fontSize: Style.fontSizeM
property int fontWeight: Style.fontWeightSemiBold
property real iconSize: Style.fontSizeL
property bool outlined: false
property int horizontalAlignment: Qt.AlignHCenter
property real buttonRadius: Style.iRadiusS
// Signals
signal clicked
signal rightClicked
signal middleClicked
signal entered
signal exited
// Internal properties
property bool hovered: false
readonly property color contentColor: {
if (!root.enabled) {
return Color.mOnSurfaceVariant;
}
if (root.hovered) {
return root.textHoverColor;
}
if (root.outlined) {
return root.backgroundColor;
}
return root.textColor;
}
// Dimensions - include margin so border renders cleanly at fractional scales
implicitWidth: bg.implicitWidth + 2 * Style.borderS
implicitHeight: bg.implicitHeight + 2 * Style.borderS
opacity: enabled ? 1.0 : 0.6
Rectangle {
id: bg
anchors.fill: parent
anchors.margins: Style.borderS
implicitWidth: contentRow.implicitWidth + (root.fontSize * 2)
implicitHeight: contentRow.implicitHeight + (root.fontSize)
radius: root.buttonRadius
color: {
if (!root.enabled)
return root.outlined ? "transparent" : Qt.lighter(Color.mSurfaceVariant, 1.2);
if (root.hovered)
return root.hoverColor;
return root.outlined ? "transparent" : root.backgroundColor;
}
border.width: root.outlined ? Style.borderS : 0
border.color: {
if (!root.enabled)
return Color.mOutline;
if (root.hovered)
return root.hoverColor;
return root.outlined ? root.backgroundColor : "transparent";
}
Behavior on color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.OutCubic
}
}
Behavior on border.color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.OutCubic
}
}
// Content
RowLayout {
id: contentRow
anchors.verticalCenter: parent.verticalCenter
anchors.left: root.horizontalAlignment === Qt.AlignLeft ? parent.left : undefined
anchors.horizontalCenter: root.horizontalAlignment === Qt.AlignHCenter ? parent.horizontalCenter : undefined
anchors.leftMargin: root.horizontalAlignment === Qt.AlignLeft ? Style.marginL : 0
spacing: Style.marginXS
// Icon (optional)
NIcon {
Layout.alignment: Qt.AlignVCenter
visible: root.icon !== ""
icon: root.icon
pointSize: root.iconSize
color: root.contentColor
Behavior on color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.OutCubic
}
}
}
// Text
NText {
Layout.alignment: Qt.AlignVCenter
visible: root.text !== ""
text: root.text
pointSize: root.fontSize
font.weight: root.fontWeight
color: root.contentColor
Behavior on color {
enabled: !Color.isTransitioning
ColorAnimation {
duration: Style.animationFast
easing.type: Easing.OutCubic
}
}
}
}
// Mouse interaction
MouseArea {
id: mouseArea
anchors.fill: parent
enabled: root.enabled
hoverEnabled: true
acceptedButtons: Qt.LeftButton | Qt.RightButton | Qt.MiddleButton
cursorShape: root.enabled ? Qt.PointingHandCursor : Qt.ArrowCursor
onEntered: {
root.hovered = root.enabled ? true : false;
root.entered();
if (root.hovered && root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.show(root, root.tooltipText);
}
}
onExited: {
root.hovered = false;
root.exited();
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
}
onPressed: mouse => {
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
if (mouse.button === Qt.LeftButton) {
root.clicked();
} else if (mouse.button == Qt.RightButton) {
root.rightClicked();
} else if (mouse.button == Qt.MiddleButton) {
root.middleClicked();
}
}
onCanceled: {
root.hovered = false;
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
}
}
}
}
@@ -0,0 +1,87 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import qs.compat.noctalia.Commons
RowLayout {
id: root
// Public API
property string label: ""
property string description: ""
property bool checked: false
property bool hovering: false
property color activeColor: Color.mPrimary
property color activeOnColor: Color.mOnPrimary
property int baseSize: root.defaultSize
property real labelSize: Style.fontSizeL
readonly property int defaultSize: Style.baseWidgetSize * 0.7
signal toggled(bool checked)
signal entered
signal exited
Layout.fillWidth: true
NLabel {
label: root.label
labelSize: root.labelSize
description: root.description
visible: root.label !== "" || root.description !== ""
}
// Spacer to push the checkbox to the far right
Item {
Layout.fillWidth: true
}
Rectangle {
id: box
opacity: enabled ? 1.0 : 0.6
Layout.margins: Style.borderS
implicitWidth: Style.toOdd(root.baseSize)
implicitHeight: Style.toOdd(root.baseSize)
radius: Style.iRadiusXS * (root.baseSize / root.defaultSize)
color: root.checked ? root.activeColor : Color.mSurface
border.color: Color.mOutline
border.width: Style.borderS
Behavior on color {
ColorAnimation {
duration: Style.animationFast
}
}
Behavior on border.color {
ColorAnimation {
duration: Style.animationFast
}
}
NIcon {
visible: root.checked
x: Style.pixelAlignCenter(parent.width, width)
y: Style.pixelAlignCenter(parent.height, height)
icon: "check"
color: root.activeOnColor
pointSize: Style.toOdd(root.baseSize * 0.5)
}
MouseArea {
anchors.fill: parent
cursorShape: Qt.PointingHandCursor
hoverEnabled: true
onEntered: {
hovering = true;
root.entered();
}
onExited: {
hovering = false;
root.exited();
}
onClicked: root.toggled(!root.checked)
}
}
}
@@ -0,0 +1,164 @@
import QtQuick
import QtQuick.Layouts
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Services.UI
import qs.compat.noctalia.Widgets
// Compact circular statistic display using Layout management
Item {
id: root
property real ratio: 0 // 0..1 range
property string icon: ""
property string suffix: "%"
property real contentScale: 1.0
property color fillColor: Color.mPrimary
property var tooltipText
property string tooltipDirection: "top"
// Arc geometry constants
readonly property real _gaugeSize: 60 * contentScale
readonly property real _lineWidth: 6 * contentScale
readonly property real _arcRadius: _gaugeSize / 2 - 5 * contentScale
// Arc goes from 150° to 390° (30°), gap at bottom
// Bottom of arc is at y = center + radius * sin(30°) = center + radius * 0.5
// Plus half line width for stroke
readonly property real _arcBottomY: _gaugeSize / 2 + _arcRadius * 0.5 + _lineWidth / 2
// Height needs to include the icon which sits inside the arc gap
// Icon is ~12px tall, positioned 4px below text center, need ~4px more padding
readonly property real _contentHeight: _arcBottomY + 4 * contentScale
implicitWidth: Math.round(_gaugeSize)
implicitHeight: Math.round(_contentHeight)
Layout.maximumWidth: implicitWidth
Layout.maximumHeight: implicitHeight
// Animated ratio for smooth transitions - reduces repaint frequency
property real animatedRatio: ratio
Behavior on animatedRatio {
enabled: !Settings.data.general.animationDisabled
NumberAnimation {
duration: Style.animationNormal
easing.type: Easing.OutCubic
}
}
// Repaint gauge when animated ratio changes (throttled by animation)
onAnimatedRatioChanged: {
if (!repaintTimer.running) {
repaintTimer.start();
}
}
onFillColorChanged: gauge.requestPaint()
// Throttle timer to limit repaint frequency during animation (~30 FPS)
Timer {
id: repaintTimer
interval: 33
repeat: true
onTriggered: {
gauge.requestPaint();
// Stop repeating once animation settles
if (Math.abs(root.animatedRatio - root.ratio) < 0.001) {
stop();
}
}
}
Canvas {
id: gauge
width: root._gaugeSize
height: root._gaugeSize
anchors.horizontalCenter: parent.horizontalCenter
y: 0
// Optimized Canvas settings for better GPU performance
renderStrategy: Canvas.Cooperative
renderTarget: Canvas.FramebufferObject
// Enable layer caching - critical for performance!
layer.enabled: true
layer.smooth: true
// Hide until first paint to avoid white FBO flash
visible: false
onPainted: visible = true
Component.onCompleted: {
requestPaint();
}
onPaint: {
const ctx = getContext("2d");
const w = width, h = height;
const cx = w / 2, cy = h / 2;
const r = root._arcRadius;
// Rotated 90° to the right: gap at the bottom
// Start at 150° and end at 390° (30°) → bottom opening
const start = Math.PI * 5 / 6; // 150°
const endBg = Math.PI * 13 / 6; // 390° (equivalent to 30°)
ctx.reset();
ctx.lineWidth = root._lineWidth;
ctx.lineCap = Settings.data.general.iRadiusRatio > 0 ? "round" : "butt";
// Track uses outline for contrast against surfaceVariant backgrounds
ctx.strokeStyle = Color.mSurface;
ctx.beginPath();
ctx.arc(cx, cy, r, start, endBg);
ctx.stroke();
// Value arc - only draw if ratio is meaningful (> 0.5%)
const r2 = Math.max(0, Math.min(1, root.animatedRatio));
if (r2 > 0.005) {
const end = start + (endBg - start) * r2;
ctx.strokeStyle = root.fillColor;
ctx.beginPath();
ctx.arc(cx, cy, r, start, end);
ctx.stroke();
}
}
}
// Percent centered in the circle
NText {
id: valueLabel
anchors.horizontalCenter: gauge.horizontalCenter
anchors.verticalCenter: gauge.verticalCenter
anchors.verticalCenterOffset: -4 * root.contentScale
text: `${Math.round(root.animatedRatio * 100)}${root.suffix}`
pointSize: Style.fontSizeM * root.contentScale * 0.9
font.weight: Style.fontWeightBold
color: root.fillColor
horizontalAlignment: Text.AlignHCenter
}
NIcon {
id: iconText
anchors.horizontalCenter: gauge.horizontalCenter
anchors.top: valueLabel.bottom
anchors.topMargin: 4 * root.contentScale
icon: root.icon
color: root.fillColor
pointSize: Style.fontSizeM * root.contentScale
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
MouseArea {
anchors.fill: parent
hoverEnabled: true
onEntered: {
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.show(root, root.tooltipText, root.tooltipDirection);
}
}
onExited: {
if (root.tooltipText && (!Array.isArray(root.tooltipText) || root.tooltipText.length > 0)) {
TooltipService.hide();
}
}
}
}
@@ -0,0 +1,442 @@
import QtQuick
import QtQuick.Layouts
import Quickshell
import "../Helpers/ColorsConvert.js" as ColorsConvert
import qs.compat.noctalia.Commons
import qs.compat.noctalia.Widgets
Item {
id: root
property var now: Time.now
// Style: "analog" or "digital"
property string clockStyle: "analog"
// Show seconds progress ring (digital only)
property bool showProgress: true
// Color properties
property color backgroundColor: Color.mPrimary
property color clockColor: Color.mOnPrimary
property color secondHandColor: {
var defaultColor = Color.mError;
var bestContrast = 1.0; // 1.0 is "no contrast"
var bestColor = defaultColor;
var candidates = [Color.mSecondary, Color.mTertiary, Color.mError];
const minContrast = 1.149;
for (var i = 0; i < candidates.length; i++) {
var candidate = candidates[i];
var contrastClock = ColorsConvert.getContrastRatio(candidate.toString(), clockColor.toString());
if (contrastClock < minContrast) {
continue;
}
var contrastBg = ColorsConvert.getContrastRatio(candidate.toString(), backgroundColor.toString());
if (contrastBg < minContrast) {
continue;
}
var currentWorstContrast = Math.min(contrastBg, contrastClock);
if (currentWorstContrast > bestContrast) {
bestContrast = currentWorstContrast;
bestColor = candidate;
}
}
return bestColor;
}
property color progressColor: root.secondHandColor
// Font size properties for digital clock
property real hoursFontSize: Style.fontSizeXS
property real minutesFontSize: Style.fontSizeXXS
property int hoursFontWeight: Style.fontWeightBold
property int minutesFontWeight: Style.fontWeightBold
// Scale ratio for canvas line widths (used by desktop widget scaling)
property real scaleRatio: Style.uiScaleRatio
height: Math.round((Style.fontSizeXXXL * 1.9) / 2 * Style.uiScaleRatio) * 2
width: root.height
Loader {
id: clockLoader
anchors.fill: parent
sourceComponent: {
if (root.clockStyle === "analog")
return analogClockComponent;
if (root.clockStyle === "binary")
return binaryClockComponent;
return digitalClockComponent;
}
onLoaded: {
item.now = Qt.binding(function () {
return root.now;
});
item.backgroundColor = Qt.binding(function () {
return root.backgroundColor;
});
item.clockColor = Qt.binding(function () {
return root.clockColor;
});
if (item.hasOwnProperty("secondHandColor")) {
item.secondHandColor = Qt.binding(function () {
return root.secondHandColor;
});
}
if (item.hasOwnProperty("progressColor")) {
item.progressColor = Qt.binding(function () {
return root.progressColor;
});
}
if (item.hasOwnProperty("hoursFontSize")) {
item.hoursFontSize = Qt.binding(function () {
return root.hoursFontSize;
});
}
if (item.hasOwnProperty("minutesFontSize")) {
item.minutesFontSize = Qt.binding(function () {
return root.minutesFontSize;
});
}
if ("hoursFontWeight" in item) {
item.hoursFontWeight = Qt.binding(function () {
return root.hoursFontWeight;
});
}
if ("minutesFontWeight" in item) {
item.minutesFontWeight = Qt.binding(function () {
return root.minutesFontWeight;
});
}
if (item.hasOwnProperty("scaleRatio")) {
item.scaleRatio = Qt.binding(function () {
return root.scaleRatio;
});
}
if ("showProgress" in item) {
item.showProgress = Qt.binding(function () {
return root.showProgress;
});
}
}
}
// Analog Clock Component
component NClockAnalog: Item {
property var now
property color backgroundColor: Color.mPrimary
property color clockColor: Color.mOnPrimary
property color secondHandColor: Color.mError
property real scaleRatio: Style.uiScaleRatio
anchors.fill: parent
Canvas {
id: clockCanvas
anchors.fill: parent
Connections {
target: Time
function onNowChanged() {
clockCanvas.requestPaint();
}
}
onPaint: {
var currentTime = Time.now;
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
const markAlpha = 0.7;
var ctx = getContext("2d");
ctx.reset();
ctx.translate(width / 2, height / 2);
var radius = Math.min(width, height) / 2;
// Hour marks
ctx.strokeStyle = Qt.alpha(clockColor, markAlpha);
ctx.lineWidth = 2 * scaleRatio;
var scaleFactor = 0.7;
for (var i = 0; i < 12; i++) {
var scaleFactor = 0.8;
if (i % 3 === 0) {
scaleFactor = 0.65;
}
ctx.save();
ctx.rotate(i * Math.PI / 6);
ctx.beginPath();
ctx.moveTo(0, -radius * scaleFactor);
ctx.lineTo(0, -radius);
ctx.stroke();
ctx.restore();
}
// Hour hand
ctx.save();
var hourAngle = (hours % 12 + minutes / 60) * Math.PI / 6;
ctx.rotate(hourAngle);
ctx.strokeStyle = clockColor;
ctx.lineWidth = 3 * scaleRatio;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -radius * 0.6);
ctx.stroke();
ctx.restore();
// Minute hand
ctx.save();
var minuteAngle = (minutes + seconds / 60) * Math.PI / 30;
ctx.rotate(minuteAngle);
ctx.strokeStyle = clockColor;
ctx.lineWidth = 2 * scaleRatio;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -radius * 0.9);
ctx.stroke();
ctx.restore();
// Second hand
ctx.save();
var secondAngle = seconds * Math.PI / 30;
ctx.rotate(secondAngle);
ctx.strokeStyle = secondHandColor;
ctx.lineWidth = 1.6 * scaleRatio;
ctx.lineCap = "round";
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -radius);
ctx.stroke();
ctx.restore();
// Center dot
ctx.beginPath();
ctx.arc(0, 0, 3 * scaleRatio, 0, 2 * Math.PI);
ctx.fillStyle = clockColor;
ctx.fill();
}
Component.onCompleted: requestPaint()
}
}
// Digital Clock Component
component NClockDigital: Item {
property var now
property color backgroundColor: Color.mPrimary
property color clockColor: Color.mOnPrimary
property color progressColor: Color.mError
property real hoursFontSize: Style.fontSizeXS
property real minutesFontSize: Style.fontSizeXXS
property int hoursFontWeight: Style.fontWeightBold
property int minutesFontWeight: Style.fontWeightBold
property real scaleRatio: Style.uiScaleRatio
property bool showProgress: true
anchors.fill: parent
// Digital clock's seconds circular progress
Canvas {
id: secondsProgress
anchors.fill: parent
visible: showProgress
property real progress: now.getSeconds() / 60
onProgressChanged: requestPaint()
Connections {
target: Time
function onNowChanged() {
const total = now.getSeconds() * 1000 + now.getMilliseconds();
secondsProgress.progress = total / 60000;
}
}
onPaint: {
var ctx = getContext("2d");
var centerX = width / 2;
var centerY = height / 2;
var radius = Math.min(width, height) / 2 - 3 * scaleRatio;
ctx.reset();
// Background circle
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
ctx.lineWidth = 2.5 * scaleRatio;
ctx.strokeStyle = Qt.alpha(clockColor, 0.15);
ctx.stroke();
// Progress arc
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -Math.PI / 2, -Math.PI / 2 + progress * 2 * Math.PI);
ctx.lineWidth = 2.5 * scaleRatio;
ctx.strokeStyle = progressColor;
ctx.lineCap = "round";
ctx.stroke();
}
}
// Digital clock
ColumnLayout {
anchors.centerIn: parent
spacing: -Style.marginXXS
NText {
text: {
var t = Settings.data.location.use12hourFormat ? I18n.locale.toString(now, "hh AP") : I18n.locale.toString(now, "HH");
return t.split(" ")[0];
}
pointSize: hoursFontSize
font.weight: hoursFontWeight
color: clockColor
family: Settings.data.ui.fontFixed
Layout.alignment: Qt.AlignHCenter
}
NText {
text: Qt.formatTime(now, "mm")
pointSize: minutesFontSize
font.weight: minutesFontWeight
color: clockColor
family: Settings.data.ui.fontFixed
Layout.alignment: Qt.AlignHCenter
}
}
}
// Binary Clock Component
component NClockBinary: Item {
property var now
property color backgroundColor
property color clockColor: Color.mOnPrimary
anchors.fill: parent
readonly property int h: now.getHours()
readonly property int m: now.getMinutes()
readonly property int s: now.getSeconds()
// BCD (Binary Coded Decimal) Format:
// H1 H2 : M1 M2 : S1 S2
// H1 (tens): 0-2 (2 bits)
// H2 (ones): 0-9 (4 bits)
// M1 (tens): 0-5 (3 bits)
// M2 (ones): 0-9 (4 bits)
// S1 (tens): 0-5 (3 bits)
// S2 (ones): 0-9 (4 bits)
RowLayout {
anchors.centerIn: parent
spacing: parent.width * 0.05
// Hours
RowLayout {
spacing: parent.parent.width * 0.02
BinaryColumn {
value: Math.floor(h / 10)
bits: 2
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
BinaryColumn {
value: h % 10
bits: 4
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
}
// Minutes
RowLayout {
spacing: parent.parent.width * 0.02
BinaryColumn {
value: Math.floor(m / 10)
bits: 3
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
BinaryColumn {
value: m % 10
bits: 4
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
}
// Seconds
RowLayout {
spacing: parent.parent.width * 0.02
BinaryColumn {
value: Math.floor(s / 10)
bits: 3
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
BinaryColumn {
value: s % 10
bits: 4
dotSize: root.width * 0.08
activeColor: clockColor
Layout.alignment: Qt.AlignBottom
}
}
}
}
component BinaryColumn: Column {
property int value: 0
property int bits: 4
property real dotSize: 10
property color activeColor: "white"
spacing: dotSize * 0.4
Repeater {
model: bits
Rectangle {
property int bitIndex: (bits - 1) - index
property bool isActive: (value >> bitIndex) & 1
width: dotSize
height: dotSize
radius: dotSize / 2
color: isActive ? activeColor : Qt.alpha(activeColor, 0.2)
Behavior on color {
ColorAnimation {
duration: 200
}
}
}
}
}
Component {
id: analogClockComponent
NClockAnalog {}
}
Component {
id: digitalClockComponent
NClockDigital {}
}
Component {
id: binaryClockComponent
NClockBinary {}
}
}
Loaded 100 of 433 files, more files were not shown because too many files have changed in this diff. Show more