diff --git a/desktop/shell/shell/plugins/services/idle/IdleModel.js b/desktop/shell/shell/plugins/services/idle/IdleModel.js index bf33d661..52e61ea7 100644 --- a/desktop/shell/shell/plugins/services/idle/IdleModel.js +++ b/desktop/shell/shell/plugins/services/idle/IdleModel.js @@ -24,10 +24,132 @@ function delayAfterFirstIdle(timeoutSeconds, firstIdleSeconds) { return delay > 0 ? delay : 0 } +var INTERNAL_OUTPUT_RE = /^(eDP|LVDS|DSI|Unknown)-/ +var MIN_IDLE_REFRESH_HZ = 23.5 + +function formatRefreshHz(refresh) { + var fixed = Number(refresh).toFixed(3) + return fixed.replace(/\.?0+$/, "") +} + +function formatMode(width, height, refresh) { + return width + "x" + height + "@" + formatRefreshHz(refresh) + "Hz" +} + +// Inspect `wlr-randr --json` output and pick the lowest safe refresh rate +// (>= 24 Hz) at the current resolution of the first multi-rate built-in display. +// Returns { valid, hasEnabledInternal, supported, output, activeMode, idleMode, activeRefresh, idleRefresh }. +// On single-mode displays `supported` is false so the shell skips creating an +// idle refresh monitor altogether. +function selectIdleRefreshPlan(outputsOrJson) { + var invalid = { + valid: false, + hasEnabledInternal: false, + supported: false, + output: "", + activeMode: "", + idleMode: "", + activeRefresh: 0, + idleRefresh: 0 + } + var outputs = outputsOrJson + if (typeof outputs === "string") { + try { outputs = JSON.parse(outputs) } catch (e) { return invalid } + } + if (!Array.isArray(outputs)) return invalid + + var hasEnabledInternal = false + for (var i = 0; i < outputs.length; i++) { + var out = outputs[i] + if (!out || out.enabled !== true || !INTERNAL_OUTPUT_RE.test(String(out.name || ""))) continue + var modes = Array.isArray(out.modes) ? out.modes : [] + var current = null + for (var j = 0; j < modes.length; j++) { + if (modes[j] && modes[j].current) { current = modes[j]; break } + } + if (!current || !(current.width > 0) || !(current.height > 0) || !(current.refresh > 0)) continue + hasEnabledInternal = true + + var lowest = null + var highest = null + for (var k = 0; k < modes.length; k++) { + var m = modes[k] + if (!m || m.width !== current.width || m.height !== current.height) continue + var hz = Number(m.refresh) + if (!isFinite(hz) || hz < MIN_IDLE_REFRESH_HZ) continue + if (lowest === null || hz < lowest.refresh) lowest = m + if (highest === null || hz > highest.refresh) highest = m + } + + var supported = lowest !== null && highest !== null && (highest.refresh - lowest.refresh) > 1.0 + if (!supported) continue + var canLower = (current.refresh - lowest.refresh) > 1.0 + return { + valid: true, + hasEnabledInternal: true, + supported: true, + output: String(out.name), + activeMode: formatMode(current.width, current.height, current.refresh), + idleMode: canLower ? formatMode(lowest.width, lowest.height, lowest.refresh) : "", + activeRefresh: Number(current.refresh), + idleRefresh: canLower ? Number(lowest.refresh) : 0 + } + } + return { + valid: true, + hasEnabledInternal: hasEnabledInternal, + supported: false, + output: "", + activeMode: "", + idleMode: "", + activeRefresh: 0, + idleRefresh: 0 + } +} + +// Before restoring the saved mode, confirm the same enabled output still holds +// the exact idle mode this service applied so manual mode changes are preserved. +// `outputPresent` is false when the output is temporarily absent or disabled so +// the caller can retain the saved mode until the panel returns. +function shouldRestoreIdleRefresh(outputsOrJson, outputName, appliedIdleMode) { + var outputs = outputsOrJson + if (typeof outputs === "string") { + try { outputs = JSON.parse(outputs) } catch (e) { + return { valid: false, outputPresent: false, restore: false, currentMode: "" } + } + } + if (!Array.isArray(outputs)) return { valid: false, outputPresent: false, restore: false, currentMode: "" } + + for (var i = 0; i < outputs.length; i++) { + var out = outputs[i] + if (!out || String(out.name || "") !== String(outputName || "")) continue + if (out.enabled !== true) return { valid: true, outputPresent: false, restore: false, currentMode: "" } + var modes = Array.isArray(out.modes) ? out.modes : [] + for (var j = 0; j < modes.length; j++) { + var m = modes[j] + if (m && m.current && m.width > 0 && m.height > 0 && m.refresh > 0) { + var currentMode = formatMode(m.width, m.height, m.refresh) + return { + valid: true, + outputPresent: true, + restore: currentMode === String(appliedIdleMode || ""), + currentMode: currentMode + } + } + } + return { valid: true, outputPresent: false, restore: false, currentMode: "" } + } + return { valid: true, outputPresent: false, restore: false, currentMode: "" } +} + if (typeof module !== "undefined") { module.exports = { secondsFromConfig: secondsFromConfig, firstIdleTimeout: firstIdleTimeout, - delayAfterFirstIdle: delayAfterFirstIdle + delayAfterFirstIdle: delayAfterFirstIdle, + formatRefreshHz: formatRefreshHz, + formatMode: formatMode, + selectIdleRefreshPlan: selectIdleRefreshPlan, + shouldRestoreIdleRefresh: shouldRestoreIdleRefresh } } diff --git a/desktop/shell/shell/plugins/services/idle/Service.qml b/desktop/shell/shell/plugins/services/idle/Service.qml index cdf4fa71..b42e157c 100644 --- a/desktop/shell/shell/plugins/services/idle/Service.qml +++ b/desktop/shell/shell/plugins/services/idle/Service.qml @@ -16,10 +16,12 @@ Item { readonly property string stayAwakeStatePath: stayAwakeStateDir + "/stay-awake" readonly property int defaultScreensaverSeconds: 150 readonly property int defaultLockSeconds: 300 + readonly property int defaultIdleRefreshSeconds: 5 readonly property var idleConfig: shell && shell.shellConfig && shell.shellConfig.idle ? shell.shellConfig.idle : (shell && shell.idleConfig ? shell.idleConfig : ({})) readonly property int screensaverTimeoutSeconds: secondsFromConfig(idleConfig.screensaver, defaultScreensaverSeconds) readonly property int lockTimeoutSeconds: secondsFromConfig(idleConfig.lock, defaultLockSeconds) + readonly property int idleRefreshTimeoutSeconds: secondsFromConfig(idleConfig.refreshRate, defaultIdleRefreshSeconds) readonly property bool screensaverEnabled: screensaverTimeoutSeconds > 0 readonly property bool lockEnabled: lockTimeoutSeconds > 0 readonly property bool idleTimersEnabled: screensaverEnabled || lockEnabled @@ -27,6 +29,7 @@ Item { readonly property int screensaverDelaySeconds: IdleModel.delayAfterFirstIdle(screensaverTimeoutSeconds, firstIdleTimeoutSeconds) readonly property int lockDelaySeconds: IdleModel.delayAfterFirstIdle(lockTimeoutSeconds, firstIdleTimeoutSeconds) readonly property bool idleEnabled: stayAwakeStateLoaded && !stayAwake + readonly property bool idleRefreshEnabled: idleEnabled && idleRefreshSupported && idleRefreshTimeoutSeconds > 0 // A retimed IdleMonitor can reuse its notification's address and never rebind isIdle; pulsing it off sends the pointer through null. // While idle that pulse would read as the user coming back, so retiming waits until they have. @@ -41,7 +44,19 @@ Item { } } + function retimeRefreshIdleMonitor() { + var timeout = Math.max(1, root.idleRefreshTimeoutSeconds) + if (refreshIdleMonitor.isIdle || refreshIdleMonitor.timeout === timeout) return + + refreshIdleMonitor.timeout = timeout + if (root.idleRefreshEnabled) { + root.logEvent("refresh-monitor-rearm", "timeout=" + timeout) + refreshIdleMonitorRearmTimer.restart() + } + } + onFirstIdleTimeoutSecondsChanged: retimeIdleMonitor() + onIdleRefreshTimeoutSecondsChanged: retimeRefreshIdleMonitor() property bool stayAwake: false property bool stayAwakeStateLoaded: false @@ -49,6 +64,21 @@ Item { property bool pendingStayAwakePersist: false property bool idledThisCycle: false property bool screensaverStartedThisCycle: false + property bool idleRefreshSupported: false + property bool refreshProbeConfirmed: false + property bool refreshLowered: false + property bool refreshLowerFailedThisIdle: false + property string refreshOutput: "" + property string refreshSavedMode: "" + property string refreshIdleMode: "" + property string refreshApplyingTarget: "" + property string refreshProbePurpose: "" + property bool refreshProbeExited: false + property bool refreshProbeStreamDone: false + property int refreshProbeExitCode: -1 + property string refreshProbeText: "" + property int refreshProbeRetries: 0 + property int refreshRestoreRetries: 0 property string lastEvent: "starting" property string lastEventAt: "" @@ -173,6 +203,185 @@ Item { else handleActiveSignal() } + function startRefreshProbe(purpose) { + if (refreshProbeProcess.running) return false + root.refreshProbePurpose = purpose + root.refreshProbeExited = false + root.refreshProbeStreamDone = false + root.refreshProbeExitCode = -1 + root.refreshProbeText = "" + refreshProbeProcess.running = true + return true + } + + function maybeFinishRefreshProbe() { + if (!root.refreshProbeExited || !root.refreshProbeStreamDone) return + var code = root.refreshProbeExitCode + var raw = root.refreshProbeText + root.refreshProbeExited = false + root.refreshProbeStreamDone = false + root.handleRefreshProbeExited(code, raw) + } + + function scheduleRefreshProbeRetry() { + if (root.refreshProbeRetries >= 3) return + root.refreshProbeRetries++ + refreshProbeRetryTimer.restart() + } + + function scheduleRefreshRestoreRetry() { + if (root.refreshRestoreRetries >= 3) return + root.refreshRestoreRetries++ + refreshRestoreRetryTimer.restart() + } + + function reconcileRefreshRate() { + if (refreshProbeProcess.running || refreshApplyProcess.running) return + + var wantLowered = root.idleRefreshEnabled && refreshIdleMonitor.isIdle + if (wantLowered && !root.refreshLowered && !root.refreshLowerFailedThisIdle) { + refreshRestoreRetryTimer.stop() + startRefreshProbe("lower") + } else if (!wantLowered && root.refreshLowered) { + if (!root.refreshOutput || !root.refreshSavedMode || !root.refreshIdleMode) { + root.refreshLowered = false + root.refreshSavedMode = "" + root.refreshIdleMode = "" + return + } + startRefreshProbe("verify-restore") + } + } + + function handleRefreshProbeExited(exitCode, raw) { + var purpose = root.refreshProbePurpose + root.refreshProbePurpose = "" + + if (purpose === "detect") { + if (exitCode !== 0) { + scheduleRefreshProbeRetry() + return + } + var detected = IdleModel.selectIdleRefreshPlan(raw) + if (!detected.valid || !detected.hasEnabledInternal) { + // Output list is empty or panel not enabled yet: do not permanently disable. + scheduleRefreshProbeRetry() + return + } + root.refreshProbeRetries = 0 + root.refreshProbeConfirmed = true + root.idleRefreshSupported = detected.supported + Qt.callLater(root.reconcileRefreshRate) + return + } + + if (purpose === "lower") { + if (!(root.idleRefreshEnabled && refreshIdleMonitor.isIdle) || root.refreshLowered || root.refreshLowerFailedThisIdle) { + Qt.callLater(root.reconcileRefreshRate) + return + } + if (exitCode !== 0) { + root.refreshLowerFailedThisIdle = true + return + } + var plan = IdleModel.selectIdleRefreshPlan(raw) + if (!plan.valid || !plan.hasEnabledInternal) { + root.refreshLowerFailedThisIdle = true + return + } + root.idleRefreshSupported = plan.supported + if (!plan.idleMode || !plan.output) return + + root.refreshOutput = plan.output + root.refreshSavedMode = plan.activeMode + root.refreshIdleMode = plan.idleMode + root.refreshApplyingTarget = "lower" + refreshApplyProcess.command = ["wlr-randr", "--output", plan.output, "--mode", plan.idleMode] + refreshApplyProcess.running = true + return + } + + if (purpose === "verify-restore") { + if (root.idleRefreshEnabled && refreshIdleMonitor.isIdle) return + if (exitCode !== 0) { + scheduleRefreshRestoreRetry() + return + } + var check = IdleModel.shouldRestoreIdleRefresh(raw, root.refreshOutput, root.refreshIdleMode) + if (!check.valid || !check.outputPresent) { + // Panel is temporarily absent or disabled: retain saved mode until it returns. + scheduleRefreshRestoreRetry() + return + } + if (!check.restore) { + // Output is enabled and another actor changed its mode: preserve their choice. + logEvent("refresh-preserved", root.refreshOutput + " current=" + (check.currentMode || "none")) + root.refreshLowered = false + root.refreshSavedMode = "" + root.refreshIdleMode = "" + root.refreshRestoreRetries = 0 + refreshRestoreRetryTimer.stop() + Qt.callLater(root.reconcileRefreshRate) + return + } + root.refreshApplyingTarget = "restore" + refreshApplyProcess.command = ["wlr-randr", "--output", root.refreshOutput, "--mode", root.refreshSavedMode] + refreshApplyProcess.running = true + } + } + + function handleRefreshApplyExited(exitCode) { + var target = root.refreshApplyingTarget + root.refreshApplyingTarget = "" + if (target === "lower") { + if (exitCode === 0) { + root.refreshLowered = true + root.refreshLowerFailedThisIdle = false + root.refreshRestoreRetries = 0 + refreshRestoreRetryTimer.stop() + logEvent("refresh-idle", root.refreshOutput + " " + root.refreshSavedMode + " -> " + root.refreshIdleMode) + Qt.callLater(root.reconcileRefreshRate) + } else { + // Do not tight-loop on a rejected mode; wait for a new idle cycle or output change. + logEvent("refresh-idle-failed", root.refreshOutput + " -> " + root.refreshIdleMode + " exitCode=" + exitCode) + root.refreshLowerFailedThisIdle = true + root.refreshSavedMode = "" + root.refreshIdleMode = "" + } + return + } + + if (target === "restore") { + if (exitCode === 0) { + var restoredMode = root.refreshSavedMode + var restoredOutput = root.refreshOutput + root.refreshLowered = false + root.refreshSavedMode = "" + root.refreshIdleMode = "" + root.refreshRestoreRetries = 0 + refreshRestoreRetryTimer.stop() + logEvent("refresh-active", restoredOutput + " -> " + restoredMode) + Qt.callLater(root.reconcileRefreshRate) + } else { + // Retain saved mode so a retry or subsequent activity can still restore it. + logEvent("refresh-restore-failed", root.refreshOutput + " -> " + root.refreshSavedMode + " exitCode=" + exitCode) + scheduleRefreshRestoreRetry() + } + } + } + + onIdleRefreshEnabledChanged: { + if (idleRefreshEnabled) retimeRefreshIdleMonitor() + reconcileRefreshRate() + } + + onIdleEnabledChanged: { + if (idleEnabled && !refreshProbeConfirmed && !refreshProbeProcess.running) { + root.refreshProbeRetries = 0 + startRefreshProbe("detect") + } + } + function statusJson() { return JSON.stringify({ enabled: root.idleEnabled, @@ -197,6 +406,15 @@ Item { lock: lockProcess.running, wake: wakeProcess.running }, + refreshRate: { + supported: root.idleRefreshSupported, + enabled: root.idleRefreshEnabled, + lowered: root.refreshLowered, + timeout: root.idleRefreshTimeoutSeconds, + output: root.refreshOutput, + savedMode: root.refreshSavedMode, + idleMode: root.refreshIdleMode + }, lastEvent: root.lastEvent, lastEventAt: root.lastEventAt }) @@ -282,6 +500,82 @@ Item { } Process { id: dimProcess } + // On displays that advertise lower refresh rates (>= 24 Hz) at their active + // resolution, step down after brief inactivity and restore on the first + // input. Respects Wayland idle inhibitors (video playback, games) and Stay + // Awake, and stays disabled on single-mode panels. + IdleMonitor { + id: refreshIdleMonitor + enabled: root.idleRefreshEnabled && !refreshIdleMonitorRearmTimer.running + respectInhibitors: true + onIsIdleChanged: { + if (!isIdle) { + root.refreshLowerFailedThisIdle = false + root.refreshRestoreRetries = 0 + root.retimeRefreshIdleMonitor() + } + root.reconcileRefreshRate() + } + } + + Connections { + target: Quickshell + ignoreUnknownSignals: true + function onScreensChanged() { + root.refreshLowerFailedThisIdle = false + root.refreshRestoreRetries = 0 + if (!root.refreshLowered) { + root.refreshProbeConfirmed = false + root.refreshProbeRetries = 0 + root.startRefreshProbe("detect") + } + root.reconcileRefreshRate() + } + } + + Timer { + id: refreshIdleMonitorRearmTimer + interval: 150 + repeat: false + } + + Timer { + id: refreshProbeRetryTimer + interval: 3000 + repeat: false + onTriggered: if (!root.refreshProbeConfirmed) root.startRefreshProbe("detect") + } + + Timer { + id: refreshRestoreRetryTimer + interval: 2000 + repeat: false + onTriggered: root.reconcileRefreshRate() + } + + Process { + id: refreshProbeProcess + command: ["wlr-randr", "--json"] + stdout: StdioCollector { + waitForEnd: true + onStreamFinished: { + root.refreshProbeText = text + root.refreshProbeStreamDone = true + root.maybeFinishRefreshProbe() + } + } + onExited: function(exitCode) { + root.refreshProbeExitCode = exitCode + root.refreshProbeExited = true + root.maybeFinishRefreshProbe() + } + } + + Process { + id: refreshApplyProcess + onExited: function(exitCode) { root.handleRefreshApplyExited(exitCode) } + } + Timer { id: lockTimer repeat: false @@ -356,7 +650,51 @@ Item { Component.onCompleted: { logEvent("service-ready") retimeIdleMonitor() + retimeRefreshIdleMonitor() refreshStayAwakeState() + startRefreshProbe("detect") + } + + Component.onDestruction: { + var mayBeLowered = root.refreshLowered || root.refreshApplyingTarget === "lower" + if (mayBeLowered && root.refreshOutput && root.refreshSavedMode && root.refreshIdleMode) { + // Re-verify the output's mode before every attempt so manual mode changes + // are preserved, and retry transient restore failures within a bound. + var script = + "import json, subprocess, sys, time\n" + + "out, idle, saved, inflight = sys.argv[1:5]\n" + + "tries = 6\n" + + "for i in range(tries):\n" + + " try:\n" + + " data = json.loads(subprocess.check_output(['wlr-randr', '--json'], text=True, timeout=3))\n" + + " except Exception:\n" + + " if i + 1 < tries: time.sleep(0.1)\n" + + " continue\n" + + " cur = None\n" + + " for o in data:\n" + + " if o.get('name') == out and o.get('enabled'):\n" + + " for m in o.get('modes') or []:\n" + + " if m.get('current'):\n" + + " hz = ('%.3f' % float(m['refresh'])).rstrip('0').rstrip('.')\n" + + " cur = '%sx%s@%sHz' % (m['width'], m['height'], hz)\n" + + " break\n" + + " if cur == idle:\n" + + " try:\n" + + " res = subprocess.run(['wlr-randr', '--output', out, '--mode', saved], timeout=3)\n" + + " if res.returncode == 0:\n" + + " break\n" + + " except Exception:\n" + + " pass\n" + + " elif cur is not None and inflight != '1':\n" + + " break\n" + + " if i + 1 < tries:\n" + + " time.sleep(0.1)\n" + Quickshell.execDetached([ + "python3", "-c", script, + root.refreshOutput, root.refreshIdleMode, root.refreshSavedMode, + root.refreshApplyingTarget !== "" ? "1" : "0" + ]) + } } ShellIpc { diff --git a/docs/power-and-lock.md b/docs/power-and-lock.md index 74812207..4ad222cd 100644 --- a/docs/power-and-lock.md +++ b/docs/power-and-lock.md @@ -220,6 +220,7 @@ instant, and sleep only follows 10 s after the last one left it dark. | Idle lock grace | 8 s | Quick wake does not require a new PIN; explicit lock is unchanged | | Screen fade | 240 ms | Smoothstep easing, reversible immediately; event loop never sleeps for animation | | Settle (lock requested → sleep) | 10 s | After Power immediately, or after the idle grace expires | +| Desktop idle → lower refresh rate | 5 s | the shell's `idle.refreshRate` (`0` disables); multi-rate internal panels only, respects idle inhibitors and Stay Awake | | Desktop idle → dark | 5 min | the shell's `idle.lock` | | Lock screen idle → dark | 30 s | the lock's blank timer, sent as `idle` | | Playback check | 1 s, only while dark | `SETTLING` is longer, so it is seen first | diff --git a/tests/test_idle_refresh.py b/tests/test_idle_refresh.py new file mode 100644 index 00000000..a977d976 --- /dev/null +++ b/tests/test_idle_refresh.py @@ -0,0 +1,271 @@ +"""Tests for adaptive idle refresh-rate selection and teardown safety.""" + +import json +import os +from pathlib import Path +import re +import shutil +import stat +import subprocess +import tempfile +import unittest + +PROJECT = Path(__file__).resolve().parents[1] +MODEL = PROJECT / 'desktop/shell/shell/plugins/services/idle/IdleModel.js' +SERVICE = PROJECT / 'desktop/shell/shell/plugins/services/idle/Service.qml' + + +def eval_js(expr, *args): + script = f'const m = require(process.argv[1]); console.log(JSON.stringify({expr}));' + res = subprocess.run( + ['node', '-e', script, str(MODEL), *(json.dumps(a) for a in args)], + capture_output=True, text=True, check=True, + ) + return json.loads(res.stdout) + + +def extract_teardown_script(): + text = SERVICE.read_text() + m = re.search(r'var script =\n((?:\s+"[^"]*"(?:\s*\+)?\n)+)', text) + assert m, 'teardown script not found in Service.qml' + parts = re.findall(r'"((?:[^"\\]|\\.)*)"', m.group(1)) + return ''.join(bytes(p, 'utf-8').decode('unicode_escape') for p in parts) + + +@unittest.skipUnless(shutil.which('node'), 'node not installed') +class IdleRefreshModelTests(unittest.TestCase): + def test_promotion_panel_lowers_from_60_or_120_to_24(self): + for current_hz in (60.0, 120.0): + outputs = [{ + 'name': 'Unknown-1', + 'enabled': True, + 'modes': [ + {'width': 1668, 'height': 2224, 'refresh': 60.0, 'current': current_hz == 60.0}, + {'width': 1668, 'height': 2224, 'refresh': 120.0, 'current': current_hz == 120.0}, + {'width': 1668, 'height': 2224, 'refresh': 48.0, 'current': False}, + {'width': 1668, 'height': 2224, 'refresh': 30.0, 'current': False}, + {'width': 1668, 'height': 2224, 'refresh': 24.0, 'current': False}, + ], + }] + plan = eval_js('m.selectIdleRefreshPlan(JSON.parse(process.argv[2]))', outputs) + self.assertTrue(plan['valid']) + self.assertTrue(plan['supported']) + self.assertEqual(plan['output'], 'Unknown-1') + self.assertEqual(plan['activeMode'], f'1668x2224@{int(current_hz)}Hz') + self.assertEqual(plan['idleMode'], '1668x2224@24Hz') + + def test_already_at_lowest_mode_stays_supported_but_does_not_switch(self): + outputs = [{ + 'name': 'DSI-1', + 'enabled': True, + 'modes': [ + {'width': 1668, 'height': 2224, 'refresh': 60.0, 'current': False}, + {'width': 1668, 'height': 2224, 'refresh': 24.0, 'current': True}, + ], + }] + plan = eval_js('m.selectIdleRefreshPlan(JSON.parse(process.argv[2]))', outputs) + self.assertTrue(plan['valid']) + self.assertTrue(plan['supported']) + self.assertEqual(plan['idleMode'], '') + + def test_single_mode_panel_is_unsupported(self): + outputs = [{ + 'name': 'Unknown-1', + 'enabled': True, + 'modes': [ + {'width': 1536, 'height': 2048, 'refresh': 60.0, 'current': True}, + ], + }] + plan = eval_js('m.selectIdleRefreshPlan(JSON.parse(process.argv[2]))', outputs) + self.assertTrue(plan['valid']) + self.assertFalse(plan['supported']) + self.assertEqual(plan['idleMode'], '') + + def test_scans_past_single_mode_internal_connector_to_find_multi_rate_panel(self): + outputs = [ + { + 'name': 'DSI-1', + 'enabled': True, + 'modes': [{'width': 800, 'height': 600, 'refresh': 60.0, 'current': True}], + }, + { + 'name': 'eDP-1', + 'enabled': True, + 'modes': [ + {'width': 2560, 'height': 1600, 'refresh': 120.0, 'current': True}, + {'width': 2560, 'height': 1600, 'refresh': 24.0, 'current': False}, + ], + }, + ] + plan = eval_js('m.selectIdleRefreshPlan(JSON.parse(process.argv[2]))', outputs) + self.assertTrue(plan['valid']) + self.assertTrue(plan['supported']) + self.assertEqual(plan['output'], 'eDP-1') + self.assertEqual(plan['idleMode'], '2560x1600@24Hz') + + def test_ignores_external_outputs_and_sub_24hz_or_other_resolutions(self): + outputs = [ + { + 'name': 'HDMI-A-1', + 'enabled': True, + 'modes': [ + {'width': 1920, 'height': 1080, 'refresh': 60.0, 'current': True}, + {'width': 1920, 'height': 1080, 'refresh': 24.0, 'current': False}, + ], + }, + { + 'name': 'eDP-1', + 'enabled': True, + 'modes': [ + {'width': 2560, 'height': 1600, 'refresh': 59.998, 'current': True}, + {'width': 2560, 'height': 1600, 'refresh': 47.952, 'current': False}, + {'width': 2560, 'height': 1600, 'refresh': 10.0, 'current': False}, + {'width': 1280, 'height': 800, 'refresh': 24.0, 'current': False}, + ], + }, + ] + plan = eval_js('m.selectIdleRefreshPlan(JSON.parse(process.argv[2]))', outputs) + self.assertTrue(plan['valid']) + self.assertTrue(plan['supported']) + self.assertEqual(plan['output'], 'eDP-1') + self.assertEqual(plan['activeMode'], '2560x1600@59.998Hz') + self.assertEqual(plan['idleMode'], '2560x1600@47.952Hz') + + def test_invalid_or_empty_json_distinguishes_transient_absence(self): + plan = eval_js('m.selectIdleRefreshPlan(JSON.parse(process.argv[2]))', 'not valid json') + self.assertFalse(plan['valid']) + self.assertFalse(plan['hasEnabledInternal']) + self.assertFalse(plan['supported']) + + empty = eval_js('m.selectIdleRefreshPlan(JSON.parse(process.argv[2]))', []) + self.assertTrue(empty['valid']) + self.assertFalse(empty['hasEnabledInternal']) + self.assertFalse(empty['supported']) + + def test_should_restore_only_when_output_still_holds_applied_idle_mode(self): + at_24 = [{ + 'name': 'Unknown-1', + 'enabled': True, + 'modes': [ + {'width': 1668, 'height': 2224, 'refresh': 120.0, 'current': False}, + {'width': 1668, 'height': 2224, 'refresh': 24.0, 'current': True}, + ], + }] + res = eval_js( + 'm.shouldRestoreIdleRefresh(JSON.parse(process.argv[2]), "Unknown-1", "1668x2224@24Hz")', + at_24, + ) + self.assertEqual(res, {'valid': True, 'outputPresent': True, 'restore': True, 'currentMode': '1668x2224@24Hz'}) + + # User manually selected 48 Hz while idle -> output is present, preserve choice. + at_48 = [{ + 'name': 'Unknown-1', + 'enabled': True, + 'modes': [{'width': 1668, 'height': 2224, 'refresh': 48.0, 'current': True}], + }] + res2 = eval_js( + 'm.shouldRestoreIdleRefresh(JSON.parse(process.argv[2]), "Unknown-1", "1668x2224@24Hz")', + at_48, + ) + self.assertEqual(res2, {'valid': True, 'outputPresent': True, 'restore': False, 'currentMode': '1668x2224@48Hz'}) + + # Temporarily absent or disabled output -> outputPresent=False so caller retains saved mode. + disabled = [{'name': 'Unknown-1', 'enabled': False, 'modes': []}] + self.assertEqual( + eval_js('m.shouldRestoreIdleRefresh(JSON.parse(process.argv[2]), "Unknown-1", "1668x2224@24Hz")', disabled), + {'valid': True, 'outputPresent': False, 'restore': False, 'currentMode': ''}, + ) + self.assertEqual( + eval_js('m.shouldRestoreIdleRefresh(JSON.parse(process.argv[2]), "Unknown-1", "1668x2224@24Hz")', []), + {'valid': True, 'outputPresent': False, 'restore': False, 'currentMode': ''}, + ) + self.assertEqual( + eval_js('m.shouldRestoreIdleRefresh(JSON.parse(process.argv[2]), "Unknown-1", "1668x2224@24Hz")', 'bad'), + {'valid': False, 'outputPresent': False, 'restore': False, 'currentMode': ''}, + ) + + +class IdleRefreshTeardownTests(unittest.TestCase): + def run_teardown(self, responses, output, idle_mode, saved_mode, inflight, apply_codes=(0,)): + script = extract_teardown_script() + with tempfile.TemporaryDirectory() as tmp: + tmp_path = Path(tmp) + state_file = tmp_path / 'responses.json' + codes_file = tmp_path / 'codes.json' + calls_file = tmp_path / 'calls.log' + state_file.write_text(json.dumps(responses)) + codes_file.write_text(json.dumps(list(apply_codes))) + fake = tmp_path / 'wlr-randr' + fake.write_text( + '#!/usr/bin/env python3\n' + 'import json, sys\n' + f'state = {str(state_file)!r}\n' + f'codes = {str(codes_file)!r}\n' + f'log = {str(calls_file)!r}\n' + 'if sys.argv[1:] == ["--json"]:\n' + ' items = json.loads(open(state).read())\n' + ' cur = items.pop(0) if len(items) > 1 else items[0]\n' + ' open(state, "w").write(json.dumps(items))\n' + ' print(json.dumps(cur))\n' + 'else:\n' + ' with open(log, "a") as f: f.write(" ".join(sys.argv[1:]) + "\\n")\n' + ' rc_list = json.loads(open(codes).read())\n' + ' rc = rc_list.pop(0) if len(rc_list) > 1 else rc_list[0]\n' + ' open(codes, "w").write(json.dumps(rc_list))\n' + ' sys.exit(rc)\n' + ) + fake.chmod(fake.stat().st_mode | stat.S_IXUSR) + env = dict(os.environ, PATH=f'{tmp}:{os.environ.get("PATH", "")}') + subprocess.run( + ['python3', '-c', script, output, idle_mode, saved_mode, '1' if inflight else '0'], + env=env, check=True, + ) + return calls_file.read_text().splitlines() if calls_file.exists() else [] + + def test_teardown_restores_retries_failures_and_preserves_manual_mode(self): + at_24 = [{'name': 'Unknown-1', 'enabled': True, 'modes': [{'width': 1668, 'height': 2224, 'refresh': 24.0, 'current': True}]}] + at_48 = [{'name': 'Unknown-1', 'enabled': True, 'modes': [{'width': 1668, 'height': 2224, 'refresh': 48.0, 'current': True}]}] + at_120 = [{'name': 'Unknown-1', 'enabled': True, 'modes': [{'width': 1668, 'height': 2224, 'refresh': 120.0, 'current': True}]}] + + # Normal lowered teardown -> restores saved 120 Hz. + self.assertEqual( + self.run_teardown([at_24], 'Unknown-1', '1668x2224@24Hz', '1668x2224@120Hz', False), + ['--output Unknown-1 --mode 1668x2224@120Hz'], + ) + # User manually switched to 48 Hz -> teardown preserves 48 Hz. + self.assertEqual( + self.run_teardown([at_48], 'Unknown-1', '1668x2224@24Hz', '1668x2224@120Hz', False), + [], + ) + # Teardown during an in-flight lower that lands on the second poll -> restores 120 Hz. + self.assertEqual( + self.run_teardown([at_120, at_24], 'Unknown-1', '1668x2224@24Hz', '1668x2224@120Hz', True), + ['--output Unknown-1 --mode 1668x2224@120Hz'], + ) + # Rejected restore retries and succeeds on the second attempt. + self.assertEqual( + self.run_teardown([at_24, at_24], 'Unknown-1', '1668x2224@24Hz', '1668x2224@120Hz', False, apply_codes=(1, 0)), + [ + '--output Unknown-1 --mode 1668x2224@120Hz', + '--output Unknown-1 --mode 1668x2224@120Hz', + ], + ) + # Rejected restore stops retrying if a manual 48 Hz switch happens before the retry. + self.assertEqual( + self.run_teardown([at_24, at_48], 'Unknown-1', '1668x2224@24Hz', '1668x2224@120Hz', False, apply_codes=(1, 0)), + ['--output Unknown-1 --mode 1668x2224@120Hz'], + ) + + def test_service_guards_rejected_lowers_and_screen_changes(self): + text = SERVICE.read_text() + self.assertIn('readonly property bool idleRefreshEnabled: idleEnabled && idleRefreshSupported && idleRefreshTimeoutSeconds > 0', text) + self.assertIn('function retimeRefreshIdleMonitor()', text) + self.assertIn('refreshIdleMonitorRearmTimer', text) + self.assertIn('refreshLowerFailedThisIdle', text) + self.assertIn('function onScreensChanged()', text) + self.assertIn('respectInhibitors: true', text) + self.assertIn('shouldRestoreIdleRefresh', text) + + +if __name__ == '__main__': + unittest.main()