Compare commits
26
Commits
v0.4.0
..
4037a1dd0f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4037a1dd0f | ||
|
|
03ef51cd0c | ||
|
|
a41c0adb3e | ||
|
|
33c9432390 | ||
|
|
bfaba488f3 | ||
|
|
0c788ca4dc | ||
|
|
c42feec312 | ||
|
|
ba567efc22 | ||
|
|
da21675f03 | ||
|
|
8883d98b00
|
||
|
|
cf907089da
|
||
|
|
070fe7add0 | ||
|
|
ec80adf0a5 | ||
|
|
88a2808a47 | ||
|
|
a13daf27a6 | ||
|
|
75de349ff4 | ||
|
|
bf5a8b8049 | ||
|
|
a9bbb21f54 | ||
|
|
bb50cf756d | ||
|
|
57147dc7c1 | ||
|
|
620fe001a4 | ||
|
|
85320e9ea1 | ||
|
|
259a4dde7a | ||
|
|
d6230bef34 | ||
|
|
4ee9bb3f12 | ||
|
|
8789d2d322 |
+22
-87
@@ -1,12 +1,15 @@
|
|||||||
name: Python
|
name: Python
|
||||||
|
|
||||||
|
env:
|
||||||
|
APT_DEPS: git python3 python3-pip python3-venv python3-gi python3-cairo python3-dbus python3-pyudev python3-psutil python3-evdev python3-yaml python3-xlib python3-pillow gir1.2-gtk-3.0
|
||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
fmt:
|
static:
|
||||||
runs-on: alpine
|
runs-on: debian
|
||||||
container: node:26-alpine
|
container: node:26-trixie-slim
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
@@ -14,10 +17,8 @@ jobs:
|
|||||||
|
|
||||||
- name: Install tools
|
- name: Install tools
|
||||||
run: |
|
run: |
|
||||||
apk add --no-cache \
|
apt-get update
|
||||||
git \
|
apt-get install -y --no-install-recommends git python3 python3-pip python3-venv
|
||||||
python3 \
|
|
||||||
py3-pip
|
|
||||||
python3 -m venv .venv
|
python3 -m venv .venv
|
||||||
. .venv/bin/activate
|
. .venv/bin/activate
|
||||||
pip install --no-cache-dir ruff
|
pip install --no-cache-dir ruff
|
||||||
@@ -27,32 +28,15 @@ jobs:
|
|||||||
. .venv/bin/activate
|
. .venv/bin/activate
|
||||||
ruff format --check .
|
ruff format --check .
|
||||||
|
|
||||||
lint:
|
|
||||||
runs-on: alpine
|
|
||||||
container: node:26-alpine
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install tools
|
|
||||||
run: |
|
|
||||||
apk add --no-cache \
|
|
||||||
git \
|
|
||||||
python3 \
|
|
||||||
py3-pip
|
|
||||||
python3 -m venv .venv
|
|
||||||
. .venv/bin/activate
|
|
||||||
pip install --no-cache-dir ruff
|
|
||||||
|
|
||||||
- name: Lint
|
- name: Lint
|
||||||
run: |
|
run: |
|
||||||
. .venv/bin/activate
|
. .venv/bin/activate
|
||||||
ruff check .
|
ruff check .
|
||||||
|
|
||||||
test:
|
verify:
|
||||||
runs-on: alpine
|
if: always()
|
||||||
container: node:26-alpine
|
runs-on: debian
|
||||||
|
container: node:26-trixie-slim
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
@@ -60,20 +44,16 @@ jobs:
|
|||||||
|
|
||||||
- name: Install tools
|
- name: Install tools
|
||||||
run: |
|
run: |
|
||||||
apk add --no-cache \
|
apt-get update
|
||||||
git \
|
apt-get install -y --no-install-recommends $APT_DEPS build-essential python3-dev
|
||||||
python3 \
|
python3 -m venv --system-site-packages .venv
|
||||||
py3-pip \
|
|
||||||
py3-pillow \
|
|
||||||
build-base
|
|
||||||
python3 -m venv .venv
|
|
||||||
. .venv/bin/activate
|
. .venv/bin/activate
|
||||||
pip install --no-cache-dir \
|
pip install --no-cache-dir basedpyright nuitka .
|
||||||
typer \
|
|
||||||
pillow \
|
- name: Type check
|
||||||
materialyoucolor \
|
run: |
|
||||||
jinja2 \
|
. .venv/bin/activate
|
||||||
pytest
|
basedpyright
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: |
|
run: |
|
||||||
@@ -81,52 +61,7 @@ jobs:
|
|||||||
cd cli
|
cd cli
|
||||||
python -m pytest tests/ -v
|
python -m pytest tests/ -v
|
||||||
|
|
||||||
typecheck:
|
|
||||||
runs-on: alpine
|
|
||||||
container: node:26-alpine
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install tools
|
|
||||||
run: |
|
|
||||||
apk add --no-cache \
|
|
||||||
git \
|
|
||||||
python3 \
|
|
||||||
py3-pip
|
|
||||||
python3 -m venv .venv
|
|
||||||
. .venv/bin/activate
|
|
||||||
pip install --no-cache-dir basedpyright typer pillow materialyoucolor jinja2
|
|
||||||
|
|
||||||
- name: Type check
|
|
||||||
run: |
|
|
||||||
. .venv/bin/activate
|
|
||||||
basedpyright
|
|
||||||
|
|
||||||
buildcheck:
|
|
||||||
runs-on: alpine
|
|
||||||
container: node:26-alpine
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Install tools
|
|
||||||
run: |
|
|
||||||
apk add --no-cache \
|
|
||||||
git \
|
|
||||||
python3 \
|
|
||||||
py3-pip \
|
|
||||||
build-base \
|
|
||||||
python3-dev \
|
|
||||||
gcc \
|
|
||||||
g++
|
|
||||||
python3 -m venv .venv
|
|
||||||
. .venv/bin/activate
|
|
||||||
pip install --no-cache-dir nuitka
|
|
||||||
|
|
||||||
- name: Nuitka module check
|
- name: Nuitka module check
|
||||||
run: |
|
run: |
|
||||||
. .venv/bin/activate
|
. .venv/bin/activate
|
||||||
nuitka --module --include-package=zshell cli/src/zshell/
|
nuitka --module --include-package=zshell cli/src/zshell/
|
||||||
@@ -16,3 +16,5 @@ dist/
|
|||||||
**/test-plugins/
|
**/test-plugins/
|
||||||
**/Charts/
|
**/Charts/
|
||||||
network-dev/
|
network-dev/
|
||||||
|
**/zshell.build/
|
||||||
|
**/zshell.dist/
|
||||||
|
|||||||
@@ -93,6 +93,8 @@ if("shell" IN_LIST ENABLE_MODULES)
|
|||||||
${NUITKA_EXECUTABLE}
|
${NUITKA_EXECUTABLE}
|
||||||
--standalone
|
--standalone
|
||||||
--include-data-dir=${CMAKE_SOURCE_DIR}/cli/src/zshell/assets=zshell/assets
|
--include-data-dir=${CMAKE_SOURCE_DIR}/cli/src/zshell/assets=zshell/assets
|
||||||
|
--include-package=gi.overrides
|
||||||
|
--include-package-data=solaar
|
||||||
--output-dir=${ZSHELL_CLI_BUILD_DIR}
|
--output-dir=${ZSHELL_CLI_BUILD_DIR}
|
||||||
--output-filename=zshell-cli
|
--output-filename=zshell-cli
|
||||||
${CMAKE_SOURCE_DIR}/cli/src/zshell/
|
${CMAKE_SOURCE_DIR}/cli/src/zshell/
|
||||||
|
|||||||
+40
-12
@@ -1,35 +1,63 @@
|
|||||||
pragma Singleton
|
pragma Singleton
|
||||||
|
|
||||||
import Quickshell
|
import Quickshell
|
||||||
|
import Quickshell.Io
|
||||||
import Quickshell.Services.UPower
|
import Quickshell.Services.UPower
|
||||||
import ZShell.Config
|
import ZShell.Config
|
||||||
import qs.Services
|
import qs.Services
|
||||||
|
import qs.Paths
|
||||||
|
|
||||||
Singleton {
|
Singleton {
|
||||||
id: root
|
id: root
|
||||||
|
|
||||||
readonly property var colors: {
|
readonly property list<var> allPeripherals: [...logiDevices, ...upowerDevices.filter(d => !Battery.logiDevices.some(l => l.nativePath === d.nativePath))]
|
||||||
if (deviceState === UPowerDeviceState.Charging || deviceState === UPowerDeviceState.FullyCharged)
|
readonly property real currentPerc: UPower.displayDevice.percentage
|
||||||
|
readonly property var deviceState: UPower.displayDevice.state
|
||||||
|
readonly property string deviceStateString: UPowerDeviceState.toString(deviceState)
|
||||||
|
readonly property bool isLaptop: UPower.displayDevice.isLaptopBattery
|
||||||
|
readonly property alias logiDevices: adapter.devices
|
||||||
|
readonly property var lowestPeripheral: allPeripherals.reduce((lowest, current) => current.percentage < lowest.percentage ? current : lowest)
|
||||||
|
readonly property bool onBattery: UPower.onBattery
|
||||||
|
readonly property bool ready: UPower.displayDevice.ready
|
||||||
|
readonly property real timeToEmpty: UPower.displayDevice.timeToEmpty
|
||||||
|
readonly property real timeToFull: UPower.displayDevice.timeToFull
|
||||||
|
readonly property list<UPowerDevice> upowerDevices: UPower.devices.values.filter(d => d.state !== UPowerDeviceState.Unknown)
|
||||||
|
|
||||||
|
function getColors(percentage: real, state: string): var {
|
||||||
|
if (state === "charging" || state === "full" || state === "recharging")
|
||||||
return {
|
return {
|
||||||
fg: Colors.swapRG(Colors.palette.m3error),
|
fg: Colors.swapRG(Colors.palette.m3error),
|
||||||
bg: Colors.swapRG(Colors.palette.m3onError)
|
bg: Colors.swapRG(Colors.palette.m3onError)
|
||||||
};
|
};
|
||||||
else if (currentPerc <= 0.2)
|
else if (percentage <= 0.2)
|
||||||
return {
|
return {
|
||||||
fg: Colors.palette.m3error,
|
fg: Colors.palette.m3error,
|
||||||
bg: Colors.palette.m3onError
|
bg: Colors.palette.m3onError
|
||||||
};
|
};
|
||||||
else
|
else
|
||||||
return {
|
return {
|
||||||
fg: Colors.palette.m3onSurface,
|
fg: Colors.palette.m3tertiary,
|
||||||
bg: Colors.palette.m3surface
|
bg: Colors.palette.m3onTertiary
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
readonly property real currentPerc: UPower.displayDevice.percentage
|
|
||||||
readonly property var deviceState: UPower.displayDevice.state
|
function startDaemon(): void {
|
||||||
readonly property bool isLaptop: UPower.displayDevice.isLaptopBattery
|
Quickshell.execDetached(["zshell-cli", "battery", "daemon"]);
|
||||||
readonly property bool onBattery: UPower.onBattery
|
}
|
||||||
readonly property bool ready: UPower.displayDevice.ready
|
|
||||||
readonly property real timeToEmpty: UPower.displayDevice.timeToEmpty
|
FileView {
|
||||||
readonly property real timeToFull: UPower.displayDevice.timeToFull
|
id: fileView
|
||||||
|
|
||||||
|
path: `${Paths.cache}/battery.json`
|
||||||
|
watchChanges: true
|
||||||
|
|
||||||
|
onFileChanged: reload()
|
||||||
|
|
||||||
|
JsonAdapter {
|
||||||
|
id: adapter
|
||||||
|
|
||||||
|
property list<var> devices: []
|
||||||
|
property real updated: 0.0
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-41
@@ -11,8 +11,8 @@ Singleton {
|
|||||||
id: root
|
id: root
|
||||||
|
|
||||||
property int availableUpdates: 0
|
property int availableUpdates: 0
|
||||||
property string cmd: ""
|
|
||||||
property bool commandReady
|
property bool commandReady
|
||||||
|
property bool hasHelper
|
||||||
property bool loaded
|
property bool loaded
|
||||||
property double now: Date.now()
|
property double now: Date.now()
|
||||||
property var updates: ({})
|
property var updates: ({})
|
||||||
@@ -38,18 +38,12 @@ Singleton {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function performPackageUpdate(pkg: string): void {
|
function performPackageUpdate(pkg: string): void {
|
||||||
if (root.cmd === "pacman")
|
pkgUpdateProc.command = ["pkexec", "pacman", "--noconfirm", "-Sy", pkg];
|
||||||
pkgUpdateProc.command = ["pkexec", root.cmd, "--noconfirm", "-Sy", pkg];
|
|
||||||
else
|
|
||||||
pkgUpdateProc.command = [root.cmd, "--noconfirm", "--sudo", "pkexec", "-Sy", pkg];
|
|
||||||
pkgUpdateProc.running = true;
|
pkgUpdateProc.running = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function performSystemUpdate(): void {
|
function performSystemUpdate(): void {
|
||||||
if (root.cmd === "pacman")
|
sysUpdateProc.command = ["pkexec", "pacman", "--noconfirm", "-Syu"];
|
||||||
sysUpdateProc.command = ["pkexec", root.cmd, "--noconfirm", "-Syu"];
|
|
||||||
else
|
|
||||||
sysUpdateProc.command = [root.cmd, "--noconfirm", "--sudo", "pkexec", "-Syu"];
|
|
||||||
sysUpdateProc.running = true;
|
sysUpdateProc.running = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,7 +81,7 @@ Singleton {
|
|||||||
Process {
|
Process {
|
||||||
id: cmdDetect
|
id: cmdDetect
|
||||||
|
|
||||||
command: ["sh", "-c", "command -v checkupdates || command -v yay || command -v paru"]
|
command: ["sh", "-c", "command -v checkupdates"]
|
||||||
running: true
|
running: true
|
||||||
|
|
||||||
stdout: StdioCollector {
|
stdout: StdioCollector {
|
||||||
@@ -96,47 +90,20 @@ Singleton {
|
|||||||
let helper;
|
let helper;
|
||||||
|
|
||||||
if (cmd.length > 0) {
|
if (cmd.length > 0) {
|
||||||
helper = cmd.split("/").pop();
|
helper = true;
|
||||||
} else {
|
} else {
|
||||||
helper = "pacman";
|
helper = false;
|
||||||
}
|
|
||||||
|
|
||||||
if (helper === "checkupdates") {
|
|
||||||
updatesProc.command = [helper];
|
|
||||||
} else {
|
|
||||||
updatesProc.command = [helper, "-Qu"];
|
|
||||||
}
|
}
|
||||||
|
root.hasHelper = helper;
|
||||||
root.commandReady = true;
|
root.commandReady = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Process {
|
|
||||||
id: updateCmdDetect
|
|
||||||
|
|
||||||
command: ["sh", "-c", "command -v yay || command -v paru"]
|
|
||||||
running: true
|
|
||||||
|
|
||||||
stdout: StdioCollector {
|
|
||||||
onStreamFinished: {
|
|
||||||
const cmd = this.text.trim();
|
|
||||||
let helper;
|
|
||||||
|
|
||||||
if (cmd.length > 0) {
|
|
||||||
helper = cmd.split("/").pop();
|
|
||||||
} else {
|
|
||||||
helper = "pacman";
|
|
||||||
}
|
|
||||||
|
|
||||||
root.cmd = helper;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Process {
|
Process {
|
||||||
id: updatesProc
|
id: updatesProc
|
||||||
|
|
||||||
command: []
|
command: root.hasHelper ? ["checkupdates"] : []
|
||||||
running: false
|
running: false
|
||||||
|
|
||||||
stdout: StdioCollector {
|
stdout: StdioCollector {
|
||||||
|
|||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import QtQuick
|
||||||
|
import ZShell.Config
|
||||||
|
import qs.Services
|
||||||
|
import qs.Components
|
||||||
|
import qs.Helpers
|
||||||
|
|
||||||
|
Row {
|
||||||
|
id: root
|
||||||
|
|
||||||
|
property real batHeight: Tokens.padding.smaller * 2
|
||||||
|
property real batWidth: Tokens.padding.larger * 2
|
||||||
|
required property string devState
|
||||||
|
property real nubHeight: Tokens.padding.small
|
||||||
|
property real nubWidth: 2
|
||||||
|
required property real percentage
|
||||||
|
property real radius: Tokens.rounding.smallest / 2
|
||||||
|
|
||||||
|
spacing: 1
|
||||||
|
|
||||||
|
CustomRect {
|
||||||
|
id: track
|
||||||
|
|
||||||
|
anchors.verticalCenter: parent.verticalCenter
|
||||||
|
color: Battery.getColors(root.percentage, root.devState).bg
|
||||||
|
height: root.batHeight
|
||||||
|
radius: root.radius
|
||||||
|
width: root.batWidth
|
||||||
|
|
||||||
|
CustomText {
|
||||||
|
color: Battery.getColors(root.percentage, root.devState).fg
|
||||||
|
font.pointSize: Tokens.font.size.larger / 1.5
|
||||||
|
font.weight: 800
|
||||||
|
height: track.height
|
||||||
|
horizontalAlignment: Text.AlignHCenter
|
||||||
|
text: Math.round(root.percentage * 100)
|
||||||
|
verticalAlignment: Text.AlignVCenter
|
||||||
|
width: track.width
|
||||||
|
}
|
||||||
|
|
||||||
|
Item {
|
||||||
|
clip: true
|
||||||
|
width: parent.width * root.percentage
|
||||||
|
|
||||||
|
anchors {
|
||||||
|
bottom: parent.bottom
|
||||||
|
left: parent.left
|
||||||
|
top: parent.top
|
||||||
|
}
|
||||||
|
|
||||||
|
CustomRect {
|
||||||
|
id: fill
|
||||||
|
|
||||||
|
color: Battery.getColors(root.percentage, root.devState).fg
|
||||||
|
height: track.height
|
||||||
|
radius: track.radius
|
||||||
|
width: track.width
|
||||||
|
|
||||||
|
CustomText {
|
||||||
|
id: batteryLabel
|
||||||
|
|
||||||
|
clip: true
|
||||||
|
color: Battery.getColors(root.percentage, root.devState).bg
|
||||||
|
font.pointSize: Tokens.font.size.larger / 1.5
|
||||||
|
font.weight: 800
|
||||||
|
height: track.height
|
||||||
|
horizontalAlignment: Text.AlignHCenter
|
||||||
|
text: Math.round(root.percentage * 100)
|
||||||
|
verticalAlignment: Text.AlignVCenter
|
||||||
|
width: track.width
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CustomRect {
|
||||||
|
id: nub
|
||||||
|
|
||||||
|
anchors.verticalCenter: parent.verticalCenter
|
||||||
|
bottomRightRadius: 20
|
||||||
|
color: root.percentage < 0.99 ? track.color : fill.color
|
||||||
|
height: root.nubHeight
|
||||||
|
topRightRadius: 20
|
||||||
|
width: root.nubWidth
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -112,7 +112,6 @@ WidgetBase {
|
|||||||
name: "upower"
|
name: "upower"
|
||||||
|
|
||||||
UPowerWidget {
|
UPowerWidget {
|
||||||
horizontal: root.horizontal
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,16 +2,17 @@ import Quickshell.Services.UPower
|
|||||||
import QtQuick
|
import QtQuick
|
||||||
import QtQuick.Layouts
|
import QtQuick.Layouts
|
||||||
import ZShell.Config
|
import ZShell.Config
|
||||||
|
import qs.Modules.Bar.Components.Common
|
||||||
import qs.Components
|
import qs.Components
|
||||||
import qs.Helpers
|
import qs.Helpers
|
||||||
|
|
||||||
Item {
|
Item {
|
||||||
id: root
|
id: root
|
||||||
|
|
||||||
required property bool horizontal
|
readonly property Item currentItem: batteryIconLoader?.item ?? peripheralIconLoader?.item ?? upowerIconLoader.item
|
||||||
|
|
||||||
implicitHeight: Battery.isLaptop ? batteryIconLoader.item.implicitHeight : upowerIconLoader.item.implicitHeight
|
implicitHeight: currentItem?.implicitHeight ?? 0
|
||||||
implicitWidth: Battery.isLaptop ? batteryIconLoader.item.implicitWidth : upowerIconLoader.item.implicitWidth
|
implicitWidth: currentItem?.implicitWidth ?? 0
|
||||||
|
|
||||||
Behavior on Layout.preferredHeight {
|
Behavior on Layout.preferredHeight {
|
||||||
Anim {
|
Anim {
|
||||||
@@ -30,95 +31,36 @@ Item {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Component.onCompleted: Battery.startDaemon()
|
||||||
|
|
||||||
Loader {
|
Loader {
|
||||||
id: batteryIconLoader
|
id: batteryIconLoader
|
||||||
|
|
||||||
active: Battery.isLaptop
|
active: Battery.isLaptop
|
||||||
anchors.centerIn: parent
|
anchors.centerIn: parent
|
||||||
|
|
||||||
sourceComponent: Row {
|
sourceComponent: BatteryIcon {
|
||||||
id: batteryIcon
|
devState: Battery.deviceStateString
|
||||||
|
percentage: Battery.currentPerc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
property real batHeight: 16
|
Loader {
|
||||||
property real batWidth: 30
|
id: peripheralIconLoader
|
||||||
property real nubHeight: 6
|
|
||||||
property real nubWidth: 2
|
|
||||||
property real radius: Tokens.rounding.smallest / 2
|
|
||||||
|
|
||||||
spacing: 1
|
active: (Battery.lowestPeripheral?.isPresent ?? false) && !batteryIconLoader.active
|
||||||
|
anchors.centerIn: parent
|
||||||
|
|
||||||
CustomRect {
|
sourceComponent: BatteryIcon {
|
||||||
id: track
|
devState: Battery.lowestPeripheral?.state ?? ""
|
||||||
|
percentage: Battery.lowestPeripheral?.percentage ?? 0
|
||||||
anchors.verticalCenter: parent.verticalCenter
|
|
||||||
color: Battery.colors.bg
|
|
||||||
height: batteryIcon.batHeight
|
|
||||||
radius: batteryIcon.radius
|
|
||||||
width: batteryIcon.batWidth
|
|
||||||
|
|
||||||
CustomText {
|
|
||||||
color: Battery.colors.fg
|
|
||||||
font.pointSize: Tokens.font.size.larger / 1.5
|
|
||||||
font.weight: 800
|
|
||||||
height: track.height
|
|
||||||
horizontalAlignment: Text.AlignHCenter
|
|
||||||
text: Math.round(Battery.currentPerc * 100)
|
|
||||||
verticalAlignment: Text.AlignVCenter
|
|
||||||
width: track.width
|
|
||||||
}
|
|
||||||
|
|
||||||
Item {
|
|
||||||
clip: true
|
|
||||||
width: parent.width * Battery.currentPerc
|
|
||||||
|
|
||||||
anchors {
|
|
||||||
bottom: parent.bottom
|
|
||||||
left: parent.left
|
|
||||||
top: parent.top
|
|
||||||
}
|
|
||||||
|
|
||||||
CustomRect {
|
|
||||||
id: fill
|
|
||||||
|
|
||||||
color: Battery.colors.fg
|
|
||||||
height: track.height
|
|
||||||
radius: track.radius
|
|
||||||
width: track.width
|
|
||||||
|
|
||||||
CustomText {
|
|
||||||
id: batteryLabel
|
|
||||||
|
|
||||||
clip: true
|
|
||||||
color: Battery.colors.bg
|
|
||||||
font.pointSize: 7.5
|
|
||||||
font.weight: 800
|
|
||||||
height: track.height
|
|
||||||
horizontalAlignment: Text.AlignHCenter
|
|
||||||
text: Math.round(Battery.currentPerc * 100)
|
|
||||||
verticalAlignment: Text.AlignVCenter
|
|
||||||
width: track.width
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CustomRect {
|
|
||||||
id: nub
|
|
||||||
|
|
||||||
anchors.verticalCenter: parent.verticalCenter
|
|
||||||
bottomRightRadius: 20
|
|
||||||
color: Battery.currentPerc < 0.99 ? track.color : fill.color
|
|
||||||
height: batteryIcon.nubHeight
|
|
||||||
topRightRadius: 20
|
|
||||||
width: batteryIcon.nubWidth
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Loader {
|
Loader {
|
||||||
id: upowerIconLoader
|
id: upowerIconLoader
|
||||||
|
|
||||||
active: !Battery.isLaptop
|
active: !batteryIconLoader.active && !peripheralIconLoader.active
|
||||||
anchors.centerIn: parent
|
anchors.centerIn: parent
|
||||||
|
|
||||||
sourceComponent: MaterialIcon {
|
sourceComponent: MaterialIcon {
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
pragma ComponentBehavior: Bound
|
pragma ComponentBehavior: Bound
|
||||||
|
|
||||||
import QtQuick
|
import QtQuick
|
||||||
|
import QtQuick.Layouts
|
||||||
import Quickshell.Services.UPower
|
import Quickshell.Services.UPower
|
||||||
import ZShell.Config
|
import ZShell.Config
|
||||||
|
import qs.Modules.Bar.Components.Common
|
||||||
import qs.Helpers
|
import qs.Helpers
|
||||||
import qs.Components
|
import qs.Components
|
||||||
import qs.Services
|
import qs.Services
|
||||||
@@ -22,6 +24,31 @@ Column {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Repeater {
|
||||||
|
model: Battery.allPeripherals
|
||||||
|
|
||||||
|
RowLayout {
|
||||||
|
id: layout
|
||||||
|
|
||||||
|
required property var modelData
|
||||||
|
|
||||||
|
anchors.left: parent.left
|
||||||
|
anchors.leftMargin: Tokens.padding.normal
|
||||||
|
anchors.right: parent.right
|
||||||
|
anchors.rightMargin: Tokens.padding.normal
|
||||||
|
|
||||||
|
CustomText {
|
||||||
|
Layout.fillWidth: true
|
||||||
|
text: layout.modelData.model
|
||||||
|
}
|
||||||
|
|
||||||
|
BatteryIcon {
|
||||||
|
devState: layout.modelData.state
|
||||||
|
percentage: layout.modelData.percentage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
CustomText {
|
CustomText {
|
||||||
function formatSeconds(s: int, fallback: string): string {
|
function formatSeconds(s: int, fallback: string): string {
|
||||||
const day = Math.floor(s / 86400);
|
const day = Math.floor(s / 86400);
|
||||||
@@ -75,7 +102,7 @@ Column {
|
|||||||
CustomText {
|
CustomText {
|
||||||
anchors.verticalCenter: parent.verticalCenter
|
anchors.verticalCenter: parent.verticalCenter
|
||||||
color: Colors.palette.m3onError
|
color: Colors.palette.m3onError
|
||||||
font.family: Appearance.font.family.mono
|
font.family: Config.appearance.font.family.mono
|
||||||
text: qsTr("Performance Degraded")
|
text: qsTr("Performance Degraded")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -78,8 +78,6 @@ CustomClippingRect {
|
|||||||
required property var modelData
|
required property var modelData
|
||||||
readonly property list<string> sections: modelData.update.split(" ")
|
readonly property list<string> sections: modelData.update.split(" ")
|
||||||
|
|
||||||
// anchors.left: parent.left
|
|
||||||
// anchors.right: parent.right
|
|
||||||
color: Colors.tPalette.m3surfaceContainer
|
color: Colors.tPalette.m3surfaceContainer
|
||||||
implicitHeight: root.itemHeight
|
implicitHeight: root.itemHeight
|
||||||
implicitWidth: 600
|
implicitWidth: 600
|
||||||
|
|||||||
Executable
+55
@@ -0,0 +1,55 @@
|
|||||||
|
import Quickshell
|
||||||
|
import QtQuick
|
||||||
|
import ZShell.Components
|
||||||
|
import ZShell.Config
|
||||||
|
import qs.Modules.Launcher.Items
|
||||||
|
import qs.Components
|
||||||
|
import qs.Helpers
|
||||||
|
|
||||||
|
CarouselView {
|
||||||
|
id: root
|
||||||
|
|
||||||
|
required property var panels
|
||||||
|
readonly property var screen: QsWindow.window?.screen
|
||||||
|
required property SearchBar search
|
||||||
|
readonly property var values: Wallpapers.query(root.search.text.split(" ").slice(1).join(" "))
|
||||||
|
required property var visibilities
|
||||||
|
|
||||||
|
// Forwarded verbatim as a property of the same name onto every delegate
|
||||||
|
// instance (the delegate declares `required property PersistentProperties visibilities`).
|
||||||
|
delegateProperties: ({
|
||||||
|
visibilities: root.visibilities
|
||||||
|
})
|
||||||
|
focalWidth: Config.launcher.sizes.wallpaperWidth
|
||||||
|
glideDuration: 250
|
||||||
|
glideEasingType: Easing.OutCubic
|
||||||
|
implicitHeight: tileHeight + Tokens.spacing.small / 2 + Tokens.padding.large + Tokens.padding.normal
|
||||||
|
itemSpacing: Tokens.spacing.small
|
||||||
|
maxWidth: {
|
||||||
|
if (!screen)
|
||||||
|
return 0;
|
||||||
|
const barMargins = Config.bar.border * 2;
|
||||||
|
let margins = 0;
|
||||||
|
if (visibilities.utilities || visibilities.sidebar)
|
||||||
|
margins = panels.utilities.implicitWidth;
|
||||||
|
return screen.width - (barMargins + margins) * 2 - Config.bar.rounding * 4;
|
||||||
|
}
|
||||||
|
minEdgeWidth: 56
|
||||||
|
model: values
|
||||||
|
tileHeight: focalWidth / 16 * 9
|
||||||
|
|
||||||
|
delegate: Component {
|
||||||
|
WallpaperTile {
|
||||||
|
} // your existing delegate file, unchanged
|
||||||
|
}
|
||||||
|
|
||||||
|
Component.onCompleted: {
|
||||||
|
const idx = Wallpapers.list.findIndex(w => w.path === Wallpapers.actualCurrent);
|
||||||
|
if (idx >= 0)
|
||||||
|
jumpToIndex(idx);
|
||||||
|
}
|
||||||
|
Component.onDestruction: Wallpapers.stopPreview()
|
||||||
|
onPreviewIndexChanged: (realIndex, modelData) => {
|
||||||
|
Wallpapers.preview(modelData.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -111,8 +111,8 @@ Item {
|
|||||||
anchors.horizontalCenter: parent.horizontalCenter
|
anchors.horizontalCenter: parent.horizontalCenter
|
||||||
anchors.top: parent.top
|
anchors.top: parent.top
|
||||||
|
|
||||||
sourceComponent: WallpaperList {
|
sourceComponent: CarouselView {
|
||||||
content: root.content
|
// content: root.content
|
||||||
panels: root.panels
|
panels: root.panels
|
||||||
search: root.search
|
search: root.search
|
||||||
visibilities: root.visibilities
|
visibilities: root.visibilities
|
||||||
|
|||||||
@@ -1,96 +0,0 @@
|
|||||||
import ZShell.Models
|
|
||||||
import Quickshell
|
|
||||||
import QtQuick
|
|
||||||
import qs.Components
|
|
||||||
import qs.Helpers
|
|
||||||
import ZShell.Config
|
|
||||||
import qs.Modules
|
|
||||||
import qs.Services
|
|
||||||
|
|
||||||
Item {
|
|
||||||
id: root
|
|
||||||
|
|
||||||
required property FileSystemEntry modelData
|
|
||||||
required property PersistentProperties visibilities
|
|
||||||
|
|
||||||
implicitHeight: image.height + label.height + Tokens.spacing.small / 2 + Tokens.padding.large + Tokens.padding.normal
|
|
||||||
implicitWidth: image.width + Tokens.padding.larger * 2
|
|
||||||
opacity: 0
|
|
||||||
scale: 0.5
|
|
||||||
z: PathView.z ?? 0
|
|
||||||
|
|
||||||
Behavior on opacity {
|
|
||||||
Anim {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Behavior on scale {
|
|
||||||
Anim {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Component.onCompleted: {
|
|
||||||
scale = Qt.binding(() => PathView.isCurrentItem ? 1 : PathView.onPath ? 0.8 : 0);
|
|
||||||
opacity = Qt.binding(() => PathView.onPath ? 1 : 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
StateLayer {
|
|
||||||
radius: Tokens.rounding.normal
|
|
||||||
|
|
||||||
onClicked: {
|
|
||||||
Wallpapers.setWallpaper(root.modelData.path);
|
|
||||||
root.visibilities.launcher = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Elevation {
|
|
||||||
anchors.fill: image
|
|
||||||
level: 4
|
|
||||||
opacity: root.PathView.isCurrentItem ? 1 : 0
|
|
||||||
radius: image.radius
|
|
||||||
|
|
||||||
Behavior on opacity {
|
|
||||||
Anim {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CustomClippingRect {
|
|
||||||
id: image
|
|
||||||
|
|
||||||
anchors.horizontalCenter: parent.horizontalCenter
|
|
||||||
color: Colors.tPalette.m3surfaceContainer
|
|
||||||
implicitHeight: implicitWidth / 16 * 9
|
|
||||||
implicitWidth: Config.launcher.sizes.wallpaperWidth
|
|
||||||
radius: Tokens.rounding.small
|
|
||||||
y: Tokens.padding.large
|
|
||||||
|
|
||||||
MaterialIcon {
|
|
||||||
anchors.centerIn: parent
|
|
||||||
color: Colors.tPalette.m3outline
|
|
||||||
font.pointSize: Tokens.font.size.extraLarge * 2
|
|
||||||
font.weight: 600
|
|
||||||
text: "image"
|
|
||||||
}
|
|
||||||
|
|
||||||
CachingImage {
|
|
||||||
anchors.fill: parent
|
|
||||||
cache: true
|
|
||||||
path: root.modelData.path
|
|
||||||
smooth: !root.PathView.view.moving
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CustomText {
|
|
||||||
id: label
|
|
||||||
|
|
||||||
anchors.horizontalCenter: parent.horizontalCenter
|
|
||||||
anchors.top: image.bottom
|
|
||||||
anchors.topMargin: Tokens.spacing.small / 2
|
|
||||||
elide: Text.ElideRight
|
|
||||||
font.pointSize: Tokens.font.size.normal
|
|
||||||
horizontalAlignment: Text.AlignHCenter
|
|
||||||
renderType: Text.QtRendering
|
|
||||||
text: root.modelData.relativePath
|
|
||||||
width: image.width - Tokens.padding.normal * 2
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Executable
+58
@@ -0,0 +1,58 @@
|
|||||||
|
import Quickshell
|
||||||
|
import QtQuick
|
||||||
|
import ZShell.Config
|
||||||
|
import qs.Components
|
||||||
|
import qs.Helpers
|
||||||
|
import qs.Services
|
||||||
|
|
||||||
|
Item {
|
||||||
|
id: root
|
||||||
|
|
||||||
|
required property bool isCurrent
|
||||||
|
required property var modelData // FileSystemEntry-like {path, relativePath}
|
||||||
|
required property real tileHeight
|
||||||
|
required property real tileWidth
|
||||||
|
required property PersistentProperties visibilities
|
||||||
|
|
||||||
|
signal requestActivate
|
||||||
|
|
||||||
|
implicitHeight: tileHeight + Tokens.padding.large * 2
|
||||||
|
implicitWidth: tileWidth
|
||||||
|
|
||||||
|
CustomClippingRect {
|
||||||
|
id: image
|
||||||
|
|
||||||
|
anchors.horizontalCenter: parent.horizontalCenter
|
||||||
|
color: Colors.tPalette.m3surfaceContainer
|
||||||
|
implicitHeight: root.tileHeight
|
||||||
|
implicitWidth: root.tileWidth
|
||||||
|
radius: Tokens.rounding.small
|
||||||
|
y: Tokens.padding.large
|
||||||
|
|
||||||
|
MaterialIcon {
|
||||||
|
anchors.centerIn: parent
|
||||||
|
color: Colors.tPalette.m3outline
|
||||||
|
font.pointSize: Tokens.font.size.extraLarge * 2
|
||||||
|
font.weight: 600
|
||||||
|
text: "image"
|
||||||
|
}
|
||||||
|
|
||||||
|
CachingImage {
|
||||||
|
anchors.bottom: parent.bottom
|
||||||
|
anchors.horizontalCenter: parent.horizontalCenter
|
||||||
|
anchors.top: parent.top
|
||||||
|
cache: true
|
||||||
|
fillMode: Image.PreserveAspectCrop
|
||||||
|
height: root.tileHeight
|
||||||
|
path: root.modelData ? root.modelData.path : ""
|
||||||
|
smooth: root.isCurrent
|
||||||
|
sourceSize.height: root.tileHeight
|
||||||
|
sourceSize.width: root.tileHeight * (16 / 9)
|
||||||
|
width: root.tileHeight * (16 / 9)
|
||||||
|
}
|
||||||
|
|
||||||
|
StateLayer {
|
||||||
|
onClicked: root.requestActivate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
pragma ComponentBehavior: Bound
|
|
||||||
|
|
||||||
import Quickshell
|
|
||||||
import QtQuick
|
|
||||||
import qs.Components
|
|
||||||
import qs.Helpers
|
|
||||||
import ZShell.Config
|
|
||||||
import qs.Modules.Launcher.Items
|
|
||||||
|
|
||||||
PathView {
|
|
||||||
id: root
|
|
||||||
|
|
||||||
required property var content
|
|
||||||
readonly property int itemWidth: Config.launcher.sizes.wallpaperWidth * 0.9 + Tokens.padding.larger * 2
|
|
||||||
readonly property int numItems: {
|
|
||||||
const screen = QsWindow.window?.screen;
|
|
||||||
if (!screen)
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
// Screen width - 4x outer rounding - 2x max side thickness (cause centered)
|
|
||||||
const barMargins = panels.bar.implicitWidth;
|
|
||||||
let outerMargins = 0;
|
|
||||||
if ((visibilities.utilities || visibilities.sidebar) && panels.utilities.implicitWidth > outerMargins)
|
|
||||||
outerMargins = panels.utilities.implicitWidth;
|
|
||||||
const maxWidth = screen.width - Config.bar.rounding * 4 - (barMargins + outerMargins) * 2;
|
|
||||||
|
|
||||||
if (maxWidth <= 0)
|
|
||||||
return 0;
|
|
||||||
|
|
||||||
const maxItemsOnScreen = Math.floor(maxWidth / itemWidth);
|
|
||||||
const visible = Math.min(maxItemsOnScreen, Config.launcher.maxWallpapers, scriptModel.values.length);
|
|
||||||
|
|
||||||
if (visible === 2)
|
|
||||||
return 1;
|
|
||||||
if (visible > 1 && visible % 2 === 0)
|
|
||||||
return visible - 1;
|
|
||||||
return visible;
|
|
||||||
}
|
|
||||||
required property var panels
|
|
||||||
required property SearchBar search
|
|
||||||
required property var visibilities
|
|
||||||
|
|
||||||
cacheItemCount: 4
|
|
||||||
highlightRangeMode: PathView.StrictlyEnforceRange
|
|
||||||
implicitWidth: Math.min(numItems, count) * itemWidth
|
|
||||||
pathItemCount: numItems
|
|
||||||
preferredHighlightBegin: 0.5
|
|
||||||
preferredHighlightEnd: 0.5
|
|
||||||
snapMode: PathView.SnapToItem
|
|
||||||
|
|
||||||
delegate: WallpaperItem {
|
|
||||||
visibilities: root.visibilities
|
|
||||||
}
|
|
||||||
model: ScriptModel {
|
|
||||||
id: scriptModel
|
|
||||||
|
|
||||||
readonly property string search: root.search.text.split(" ").slice(1).join(" ")
|
|
||||||
|
|
||||||
values: Wallpapers.query(search)
|
|
||||||
|
|
||||||
onValuesChanged: root.currentIndex = search ? 0 : values.findIndex(w => w.path === Wallpapers.actualCurrent)
|
|
||||||
}
|
|
||||||
path: Path {
|
|
||||||
startY: root.height / 2
|
|
||||||
|
|
||||||
PathAttribute {
|
|
||||||
name: "z"
|
|
||||||
value: 0
|
|
||||||
}
|
|
||||||
|
|
||||||
PathLine {
|
|
||||||
relativeY: 0
|
|
||||||
x: root.width / 2
|
|
||||||
}
|
|
||||||
|
|
||||||
PathAttribute {
|
|
||||||
name: "z"
|
|
||||||
value: 1
|
|
||||||
}
|
|
||||||
|
|
||||||
PathLine {
|
|
||||||
relativeY: 0
|
|
||||||
x: root.width
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Component.onCompleted: currentIndex = Wallpapers.list.findIndex(w => w.path === Wallpapers.actualCurrent)
|
|
||||||
Component.onDestruction: Wallpapers.stopPreview()
|
|
||||||
onCurrentItemChanged: {
|
|
||||||
if (currentItem)
|
|
||||||
Wallpapers.preview(currentItem.modelData.path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,103 +5,46 @@ import Quickshell.Hyprland
|
|||||||
import QtQuick
|
import QtQuick
|
||||||
import qs.Components
|
import qs.Components
|
||||||
import qs.Helpers
|
import qs.Helpers
|
||||||
import ZShell.Config
|
|
||||||
import ZShell.Internal
|
import ZShell.Internal
|
||||||
|
|
||||||
Item {
|
Item {
|
||||||
id: root
|
id: root
|
||||||
|
|
||||||
property bool completed
|
|
||||||
property real cropHeight: displayData?.height ?? 1.0
|
|
||||||
property real cropWidth: displayData?.width ?? 1.0
|
|
||||||
property real cropX: displayData?.x ?? 0.0
|
|
||||||
property real cropY: displayData?.y ?? 0.0
|
|
||||||
property WallpaperImage current
|
|
||||||
readonly property var displayData: Wallpapers.getCrop(screen.name)
|
readonly property var displayData: Wallpapers.getCrop(screen.name)
|
||||||
required property ShellScreen screen
|
required property ShellScreen screen
|
||||||
property size screenResolution: Qt.size(screen.width * screenScale, screen.height * screenScale)
|
property size screenResolution: Qt.size(screen.width * screenScale, screen.height * screenScale)
|
||||||
property real screenScale: Hyprland.monitorFor(screen).scale
|
property real screenScale: Hyprland.monitorFor(screen).scale
|
||||||
property string source: Wallpapers.current
|
|
||||||
|
|
||||||
anchors.fill: parent
|
anchors.fill: parent
|
||||||
|
|
||||||
Component.onCompleted: {
|
Component.onCompleted: Hyprland.refreshMonitors()
|
||||||
Hyprland.refreshMonitors();
|
|
||||||
|
|
||||||
if (source)
|
WallpaperImage {
|
||||||
Qt.callLater(() => {
|
id: img
|
||||||
current = imgComp.createObject(this, {
|
|
||||||
source
|
|
||||||
});
|
|
||||||
completed = true;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
onSourceChanged: {
|
|
||||||
if (!source)
|
|
||||||
current = null;
|
|
||||||
else
|
|
||||||
current = imgComp.createObject(this, {
|
|
||||||
source: source
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Component {
|
anchors.fill: parent
|
||||||
id: imgComp
|
cropHeight: root.displayData?.height ?? 1.0
|
||||||
|
cropWidth: root.displayData?.width ?? 1.0
|
||||||
|
cropX: root.displayData?.x ?? 0.0
|
||||||
|
cropY: root.displayData?.y ?? 0.0
|
||||||
|
fadeDuration: 150
|
||||||
|
screenResolution: root.screenResolution
|
||||||
|
source: Wallpapers.current
|
||||||
|
|
||||||
WallpaperImage {
|
Behavior on cropHeight {
|
||||||
id: img
|
Anim {
|
||||||
|
|
||||||
anchors.fill: parent
|
|
||||||
cropHeight: root.cropHeight
|
|
||||||
cropWidth: root.cropWidth
|
|
||||||
cropX: root.cropX
|
|
||||||
cropY: root.cropY
|
|
||||||
opacity: 0
|
|
||||||
screenResolution: root.screenResolution
|
|
||||||
source: root.source
|
|
||||||
|
|
||||||
Behavior on cropHeight {
|
|
||||||
Anim {
|
|
||||||
id: heightAnim
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Behavior on cropWidth {
|
}
|
||||||
Anim {
|
Behavior on cropWidth {
|
||||||
id: widthAnim
|
Anim {
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Behavior on cropX {
|
}
|
||||||
Anim {
|
Behavior on cropX {
|
||||||
id: xAnim
|
Anim {
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Behavior on cropY {
|
}
|
||||||
Anim {
|
Behavior on cropY {
|
||||||
id: yAnim
|
Anim {
|
||||||
}
|
|
||||||
}
|
|
||||||
Anim on opacity {
|
|
||||||
id: anim
|
|
||||||
|
|
||||||
from: 0
|
|
||||||
running: false
|
|
||||||
to: 1
|
|
||||||
type: Anim.SlowEffects
|
|
||||||
}
|
|
||||||
|
|
||||||
onStatusChanged: {
|
|
||||||
if (status === Image.Ready) {
|
|
||||||
anim.start();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Timer {
|
|
||||||
id: destroyTimer
|
|
||||||
|
|
||||||
interval: anim.duration * 2
|
|
||||||
running: root.current !== img && root.current?.status === Image.Ready
|
|
||||||
|
|
||||||
onTriggered: Qt.callLater(() => img.destroy())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ qml_module(ZShell-components
|
|||||||
lazylistview.hpp lazylistview.cpp
|
lazylistview.hpp lazylistview.cpp
|
||||||
wavyline.hpp wavyline.cpp
|
wavyline.hpp wavyline.cpp
|
||||||
buttonrow.hpp buttonrow.cpp
|
buttonrow.hpp buttonrow.cpp
|
||||||
|
carouselview.hpp carouselview.cpp
|
||||||
LIBRARIES
|
LIBRARIES
|
||||||
Qt::Quick
|
Qt::Quick
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,785 @@
|
|||||||
|
#include "carouselview.hpp"
|
||||||
|
|
||||||
|
#include <QQmlContext>
|
||||||
|
#include <QQmlProperty>
|
||||||
|
#include <QMouseEvent>
|
||||||
|
#include <QWheelEvent>
|
||||||
|
#include <QGuiApplication>
|
||||||
|
#include <QStyleHints>
|
||||||
|
#include <cmath>
|
||||||
|
|
||||||
|
namespace ZShell::components {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr qreal kDragThreshold = 4.0; // px before a press becomes a drag
|
||||||
|
constexpr qreal kFlickFriction = 0.0022; // px/ms^2 deceleration
|
||||||
|
constexpr qreal kMinFlickVelocity = 60.0; // px/sec below which we just snap
|
||||||
|
constexpr qreal kMaxFlickVelocity = 6000.0;
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
CarouselView::CarouselView(QQuickItem* parent) : QQuickItem(parent) {
|
||||||
|
setAcceptedMouseButtons(Qt::LeftButton);
|
||||||
|
setFlag(QQuickItem::ItemHasContents, false);
|
||||||
|
setClip(false);
|
||||||
|
|
||||||
|
m_glideAnim = new QVariantAnimation(this);
|
||||||
|
m_glideAnim->setEasingCurve(m_glideEasingType);
|
||||||
|
connect(
|
||||||
|
m_glideAnim,
|
||||||
|
&QVariantAnimation::valueChanged,
|
||||||
|
this,
|
||||||
|
[this](const QVariant& v) {
|
||||||
|
m_contentX = v.toReal();
|
||||||
|
wrapContentIfNeeded();
|
||||||
|
updateCurrentIndexFromContentX(true);
|
||||||
|
relayout();
|
||||||
|
});
|
||||||
|
connect(m_glideAnim, &QVariantAnimation::finished, this, [this]() {
|
||||||
|
updateCurrentIndexFromContentX(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
m_flickAnim = new QVariantAnimation(this);
|
||||||
|
m_flickAnim->setEasingCurve(QEasingCurve::Linear);
|
||||||
|
connect(
|
||||||
|
m_flickAnim,
|
||||||
|
&QVariantAnimation::valueChanged,
|
||||||
|
this,
|
||||||
|
[this](const QVariant& v) {
|
||||||
|
m_contentX = v.toReal();
|
||||||
|
wrapContentIfNeeded();
|
||||||
|
updateCurrentIndexFromContentX(true);
|
||||||
|
relayout();
|
||||||
|
});
|
||||||
|
connect(m_flickAnim, &QVariantAnimation::finished, this, [this]() {
|
||||||
|
snapToNearest();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
CarouselView::~CarouselView() {
|
||||||
|
releaseAllItems();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- properties
|
||||||
|
|
||||||
|
void CarouselView::setDelegate(QQmlComponent* c) {
|
||||||
|
if (m_delegate == c) return;
|
||||||
|
m_delegate = c;
|
||||||
|
releaseAllItems();
|
||||||
|
emit delegateChanged();
|
||||||
|
relayout();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setModel(const QVariantList& m) {
|
||||||
|
m_model = m;
|
||||||
|
emit modelChanged();
|
||||||
|
|
||||||
|
// Re-anchor on the currently selected path if possible, otherwise clamp.
|
||||||
|
int newCount = m_model.size();
|
||||||
|
if (newCount == 0) {
|
||||||
|
m_currentRealIndex = -1;
|
||||||
|
releaseAllItems();
|
||||||
|
rebuildArrangement();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!m_initializedLayout) {
|
||||||
|
m_centerBlockStart = (kLoopMultiplier / 2) * newCount;
|
||||||
|
m_currentVirtualIndex = m_centerBlockStart;
|
||||||
|
m_contentX = contentXForIndex(m_currentVirtualIndex);
|
||||||
|
m_currentRealIndex = realIndexOf(m_currentVirtualIndex);
|
||||||
|
m_previewRealIndex = m_currentRealIndex;
|
||||||
|
m_initializedLayout = true;
|
||||||
|
rebuildArrangement();
|
||||||
|
relayout();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Model contents changed under us (e.g. search text filtered the list).
|
||||||
|
// Re-anchor instantly on the clamped selection -- no glide, since this
|
||||||
|
// isn't a user-initiated navigation.
|
||||||
|
rebuildArrangement();
|
||||||
|
centerInstantlyOnReal(qBound(0, m_currentRealIndex, newCount - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setFocalWidth(qreal v) {
|
||||||
|
if (qFuzzyCompare(m_focalWidth, v)) return;
|
||||||
|
m_focalWidth = v;
|
||||||
|
emit focalWidthChanged();
|
||||||
|
rebuildArrangement();
|
||||||
|
relayout();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setMinEdgeWidth(qreal v) {
|
||||||
|
if (qFuzzyCompare(m_minEdgeWidth, v)) return;
|
||||||
|
m_minEdgeWidth = v;
|
||||||
|
emit minEdgeWidthChanged();
|
||||||
|
rebuildArrangement();
|
||||||
|
relayout();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setItemSpacing(qreal v) {
|
||||||
|
if (qFuzzyCompare(m_itemSpacing, v)) return;
|
||||||
|
m_itemSpacing = v;
|
||||||
|
emit itemSpacingChanged();
|
||||||
|
rebuildArrangement();
|
||||||
|
relayout();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setTileHeight(qreal v) {
|
||||||
|
if (qFuzzyCompare(m_tileHeight, v)) return;
|
||||||
|
m_tileHeight = v;
|
||||||
|
emit tileHeightChanged();
|
||||||
|
for (const Slot& s : std::as_const(m_slots)) {
|
||||||
|
if (s.active && s.item)
|
||||||
|
QQmlProperty::write(
|
||||||
|
s.item, QStringLiteral("tileHeight"), m_tileHeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setMaxWidth(qreal v) {
|
||||||
|
if (qFuzzyCompare(m_maxWidth, v)) return;
|
||||||
|
m_maxWidth = v;
|
||||||
|
emit maxWidthChanged();
|
||||||
|
rebuildArrangement();
|
||||||
|
relayout();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setGlideDuration(int v) {
|
||||||
|
if (m_glideDuration == v) return;
|
||||||
|
m_glideDuration = v;
|
||||||
|
emit glideDurationChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setGlideEasingType(QEasingCurve::Type t) {
|
||||||
|
if (m_glideEasingType == t) return;
|
||||||
|
m_glideEasingType = t;
|
||||||
|
m_glideAnim->setEasingCurve(t);
|
||||||
|
emit glideEasingTypeChanged();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setDelegateProperties(const QVariantMap& v) {
|
||||||
|
m_delegateProperties = v;
|
||||||
|
emit delegatePropertiesChanged();
|
||||||
|
for (const Slot& s : std::as_const(m_slots)) {
|
||||||
|
if (s.active && s.item) {
|
||||||
|
for (auto it = m_delegateProperties.constBegin();
|
||||||
|
it != m_delegateProperties.constEnd();
|
||||||
|
++it)
|
||||||
|
QQmlProperty::write(s.item, it.key(), it.value());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::setCurrentIndex(int idx) {
|
||||||
|
goToIndex(idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- geometry
|
||||||
|
|
||||||
|
void CarouselView::geometryChange(const QRectF& newGeo, const QRectF& oldGeo) {
|
||||||
|
QQuickItem::geometryChange(newGeo, oldGeo);
|
||||||
|
if (!qFuzzyCompare(newGeo.width(), oldGeo.width()) ||
|
||||||
|
!qFuzzyCompare(newGeo.height(), oldGeo.height())) {
|
||||||
|
// Recentre on the same virtual index rather than letting contentX
|
||||||
|
// drift, exactly like the QML version's onWidthChanged handler --
|
||||||
|
// but here it happens in the same pass as the arrangement rebuild,
|
||||||
|
// so x/width for every slot are recomputed together.
|
||||||
|
rebuildArrangement();
|
||||||
|
if (m_initializedLayout)
|
||||||
|
m_contentX = contentXForIndex(m_currentVirtualIndex);
|
||||||
|
relayout();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- arrangement math
|
||||||
|
// Direct port of the QML `arrangement` computed property + keylineCenter/
|
||||||
|
// keylineSize/sampleCenter/sampleSize helpers. Kept numerically identical on
|
||||||
|
// purpose so behaviour doesn't change, just *when* it's applied.
|
||||||
|
|
||||||
|
void CarouselView::rebuildArrangement() {
|
||||||
|
Arrangement& a = m_arrangement;
|
||||||
|
a = Arrangement{};
|
||||||
|
|
||||||
|
// IMPORTANT: this must be the external constraint (m_maxWidth), never
|
||||||
|
// width() -- width() is a *result* of this computation (see below), and
|
||||||
|
// using it here would make the arrangement depend on its own previous
|
||||||
|
// output. On first layout, before width() has ever been set, that
|
||||||
|
// bootstraps to W==0 -> n==0 -> every side item falls back to a flat
|
||||||
|
// minEdgeWidth with no taper at all, which is what caused items to slide
|
||||||
|
// off looking "pushed out" instead of shrinking.
|
||||||
|
const qreal W = m_maxWidth;
|
||||||
|
const qreal F = m_focalWidth;
|
||||||
|
const qreal M = m_minEdgeWidth;
|
||||||
|
const qreal sp = m_itemSpacing;
|
||||||
|
|
||||||
|
if (W <= 0 || F <= 0) {
|
||||||
|
a.sizes = {F};
|
||||||
|
a.centers = {0};
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int bestN = 0;
|
||||||
|
QVector<qreal> bestSizes = {F};
|
||||||
|
qreal bestWidth = F;
|
||||||
|
|
||||||
|
for (int n = 1;; ++n) {
|
||||||
|
const qreal ratio = std::pow(M / F, 1.0 / n);
|
||||||
|
QVector<qreal> sizes = {F};
|
||||||
|
qreal sideWidth = 0;
|
||||||
|
|
||||||
|
for (int i = 1; i <= n; ++i) {
|
||||||
|
const qreal size = (i == n) ? M : F * std::pow(ratio, i);
|
||||||
|
sizes.push_back(size);
|
||||||
|
sideWidth += size;
|
||||||
|
}
|
||||||
|
|
||||||
|
const qreal requiredWidth = F + 2 * n * sp + 2 * sideWidth;
|
||||||
|
if (requiredWidth > W) break;
|
||||||
|
|
||||||
|
bestN = n;
|
||||||
|
bestSizes = sizes;
|
||||||
|
bestWidth = requiredWidth;
|
||||||
|
|
||||||
|
// Safety valve: arrangement size is bounded by how many halvings fit,
|
||||||
|
// this just guards against pathological inputs (F <= M etc).
|
||||||
|
if (n > 64) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
a.n = bestN;
|
||||||
|
a.sizes = bestSizes;
|
||||||
|
a.width = bestWidth;
|
||||||
|
|
||||||
|
QVector<qreal> centers = {0};
|
||||||
|
qreal center = 0;
|
||||||
|
for (int i = 1; i <= bestN; ++i) {
|
||||||
|
center += bestSizes[i - 1] / 2.0 + sp + bestSizes[i] / 2.0;
|
||||||
|
centers.push_back(center);
|
||||||
|
}
|
||||||
|
a.centers = centers;
|
||||||
|
|
||||||
|
qreal extra = 0;
|
||||||
|
for (int i = 1; i <= bestN; ++i)
|
||||||
|
extra += pitch() - bestSizes[i];
|
||||||
|
a.effectiveExtraWidth = extra;
|
||||||
|
|
||||||
|
setImplicitWidth(m_maxWidth);
|
||||||
|
// This mirrors the original `width: arrangement.width` binding. It's
|
||||||
|
// safe against feedback because the arrangement above only ever reads
|
||||||
|
// m_maxWidth, never width() -- so if a.width doesn't change, setWidth()
|
||||||
|
// here is a no-op and geometryChange() won't recurse.
|
||||||
|
setWidth(a.width);
|
||||||
|
}
|
||||||
|
|
||||||
|
qreal CarouselView::keylineCenter(int io) const {
|
||||||
|
const int n = m_arrangement.n;
|
||||||
|
const int i = std::abs(io);
|
||||||
|
if (i == 0) return 0;
|
||||||
|
const int sign = io < 0 ? -1 : 1;
|
||||||
|
|
||||||
|
if (i <= n) return sign * m_arrangement.centers[i];
|
||||||
|
|
||||||
|
if (i == n + 1) {
|
||||||
|
const qreal lastCenter = m_arrangement.centers[n];
|
||||||
|
const qreal lastSize = m_arrangement.sizes[n];
|
||||||
|
return sign * (lastCenter + lastSize / 2.0 + m_itemSpacing +
|
||||||
|
m_minEdgeWidth / 2.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const qreal outgoingCenter = std::abs(keylineCenter(sign * (n + 1)));
|
||||||
|
return sign * (outgoingCenter + m_minEdgeWidth / 2.0 + m_itemSpacing);
|
||||||
|
}
|
||||||
|
|
||||||
|
qreal CarouselView::keylineSize(int io) const {
|
||||||
|
const int n = m_arrangement.n;
|
||||||
|
const int i = std::abs(io);
|
||||||
|
if (i == 0) return m_focalWidth;
|
||||||
|
if (i <= n) return m_arrangement.sizes[i];
|
||||||
|
if (i == n + 1) return m_minEdgeWidth;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
qreal CarouselView::sampleCenter(qreal childLoc) const {
|
||||||
|
const int n = m_arrangement.n;
|
||||||
|
if (n <= 0) return 0;
|
||||||
|
|
||||||
|
const int minIo = -(n + 2);
|
||||||
|
const int maxIo = n + 2;
|
||||||
|
const qreal p = pitch();
|
||||||
|
|
||||||
|
const int a = static_cast<int>(std::floor(childLoc / p));
|
||||||
|
if (a < minIo) return keylineCenter(minIo);
|
||||||
|
if (a >= maxIo) return keylineCenter(maxIo);
|
||||||
|
|
||||||
|
const int b = a + 1;
|
||||||
|
const qreal t = (childLoc - a * p) / p;
|
||||||
|
return keylineCenter(a) + (keylineCenter(b) - keylineCenter(a)) * t;
|
||||||
|
}
|
||||||
|
|
||||||
|
qreal CarouselView::sampleSize(qreal childLoc) const {
|
||||||
|
const int n = m_arrangement.n;
|
||||||
|
if (n <= 0) return 0;
|
||||||
|
|
||||||
|
const int minIo = -(n + 2);
|
||||||
|
const int maxIo = n + 2;
|
||||||
|
const qreal p = pitch();
|
||||||
|
|
||||||
|
const int a = static_cast<int>(std::floor(childLoc / p));
|
||||||
|
if (a < minIo) return keylineSize(minIo);
|
||||||
|
if (a >= maxIo) return keylineSize(maxIo);
|
||||||
|
|
||||||
|
const int b = a + 1;
|
||||||
|
const qreal t = (childLoc - a * p) / p;
|
||||||
|
return keylineSize(a) + (keylineSize(b) - keylineSize(a)) * t;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- index math
|
||||||
|
|
||||||
|
int CarouselView::realIndexOf(int virtualIndex) const {
|
||||||
|
const int count = m_model.size();
|
||||||
|
if (count == 0) return -1;
|
||||||
|
return ((virtualIndex % count) + count) % count;
|
||||||
|
}
|
||||||
|
|
||||||
|
qreal CarouselView::contentXForIndex(qreal index) const {
|
||||||
|
return index * pitch() + pitch() / 2.0 - width() / 2.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int CarouselView::indexForContentX(qreal x) const {
|
||||||
|
return static_cast<int>(
|
||||||
|
std::round((x + width() / 2.0 - pitch() / 2.0) / pitch()));
|
||||||
|
}
|
||||||
|
|
||||||
|
qreal CarouselView::snapTargetX(qreal x) const {
|
||||||
|
return contentXForIndex(indexForContentX(x));
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::wrapContentIfNeeded() {
|
||||||
|
const int count = m_model.size();
|
||||||
|
if (count == 0) return;
|
||||||
|
|
||||||
|
const qreal blockWidth = count * pitch();
|
||||||
|
const qreal centerX = contentXForIndex(m_centerBlockStart);
|
||||||
|
const int blocksFromCenter =
|
||||||
|
static_cast<int>(std::round((m_contentX - centerX) / blockWidth));
|
||||||
|
|
||||||
|
if (std::abs(blocksFromCenter) >= 2) {
|
||||||
|
const qreal shift = blocksFromCenter * blockWidth;
|
||||||
|
m_contentX -= shift;
|
||||||
|
|
||||||
|
if (m_glideAnim->state() == QAbstractAnimation::Running) {
|
||||||
|
const qreal newEnd = m_glideAnim->endValue().toReal() - shift;
|
||||||
|
m_glideAnim->setEndValue(newEnd);
|
||||||
|
}
|
||||||
|
if (m_flickAnim->state() == QAbstractAnimation::Running) {
|
||||||
|
const qreal newEnd = m_flickAnim->endValue().toReal() - shift;
|
||||||
|
m_flickAnim->setEndValue(newEnd);
|
||||||
|
}
|
||||||
|
// Also shift every currently-live slot's virtual index bookkeeping so
|
||||||
|
// it doesn't think it needs to be recycled just because of the wrap.
|
||||||
|
const int indexShift = static_cast<int>(std::round(shift / pitch()));
|
||||||
|
for (Slot& s : m_slots) {
|
||||||
|
if (s.active) s.virtualIndex -= indexShift;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::updateCurrentIndexFromContentX(bool emitPreview) {
|
||||||
|
const int count = m_model.size();
|
||||||
|
if (count == 0) return;
|
||||||
|
|
||||||
|
const int newVirtual = static_cast<int>(
|
||||||
|
std::round((m_contentX + width() / 2.0 - pitch() / 2.0) / pitch()));
|
||||||
|
if (newVirtual == m_currentVirtualIndex) return;
|
||||||
|
|
||||||
|
m_currentVirtualIndex = newVirtual;
|
||||||
|
const int newReal = realIndexOf(newVirtual);
|
||||||
|
|
||||||
|
if (newReal != m_currentRealIndex) {
|
||||||
|
m_currentRealIndex = newReal;
|
||||||
|
emit currentIndexChanged();
|
||||||
|
}
|
||||||
|
if (emitPreview && newReal != m_previewRealIndex) {
|
||||||
|
m_previewRealIndex = newReal;
|
||||||
|
if (newReal >= 0)
|
||||||
|
emit previewIndexChanged(newReal, m_model.at(newReal));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- pool / delegates
|
||||||
|
|
||||||
|
QQuickItem* CarouselView::acquireItem() {
|
||||||
|
if (!m_delegate) return nullptr;
|
||||||
|
|
||||||
|
QQmlContext* ctx = QQmlEngine::contextForObject(this);
|
||||||
|
QVariantMap initial;
|
||||||
|
initial.insert(QStringLiteral("isCurrent"), false);
|
||||||
|
initial.insert(QStringLiteral("modelData"), QVariant());
|
||||||
|
initial.insert(QStringLiteral("tileHeight"), m_tileHeight);
|
||||||
|
initial.insert(QStringLiteral("tileWidth"), m_focalWidth);
|
||||||
|
for (auto it = m_delegateProperties.constBegin();
|
||||||
|
it != m_delegateProperties.constEnd();
|
||||||
|
++it)
|
||||||
|
initial.insert(it.key(), it.value());
|
||||||
|
|
||||||
|
QObject* obj = m_delegate->createWithInitialProperties(initial, ctx);
|
||||||
|
if (!obj) {
|
||||||
|
qWarning(
|
||||||
|
"CarouselView: failed to create delegate instance: %s",
|
||||||
|
qPrintable(m_delegate->errorString()));
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
QQuickItem* item = qobject_cast<QQuickItem*>(obj);
|
||||||
|
if (!item) {
|
||||||
|
qWarning("CarouselView: delegate root is not an Item");
|
||||||
|
delete obj;
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
item->setParentItem(this);
|
||||||
|
QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);
|
||||||
|
|
||||||
|
const QMetaMethod activateSignal = item->metaObject()->method(
|
||||||
|
item->metaObject()->indexOfSignal("requestActivate()"));
|
||||||
|
if (activateSignal.isValid()) {
|
||||||
|
static const QMetaMethod slot = metaObject()->method(
|
||||||
|
metaObject()->indexOfSlot("handleDelegateActivate()"));
|
||||||
|
connect(item, activateSignal, this, slot);
|
||||||
|
}
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::applyPropertiesToItem(QQuickItem* item, int realIndex) const {
|
||||||
|
if (!item) return;
|
||||||
|
const bool isCurrent = (realIndex == m_currentRealIndex);
|
||||||
|
QQmlProperty::write(item, QStringLiteral("isCurrent"), isCurrent);
|
||||||
|
QQmlProperty::write(
|
||||||
|
item,
|
||||||
|
QStringLiteral("modelData"),
|
||||||
|
realIndex >= 0 && realIndex < m_model.size() ? m_model.at(realIndex)
|
||||||
|
: QVariant());
|
||||||
|
QQmlProperty::write(item, QStringLiteral("tileHeight"), m_tileHeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::updateSlotContent(Slot& slot, int virtualIndex) {
|
||||||
|
if (!slot.item) slot.item = acquireItem();
|
||||||
|
if (!slot.item) return;
|
||||||
|
|
||||||
|
slot.virtualIndex = virtualIndex;
|
||||||
|
slot.realIndex = realIndexOf(virtualIndex);
|
||||||
|
slot.active = slot.realIndex >= 0;
|
||||||
|
slot.item->setVisible(slot.active);
|
||||||
|
if (slot.active) applyPropertiesToItem(slot.item, slot.realIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::positionSlot(const Slot& slot) const {
|
||||||
|
if (!slot.item || !slot.active) return;
|
||||||
|
|
||||||
|
const qreal childLoc = slot.virtualIndex * pitch() + pitch() / 2.0 -
|
||||||
|
m_contentX - width() / 2.0;
|
||||||
|
const qreal center = sampleCenter(childLoc);
|
||||||
|
const qreal size = sampleSize(childLoc);
|
||||||
|
|
||||||
|
// slot's "column" spans one pitch, centred at width()/2 + center; item is
|
||||||
|
// centred within that column, matching the QML delegate's x expression.
|
||||||
|
const qreal slotX = childLoc + width() / 2.0 - pitch() / 2.0;
|
||||||
|
const qreal itemX = (center - childLoc) + (pitch() - size) / 2.0 + slotX;
|
||||||
|
|
||||||
|
QQmlProperty::write(slot.item, QStringLiteral("tileWidth"), size);
|
||||||
|
slot.item->setX(itemX);
|
||||||
|
slot.item->setY(0);
|
||||||
|
slot.item->setVisible(size > 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::releaseAllItems() {
|
||||||
|
for (Slot& s : m_slots) {
|
||||||
|
if (s.item) s.item->deleteLater();
|
||||||
|
}
|
||||||
|
m_slots.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- layout pass
|
||||||
|
|
||||||
|
void CarouselView::relayout() {
|
||||||
|
const int count = m_model.size();
|
||||||
|
if (count == 0 || width() <= 0 || m_focalWidth <= 0) {
|
||||||
|
for (Slot& s : m_slots)
|
||||||
|
if (s.item) s.item->setVisible(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const int n = m_arrangement.n;
|
||||||
|
// Window of virtual indices that can ever be visible, plus a small buffer
|
||||||
|
// so items don't pop in/out right at the edge during a fast flick.
|
||||||
|
const int half = n + 3;
|
||||||
|
const int lo = m_currentVirtualIndex - half;
|
||||||
|
const int hi = m_currentVirtualIndex + half;
|
||||||
|
const int needed = hi - lo + 1;
|
||||||
|
|
||||||
|
// Grow the pool if needed (shrinking is unnecessary: idle items are just
|
||||||
|
// marked inactive/invisible, which is cheap and avoids churn).
|
||||||
|
while (m_slots.size() < needed)
|
||||||
|
m_slots.append(Slot{});
|
||||||
|
|
||||||
|
// Figure out which virtual indices are already backed by a slot.
|
||||||
|
QHash<int, int> virtualToSlot; // virtualIndex -> slot list position
|
||||||
|
virtualToSlot.reserve(m_slots.size());
|
||||||
|
for (int i = 0; i < m_slots.size(); ++i) {
|
||||||
|
if (m_slots[i].active) virtualToSlot.insert(m_slots[i].virtualIndex, i);
|
||||||
|
}
|
||||||
|
|
||||||
|
QVector<bool> slotUsedThisPass(m_slots.size(), false);
|
||||||
|
|
||||||
|
for (int v = lo; v <= hi; ++v) {
|
||||||
|
auto it = virtualToSlot.find(v);
|
||||||
|
if (it != virtualToSlot.end()) {
|
||||||
|
slotUsedThisPass[it.value()] = true;
|
||||||
|
// Content (isCurrent / modelData) may still need refreshing if
|
||||||
|
// currentRealIndex changed since last pass.
|
||||||
|
applyPropertiesToItem(
|
||||||
|
m_slots[it.value()].item, m_slots[it.value()].realIndex);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// find a free slot: one not used this pass and not already at a
|
||||||
|
// virtual index inside [lo, hi] (those are all still needed).
|
||||||
|
int freeSlot = -1;
|
||||||
|
for (int i = 0; i < m_slots.size(); ++i) {
|
||||||
|
if (slotUsedThisPass[i]) continue;
|
||||||
|
if (m_slots[i].active && m_slots[i].virtualIndex >= lo &&
|
||||||
|
m_slots[i].virtualIndex <= hi)
|
||||||
|
continue;
|
||||||
|
freeSlot = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (freeSlot < 0) {
|
||||||
|
// Shouldn't happen given the pool growth above, but guard anyway.
|
||||||
|
m_slots.append(Slot{});
|
||||||
|
slotUsedThisPass.append(false);
|
||||||
|
freeSlot = m_slots.size() - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateSlotContent(m_slots[freeSlot], v);
|
||||||
|
slotUsedThisPass[freeSlot] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < m_slots.size(); ++i) {
|
||||||
|
if (!slotUsedThisPass[i] && m_slots[i].item) {
|
||||||
|
m_slots[i].active = false;
|
||||||
|
m_slots[i].item->setVisible(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const Slot& s : std::as_const(m_slots))
|
||||||
|
positionSlot(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- animation
|
||||||
|
|
||||||
|
void CarouselView::cancelAnimations() {
|
||||||
|
if (m_glideAnim->state() == QAbstractAnimation::Running)
|
||||||
|
m_glideAnim->stop();
|
||||||
|
if (m_flickAnim->state() == QAbstractAnimation::Running)
|
||||||
|
m_flickAnim->stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::glideTo(qreal dest) {
|
||||||
|
if (std::abs(dest - m_contentX) < 0.5) return;
|
||||||
|
|
||||||
|
cancelAnimations();
|
||||||
|
m_glideAnim->setDuration(m_glideDuration);
|
||||||
|
m_glideAnim->setStartValue(m_contentX);
|
||||||
|
m_glideAnim->setEndValue(dest);
|
||||||
|
m_glideAnim->start();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::snapToNearest() {
|
||||||
|
glideTo(snapTargetX(m_contentX));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- public API
|
||||||
|
|
||||||
|
void CarouselView::goToIndex(int realIndex) {
|
||||||
|
const int count = m_model.size();
|
||||||
|
if (count == 0) return;
|
||||||
|
realIndex = qBound(0, realIndex, count - 1);
|
||||||
|
|
||||||
|
const int curBlock =
|
||||||
|
static_cast<int>(std::floor(qreal(m_currentVirtualIndex) / count));
|
||||||
|
const int current = m_currentVirtualIndex;
|
||||||
|
int target = curBlock * count + realIndex;
|
||||||
|
|
||||||
|
if (target - current > count / 2)
|
||||||
|
target -= count;
|
||||||
|
else if (current - target > count / 2)
|
||||||
|
target += count;
|
||||||
|
|
||||||
|
glideTo(contentXForIndex(target));
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::incrementCurrentIndex() {
|
||||||
|
if (m_model.isEmpty()) return;
|
||||||
|
glideTo(contentXForIndex(m_currentVirtualIndex + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::decrementCurrentIndex() {
|
||||||
|
if (m_model.isEmpty()) return;
|
||||||
|
glideTo(contentXForIndex(m_currentVirtualIndex - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::jumpToIndex(int realIndex) {
|
||||||
|
centerInstantlyOnReal(realIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::centerInstantlyOnReal(int realIndex) {
|
||||||
|
const int count = m_model.size();
|
||||||
|
if (count == 0) return;
|
||||||
|
realIndex = qBound(0, realIndex, count - 1);
|
||||||
|
|
||||||
|
cancelAnimations();
|
||||||
|
|
||||||
|
const int curBlock =
|
||||||
|
static_cast<int>(std::floor(qreal(m_currentVirtualIndex) / count));
|
||||||
|
const int current = m_currentVirtualIndex;
|
||||||
|
int target = curBlock * count + realIndex;
|
||||||
|
|
||||||
|
if (target - current > count / 2)
|
||||||
|
target -= count;
|
||||||
|
else if (current - target > count / 2)
|
||||||
|
target += count;
|
||||||
|
|
||||||
|
m_currentVirtualIndex = target;
|
||||||
|
m_contentX = contentXForIndex(target);
|
||||||
|
|
||||||
|
const bool changed = (realIndex != m_currentRealIndex);
|
||||||
|
m_currentRealIndex = realIndex;
|
||||||
|
m_previewRealIndex = realIndex;
|
||||||
|
if (changed) emit currentIndexChanged();
|
||||||
|
emit previewIndexChanged(realIndex, m_model.at(realIndex));
|
||||||
|
|
||||||
|
relayout();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- input
|
||||||
|
|
||||||
|
void CarouselView::mousePressEvent(QMouseEvent* event) {
|
||||||
|
// Deliberately do NOT cancel animations here. A press that turns out to
|
||||||
|
// be a plain tap (never crosses the drag threshold) should leave any
|
||||||
|
// in-flight glide/flick completely untouched. We only touch the
|
||||||
|
// animation once we know it's actually a drag (see mouseMoveEvent).
|
||||||
|
m_dragging = true;
|
||||||
|
m_dragActive = false;
|
||||||
|
m_pressPos = event->position();
|
||||||
|
// Capture wherever contentX currently is, even mid-animation -- if this
|
||||||
|
// does turn into a drag, it should pick up smoothly from the visual
|
||||||
|
// position, not teleport to some rest position first.
|
||||||
|
m_pressContentX = m_contentX;
|
||||||
|
m_dragTimer.start();
|
||||||
|
m_lastMoveX = event->position().x();
|
||||||
|
m_lastMoveT = 0;
|
||||||
|
m_velocity = 0;
|
||||||
|
event->accept();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::mouseMoveEvent(QMouseEvent* event) {
|
||||||
|
if (!m_dragging) return;
|
||||||
|
|
||||||
|
const qreal dx = event->position().x() - m_pressPos.x();
|
||||||
|
if (!m_dragActive && std::abs(dx) > kDragThreshold) {
|
||||||
|
m_dragActive = true;
|
||||||
|
m_pressContentX =
|
||||||
|
m_contentX; // re-anchor to the live (possibly mid-animation) value
|
||||||
|
cancelAnimations();
|
||||||
|
grabMouse();
|
||||||
|
}
|
||||||
|
if (!m_dragActive) return;
|
||||||
|
|
||||||
|
m_contentX = m_pressContentX - dx;
|
||||||
|
wrapContentIfNeeded();
|
||||||
|
updateCurrentIndexFromContentX(true);
|
||||||
|
relayout();
|
||||||
|
|
||||||
|
const qint64 t = m_dragTimer.elapsed();
|
||||||
|
const qint64 dt = t - m_lastMoveT;
|
||||||
|
if (dt > 0) {
|
||||||
|
const qreal instVel =
|
||||||
|
(m_lastMoveX - event->position().x()) / (dt / 1000.0);
|
||||||
|
// Light smoothing so a single jittery sample doesn't dominate the flick.
|
||||||
|
m_velocity = m_velocity * 0.7 + instVel * 0.3;
|
||||||
|
}
|
||||||
|
m_lastMoveX = event->position().x();
|
||||||
|
m_lastMoveT = t;
|
||||||
|
|
||||||
|
event->accept();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::mouseReleaseEvent(QMouseEvent* event) {
|
||||||
|
if (!m_dragging) return;
|
||||||
|
m_dragging = false;
|
||||||
|
ungrabMouse();
|
||||||
|
|
||||||
|
if (!m_dragActive) {
|
||||||
|
// A plain click/tap with no drag: let it fall through to the
|
||||||
|
// delegate's own StateLayer/MouseArea via requestActivate().
|
||||||
|
event->accept();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
m_dragActive = false;
|
||||||
|
|
||||||
|
qreal v = qBound(-kMaxFlickVelocity, m_velocity, kMaxFlickVelocity);
|
||||||
|
if (std::abs(v) < kMinFlickVelocity) {
|
||||||
|
snapToNearest();
|
||||||
|
event->accept();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple constant-deceleration flick: distance = v^2 / (2*friction).
|
||||||
|
const qreal duration = std::abs(v) / (kFlickFriction * 1000.0); // ms
|
||||||
|
const qreal distance =
|
||||||
|
(v * (duration / 1000.0)) / 2.0; // average-velocity approximation
|
||||||
|
const qreal rawDest = m_contentX + distance;
|
||||||
|
const qreal dest = snapTargetX(rawDest);
|
||||||
|
|
||||||
|
cancelAnimations();
|
||||||
|
m_flickAnim->setDuration(
|
||||||
|
static_cast<int>(qBound<qreal>(120, duration, 900)));
|
||||||
|
m_flickAnim->setEasingCurve(QEasingCurve::OutCubic);
|
||||||
|
m_flickAnim->setStartValue(m_contentX);
|
||||||
|
m_flickAnim->setEndValue(dest);
|
||||||
|
m_flickAnim->start();
|
||||||
|
|
||||||
|
event->accept();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::mouseUngrabEvent() {
|
||||||
|
m_dragging = false;
|
||||||
|
m_dragActive = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CarouselView::wheelEvent(QWheelEvent* event) {
|
||||||
|
const int steps = event->angleDelta().y() / 120;
|
||||||
|
if (steps > 0)
|
||||||
|
decrementCurrentIndex();
|
||||||
|
else if (steps < 0)
|
||||||
|
incrementCurrentIndex();
|
||||||
|
event->accept();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- delegate signal
|
||||||
|
|
||||||
|
void CarouselView::handleDelegateActivate() {
|
||||||
|
QQuickItem* item = qobject_cast<QQuickItem*>(sender());
|
||||||
|
if (!item) return;
|
||||||
|
|
||||||
|
for (const Slot& s : std::as_const(m_slots)) {
|
||||||
|
if (s.item == item && s.active) {
|
||||||
|
if (s.realIndex == m_currentRealIndex) {
|
||||||
|
emit activated(s.realIndex, m_model.at(s.realIndex));
|
||||||
|
} else {
|
||||||
|
goToIndex(s.realIndex);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace ZShell::components
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <QQuickItem>
|
||||||
|
#include <QQmlComponent>
|
||||||
|
#include <QQmlEngine>
|
||||||
|
#include <QVariantList>
|
||||||
|
#include <QVariantAnimation>
|
||||||
|
#include <QEasingCurve>
|
||||||
|
#include <QElapsedTimer>
|
||||||
|
#include <QPointF>
|
||||||
|
#include <QVector>
|
||||||
|
#include <QList>
|
||||||
|
|
||||||
|
namespace ZShell::components {
|
||||||
|
|
||||||
|
class CarouselView : public QQuickItem {
|
||||||
|
Q_OBJECT
|
||||||
|
QML_ELEMENT
|
||||||
|
|
||||||
|
Q_PROPERTY(
|
||||||
|
QQmlComponent* delegate READ delegate WRITE setDelegate NOTIFY
|
||||||
|
delegateChanged)
|
||||||
|
Q_PROPERTY(QVariantList model READ model WRITE setModel NOTIFY modelChanged)
|
||||||
|
|
||||||
|
Q_PROPERTY(
|
||||||
|
qreal focalWidth READ focalWidth WRITE setFocalWidth NOTIFY
|
||||||
|
focalWidthChanged)
|
||||||
|
Q_PROPERTY(
|
||||||
|
qreal minEdgeWidth READ minEdgeWidth WRITE setMinEdgeWidth NOTIFY
|
||||||
|
minEdgeWidthChanged)
|
||||||
|
Q_PROPERTY(
|
||||||
|
qreal itemSpacing READ itemSpacing WRITE setItemSpacing NOTIFY
|
||||||
|
itemSpacingChanged)
|
||||||
|
Q_PROPERTY(
|
||||||
|
qreal tileHeight READ tileHeight WRITE setTileHeight NOTIFY
|
||||||
|
tileHeightChanged)
|
||||||
|
Q_PROPERTY(
|
||||||
|
qreal maxWidth READ maxWidth WRITE setMaxWidth NOTIFY maxWidthChanged)
|
||||||
|
|
||||||
|
Q_PROPERTY(
|
||||||
|
int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY
|
||||||
|
currentIndexChanged)
|
||||||
|
Q_PROPERTY(
|
||||||
|
int glideDuration READ glideDuration WRITE setGlideDuration NOTIFY
|
||||||
|
glideDurationChanged)
|
||||||
|
Q_PROPERTY(
|
||||||
|
QEasingCurve::Type glideEasingType READ glideEasingType WRITE
|
||||||
|
setGlideEasingType NOTIFY glideEasingTypeChanged)
|
||||||
|
|
||||||
|
// Extra properties (e.g. { visibilities: root.visibilities }) forwarded
|
||||||
|
// verbatim onto every delegate instance as a property of the same name.
|
||||||
|
Q_PROPERTY(
|
||||||
|
QVariantMap delegateProperties READ delegateProperties WRITE
|
||||||
|
setDelegateProperties NOTIFY delegatePropertiesChanged)
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit CarouselView(QQuickItem* parent = nullptr);
|
||||||
|
~CarouselView() override;
|
||||||
|
|
||||||
|
QQmlComponent* delegate() const { return m_delegate; }
|
||||||
|
void setDelegate(QQmlComponent* c);
|
||||||
|
|
||||||
|
QVariantList model() const { return m_model; }
|
||||||
|
void setModel(const QVariantList& m);
|
||||||
|
|
||||||
|
qreal focalWidth() const { return m_focalWidth; }
|
||||||
|
void setFocalWidth(qreal v);
|
||||||
|
|
||||||
|
qreal minEdgeWidth() const { return m_minEdgeWidth; }
|
||||||
|
void setMinEdgeWidth(qreal v);
|
||||||
|
|
||||||
|
qreal itemSpacing() const { return m_itemSpacing; }
|
||||||
|
void setItemSpacing(qreal v);
|
||||||
|
|
||||||
|
qreal tileHeight() const { return m_tileHeight; }
|
||||||
|
void setTileHeight(qreal v);
|
||||||
|
|
||||||
|
qreal maxWidth() const { return m_maxWidth; }
|
||||||
|
void setMaxWidth(qreal v);
|
||||||
|
|
||||||
|
int currentIndex() const { return m_currentRealIndex; }
|
||||||
|
void setCurrentIndex(int idx); // jumps (animated glide) to a real index
|
||||||
|
|
||||||
|
int glideDuration() const { return m_glideDuration; }
|
||||||
|
void setGlideDuration(int v);
|
||||||
|
|
||||||
|
QEasingCurve::Type glideEasingType() const { return m_glideEasingType; }
|
||||||
|
void setGlideEasingType(QEasingCurve::Type t);
|
||||||
|
|
||||||
|
QVariantMap delegateProperties() const { return m_delegateProperties; }
|
||||||
|
void setDelegateProperties(const QVariantMap& v);
|
||||||
|
|
||||||
|
// Animated (glides).
|
||||||
|
Q_INVOKABLE void goToIndex(int realIndex);
|
||||||
|
Q_INVOKABLE void incrementCurrentIndex();
|
||||||
|
Q_INVOKABLE void decrementCurrentIndex();
|
||||||
|
|
||||||
|
// Instant, no animation -- use for initial placement (e.g. restoring the
|
||||||
|
// saved wallpaper on Component.onCompleted) where a glide would be wrong.
|
||||||
|
Q_INVOKABLE void jumpToIndex(int realIndex);
|
||||||
|
|
||||||
|
signals:
|
||||||
|
void delegateChanged();
|
||||||
|
void modelChanged();
|
||||||
|
void focalWidthChanged();
|
||||||
|
void minEdgeWidthChanged();
|
||||||
|
void itemSpacingChanged();
|
||||||
|
void tileHeightChanged();
|
||||||
|
void maxWidthChanged();
|
||||||
|
void currentIndexChanged();
|
||||||
|
void glideDurationChanged();
|
||||||
|
void glideEasingTypeChanged();
|
||||||
|
void delegatePropertiesChanged();
|
||||||
|
|
||||||
|
// Emitted when the currently-centred delegate is clicked while already
|
||||||
|
// centred (i.e. "activate/select this one").
|
||||||
|
void activated(int realIndex, QVariant modelData);
|
||||||
|
// Emitted continuously as the centred item changes, for preview-on-scroll
|
||||||
|
// behaviour (used to drive Wallpapers.preview() from QML).
|
||||||
|
void previewIndexChanged(int realIndex, QVariant modelData);
|
||||||
|
|
||||||
|
protected:
|
||||||
|
void geometryChange(const QRectF& newGeo, const QRectF& oldGeo) override;
|
||||||
|
void mousePressEvent(QMouseEvent* event) override;
|
||||||
|
void mouseMoveEvent(QMouseEvent* event) override;
|
||||||
|
void mouseReleaseEvent(QMouseEvent* event) override;
|
||||||
|
void mouseUngrabEvent() override;
|
||||||
|
void wheelEvent(QWheelEvent* event) override;
|
||||||
|
|
||||||
|
private slots:
|
||||||
|
void handleDelegateActivate();
|
||||||
|
|
||||||
|
private:
|
||||||
|
struct Arrangement {
|
||||||
|
int n = 0;
|
||||||
|
qreal width = 0;
|
||||||
|
QVector<qreal> sizes; // sizes[0] = focal, sizes[i] = i-th side item
|
||||||
|
QVector<qreal>
|
||||||
|
centers; // centers[0] = 0, centers[i] = i-th side centre offset
|
||||||
|
qreal effectiveExtraWidth = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Slot {
|
||||||
|
QQuickItem* item = nullptr;
|
||||||
|
int virtualIndex =
|
||||||
|
0; // which "virtual" (unbounded) index this slot currently renders
|
||||||
|
int realIndex = -1; // resolved model index, -1 if none / hidden
|
||||||
|
bool active = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
void rebuildArrangement();
|
||||||
|
void relayout(); // recomputes window + positions every slot (one pass)
|
||||||
|
void updateSlotContent(Slot& slot, int virtualIndex);
|
||||||
|
void positionSlot(const Slot& slot) const;
|
||||||
|
void applyPropertiesToItem(QQuickItem* item, int realIndex) const;
|
||||||
|
|
||||||
|
qreal pitch() const { return m_focalWidth + m_itemSpacing; }
|
||||||
|
qreal contentXForIndex(qreal index) const;
|
||||||
|
int indexForContentX(qreal x) const;
|
||||||
|
qreal snapTargetX(qreal x) const;
|
||||||
|
void snapToNearest();
|
||||||
|
void glideTo(qreal dest);
|
||||||
|
void cancelAnimations();
|
||||||
|
|
||||||
|
qreal keylineCenter(int io) const;
|
||||||
|
qreal keylineSize(int io) const;
|
||||||
|
qreal sampleCenter(qreal childLoc) const;
|
||||||
|
qreal sampleSize(qreal childLoc) const;
|
||||||
|
|
||||||
|
int realIndexOf(int virtualIndex) const;
|
||||||
|
void updateCurrentIndexFromContentX(bool emitPreview);
|
||||||
|
void wrapContentIfNeeded();
|
||||||
|
void centerInstantlyOnReal(int realIndex); // no animation, no glide
|
||||||
|
|
||||||
|
QQuickItem* acquireItem();
|
||||||
|
void releaseAllItems();
|
||||||
|
|
||||||
|
QQmlComponent* m_delegate = nullptr;
|
||||||
|
QVariantList m_model;
|
||||||
|
QVariantMap m_delegateProperties;
|
||||||
|
|
||||||
|
qreal m_focalWidth = 0;
|
||||||
|
qreal m_minEdgeWidth = 56;
|
||||||
|
qreal m_itemSpacing = 8;
|
||||||
|
qreal m_tileHeight = 0;
|
||||||
|
qreal m_maxWidth = 0;
|
||||||
|
|
||||||
|
Arrangement m_arrangement;
|
||||||
|
|
||||||
|
qreal m_contentX = 0;
|
||||||
|
int m_currentVirtualIndex = 0;
|
||||||
|
int m_currentRealIndex = -1;
|
||||||
|
int m_previewRealIndex = -1;
|
||||||
|
|
||||||
|
static constexpr int kLoopMultiplier = 401;
|
||||||
|
int m_centerBlockStart = 0;
|
||||||
|
|
||||||
|
QList<Slot>
|
||||||
|
m_slots; // pooled delegate slots, unordered; window recomputed each relayout
|
||||||
|
|
||||||
|
int m_glideDuration = 250;
|
||||||
|
QEasingCurve::Type m_glideEasingType = QEasingCurve::OutCubic;
|
||||||
|
QVariantAnimation* m_glideAnim = nullptr;
|
||||||
|
|
||||||
|
// Drag / flick state
|
||||||
|
bool m_dragging = false;
|
||||||
|
bool m_dragActive = false; // exceeded the drag threshold
|
||||||
|
QPointF m_pressPos;
|
||||||
|
qreal m_pressContentX = 0;
|
||||||
|
QElapsedTimer m_dragTimer;
|
||||||
|
qreal m_lastMoveX = 0;
|
||||||
|
qint64 m_lastMoveT = 0;
|
||||||
|
qreal m_velocity = 0; // px/sec
|
||||||
|
QVariantAnimation* m_flickAnim = nullptr;
|
||||||
|
|
||||||
|
bool m_initializedLayout = false;
|
||||||
|
bool m_relayoutQueued = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
}; // namespace ZShell::components
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
#include "cachingimagemanager.hpp"
|
#include "cachingimagemanager.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
#include <QtQuick/qquickwindow.h>
|
#include <QtQuick/qquickwindow.h>
|
||||||
#include <qcryptographichash.h>
|
#include <qcryptographichash.h>
|
||||||
#include <qdir.h>
|
#include <qdir.h>
|
||||||
@@ -7,10 +9,27 @@
|
|||||||
#include <qfuturewatcher.h>
|
#include <qfuturewatcher.h>
|
||||||
#include <qimagereader.h>
|
#include <qimagereader.h>
|
||||||
#include <qpainter.h>
|
#include <qpainter.h>
|
||||||
|
#include <qthread.h>
|
||||||
|
#include <qthreadpool.h>
|
||||||
#include <qtconcurrentrun.h>
|
#include <qtconcurrentrun.h>
|
||||||
|
|
||||||
namespace ZShell::internal {
|
namespace ZShell::internal {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
QThreadPool* imageIoPool() {
|
||||||
|
static QThreadPool pool;
|
||||||
|
static const bool init = [] {
|
||||||
|
pool.setMaxThreadCount(std::max(2, QThread::idealThreadCount() / 2));
|
||||||
|
return true;
|
||||||
|
}();
|
||||||
|
(void)init;
|
||||||
|
|
||||||
|
return &pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
qreal CachingImageManager::effectiveScale() const {
|
qreal CachingImageManager::effectiveScale() const {
|
||||||
if (m_item && m_item->window()) {
|
if (m_item && m_item->window()) {
|
||||||
return m_item->window()->devicePixelRatio();
|
return m_item->window()->devicePixelRatio();
|
||||||
@@ -101,14 +120,13 @@ void CachingImageManager::updateSource() {
|
|||||||
|
|
||||||
void CachingImageManager::updateSource(const QString& path) {
|
void CachingImageManager::updateSource(const QString& path) {
|
||||||
if (path.isEmpty() || path == m_shaPath) {
|
if (path.isEmpty() || path == m_shaPath) {
|
||||||
// Path is empty or already calculating sha for path
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
m_shaPath = path;
|
m_shaPath = path;
|
||||||
|
|
||||||
const auto future =
|
const auto future =
|
||||||
QtConcurrent::run(&CachingImageManager::sha256sum, path);
|
QtConcurrent::run(imageIoPool(), &CachingImageManager::sha256sum, path);
|
||||||
|
|
||||||
const auto watcher = new QFutureWatcher<QString>(this);
|
const auto watcher = new QFutureWatcher<QString>(this);
|
||||||
|
|
||||||
@@ -118,7 +136,16 @@ void CachingImageManager::updateSource(const QString& path) {
|
|||||||
this,
|
this,
|
||||||
[watcher, path, this]() {
|
[watcher, path, this]() {
|
||||||
if (m_path != path) {
|
if (m_path != path) {
|
||||||
// Object is destroyed or path has changed, ignore
|
watcher->deleteLater();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const QString key = watcher->result();
|
||||||
|
|
||||||
|
if (key.isEmpty()) {
|
||||||
|
if (m_shaPath == path) {
|
||||||
|
m_shaPath = QString();
|
||||||
|
}
|
||||||
watcher->deleteLater();
|
watcher->deleteLater();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -126,19 +153,29 @@ void CachingImageManager::updateSource(const QString& path) {
|
|||||||
const QSize size = effectiveSize();
|
const QSize size = effectiveSize();
|
||||||
|
|
||||||
if (!m_item || !size.width() || !size.height()) {
|
if (!m_item || !size.width() || !size.height()) {
|
||||||
|
if (m_shaPath == path) {
|
||||||
|
m_shaPath = QString();
|
||||||
|
}
|
||||||
watcher->deleteLater();
|
watcher->deleteLater();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const QString fillMode = m_item->property("fillMode").toString();
|
const QString fillMode = m_item->property("fillMode").toString();
|
||||||
// clang-format off
|
const QString filename =
|
||||||
const QString filename = QString("%1@%2x%3-%4.png")
|
QString("%1@%2x%3-%4.png")
|
||||||
.arg(watcher->result()).arg(size.width()).arg(size.height())
|
.arg(key)
|
||||||
.arg(fillMode == "PreserveAspectCrop" ? "crop" : fillMode == "PreserveAspectFit" ? "fit" : "stretch");
|
.arg(size.width())
|
||||||
// clang-format on
|
.arg(size.height())
|
||||||
|
.arg(
|
||||||
|
fillMode == "PreserveAspectCrop" ? "crop"
|
||||||
|
: fillMode == "PreserveAspectFit" ? "fit"
|
||||||
|
: "stretch");
|
||||||
|
|
||||||
const QUrl cache = m_cacheDir.resolved(QUrl(filename));
|
const QUrl cache = m_cacheDir.resolved(QUrl(filename));
|
||||||
if (m_cachePath == cache) {
|
if (m_cachePath == cache) {
|
||||||
|
if (m_shaPath == path) {
|
||||||
|
m_shaPath = QString();
|
||||||
|
}
|
||||||
watcher->deleteLater();
|
watcher->deleteLater();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -149,6 +186,9 @@ void CachingImageManager::updateSource(const QString& path) {
|
|||||||
if (!cache.isLocalFile()) {
|
if (!cache.isLocalFile()) {
|
||||||
qWarning() << "CachingImageManager::updateSource: cachePath"
|
qWarning() << "CachingImageManager::updateSource: cachePath"
|
||||||
<< cache << "is not a local file";
|
<< cache << "is not a local file";
|
||||||
|
if (m_shaPath == path) {
|
||||||
|
m_shaPath = QString();
|
||||||
|
}
|
||||||
watcher->deleteLater();
|
watcher->deleteLater();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -161,7 +201,6 @@ void CachingImageManager::updateSource(const QString& path) {
|
|||||||
createCache(path, cache.toLocalFile(), fillMode, size);
|
createCache(path, cache.toLocalFile(), fillMode, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear current running sha if same
|
|
||||||
if (m_shaPath == path) {
|
if (m_shaPath == path) {
|
||||||
m_shaPath = QString();
|
m_shaPath = QString();
|
||||||
}
|
}
|
||||||
@@ -170,7 +209,6 @@ void CachingImageManager::updateSource(const QString& path) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
watcher->setFuture(future);
|
watcher->setFuture(future);
|
||||||
// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
QUrl CachingImageManager::cachePath() const {
|
QUrl CachingImageManager::cachePath() const {
|
||||||
@@ -182,61 +220,105 @@ void CachingImageManager::createCache(
|
|||||||
const QString& cache,
|
const QString& cache,
|
||||||
const QString& fillMode,
|
const QString& fillMode,
|
||||||
const QSize& size) const {
|
const QSize& size) const {
|
||||||
QThreadPool::globalInstance()->start([path, cache, fillMode, size] {
|
auto* watcher =
|
||||||
QImage image(path);
|
new QFutureWatcher<bool>(const_cast<CachingImageManager*>(this));
|
||||||
|
|
||||||
if (image.isNull()) {
|
connect(
|
||||||
qWarning() << "CachingImageManager::createCache: failed to read"
|
watcher,
|
||||||
<< path;
|
&QFutureWatcher<bool>::finished,
|
||||||
return;
|
this,
|
||||||
}
|
[this, watcher, cache, path]() {
|
||||||
|
if (watcher->result() && m_item && m_path == path &&
|
||||||
|
m_cachePath.toLocalFile() == cache) {
|
||||||
|
m_item->setProperty("source", QUrl::fromLocalFile(cache));
|
||||||
|
}
|
||||||
|
|
||||||
image.convertTo(QImage::Format_ARGB32);
|
watcher->deleteLater();
|
||||||
|
});
|
||||||
|
|
||||||
if (fillMode == "PreserveAspectCrop") {
|
const auto future =
|
||||||
image = image.scaled(
|
QtConcurrent::run(
|
||||||
size, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
|
imageIoPool(), [path, cache, fillMode, size]() -> bool {
|
||||||
} else if (fillMode == "PreserveAspectFit") {
|
QImageReader reader(path);
|
||||||
image = image.scaled(
|
|
||||||
size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
|
|
||||||
} else {
|
|
||||||
image = image.scaled(
|
|
||||||
size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fillMode == "PreserveAspectCrop" ||
|
if (reader.supportsOption(QImageIOHandler::ScaledSize)) {
|
||||||
fillMode == "PreserveAspectFit") {
|
const QSize full = reader.size();
|
||||||
QImage canvas(size, QImage::Format_ARGB32);
|
if (full.isValid() && !full.isEmpty()) {
|
||||||
canvas.fill(Qt::transparent);
|
const QSize hint = size * 2;
|
||||||
|
QSize scaled = full;
|
||||||
|
scaled.scale(hint, Qt::KeepAspectRatioByExpanding);
|
||||||
|
scaled = QSize(
|
||||||
|
std::min(scaled.width(), full.width()),
|
||||||
|
std::min(scaled.height(), full.height()));
|
||||||
|
reader.setScaledSize(scaled);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
QPainter painter(&canvas);
|
QImage image = reader.read();
|
||||||
painter.drawImage(
|
|
||||||
(size.width() - image.width()) / 2,
|
|
||||||
(size.height() - image.height()) / 2,
|
|
||||||
image);
|
|
||||||
painter.end();
|
|
||||||
|
|
||||||
image = canvas;
|
if (image.isNull()) {
|
||||||
}
|
qWarning()
|
||||||
|
<< "CachingImageManager::createCache: failed to read"
|
||||||
|
<< path << reader.errorString();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
const QString parent = QFileInfo(cache).absolutePath();
|
image.convertTo(QImage::Format_ARGB32);
|
||||||
if (!QDir().mkpath(parent) || !image.save(cache)) {
|
|
||||||
qWarning() << "CachingImageManager::createCache: failed to save to"
|
if (fillMode == "PreserveAspectCrop") {
|
||||||
<< cache;
|
image = image.scaled(
|
||||||
}
|
size,
|
||||||
});
|
Qt::KeepAspectRatioByExpanding,
|
||||||
|
Qt::SmoothTransformation);
|
||||||
|
} else if (fillMode == "PreserveAspectFit") {
|
||||||
|
image = image.scaled(
|
||||||
|
size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
|
||||||
|
} else {
|
||||||
|
image = image.scaled(
|
||||||
|
size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fillMode == "PreserveAspectCrop" ||
|
||||||
|
fillMode == "PreserveAspectFit") {
|
||||||
|
QImage canvas(size, QImage::Format_ARGB32);
|
||||||
|
canvas.fill(Qt::transparent);
|
||||||
|
|
||||||
|
QPainter painter(&canvas);
|
||||||
|
painter.drawImage(
|
||||||
|
(size.width() - image.width()) / 2,
|
||||||
|
(size.height() - image.height()) / 2,
|
||||||
|
image);
|
||||||
|
painter.end();
|
||||||
|
|
||||||
|
image = canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
const QString parent = QFileInfo(cache).absolutePath();
|
||||||
|
if (!QDir().mkpath(parent) || !image.save(cache)) {
|
||||||
|
qWarning()
|
||||||
|
<< "CachingImageManager::createCache: failed to save to"
|
||||||
|
<< cache;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
watcher->setFuture(future);
|
||||||
}
|
}
|
||||||
|
|
||||||
QString CachingImageManager::sha256sum(const QString& path) {
|
QString CachingImageManager::sha256sum(const QString& path) {
|
||||||
QFile file(path);
|
const QFileInfo info(path);
|
||||||
if (!file.open(QIODevice::ReadOnly)) {
|
|
||||||
qWarning() << "CachingImageManager::sha256sum: failed to open" << path;
|
if (!info.exists() || !info.isFile()) {
|
||||||
return "";
|
qWarning() << "CachingImageManager::sha256sum: failed to stat" << path;
|
||||||
|
return QString();
|
||||||
}
|
}
|
||||||
|
|
||||||
QCryptographicHash hash(QCryptographicHash::Sha256);
|
QCryptographicHash hash(QCryptographicHash::Sha256);
|
||||||
hash.addData(&file);
|
hash.addData(path.toUtf8());
|
||||||
file.close();
|
hash.addData(QByteArray::number(info.size()));
|
||||||
|
hash.addData(QByteArray::number(info.lastModified().toMSecsSinceEpoch()));
|
||||||
|
|
||||||
return hash.result().toHex();
|
return hash.result().toHex();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,14 +4,31 @@
|
|||||||
#include <QCryptographicHash>
|
#include <QCryptographicHash>
|
||||||
#include <QDir>
|
#include <QDir>
|
||||||
#include <QFileInfo>
|
#include <QFileInfo>
|
||||||
|
#include <QImageReader>
|
||||||
#include <QtConcurrent>
|
#include <QtConcurrent>
|
||||||
#include <QSGImageNode>
|
|
||||||
#include <QQuickWindow>
|
#include <QQuickWindow>
|
||||||
|
|
||||||
namespace ZShell::internal {
|
namespace ZShell::internal {
|
||||||
|
|
||||||
|
QThreadPool* WallpaperImage::loadPool() {
|
||||||
|
static QThreadPool* pool = [] {
|
||||||
|
auto* p = new QThreadPool();
|
||||||
|
p->setMaxThreadCount(4);
|
||||||
|
return p;
|
||||||
|
}();
|
||||||
|
return pool;
|
||||||
|
}
|
||||||
|
|
||||||
WallpaperImage::WallpaperImage(QQuickItem* parent) : QQuickItem(parent) {
|
WallpaperImage::WallpaperImage(QQuickItem* parent) : QQuickItem(parent) {
|
||||||
setFlag(ItemHasContents, true);
|
setFlag(ItemHasContents, true);
|
||||||
|
|
||||||
|
m_loadDebounceTimer.setSingleShot(true);
|
||||||
|
connect(
|
||||||
|
&m_loadDebounceTimer,
|
||||||
|
&QTimer::timeout,
|
||||||
|
this,
|
||||||
|
&WallpaperImage::beginLoad);
|
||||||
|
|
||||||
connect(
|
connect(
|
||||||
&m_imageWatcher,
|
&m_imageWatcher,
|
||||||
&QFutureWatcher<QImage>::finished,
|
&QFutureWatcher<QImage>::finished,
|
||||||
@@ -20,12 +37,15 @@ WallpaperImage::WallpaperImage(QQuickItem* parent) : QQuickItem(parent) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
WallpaperImage::~WallpaperImage() {
|
WallpaperImage::~WallpaperImage() {
|
||||||
|
m_requestGeneration->fetch_add(1, std::memory_order_relaxed);
|
||||||
|
m_imageWatcher.disconnect();
|
||||||
|
|
||||||
if (m_texture) delete m_texture;
|
if (m_texture) delete m_texture;
|
||||||
|
if (m_previousTexture) delete m_previousTexture;
|
||||||
}
|
}
|
||||||
|
|
||||||
void WallpaperImage::setStatus(const Status s) {
|
void WallpaperImage::setStatus(const Status s) {
|
||||||
if (m_status == s) return;
|
if (m_status == s) return;
|
||||||
|
|
||||||
m_status = s;
|
m_status = s;
|
||||||
emit statusChanged();
|
emit statusChanged();
|
||||||
}
|
}
|
||||||
@@ -36,14 +56,14 @@ void WallpaperImage::setSource(const QUrl& source) {
|
|||||||
emit sourceChanged();
|
emit sourceChanged();
|
||||||
|
|
||||||
setStatus(Loading);
|
setStatus(Loading);
|
||||||
loadImage();
|
m_loadDebounceTimer.start(80);
|
||||||
}
|
}
|
||||||
|
|
||||||
void WallpaperImage::setScreenResolution(const QSize& screenResolution) {
|
void WallpaperImage::setScreenResolution(const QSize& screenResolution) {
|
||||||
if (m_screenResolution == screenResolution) return;
|
if (m_screenResolution == screenResolution) return;
|
||||||
m_screenResolution = screenResolution;
|
m_screenResolution = screenResolution;
|
||||||
emit screenResolutionChanged();
|
emit screenResolutionChanged();
|
||||||
loadImage();
|
beginLoad();
|
||||||
}
|
}
|
||||||
|
|
||||||
void WallpaperImage::setZoom(qreal zoom) {
|
void WallpaperImage::setZoom(qreal zoom) {
|
||||||
@@ -53,6 +73,13 @@ void WallpaperImage::setZoom(qreal zoom) {
|
|||||||
update();
|
update();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void WallpaperImage::setFadeDuration(int ms) {
|
||||||
|
if (ms < 0) ms = 0;
|
||||||
|
if (m_fadeDuration == ms) return;
|
||||||
|
m_fadeDuration = ms;
|
||||||
|
emit fadeDurationChanged();
|
||||||
|
}
|
||||||
|
|
||||||
void WallpaperImage::setCropX(qreal x) {
|
void WallpaperImage::setCropX(qreal x) {
|
||||||
if (qFuzzyCompare(m_cropX, x)) return;
|
if (qFuzzyCompare(m_cropX, x)) return;
|
||||||
m_cropX = x;
|
m_cropX = x;
|
||||||
@@ -100,143 +127,227 @@ QString WallpaperImage::getCacheFilePath() const {
|
|||||||
return cachePath + "/" + hash + ".png";
|
return cachePath + "/" + hash + ".png";
|
||||||
}
|
}
|
||||||
|
|
||||||
void WallpaperImage::loadImage() {
|
void WallpaperImage::beginLoad() {
|
||||||
if (m_source.isEmpty()) {
|
if (m_source.isEmpty()) {
|
||||||
setStatus(Null);
|
setStatus(Null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const quint64 requestId =
|
||||||
|
m_requestGeneration->fetch_add(1, std::memory_order_relaxed) + 1;
|
||||||
|
|
||||||
QString cacheFile = getCacheFilePath();
|
QString cacheFile = getCacheFilePath();
|
||||||
QString sourceFile = m_source.isLocalFile() ? m_source.toLocalFile()
|
QString sourceFile = m_source.isLocalFile() ? m_source.toLocalFile()
|
||||||
: m_source.toString();
|
: m_source.toString();
|
||||||
|
if (sourceFile.startsWith("qrc:/")) sourceFile = sourceFile.mid(3);
|
||||||
if (sourceFile.startsWith("qrc:/")) {
|
|
||||||
sourceFile = sourceFile.mid(3);
|
|
||||||
}
|
|
||||||
|
|
||||||
QSize targetRes = m_screenResolution;
|
QSize targetRes = m_screenResolution;
|
||||||
|
auto generation = m_requestGeneration;
|
||||||
|
|
||||||
|
QFuture<QImage> future = QtConcurrent::run(
|
||||||
|
loadPool(),
|
||||||
|
[sourceFile, cacheFile, targetRes, requestId, generation]() -> QImage {
|
||||||
|
auto stale = [&] {
|
||||||
|
return generation->load(std::memory_order_relaxed) != requestId;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (stale()) return QImage();
|
||||||
|
|
||||||
QFuture<QImage> future =
|
|
||||||
QtConcurrent::run([sourceFile, cacheFile, targetRes]() -> QImage {
|
|
||||||
if (!targetRes.isEmpty() && !cacheFile.isEmpty() &&
|
if (!targetRes.isEmpty() && !cacheFile.isEmpty() &&
|
||||||
QFileInfo::exists(cacheFile)) {
|
QFileInfo::exists(cacheFile)) {
|
||||||
QImage cached(cacheFile);
|
QImage cached(cacheFile);
|
||||||
if (!cached.isNull()) return cached;
|
if (!cached.isNull()) return cached;
|
||||||
}
|
}
|
||||||
|
|
||||||
QImage original(sourceFile);
|
if (stale()) return QImage();
|
||||||
|
|
||||||
|
QImage original;
|
||||||
|
QImageReader reader(sourceFile);
|
||||||
|
if (!targetRes.isEmpty() &&
|
||||||
|
reader.supportsOption(QImageIOHandler::Size)) {
|
||||||
|
QSize actual = reader.size();
|
||||||
|
if (actual.isValid() &&
|
||||||
|
(actual.width() > targetRes.width() ||
|
||||||
|
actual.height() > targetRes.height())) {
|
||||||
|
QSize scaledSize =
|
||||||
|
actual.scaled(targetRes, Qt::KeepAspectRatioByExpanding);
|
||||||
|
reader.setScaledSize(scaledSize);
|
||||||
|
}
|
||||||
|
original = reader.read();
|
||||||
|
} else {
|
||||||
|
original = QImage(sourceFile);
|
||||||
|
}
|
||||||
if (original.isNull()) return QImage();
|
if (original.isNull()) return QImage();
|
||||||
|
|
||||||
if (targetRes.isEmpty()) {
|
if (stale()) return QImage();
|
||||||
return original;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (original.width() > targetRes.width() ||
|
if (targetRes.isEmpty()) return original;
|
||||||
original.height() > targetRes.height()) {
|
|
||||||
QImage scaled = original.scaled(
|
|
||||||
targetRes,
|
|
||||||
Qt::KeepAspectRatioByExpanding,
|
|
||||||
Qt::SmoothTransformation);
|
|
||||||
if (!cacheFile.isEmpty()) scaled.save(cacheFile, "PNG");
|
|
||||||
return scaled;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cacheFile.isEmpty()) original.save(cacheFile, "PNG");
|
QImage scaled = (original.width() > targetRes.width() ||
|
||||||
return original;
|
original.height() > targetRes.height())
|
||||||
|
? original.scaled(
|
||||||
|
targetRes,
|
||||||
|
Qt::KeepAspectRatioByExpanding,
|
||||||
|
Qt::SmoothTransformation)
|
||||||
|
: original;
|
||||||
|
|
||||||
|
if (stale()) return scaled;
|
||||||
|
|
||||||
|
if (!cacheFile.isEmpty()) scaled.save(cacheFile, "PNG");
|
||||||
|
return scaled;
|
||||||
});
|
});
|
||||||
|
|
||||||
m_imageWatcher.setFuture(future);
|
m_imageWatcher.setFuture(future);
|
||||||
}
|
}
|
||||||
|
|
||||||
void WallpaperImage::handleImageLoaded() {
|
void WallpaperImage::handleImageLoaded() {
|
||||||
m_image = m_imageWatcher.result();
|
QImage result = m_imageWatcher.result();
|
||||||
|
if (result.isNull()) {
|
||||||
|
setStatus(Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setStatus(m_image.isNull() ? Error : Ready);
|
m_pendingImage = result;
|
||||||
|
m_hasPending = true;
|
||||||
m_textureDirty = true;
|
setStatus(Ready);
|
||||||
update();
|
update();
|
||||||
}
|
}
|
||||||
|
|
||||||
QSGNode* WallpaperImage::updatePaintNode(
|
QRectF WallpaperImage::computeSourceRect(QSGTexture* texture) const {
|
||||||
QSGNode* oldNode, UpdatePaintNodeData*) {
|
QSize texSize = texture->textureSize();
|
||||||
auto* node = static_cast<QSGImageNode*>(oldNode);
|
|
||||||
|
|
||||||
if (m_image.isNull()) {
|
qreal cW = m_cropWidth / m_zoom;
|
||||||
delete node;
|
qreal cH = m_cropHeight / m_zoom;
|
||||||
return nullptr;
|
|
||||||
|
QRectF reqRect(
|
||||||
|
m_cropX * texSize.width(),
|
||||||
|
m_cropY * texSize.height(),
|
||||||
|
cW * texSize.width(),
|
||||||
|
cH * texSize.height());
|
||||||
|
|
||||||
|
QRectF bounds = boundingRect();
|
||||||
|
if (bounds.isEmpty() || reqRect.isEmpty()) return reqRect;
|
||||||
|
|
||||||
|
qreal targetRatio = bounds.width() / bounds.height();
|
||||||
|
qreal reqRatio = reqRect.width() / reqRect.height();
|
||||||
|
|
||||||
|
QRectF sourceRect = reqRect;
|
||||||
|
|
||||||
|
if (reqRatio > targetRatio) {
|
||||||
|
qreal newWidth = reqRect.height() * targetRatio;
|
||||||
|
qreal xOffset = (reqRect.width() - newWidth) / 2.0;
|
||||||
|
sourceRect.setX(reqRect.x() + xOffset);
|
||||||
|
sourceRect.setWidth(newWidth);
|
||||||
|
} else if (reqRatio < targetRatio) {
|
||||||
|
qreal newHeight = reqRect.width() / targetRatio;
|
||||||
|
qreal yOffset = (reqRect.height() - newHeight) / 2.0;
|
||||||
|
sourceRect.setY(reqRect.y() + yOffset);
|
||||||
|
sourceRect.setHeight(newHeight);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!node) {
|
return sourceRect;
|
||||||
node = window()->createImageNode();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (m_textureDirty) {
|
void WallpaperImage::configureImageNode(
|
||||||
if (m_texture) delete m_texture;
|
QSGImageNode* node, QSGTexture* texture) {
|
||||||
m_texture = window()->createTextureFromImage(
|
node->setTexture(texture);
|
||||||
m_image, QQuickWindow::TextureHasAlphaChannel);
|
node->setRect(boundingRect());
|
||||||
m_textureDirty = false;
|
node->setFiltering(QSGTexture::Linear);
|
||||||
}
|
|
||||||
|
|
||||||
if (m_texture) {
|
QRectF sourceRect = computeSourceRect(texture);
|
||||||
node->setTexture(m_texture);
|
node->setSourceRect(sourceRect);
|
||||||
node->setRect(boundingRect());
|
|
||||||
node->setFiltering(QSGTexture::Linear);
|
|
||||||
|
|
||||||
qreal cW = m_cropWidth / m_zoom;
|
|
||||||
qreal cH = m_cropHeight / m_zoom;
|
|
||||||
|
|
||||||
QRectF reqRect(
|
|
||||||
m_cropX * m_texture->textureSize().width(),
|
|
||||||
m_cropY * m_texture->textureSize().height(),
|
|
||||||
cW * m_texture->textureSize().width(),
|
|
||||||
cH * m_texture->textureSize().height());
|
|
||||||
|
|
||||||
QRectF bounds = boundingRect();
|
|
||||||
if (bounds.isEmpty() || reqRect.isEmpty()) return node;
|
|
||||||
|
|
||||||
qreal targetRatio = bounds.width() / bounds.height();
|
|
||||||
qreal reqRatio = reqRect.width() / reqRect.height();
|
|
||||||
|
|
||||||
QRectF sourceRect = reqRect;
|
|
||||||
|
|
||||||
if (reqRatio > targetRatio) {
|
|
||||||
qreal newWidth = reqRect.height() * targetRatio;
|
|
||||||
qreal xOffset = (reqRect.width() - newWidth) / 2.0;
|
|
||||||
sourceRect.setX(reqRect.x() + xOffset);
|
|
||||||
sourceRect.setWidth(newWidth);
|
|
||||||
} else if (reqRatio < targetRatio) {
|
|
||||||
qreal newHeight = reqRect.width() / targetRatio;
|
|
||||||
qreal yOffset = (reqRect.height() - newHeight) / 2.0;
|
|
||||||
sourceRect.setY(reqRect.y() + yOffset);
|
|
||||||
sourceRect.setHeight(newHeight);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if (texture == m_texture) {
|
||||||
|
QSize texSize = texture->textureSize();
|
||||||
QRectF normalizedActual(
|
QRectF normalizedActual(
|
||||||
sourceRect.x() / m_texture->textureSize().width(),
|
sourceRect.x() / texSize.width(),
|
||||||
sourceRect.y() / m_texture->textureSize().height(),
|
sourceRect.y() / texSize.height(),
|
||||||
sourceRect.width() / m_texture->textureSize().width(),
|
sourceRect.width() / texSize.width(),
|
||||||
sourceRect.height() / m_texture->textureSize().height());
|
sourceRect.height() / texSize.height());
|
||||||
|
|
||||||
bool changed = false;
|
bool changed = false;
|
||||||
|
|
||||||
auto updateIfChanged = [&](qreal& dst, qreal value) {
|
auto updateIfChanged = [&](qreal& dst, qreal value) {
|
||||||
if (!qFuzzyCompare(dst, value)) {
|
if (!qFuzzyCompare(dst, value)) {
|
||||||
dst = value;
|
dst = value;
|
||||||
changed = true;
|
changed = true;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
updateIfChanged(m_actualCropX, normalizedActual.x());
|
updateIfChanged(m_actualCropX, normalizedActual.x());
|
||||||
updateIfChanged(m_actualCropY, normalizedActual.y());
|
updateIfChanged(m_actualCropY, normalizedActual.y());
|
||||||
updateIfChanged(m_actualCropWidth, normalizedActual.width());
|
updateIfChanged(m_actualCropWidth, normalizedActual.width());
|
||||||
updateIfChanged(m_actualCropHeight, normalizedActual.height());
|
updateIfChanged(m_actualCropHeight, normalizedActual.height());
|
||||||
|
|
||||||
if (changed) emit actualCropChanged();
|
if (changed) emit actualCropChanged();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
node->setSourceRect(sourceRect);
|
QSGNode* WallpaperImage::updatePaintNode(
|
||||||
|
QSGNode* oldNode, UpdatePaintNodeData*) {
|
||||||
|
Q_UNUSED(oldNode);
|
||||||
|
|
||||||
|
if (m_hasPending) {
|
||||||
|
if (m_previousTexture) {
|
||||||
|
delete m_previousTexture;
|
||||||
|
m_previousTexture = nullptr;
|
||||||
|
}
|
||||||
|
m_previousTexture = m_texture;
|
||||||
|
m_texture = window()->createTextureFromImage(
|
||||||
|
m_pendingImage, QQuickWindow::TextureHasAlphaChannel);
|
||||||
|
m_pendingImage = QImage();
|
||||||
|
m_hasPending = false;
|
||||||
|
|
||||||
|
if (m_previousTexture && m_fadeDuration > 0) {
|
||||||
|
m_fading = true;
|
||||||
|
m_fadeTimer.restart();
|
||||||
|
} else {
|
||||||
|
if (m_previousTexture) {
|
||||||
|
delete m_previousTexture;
|
||||||
|
m_previousTexture = nullptr;
|
||||||
|
}
|
||||||
|
m_fading = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return node;
|
if (!m_texture) {
|
||||||
|
return m_rootNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!m_rootNode) {
|
||||||
|
m_rootNode = new QSGNode();
|
||||||
|
|
||||||
|
m_newOpacityNode = new QSGOpacityNode();
|
||||||
|
m_newImageNode = window()->createImageNode();
|
||||||
|
m_newOpacityNode->appendChildNode(m_newImageNode);
|
||||||
|
m_rootNode->appendChildNode(m_newOpacityNode);
|
||||||
|
|
||||||
|
m_oldOpacityNode = new QSGOpacityNode();
|
||||||
|
m_oldImageNode = window()->createImageNode();
|
||||||
|
m_oldOpacityNode->appendChildNode(m_oldImageNode);
|
||||||
|
m_rootNode->appendChildNode(m_oldOpacityNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
configureImageNode(m_newImageNode, m_texture);
|
||||||
|
m_newOpacityNode->setOpacity(1.0);
|
||||||
|
|
||||||
|
if (m_fading && m_previousTexture) {
|
||||||
|
qreal progress =
|
||||||
|
qBound(0.0, qreal(m_fadeTimer.elapsed()) / m_fadeDuration, 1.0);
|
||||||
|
|
||||||
|
configureImageNode(m_oldImageNode, m_previousTexture);
|
||||||
|
m_oldOpacityNode->setOpacity(1.0 - progress);
|
||||||
|
|
||||||
|
if (progress >= 1.0) {
|
||||||
|
m_fading = false;
|
||||||
|
delete m_previousTexture;
|
||||||
|
m_previousTexture = nullptr;
|
||||||
|
m_oldOpacityNode->setOpacity(0.0);
|
||||||
|
} else {
|
||||||
|
update();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
m_oldOpacityNode->setOpacity(0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return m_rootNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace ZShell::internal
|
} // namespace ZShell::internal
|
||||||
|
|||||||
@@ -4,9 +4,15 @@
|
|||||||
#include <QImage>
|
#include <QImage>
|
||||||
#include <QUrl>
|
#include <QUrl>
|
||||||
#include <QSGTexture>
|
#include <QSGTexture>
|
||||||
|
#include <QSGOpacityNode>
|
||||||
|
#include <QSGImageNode>
|
||||||
#include <QFutureWatcher>
|
#include <QFutureWatcher>
|
||||||
|
#include <QElapsedTimer>
|
||||||
|
#include <QThreadPool>
|
||||||
|
#include <QTimer>
|
||||||
#include <QtQml/qqml.h>
|
#include <QtQml/qqml.h>
|
||||||
#include <qtmetamacros.h>
|
#include <qtmetamacros.h>
|
||||||
|
#include <atomic>
|
||||||
|
|
||||||
namespace ZShell::internal {
|
namespace ZShell::internal {
|
||||||
|
|
||||||
@@ -19,6 +25,9 @@ class WallpaperImage : public QQuickItem {
|
|||||||
NOTIFY screenResolutionChanged)
|
NOTIFY screenResolutionChanged)
|
||||||
Q_PROPERTY(qreal zoom READ zoom WRITE setZoom NOTIFY zoomChanged)
|
Q_PROPERTY(qreal zoom READ zoom WRITE setZoom NOTIFY zoomChanged)
|
||||||
Q_PROPERTY(Status status READ status NOTIFY statusChanged)
|
Q_PROPERTY(Status status READ status NOTIFY statusChanged)
|
||||||
|
Q_PROPERTY(
|
||||||
|
int fadeDuration READ fadeDuration WRITE setFadeDuration NOTIFY
|
||||||
|
fadeDurationChanged)
|
||||||
|
|
||||||
Q_PROPERTY(qreal actualCropX READ actualCropX NOTIFY actualCropChanged)
|
Q_PROPERTY(qreal actualCropX READ actualCropX NOTIFY actualCropChanged)
|
||||||
Q_PROPERTY(qreal actualCropY READ actualCropY NOTIFY actualCropChanged)
|
Q_PROPERTY(qreal actualCropY READ actualCropY NOTIFY actualCropChanged)
|
||||||
@@ -54,12 +63,12 @@ class WallpaperImage : public QQuickItem {
|
|||||||
qreal zoom() const { return m_zoom; }
|
qreal zoom() const { return m_zoom; }
|
||||||
void setZoom(qreal zoom);
|
void setZoom(qreal zoom);
|
||||||
|
|
||||||
|
int fadeDuration() const { return m_fadeDuration; }
|
||||||
|
void setFadeDuration(int ms);
|
||||||
|
|
||||||
qreal actualCropX() const { return m_actualCropX; }
|
qreal actualCropX() const { return m_actualCropX; }
|
||||||
|
|
||||||
qreal actualCropY() const { return m_actualCropY; }
|
qreal actualCropY() const { return m_actualCropY; }
|
||||||
|
|
||||||
qreal actualCropWidth() const { return m_actualCropWidth; }
|
qreal actualCropWidth() const { return m_actualCropWidth; }
|
||||||
|
|
||||||
qreal actualCropHeight() const { return m_actualCropHeight; }
|
qreal actualCropHeight() const { return m_actualCropHeight; }
|
||||||
|
|
||||||
qreal cropX() const { return m_cropX; }
|
qreal cropX() const { return m_cropX; }
|
||||||
@@ -82,6 +91,7 @@ class WallpaperImage : public QQuickItem {
|
|||||||
void sourceChanged();
|
void sourceChanged();
|
||||||
void screenResolutionChanged();
|
void screenResolutionChanged();
|
||||||
void zoomChanged();
|
void zoomChanged();
|
||||||
|
void fadeDurationChanged();
|
||||||
void actualCropChanged();
|
void actualCropChanged();
|
||||||
void cropXChanged();
|
void cropXChanged();
|
||||||
void cropYChanged();
|
void cropYChanged();
|
||||||
@@ -90,15 +100,18 @@ class WallpaperImage : public QQuickItem {
|
|||||||
void statusChanged();
|
void statusChanged();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void loadImage();
|
void beginLoad();
|
||||||
void handleImageLoaded();
|
void handleImageLoaded();
|
||||||
QString getCacheFilePath() const;
|
QString getCacheFilePath() const;
|
||||||
void setStatus(const Status s);
|
void setStatus(const Status s);
|
||||||
|
QRectF computeSourceRect(QSGTexture* texture) const;
|
||||||
|
void configureImageNode(QSGImageNode* node, QSGTexture* texture);
|
||||||
|
|
||||||
Status m_status = Null;
|
Status m_status = Null;
|
||||||
QUrl m_source;
|
QUrl m_source;
|
||||||
QSize m_screenResolution;
|
QSize m_screenResolution;
|
||||||
qreal m_zoom = 1.0;
|
qreal m_zoom = 1.0;
|
||||||
|
int m_fadeDuration = 400;
|
||||||
|
|
||||||
qreal m_actualCropX = 0.0;
|
qreal m_actualCropX = 0.0;
|
||||||
qreal m_actualCropY = 0.0;
|
qreal m_actualCropY = 0.0;
|
||||||
@@ -110,10 +123,25 @@ class WallpaperImage : public QQuickItem {
|
|||||||
qreal m_cropWidth = 1.0;
|
qreal m_cropWidth = 1.0;
|
||||||
qreal m_cropHeight = 1.0;
|
qreal m_cropHeight = 1.0;
|
||||||
|
|
||||||
QImage m_image;
|
QTimer m_loadDebounceTimer;
|
||||||
QSGTexture* m_texture = nullptr;
|
|
||||||
bool m_textureDirty = false;
|
|
||||||
QFutureWatcher<QImage> m_imageWatcher;
|
QFutureWatcher<QImage> m_imageWatcher;
|
||||||
|
std::shared_ptr<std::atomic<quint64>> m_requestGeneration =
|
||||||
|
std::make_shared<std::atomic<quint64>>(0);
|
||||||
|
static QThreadPool* loadPool();
|
||||||
|
QImage m_pendingImage;
|
||||||
|
bool m_hasPending = false;
|
||||||
|
|
||||||
|
QSGTexture* m_texture = nullptr;
|
||||||
|
QSGTexture* m_previousTexture = nullptr;
|
||||||
|
|
||||||
|
bool m_fading = false;
|
||||||
|
QElapsedTimer m_fadeTimer;
|
||||||
|
|
||||||
|
QSGNode* m_rootNode = nullptr;
|
||||||
|
QSGOpacityNode* m_newOpacityNode = nullptr;
|
||||||
|
QSGOpacityNode* m_oldOpacityNode = nullptr;
|
||||||
|
QSGImageNode* m_newImageNode = nullptr;
|
||||||
|
QSGImageNode* m_oldImageNode = nullptr;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace ZShell::internal
|
} // namespace ZShell::internal
|
||||||
|
|||||||
@@ -8,7 +8,14 @@ import typer
|
|||||||
from typer._completion_classes import completion_init
|
from typer._completion_classes import completion_init
|
||||||
from typer._completion_shared import _get_shell_name, install
|
from typer._completion_shared import _get_shell_name, install
|
||||||
|
|
||||||
from zshell.subcommands import record, scheme, screenshot, shell, wallpaper
|
from zshell.subcommands import (
|
||||||
|
battery,
|
||||||
|
record,
|
||||||
|
scheme,
|
||||||
|
screenshot,
|
||||||
|
shell,
|
||||||
|
wallpaper,
|
||||||
|
)
|
||||||
|
|
||||||
app = typer.Typer(name="zshell-cli", add_completion=False)
|
app = typer.Typer(name="zshell-cli", add_completion=False)
|
||||||
|
|
||||||
@@ -17,6 +24,7 @@ app.add_typer(scheme.app, name="scheme")
|
|||||||
app.add_typer(screenshot.app, name="screenshot")
|
app.add_typer(screenshot.app, name="screenshot")
|
||||||
app.add_typer(wallpaper.app, name="wallpaper")
|
app.add_typer(wallpaper.app, name="wallpaper")
|
||||||
app.add_typer(record.app, name="record")
|
app.add_typer(record.app, name="record")
|
||||||
|
app.add_typer(battery.app, name="battery")
|
||||||
|
|
||||||
|
|
||||||
def _completion_installed() -> bool:
|
def _completion_installed() -> bool:
|
||||||
|
|||||||
@@ -0,0 +1,819 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import fcntl
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import struct
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from collections.abc import Callable
|
||||||
|
from dataclasses import asdict, dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import typer
|
||||||
|
from logitech_receiver import hidpp10, hidpp20
|
||||||
|
from logitech_receiver.common import Battery, BatteryStatus, Notification
|
||||||
|
from logitech_receiver.hidpp10_constants import Registers
|
||||||
|
from logitech_receiver.hidpp20_constants import SupportedFeature
|
||||||
|
|
||||||
|
app = typer.Typer(
|
||||||
|
help="Read live battery status from Logitech HID++ peripherals."
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("zshell.battery")
|
||||||
|
|
||||||
|
DEFAULT_OUTPUT = Path.home() / ".cache" / "zshell" / "battery.json"
|
||||||
|
|
||||||
|
_RUNTIME_DIR = Path(
|
||||||
|
os.environ.get("XDG_RUNTIME_DIR") or (Path.home() / ".cache" / "zshell")
|
||||||
|
)
|
||||||
|
DEFAULT_LOCK = _RUNTIME_DIR / "zshell-battery-daemon.lock"
|
||||||
|
|
||||||
|
|
||||||
|
def _acquire_singleton_lock(path: Path) -> int | None:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd = os.open(path, os.O_CREAT | os.O_RDWR, 0o644)
|
||||||
|
try:
|
||||||
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
except BlockingIOError:
|
||||||
|
os.close(fd)
|
||||||
|
return None
|
||||||
|
os.ftruncate(fd, 0)
|
||||||
|
os.write(fd, str(os.getpid()).encode())
|
||||||
|
return fd
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DeviceBattery:
|
||||||
|
model: str
|
||||||
|
nativePath: str | None
|
||||||
|
serial: str | None
|
||||||
|
type: str | None
|
||||||
|
wired: bool
|
||||||
|
percentage: float | None
|
||||||
|
state: str | None
|
||||||
|
charging: bool
|
||||||
|
isPresent: bool
|
||||||
|
|
||||||
|
|
||||||
|
_SYSFS_POWER_SUPPLY = Path("/sys/class/power_supply")
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_serial(s: str) -> str:
|
||||||
|
return re.sub(r"[^0-9A-Za-z]", "", s).upper()
|
||||||
|
|
||||||
|
|
||||||
|
def _find_upower_native_path(serial: str | None) -> str | None:
|
||||||
|
if not serial or not _SYSFS_POWER_SUPPLY.is_dir():
|
||||||
|
return None
|
||||||
|
target = _normalize_serial(serial)
|
||||||
|
for entry in _SYSFS_POWER_SUPPLY.glob("hidpp_battery_*"):
|
||||||
|
try:
|
||||||
|
raw = (entry / "serial_number").read_text().strip()
|
||||||
|
except OSError:
|
||||||
|
logger.debug(
|
||||||
|
"couldn't read serial_number under %s", entry, exc_info=True
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
if _normalize_serial(raw) == target:
|
||||||
|
return entry.name
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _process_battery_notification(dev, n) -> bool:
|
||||||
|
|
||||||
|
if not getattr(dev, "isDevice", False):
|
||||||
|
return False
|
||||||
|
|
||||||
|
if int(n.sub_id) & 0x80:
|
||||||
|
return False
|
||||||
|
if n.sub_id == Notification.NO_OPERATION:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if getattr(dev, "protocol", None) is not None and dev.protocol < 2.0:
|
||||||
|
if n.sub_id in (Registers.BATTERY_STATUS, Registers.BATTERY_CHARGE):
|
||||||
|
if n.data[-1:] != b"\x00":
|
||||||
|
return False
|
||||||
|
data = bytes([n.address]) + n.data
|
||||||
|
dev.set_battery_info(hidpp10.parse_battery_status(n.sub_id, data))
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
features = getattr(dev, "features", None)
|
||||||
|
if not features:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
feature = features.get_feature(n.sub_id)
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if feature == SupportedFeature.BATTERY_STATUS:
|
||||||
|
if n.address == 0x00:
|
||||||
|
dev.set_battery_info(hidpp20.decipher_battery_status(n.data)[1])
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
if feature == SupportedFeature.BATTERY_VOLTAGE:
|
||||||
|
if n.address == 0x00:
|
||||||
|
dev.set_battery_info(hidpp20.decipher_battery_voltage(n.data)[1])
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
if feature == SupportedFeature.UNIFIED_BATTERY:
|
||||||
|
if n.address == 0x00:
|
||||||
|
dev.set_battery_info(hidpp20.decipher_battery_unified(n.data)[1])
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
if feature == SupportedFeature.ADC_MEASUREMENT:
|
||||||
|
if n.address == 0x00:
|
||||||
|
result = hidpp20.decipher_adc_measurement(n.data)
|
||||||
|
if result:
|
||||||
|
dev.set_battery_info(result[1])
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
if feature == SupportedFeature.CENTURION_BATTERY_SOC:
|
||||||
|
dev.set_battery_info(hidpp20.decipher_battery_centurion(n.data)[1])
|
||||||
|
return True
|
||||||
|
|
||||||
|
if feature == SupportedFeature.SOLAR_DASHBOARD:
|
||||||
|
if n.data[5:9] == b"GOOD":
|
||||||
|
charge, lux, _ = struct.unpack("!BHH", n.data[:5])
|
||||||
|
status = BatteryStatus.DISCHARGING
|
||||||
|
if n.address == 0x10 and lux > 200:
|
||||||
|
status = BatteryStatus.RECHARGING
|
||||||
|
dev.set_battery_info(Battery(charge, None, status, None, lux))
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _import_listener_deps():
|
||||||
|
try:
|
||||||
|
from logitech_receiver import base, device, receiver
|
||||||
|
from logitech_receiver.listener import EventsListener
|
||||||
|
except ImportError as e:
|
||||||
|
raise RuntimeError(
|
||||||
|
"logitech_receiver isn't importable -- install it with `pip install solaar`."
|
||||||
|
) from e
|
||||||
|
except ValueError as e:
|
||||||
|
raise RuntimeError(
|
||||||
|
"logitech_receiver failed to import because a GTK3 typelib is missing "
|
||||||
|
f"({e}). Install the same GTK3 + PyGObject packages Solaar's GUI needs "
|
||||||
|
"(e.g. python3-gi + gir1.2-gtk-3.0 on Debian/Ubuntu, or the gtk3/"
|
||||||
|
"python3-gobject equivalents on your distro)."
|
||||||
|
) from e
|
||||||
|
|
||||||
|
class _BatteryEventsListener(EventsListener):
|
||||||
|
def __init__(self, receiver_or_device, on_change):
|
||||||
|
super().__init__(receiver_or_device, self._handle_notification)
|
||||||
|
self._on_change = on_change
|
||||||
|
|
||||||
|
def has_started(self):
|
||||||
|
|
||||||
|
if not self.receiver.isDevice:
|
||||||
|
try:
|
||||||
|
self.receiver.notification_flags = (
|
||||||
|
self.receiver.enable_connection_notifications()
|
||||||
|
)
|
||||||
|
self.receiver.notify_devices()
|
||||||
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"failed enabling notifications for %s", self.receiver
|
||||||
|
)
|
||||||
|
|
||||||
|
def _handle_notification(self, n):
|
||||||
|
if self.receiver.isDevice:
|
||||||
|
try:
|
||||||
|
_process_battery_notification(self.receiver, n)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("processing %s for %s", n, self.receiver)
|
||||||
|
self._on_change(self.receiver)
|
||||||
|
return
|
||||||
|
|
||||||
|
if n.devnumber == 0xFF:
|
||||||
|
try:
|
||||||
|
_process_battery_notification(self.receiver, n)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("processing receiver notification %s", n)
|
||||||
|
self._on_change(self.receiver)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not (0 < n.devnumber <= 16):
|
||||||
|
logger.warning(
|
||||||
|
"unexpected device number %s in %s", n.devnumber, n
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
dev = self.receiver[n.devnumber]
|
||||||
|
except Exception:
|
||||||
|
logger.exception(
|
||||||
|
"resolving device number %s on %s",
|
||||||
|
n.devnumber,
|
||||||
|
self.receiver,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not dev:
|
||||||
|
logger.warning(
|
||||||
|
"%s: received %s for invalid device %d",
|
||||||
|
self.receiver,
|
||||||
|
n,
|
||||||
|
n.devnumber,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
_process_battery_notification(dev, n)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("processing %s for %s", n, dev)
|
||||||
|
|
||||||
|
self._on_change(dev)
|
||||||
|
|
||||||
|
return base, device, receiver, _BatteryEventsListener
|
||||||
|
|
||||||
|
|
||||||
|
def _start_hotplug_watcher(on_hotplug: Callable[[], None]):
|
||||||
|
try:
|
||||||
|
import pyudev
|
||||||
|
except ImportError:
|
||||||
|
logger.warning(
|
||||||
|
"pyudev isn't importable -- hotplugged devices will only be "
|
||||||
|
"noticed on the next --rescan-interval tick, not instantly. "
|
||||||
|
"Install it with `pip install pyudev` (it's a core Solaar "
|
||||||
|
"dependency, so it's normally already present)."
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
debounce_lock = threading.Lock()
|
||||||
|
debounce_state: dict[str, threading.Timer | None] = {"timer": None}
|
||||||
|
DEBOUNCE_SECONDS = 0.5
|
||||||
|
|
||||||
|
def _fire():
|
||||||
|
with debounce_lock:
|
||||||
|
debounce_state["timer"] = None
|
||||||
|
on_hotplug()
|
||||||
|
|
||||||
|
def _handle_event(_device):
|
||||||
|
if _device.action not in ("add", "remove"):
|
||||||
|
return
|
||||||
|
with debounce_lock:
|
||||||
|
existing = debounce_state["timer"]
|
||||||
|
if existing is not None:
|
||||||
|
existing.cancel()
|
||||||
|
timer = threading.Timer(DEBOUNCE_SECONDS, _fire)
|
||||||
|
timer.daemon = True
|
||||||
|
debounce_state["timer"] = timer
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
context = pyudev.Context()
|
||||||
|
monitor = pyudev.Monitor.from_netlink(context)
|
||||||
|
monitor.filter_by(subsystem="hidraw")
|
||||||
|
observer = pyudev.MonitorObserver(monitor, callback=_handle_event)
|
||||||
|
observer.start()
|
||||||
|
return observer
|
||||||
|
|
||||||
|
|
||||||
|
class _ListenerRegistry:
|
||||||
|
def __init__(self, on_change):
|
||||||
|
self._on_change = on_change
|
||||||
|
self._entries = {}
|
||||||
|
self._last_change: dict[int, float] = {}
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
self._rescan_lock = threading.Lock()
|
||||||
|
self._min_rescan_interval = 1.0
|
||||||
|
self._last_rescan_time = 0.0
|
||||||
|
|
||||||
|
self._hidpp_io_lock = threading.RLock()
|
||||||
|
|
||||||
|
def _touch_and_notify(self, dev_or_receiver, *args, **kwargs):
|
||||||
|
with self._lock:
|
||||||
|
self._last_change[id(dev_or_receiver)] = time.time()
|
||||||
|
self._on_change(dev_or_receiver, *args, **kwargs)
|
||||||
|
|
||||||
|
def last_change(self, dev) -> float:
|
||||||
|
with self._lock:
|
||||||
|
return self._last_change.get(id(dev), 0.0)
|
||||||
|
|
||||||
|
def rescan(self):
|
||||||
|
now = time.monotonic()
|
||||||
|
if now - self._last_rescan_time < self._min_rescan_interval:
|
||||||
|
return
|
||||||
|
if not self._rescan_lock.acquire(blocking=False):
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
self._last_rescan_time = now
|
||||||
|
with self._hidpp_io_lock:
|
||||||
|
base, device, receiver, ListenerClass = _import_listener_deps()
|
||||||
|
|
||||||
|
with self._lock:
|
||||||
|
dead = [
|
||||||
|
p
|
||||||
|
for p, (_obj, listener) in self._entries.items()
|
||||||
|
if not listener._active
|
||||||
|
]
|
||||||
|
for p in dead:
|
||||||
|
dying_obj, _dying_listener = self._entries[p]
|
||||||
|
|
||||||
|
if dying_obj.isDevice:
|
||||||
|
ident = getattr(
|
||||||
|
dying_obj, "unitId", None
|
||||||
|
) or getattr(dying_obj, "serial", None)
|
||||||
|
info = getattr(dying_obj, "battery_info", None)
|
||||||
|
if ident and info is not None:
|
||||||
|
for (
|
||||||
|
other_path,
|
||||||
|
(other_obj, _other_listener),
|
||||||
|
) in self._entries.items():
|
||||||
|
if other_path == p or other_obj.isDevice:
|
||||||
|
continue
|
||||||
|
for child in other_obj:
|
||||||
|
child_ident = getattr(
|
||||||
|
child, "unitId", None
|
||||||
|
) or getattr(child, "serial", None)
|
||||||
|
if child_ident == ident:
|
||||||
|
child.set_battery_info(info)
|
||||||
|
break
|
||||||
|
del self._entries[p]
|
||||||
|
known_paths = set(self._entries.keys())
|
||||||
|
|
||||||
|
with self._lock:
|
||||||
|
id_to_entry = {}
|
||||||
|
for path, (obj, listener) in self._entries.items():
|
||||||
|
if obj.isDevice:
|
||||||
|
ident = obj.unitId or obj.serial
|
||||||
|
if ident:
|
||||||
|
id_to_entry[ident] = (path, obj, listener)
|
||||||
|
|
||||||
|
for dev_info in base.receivers_and_devices():
|
||||||
|
if dev_info.path in known_paths:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
if dev_info.isDevice:
|
||||||
|
obj = device.create_device(base, dev_info)
|
||||||
|
else:
|
||||||
|
obj = receiver.create_receiver(base, dev_info)
|
||||||
|
except OSError as e:
|
||||||
|
if e.errno == 13:
|
||||||
|
logger.error(
|
||||||
|
"permission denied opening %s -- check the Solaar udev rule "
|
||||||
|
"(rules.d/42-logitech-unify-permissions.rules) is installed",
|
||||||
|
dev_info.path,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.exception("failed opening %s", dev_info)
|
||||||
|
continue
|
||||||
|
except Exception:
|
||||||
|
logger.exception("failed opening %s", dev_info)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if obj is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
listener = ListenerClass(obj, self._touch_and_notify)
|
||||||
|
to_join = None
|
||||||
|
|
||||||
|
if obj.isDevice:
|
||||||
|
ident = None
|
||||||
|
try:
|
||||||
|
if obj.protocol >= 2.0:
|
||||||
|
obj.get_ids()
|
||||||
|
ident = obj.unitId or obj.serial
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if ident:
|
||||||
|
with self._lock:
|
||||||
|
existing = id_to_entry.get(ident)
|
||||||
|
if existing:
|
||||||
|
old_path, old_obj, old_listener = existing
|
||||||
|
|
||||||
|
if old_path != dev_info.path:
|
||||||
|
logger.info(
|
||||||
|
"replacing device %s (old path %s) with new path %s",
|
||||||
|
ident,
|
||||||
|
old_path,
|
||||||
|
dev_info.path,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (
|
||||||
|
getattr(obj, "battery_info", None)
|
||||||
|
is None
|
||||||
|
and getattr(
|
||||||
|
old_obj, "battery_info", None
|
||||||
|
)
|
||||||
|
is not None
|
||||||
|
):
|
||||||
|
obj.set_battery_info(
|
||||||
|
old_obj.battery_info
|
||||||
|
)
|
||||||
|
|
||||||
|
old_listener.stop()
|
||||||
|
|
||||||
|
del self._entries[old_path]
|
||||||
|
|
||||||
|
self._entries[dev_info.path] = (
|
||||||
|
obj,
|
||||||
|
listener,
|
||||||
|
)
|
||||||
|
self._last_change[id(obj)] = time.time()
|
||||||
|
|
||||||
|
to_join = old_listener
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
if (
|
||||||
|
getattr(obj, "battery_info", None)
|
||||||
|
is None
|
||||||
|
):
|
||||||
|
for (
|
||||||
|
_,
|
||||||
|
(other_obj, _other_listener),
|
||||||
|
) in self._entries.items():
|
||||||
|
if other_obj.isDevice:
|
||||||
|
continue
|
||||||
|
for child in other_obj:
|
||||||
|
child_ident = getattr(
|
||||||
|
child, "unitId", None
|
||||||
|
) or getattr(
|
||||||
|
child, "serial", None
|
||||||
|
)
|
||||||
|
if child_ident == ident:
|
||||||
|
obj.set_battery_info(
|
||||||
|
child.battery_info
|
||||||
|
)
|
||||||
|
break
|
||||||
|
if (
|
||||||
|
getattr(
|
||||||
|
obj,
|
||||||
|
"battery_info",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
is not None
|
||||||
|
):
|
||||||
|
break
|
||||||
|
|
||||||
|
with self._lock:
|
||||||
|
if dev_info.path not in self._entries:
|
||||||
|
self._entries[dev_info.path] = (obj, listener)
|
||||||
|
self._last_change[id(obj)] = time.time()
|
||||||
|
|
||||||
|
listener.start()
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"listening on %s (%s)",
|
||||||
|
dev_info.path,
|
||||||
|
"device" if dev_info.isDevice else "receiver",
|
||||||
|
)
|
||||||
|
|
||||||
|
if to_join is not None:
|
||||||
|
try:
|
||||||
|
to_join.join(timeout=1.0)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("error joining replaced listener")
|
||||||
|
del to_join
|
||||||
|
|
||||||
|
finally:
|
||||||
|
self._rescan_lock.release()
|
||||||
|
|
||||||
|
def known_devices(self):
|
||||||
|
with self._lock:
|
||||||
|
entries = list(self._entries.values())
|
||||||
|
|
||||||
|
result = []
|
||||||
|
seen_idents = set()
|
||||||
|
for obj, _listener in entries:
|
||||||
|
if obj.isDevice:
|
||||||
|
ident = obj.unitId or obj.serial
|
||||||
|
if ident and ident in seen_idents:
|
||||||
|
continue
|
||||||
|
if ident:
|
||||||
|
seen_idents.add(ident)
|
||||||
|
result.append(obj)
|
||||||
|
else:
|
||||||
|
for child in obj:
|
||||||
|
ident = child.unitId or child.serial
|
||||||
|
if ident and ident in seen_idents:
|
||||||
|
continue
|
||||||
|
if ident:
|
||||||
|
seen_idents.add(ident)
|
||||||
|
result.append(child)
|
||||||
|
return result
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
with self._lock:
|
||||||
|
entries = list(self._entries.values())
|
||||||
|
for _obj, listener in entries:
|
||||||
|
try:
|
||||||
|
listener.stop()
|
||||||
|
except Exception:
|
||||||
|
logger.exception("error stopping listener")
|
||||||
|
for _obj, listener in entries:
|
||||||
|
listener.join(timeout=2.0)
|
||||||
|
|
||||||
|
|
||||||
|
def _snapshot(registry: _ListenerRegistry) -> list[DeviceBattery]:
|
||||||
|
results: list[DeviceBattery] = []
|
||||||
|
|
||||||
|
with registry._hidpp_io_lock:
|
||||||
|
for dev in registry.known_devices():
|
||||||
|
info = dev.battery_info
|
||||||
|
if info is None:
|
||||||
|
try:
|
||||||
|
if dev.ping():
|
||||||
|
info = dev.battery()
|
||||||
|
except Exception:
|
||||||
|
logger.debug(
|
||||||
|
"initial battery() failed for %s", dev, exc_info=True
|
||||||
|
)
|
||||||
|
info = None
|
||||||
|
entry = _to_device_battery(dev, info)
|
||||||
|
if entry is not None:
|
||||||
|
results.append(entry)
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_json(path: Path) -> None:
|
||||||
|
_write_json_atomic(path, [])
|
||||||
|
|
||||||
|
|
||||||
|
def _iter_open_devices():
|
||||||
|
try:
|
||||||
|
from logitech_receiver import base, device, receiver
|
||||||
|
except ImportError as e:
|
||||||
|
raise RuntimeError(
|
||||||
|
"logitech_receiver isn't importable -- install it with `pip install solaar`."
|
||||||
|
) from e
|
||||||
|
except ValueError as e:
|
||||||
|
raise RuntimeError(
|
||||||
|
"logitech_receiver failed to import because a GTK3 typelib is missing "
|
||||||
|
f"({e}). Install the same GTK3 + PyGObject packages Solaar's GUI needs "
|
||||||
|
"(e.g. python3-gi + gir1.2-gtk-3.0 on Debian/Ubuntu, or the gtk3/"
|
||||||
|
"python3-gobject equivalents on your distro)."
|
||||||
|
) from e
|
||||||
|
|
||||||
|
for dev_info in base.receivers_and_devices():
|
||||||
|
try:
|
||||||
|
if dev_info.isDevice:
|
||||||
|
d = device.create_device(base, dev_info) # pyright: ignore[reportArgumentType]
|
||||||
|
if d is not None:
|
||||||
|
yield d
|
||||||
|
else:
|
||||||
|
d = receiver.create_receiver(base, dev_info) # pyright: ignore[reportArgumentType]
|
||||||
|
if d is not None:
|
||||||
|
yield from d
|
||||||
|
except OSError as e:
|
||||||
|
if e.errno == 13:
|
||||||
|
logger.error(
|
||||||
|
"permission denied opening %s -- check the Solaar udev rule "
|
||||||
|
"(rules.d/42-logitech-unify-permissions.rules) is installed "
|
||||||
|
"and you're in the right group",
|
||||||
|
dev_info.path,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.exception("failed opening %s", dev_info)
|
||||||
|
continue
|
||||||
|
except Exception:
|
||||||
|
logger.exception("failed opening %s", dev_info)
|
||||||
|
continue
|
||||||
|
|
||||||
|
|
||||||
|
def _to_device_battery(dev, battery) -> DeviceBattery | None:
|
||||||
|
if battery is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
percentage = battery.level / 100 if isinstance(battery.level, int) else None
|
||||||
|
state = battery.status.name.lower() if battery.status is not None else None
|
||||||
|
|
||||||
|
serial = (
|
||||||
|
getattr(dev, "serial", None) or getattr(dev, "unitId", None) or None
|
||||||
|
)
|
||||||
|
|
||||||
|
return DeviceBattery(
|
||||||
|
model=dev.name or dev.codename or "Unknown device",
|
||||||
|
nativePath=_find_upower_native_path(serial),
|
||||||
|
serial=serial,
|
||||||
|
type=str(dev.kind) if dev.kind is not None else None,
|
||||||
|
wired=dev.receiver is None,
|
||||||
|
percentage=percentage,
|
||||||
|
state=state,
|
||||||
|
charging=battery.charging(),
|
||||||
|
isPresent=battery.ok(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_battery(dev) -> DeviceBattery | None:
|
||||||
|
try:
|
||||||
|
if not dev.ping():
|
||||||
|
return None
|
||||||
|
except Exception:
|
||||||
|
logger.debug("ping failed for %s", dev, exc_info=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
battery = dev.battery()
|
||||||
|
except Exception:
|
||||||
|
logger.debug("battery() failed for %s", dev, exc_info=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
return _to_device_battery(dev, battery)
|
||||||
|
|
||||||
|
|
||||||
|
def poll_once() -> list[DeviceBattery]:
|
||||||
|
results: list[DeviceBattery] = []
|
||||||
|
seen_idents = set()
|
||||||
|
for dev in _iter_open_devices():
|
||||||
|
try:
|
||||||
|
info = _read_battery(dev)
|
||||||
|
if info is not None:
|
||||||
|
entry = _to_device_battery(dev, info)
|
||||||
|
if entry:
|
||||||
|
ident = entry.serial or (getattr(dev, "unitId", None))
|
||||||
|
if ident and ident in seen_idents:
|
||||||
|
continue
|
||||||
|
if ident:
|
||||||
|
seen_idents.add(ident)
|
||||||
|
results.append(entry)
|
||||||
|
finally:
|
||||||
|
with contextlib.suppress(Exception):
|
||||||
|
dev.close()
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def _write_json_atomic(path: Path, results: list[DeviceBattery]) -> None:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
payload = {
|
||||||
|
"updated": time.time(),
|
||||||
|
"devices": [asdict(r) for r in results],
|
||||||
|
}
|
||||||
|
fd, tmp_path = tempfile.mkstemp(
|
||||||
|
dir=path.parent, prefix=".battery-", suffix=".tmp"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with os.fdopen(fd, "w") as f:
|
||||||
|
json.dump(payload, f, indent=2)
|
||||||
|
os.replace(tmp_path, path)
|
||||||
|
except Exception:
|
||||||
|
Path(tmp_path).unlink(missing_ok=True)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
@app.command()
|
||||||
|
def daemon(
|
||||||
|
rescan_interval: float = typer.Option(
|
||||||
|
60.0,
|
||||||
|
"--rescan-interval",
|
||||||
|
"-i",
|
||||||
|
help=(
|
||||||
|
"Seconds between fallback rescans. This is NOT a battery poll "
|
||||||
|
"interval -- battery updates are event-driven and written as "
|
||||||
|
"soon as a device reports a change. New/removed devices "
|
||||||
|
"(e.g. plugging a keyboard in to charge) are normally noticed "
|
||||||
|
"within milliseconds via a udev hotplug watcher; this interval "
|
||||||
|
"is only a safety net in case a udev event is ever missed."
|
||||||
|
),
|
||||||
|
),
|
||||||
|
out: Path = typer.Option(
|
||||||
|
DEFAULT_OUTPUT,
|
||||||
|
"--out",
|
||||||
|
"-o",
|
||||||
|
help="Where to write the JSON status file.",
|
||||||
|
),
|
||||||
|
lock_file: Path = typer.Option(
|
||||||
|
DEFAULT_LOCK,
|
||||||
|
"--lock-file",
|
||||||
|
help="Path used to ensure only one daemon runs at a time.",
|
||||||
|
),
|
||||||
|
verbose: bool = typer.Option(
|
||||||
|
False,
|
||||||
|
"--verbose",
|
||||||
|
"-v",
|
||||||
|
help="Log every listener start and battery-change write to stderr.",
|
||||||
|
),
|
||||||
|
):
|
||||||
|
lock_fd = _acquire_singleton_lock(lock_file)
|
||||||
|
if lock_fd is None:
|
||||||
|
try:
|
||||||
|
holder_pid = lock_file.read_text().strip()
|
||||||
|
except OSError:
|
||||||
|
holder_pid = "unknown"
|
||||||
|
typer.echo(
|
||||||
|
f"error: a battery daemon is already running (pid {holder_pid}, lock: {lock_file})",
|
||||||
|
err=True,
|
||||||
|
)
|
||||||
|
raise typer.Exit(code=1)
|
||||||
|
|
||||||
|
if verbose:
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO, format="%(asctime)s %(name)s: %(message)s"
|
||||||
|
)
|
||||||
|
|
||||||
|
write_lock = threading.Lock()
|
||||||
|
last_payload = None
|
||||||
|
|
||||||
|
pending_write_timer: list[threading.Timer | None] = [None]
|
||||||
|
pending_write_lock = threading.Lock()
|
||||||
|
WRITE_SETTLE_SECONDS = 0.3
|
||||||
|
|
||||||
|
write_seq_lock = threading.Lock()
|
||||||
|
write_seq = 0
|
||||||
|
last_written_seq = 0
|
||||||
|
|
||||||
|
def write_if_changed():
|
||||||
|
nonlocal last_payload, write_seq, last_written_seq
|
||||||
|
with write_seq_lock:
|
||||||
|
write_seq += 1
|
||||||
|
my_seq = write_seq
|
||||||
|
|
||||||
|
results = _snapshot(registry)
|
||||||
|
with write_lock:
|
||||||
|
with write_seq_lock:
|
||||||
|
if my_seq <= last_written_seq:
|
||||||
|
return
|
||||||
|
last_written_seq = my_seq
|
||||||
|
payload = [asdict(r) for r in results]
|
||||||
|
if payload != last_payload:
|
||||||
|
_write_json_atomic(out, results)
|
||||||
|
last_payload = payload
|
||||||
|
logger.info(
|
||||||
|
"battery status changed, wrote %d device(s)", len(results)
|
||||||
|
)
|
||||||
|
|
||||||
|
def write_if_changed_coalesced():
|
||||||
|
with pending_write_lock:
|
||||||
|
existing = pending_write_timer[0]
|
||||||
|
if existing is not None:
|
||||||
|
existing.cancel()
|
||||||
|
timer = threading.Timer(WRITE_SETTLE_SECONDS, write_if_changed)
|
||||||
|
timer.daemon = True
|
||||||
|
pending_write_timer[0] = timer
|
||||||
|
timer.start()
|
||||||
|
|
||||||
|
def on_change(_device_or_receiver, alert=None, reason=None):
|
||||||
|
write_if_changed_coalesced()
|
||||||
|
|
||||||
|
registry = _ListenerRegistry(on_change)
|
||||||
|
|
||||||
|
def rescan_and_write():
|
||||||
|
try:
|
||||||
|
registry.rescan()
|
||||||
|
except Exception:
|
||||||
|
logger.exception("rescan failed")
|
||||||
|
write_if_changed_coalesced()
|
||||||
|
|
||||||
|
try:
|
||||||
|
registry.rescan()
|
||||||
|
except RuntimeError as e:
|
||||||
|
typer.echo(f"error: {e}", err=True)
|
||||||
|
raise typer.Exit(code=1) from None
|
||||||
|
|
||||||
|
write_if_changed()
|
||||||
|
|
||||||
|
hotplug_observer = _start_hotplug_watcher(rescan_and_write)
|
||||||
|
|
||||||
|
running = True
|
||||||
|
|
||||||
|
def _stop(signum, frame):
|
||||||
|
nonlocal running
|
||||||
|
running = False
|
||||||
|
|
||||||
|
signal.signal(signal.SIGINT, _stop)
|
||||||
|
signal.signal(signal.SIGTERM, _stop)
|
||||||
|
|
||||||
|
typer.echo(
|
||||||
|
f"Listening for battery events, writing to {out} (lock: {lock_file})"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
while running:
|
||||||
|
remaining = rescan_interval
|
||||||
|
while running and remaining > 0:
|
||||||
|
step = min(0.2, remaining)
|
||||||
|
time.sleep(step)
|
||||||
|
remaining -= step
|
||||||
|
if running:
|
||||||
|
rescan_and_write()
|
||||||
|
finally:
|
||||||
|
if hotplug_observer is not None:
|
||||||
|
with contextlib.suppress(Exception):
|
||||||
|
hotplug_observer.stop()
|
||||||
|
with contextlib.suppress(Exception):
|
||||||
|
_clean_json(out)
|
||||||
|
|
||||||
|
registry.stop()
|
||||||
|
typer.echo("Stopped.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app()
|
||||||
+3
-4
@@ -10,12 +10,11 @@ dependencies = [
|
|||||||
"typer",
|
"typer",
|
||||||
"pillow",
|
"pillow",
|
||||||
"jinja2",
|
"jinja2",
|
||||||
"materialyoucolor"
|
"materialyoucolor",
|
||||||
|
"solaar",
|
||||||
|
"pytest"
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.optional-dependencies]
|
|
||||||
dev = ["pytest"]
|
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
zshell-cli = "zshell:main"
|
zshell-cli = "zshell:main"
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user