Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions shell/plugins/services/battery/Service.qml
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,13 @@ Item {
powerProfileReadProcess.running = true
}

function refreshChargeLimit() {
function refreshChargeLimitState() {
topUpOnceFile.reread()
chargeLimitSignals++
}

function refreshChargeLimit() {
refreshChargeLimitState()
checkTopUpOnceRearm()
}

Expand Down Expand Up @@ -119,7 +123,9 @@ Item {

Process {
id: chargeLimitProcess
onExited: root.refreshChargeLimit()
// A failed write leaves the marker in place. Refresh the readout, but
// wait for another battery event or explicit refresh before trying again.
onExited: root.refreshChargeLimitState()
}

// Wait briefly on unplug before re-arming a one-time top-up so USB-C PD
Expand Down
10 changes: 10 additions & 0 deletions test/shell.d/battery-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,13 @@ assert(
'battery does not re-arm charge limit when one-time top-up is not active'
)
JS

if command -v quickshell >/dev/null && command -v dbus-run-session >/dev/null; then
if ! output=$(timeout 15 dbus-run-session -- /usr/bin/python3 \
"$SHELL_TEST_DIR/fixtures/battery-charge-limit.py" "$ROOT" 2>&1); then
fail "charge-limit failure waits for a new battery event before retrying" "$output"
fi
pass "charge-limit failure waits for a new battery event before retrying"
else
skip "Quickshell and dbus-run-session are needed for the charge-limit retry fixture"
fi
147 changes: 147 additions & 0 deletions test/shell.d/fixtures/battery-charge-limit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import os
from pathlib import Path
import subprocess
import sys
from tempfile import TemporaryDirectory

from gi.repository import Gio, GLib

UPOWER = "org.freedesktop.UPower"
DEVICE = UPOWER + ".Device"
ROOT = "/org/freedesktop/UPower"
BATTERY = ROOT + "/devices/battery_BAT0"
bus = Gio.bus_get_sync(Gio.BusType.SESSION)
loop = GLib.MainLoop()
props = {
"IsPresent": GLib.Variant("b", True),
"PowerSupply": GLib.Variant("b", True),
"ChargeThresholdSupported": GLib.Variant("b", True),
"ChargeThresholdEnabled": GLib.Variant("b", False),
"Percentage": GLib.Variant("d", 100.0),
"State": GLib.Variant("u", 1), # Charging; 100% also finishes a top-up.
}
attempts = 0
accept_threshold = False


def method_call(connection, sender, path, interface, method, params, invocation):
global attempts
if method == "EnumerateDevices":
invocation.return_value(GLib.Variant("(ao)", ([BATTERY],)))
elif method == "GetDisplayDevice":
invocation.return_value(GLib.Variant("(o)", (BATTERY,)))
elif method == "EnableChargeThreshold":
attempts += 1
assert params.unpack() == (True,)
if accept_threshold:
props["ChargeThresholdEnabled"] = GLib.Variant("b", True)
invocation.return_value(None)
else:
invocation.return_dbus_error("org.freedesktop.UPower.GeneralError", "test threshold write rejected")


def get_property(connection, sender, path, interface, name):
return GLib.Variant("b", False) if name == "OnBattery" else props[name]


def register(path, interface, methods, properties):
xml = f'<node><interface name="{interface}">{methods}' + "".join(
f'<property name="{name}" type="{value.get_type_string()}" access="read"/>'
for name, value in properties.items()
) + "</interface></node>"
bus.register_object(path, Gio.DBusNodeInfo.new_for_xml(xml).interfaces[0], method_call, get_property)


register(ROOT, UPOWER, """
<method name="EnumerateDevices"><arg type="ao" direction="out"/></method>
<method name="GetDisplayDevice"><arg type="o" direction="out"/></method>
""", {"OnBattery": GLib.Variant("b", False)})
register(BATTERY, DEVICE, """
<method name="EnableChargeThreshold"><arg type="b" direction="in"/></method>
""", props)
bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
"RequestName", GLib.Variant("(su)", (UPOWER, 0)), None, 0, 5000, None)


def update_percentage(percentage):
changed = {"Percentage": GLib.Variant("d", percentage)}
props.update(changed)
bus.emit_signal(None, BATTERY, "org.freedesktop.DBus.Properties", "PropertiesChanged",
GLib.Variant("(sa{sv}as)", (DEVICE, changed, [])))


def wait_until(predicate, timeout_ms=4000):
deadline = GLib.get_monotonic_time() + timeout_ms * 1000

def check():
if predicate() or GLib.get_monotonic_time() >= deadline:
loop.quit()
return GLib.SOURCE_REMOVE
return GLib.SOURCE_CONTINUE

GLib.timeout_add(10, check)
loop.run()
return predicate()


with TemporaryDirectory() as tmp:
home = Path(tmp)
state = home / "state"
marker = state / "omarchy" / "battery" / "top-up-once"
marker.parent.mkdir(parents=True)
marker.write_text("1\n")
repo = Path(sys.argv[1])
config = home / "config"
config.mkdir()
(config / "battery").symlink_to(repo / "shell/plugins/services/battery", target_is_directory=True)
(config / "Commons").symlink_to(repo / "shell/Commons", target_is_directory=True)
(config / "shell.qml").write_text("""
import Quickshell
import "battery" as Battery

ShellRoot {
Battery.Service {
readonly property int observedPercentage: batteryPercentage()
onObservedPercentageChanged: console.info("fixture percentage " + observedPercentage)
// A rejected CLI write cannot send a refresh over IPC. The service only
// emits this signal for that attempt once it has handled the child's exit.
onChargeLimitSignalsChanged: console.info("fixture charge limit refreshed")
}
}
""")
(home / "run").mkdir(mode=0o700)
env = {**os.environ, "DBUS_SYSTEM_BUS_ADDRESS": os.environ["DBUS_SESSION_BUS_ADDRESS"],
"HOME": tmp, "XDG_RUNTIME_DIR": str(home / "run"), "XDG_CONFIG_HOME": str(home / ".config"),
"XDG_CACHE_HOME": str(home / ".cache"), "XDG_STATE_HOME": str(state),
"OMARCHY_BATTERY_STATE_DIR": str(marker.parent), "OMARCHY_POWER_SUPPLY_PATH": str(home / "sys"),
"QT_QPA_PLATFORM": "offscreen", "QML_IMPORT_PATH": str(repo / "shell"),
"QS_DISABLE_CRASH_HANDLER": "1", "PATH": f"{repo}/bin:{os.environ['PATH']}"}
log_path = home / "quickshell.log"

def logged(message):
return message.encode() in log_path.read_bytes()

with log_path.open("w") as log:
shell = subprocess.Popen(["quickshell", "-p", str(config), "--no-color"], stdout=log, stderr=log, env=env)
try:
# Dispatch the real Quickshell battery service and its real CLI on a
# private bus. The fixture only supplies the battery and write outcome.
assert wait_until(lambda: attempts > 0 and logged("fixture charge limit refreshed")), \
"the first charge-limit failure did not complete"
assert marker.exists(), "a failed write must keep the request pending"
assert not wait_until(lambda: attempts > 1, 300), "the failed charge-limit write retried without a new battery event"

update_percentage(95.0)
assert wait_until(lambda: logged("fixture percentage 95")), "Quickshell did not see the below-full reading"
assert not wait_until(lambda: attempts > 1, 200), "charging below the limit must not retry"

accept_threshold = True
update_percentage(100.0)
assert wait_until(lambda: attempts >= 2 and not marker.exists()), "the successful retry did not clear the request"
assert attempts == 2, f"a new full-charge event must retry exactly once, saw {attempts}"
except Exception:
print(log_path.read_text(errors="replace")[-5000:], file=sys.stderr)
raise
finally:
shell.terminate()
shell.wait(timeout=5)