Debian Codegraph @

s_tui/power_profile_menu.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #
3 # Copyright (C) 2017-2025 Alex Manuskin, Gil Tsuker
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
18
19 """A menu to view and change CPU governor and energy performance preference."""
20
21 from __future__ import annotations
22
23 import glob
24 import logging
25 import subprocess
26 from collections.abc import Callable
27
28 import urwid
29
30 from s_tui.helper_functions import cat
31 from s_tui.sturwid.ui_elements import ViListBox
32
33 # Sysfs paths (cpu0 used for reading available options and current state)
34 SYSFS_AVAIL_GOVERNORS = (
35 "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"
36 )
37 SYSFS_GOVERNOR = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor"
38 SYSFS_AVAIL_EPP = (
39 "/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_available_preferences"
40 )
41 SYSFS_EPP = "/sys/devices/system/cpu/cpu0/cpufreq/energy_performance_preference"
42
43 # Glob patterns for writing to all cores
44 _SYSFS_ALL_GOVERNORS = "/sys/devices/system/cpu/cpu*/cpufreq/scaling_governor"
45 _SYSFS_ALL_EPP = "/sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference"
46
47 # Mapping from EPP sysfs value to powerprofilesctl profile name
48 _EPP_TO_PROFILE = {
49 "performance": "performance",
50 "balance_performance": "balanced",
51 "power": "power-saver",
52 }
53
54
55 def read_available(path: str) -> list[str]:
56 """Read space-separated values from a sysfs file, return empty list on failure."""
57 try:
58 return cat(path, binary=False).split()
59 except OSError:
60 return []
61
62
63 def _read_current(path: str) -> str:
64 """Read the current value from a sysfs file."""
65 try:
66 return cat(path, binary=False).strip()
67 except OSError:
68 return ""
69
70
71 def _write_all_cores(pattern: str, value: str) -> None:
72 """Write a value to all matching sysfs paths (requires root)."""
73 paths = sorted(glob.glob(pattern))
74 if not paths:
75 raise OSError(f"No sysfs paths found for {pattern}")
76 errors: list[OSError] = []
77 for path in paths:
78 try:
79 with open(path, "w") as f:
80 f.write(value)
81 except OSError as e:
82 errors.append(e)
83 if errors:
84 # Some cores may transiently report "busy" even though the write
85 # propagated successfully. Verify by reading cpu0's current value.
86 actual = _read_current(paths[0]).strip()
87 if actual == value:
88 logging.debug(
89 "%d/%d cores reported errors writing '%s', "
90 "but value applied successfully",
91 len(errors),
92 len(paths),
93 value,
94 )
95 return
96 # Produce a short message when all cores fail with the same reason
97 reasons = {e.strerror or str(e) for e in errors}
98 if len(reasons) == 1:
99 reason = reasons.pop()
100 raise OSError(f"{reason} (all {len(errors)} cores)")
101 raise OSError("; ".join(f"{e.filename}: {e}" for e in errors))
102
103
104 def _set_epp_via_powerprofilesctl(exe: str, epp_value: str) -> None:
105 """Set EPP using powerprofilesctl. Raises OSError on failure."""
106 profile = _EPP_TO_PROFILE.get(epp_value)
107 if profile is None:
108 raise OSError(
109 f"No powerprofilesctl mapping for '{epp_value}', "
110 f"direct sysfs write required"
111 )
112 try:
113 result = subprocess.run(
114 [exe, "set", profile],
115 capture_output=True,
116 text=True,
117 timeout=5,
118 )
119 except subprocess.TimeoutExpired as exc:
120 raise OSError(f"powerprofilesctl timed out setting '{profile}'") from exc
121 if result.returncode != 0:
122 stderr = result.stderr.strip().lower()
123 if "busy" in stderr:
124 gov = _read_current(SYSFS_GOVERNOR) or "unknown"
125 raise OSError(f"Cannot change EPP (governor: {gov})")
126 raise OSError(f"powerprofilesctl set {profile} failed")
127
128
129 class PowerProfileMenu:
130 MAX_TITLE_LEN = 50
131
132 def __init__(
133 self,
134 return_fn: Callable[[], None],
135 powerprofilesctl_exe: str | None,
136 can_write_governor: bool,
137 can_write_epp: bool,
138 available_governors: list[str] | None = None,
139 available_epp: list[str] | None = None,
140 ) -> None:
141 self.return_fn = return_fn
142 self.powerprofilesctl_exe = powerprofilesctl_exe
143 self.can_write_governor = can_write_governor
144 self.can_write_epp = can_write_epp
145
146 # Read available options if not provided
147 self.available_governors = (
148 available_governors
149 if available_governors is not None
150 else read_available(SYSFS_AVAIL_GOVERNORS)
151 )
152 self.available_epp = (
153 available_epp
154 if available_epp is not None
155 else read_available(SYSFS_AVAIL_EPP)
156 )
157
158 # Determine what's controllable
159 self.governor_controllable = (
160 can_write_governor and len(self.available_governors) > 1
161 )
162 self.epp_controllable = (
163 can_write_epp or powerprofilesctl_exe is not None
164 ) and len(self.available_epp) > 0
165
166 # Status message area
167 self.status_text = urwid.Text("")
168
169 # Build UI
170 self.titles: list[urwid.Widget] = []
171 self._build_ui()
172
173 self.main_window = urwid.LineBox(
174 ViListBox(urwid.SimpleFocusListWalker(self.titles)),
175 title="Power Profile",
176 )
177
178 def _build_ui(self) -> None:
179 title = urwid.Text(("bold text", " Power Profile \n"), "center")
180 self.titles = [title]
181
182 # Governor section
183 self.governor_group: list[urwid.RadioButton] = []
184 self.governor_buttons: list[urwid.AttrMap] = []
185 if len(self.available_governors) > 1:
186 self.titles.append(urwid.Text(("bold text", "Governor"), align="center"))
187 if self.governor_controllable:
188 current_gov = _read_current(SYSFS_GOVERNOR)
189 for gov in self.available_governors:
190 w = urwid.RadioButton(
191 self.governor_group, gov, state=(gov == current_gov)
192 )
193 am = urwid.AttrMap(w, "button normal", "button select")
194 self.governor_buttons.append(am)
195 self.titles.append(am)
196 else:
197 current_gov = _read_current(SYSFS_GOVERNOR)
198 for gov in self.available_governors:
199 marker = " *" if gov == current_gov else ""
200 self.titles.append(urwid.Text(f" {gov}{marker}"))
201 self.titles.append(
202 urwid.Text(("high temp txt", " (read-only, needs root)"))
203 )
204 self.titles.append(urwid.Divider())
205
206 # EPP section
207 self.epp_group: list[urwid.RadioButton] = []
208 self.epp_buttons: list[urwid.AttrMap] = []
209 if len(self.available_epp) > 0:
210 self.titles.append(urwid.Text(("bold text", "Energy Pref"), align="center"))
211 if self.epp_controllable:
212 current_epp = _read_current(SYSFS_EPP)
213 for epp in self.available_epp:
214 w = urwid.RadioButton(
215 self.epp_group, epp, state=(epp == current_epp)
216 )
217 am = urwid.AttrMap(w, "button normal", "button select")
218 self.epp_buttons.append(am)
219 self.titles.append(am)
220 else:
221 current_epp = _read_current(SYSFS_EPP)
222 for epp in self.available_epp:
223 marker = " *" if epp == current_epp else ""
224 self.titles.append(urwid.Text(f" {epp}{marker}"))
225 self.titles.append(urwid.Text(("high temp txt", " (read-only)")))
226 self.titles.append(urwid.Divider())
227
228 # Status + buttons
229 self.titles.append(self.status_text)
230
231 apply_button = urwid.Button("Apply", on_press=self.on_apply)
232 apply_button._label.align = "center"
233 cancel_button = urwid.Button("Cancel", on_press=self.on_cancel)
234 cancel_button._label.align = "center"
235 self.titles.append(urwid.Columns([apply_button, cancel_button]))
236
237 def get_size(self) -> tuple[int, int]:
238 return len(self.titles) + 5, self.MAX_TITLE_LEN
239
240 def is_controllable(self) -> bool:
241 """Return True if at least one section is controllable."""
242 return self.governor_controllable or self.epp_controllable
243
244 def refresh_state(self) -> None:
245 """Re-read current governor/EPP from sysfs and update radio buttons."""
246 if self.governor_controllable:
247 current_gov = _read_current(SYSFS_GOVERNOR)
248 for btn_map in self.governor_buttons:
249 rb = btn_map.original_widget
250 rb.set_state(rb.label == current_gov, do_callback=False)
251
252 if self.epp_controllable:
253 current_epp = _read_current(SYSFS_EPP)
254 for btn_map in self.epp_buttons:
255 rb = btn_map.original_widget
256 rb.set_state(rb.label == current_epp, do_callback=False)
257
258 self.status_text.set_text("")
259
260 def _get_selected_governor(self) -> str | None:
261 """Return the currently selected governor radio button label."""
262 for rb in self.governor_group:
263 if rb.state:
264 return rb.label
265 return None
266
267 def _get_selected_epp(self) -> str | None:
268 """Return the currently selected EPP radio button label."""
269 for rb in self.epp_group:
270 if rb.state:
271 return rb.label
272 return None
273
274 def on_apply(self, _: object) -> None:
275 """Apply the selected governor and/or EPP."""
276 errors = []
277
278 # Apply governor
279 if self.governor_controllable:
280 gov = self._get_selected_governor()
281 if gov:
282 try:
283 _write_all_cores(_SYSFS_ALL_GOVERNORS, gov)
284 logging.info("Set governor to %s", gov)
285 except OSError as e:
286 logging.debug("Failed to set governor: %s", e)
287 errors.append(str(e))
288
289 # Apply EPP
290 if self.epp_controllable:
291 epp = self._get_selected_epp()
292 if epp:
293 try:
294 self._apply_epp(epp)
295 logging.info("Set EPP to %s", epp)
296 except OSError as e:
297 logging.debug("Failed to set EPP: %s", e)
298 errors.append(str(e))
299
300 if errors:
301 self.status_text.set_text(("high temp txt", "\n".join(errors)))
302 else:
303 self.status_text.set_text("")
304 self.return_fn()
305
306 def _apply_epp(self, epp: str) -> None:
307 """Apply EPP value using the best available method."""
308 # Prefer powerprofilesctl if available and EPP maps to a profile
309 if self.powerprofilesctl_exe and epp in _EPP_TO_PROFILE:
310 try:
311 _set_epp_via_powerprofilesctl(self.powerprofilesctl_exe, epp)
312 return
313 except OSError:
314 if self.can_write_epp:
315 logging.debug("powerprofilesctl failed, falling back to sysfs")
316 else:
317 raise
318 # Fall back to direct sysfs write
319 if self.can_write_epp:
320 _write_all_cores(_SYSFS_ALL_EPP, epp)
321 return
322 raise OSError(
323 f"Cannot set EPP to '{epp}': no powerprofilesctl mapping "
324 f"and no sysfs write permission"
325 )
326
327 def on_cancel(self, _: object) -> None:
328 """Reset radio buttons to current state and close."""
329 self.refresh_state()
330 self.return_fn()