Add a Gaming page, and let the desktop react to games

Live first, because unlike every other page here this one has a live
dimension: card temperature, power draw, whether Game Mode actually
engaged. It polls only while it is open, since a settings page nobody is
looking at has no business waking the CPU.

The part that makes it Panama's page rather than a gamemode config
editor is the hook. gamemode runs a script when a game asks for it and
another when the game exits, so the power profile switches to
performance and notifications go quiet for exactly the duration of a
game -- and afterwards both go back to what they WERE, not to a default.
A Do Not Disturb someone set by hand survives a game; a power profile
someone chose is restored rather than replaced. Verified against real
gamemode activation, not merely by calling the hook.

Two things the page reports rather than hides. Game Mode's headline
trick is switching the CPU governor to performance, and this machine
already runs performance, so it says so instead of implying it helps.
And Proton builds are listed but never chosen: Steam picks the runtime
per game, and a control here would claim an authority this page does not
have.

The hook first called a notifications function that did not exist, and
the one that did was a TOGGLE -- the wrong primitive entirely, since
toggling at game start would unsilence notifications that were already
silent. The shell gained an explicit setter and reader.

search-routing-contract kept its own hand-written list of every page,
which made adding one fail as "not a known page" -- a sixth place to
register a page and a sixth chance to forget. It now derives the mapping
from the shell, which already knows it.

Claude-Session: https://claude.ai/code/session_01BRvzt4H8XXLPVH5MyYdk9L
This commit is contained in:
Gabriel Brown
2026-08-19 18:55:10 -04:00
parent edc504af2e
commit 4cbe3b882a
15 changed files with 915 additions and 26 deletions
@@ -724,6 +724,27 @@ Singleton {
hypr: { path: ["decoration", "dim_strength"], option: "decoration:dim_strength", readAs: "float" }
},
// ── Gaming ──────────────────────────────────────────────────────────
// What Panama does while a game runs. gamemode tells us when that
// starts and stops through its own hook scripts, so these are real
// behaviours rather than hints -- and each one is undone afterwards to
// whatever it was before, not to a default.
{
key: "gamingPerformanceProfile", type: "bool", def: true, group: "gaming",
label: "Use the performance power profile",
detail: "Switches while a game runs and switches back when it exits"
},
{
key: "gamingSilenceNotifications", type: "bool", def: true, group: "gaming",
label: "Silence notifications",
detail: "Do Not Disturb for the duration, so nothing steals focus mid-game. A Do Not Disturb you set yourself is left alone."
},
{
key: "gamingNotifyOnStart", type: "bool", def: false, group: "gaming",
label: "Say when Game Mode engages",
detail: "A notification when a game requests it, which is otherwise invisible"
},
// ── Night light ─────────────────────────────────────────────────────
{
key: "nightLightEnabled", type: "bool", def: false, group: "nightLight",
@@ -0,0 +1,240 @@
// Gaming: what the machine is doing now, and what it should do while you play.
//
// Live first, because unlike every other page here this one has a genuinely
// live dimension -- "is Game Mode actually on, and how hot is the card" is the
// question that brings someone here mid-session.
//
// The part that makes this Panama's page rather than a gamemode config editor
// is "While a game is running": gamemode runs a script when a game starts and
// another when it exits, so the power profile and Do Not Disturb can follow the
// game and be put back afterwards -- back to what they were, not to a default.
import Quickshell
import QtQuick
import qs.config
import qs.services
SettingsPage {
id: root
objectName: "gaming"
title: "Gaming"
lede: "What this machine is doing, and how it should behave while you play."
readonly property var gpu: Gaming.primaryGpu
// Polling only while this page is on screen.
Component.onCompleted: {
Gaming.refresh();
Gaming.watching = true;
}
Component.onDestruction: Gaming.watching = false
TextRow {
visible: Gaming.lastError !== ""
label: "Gaming needs attention"
detail: Gaming.lastError
value: ""
divider: false
}
// ── Right now ────────────────────────────────────────────────────────────
SettingsCard {
Column {
width: parent.width
spacing: 8
Row {
width: parent.width
spacing: 12
Text {
text: Gaming.active ? "Playing" : "Idle"
color: Theme.fg
font.family: Theme.fontFamily
font.pixelSize: Theme.fontSizeTitle
font.weight: Font.DemiBold
}
Text {
anchors.verticalCenter: parent.verticalCenter
text: Gaming.active
? "Game Mode is engaged"
: "No game has requested Game Mode"
color: Theme.fgDim
font.family: Theme.fontFamily
font.pixelSize: Theme.fontSize
}
}
}
Repeater {
model: Gaming.gpus
delegate: TextRow {
required property var modelData
required property int index
width: parent.width
label: modelData.discrete ? "Graphics card" : "Integrated graphics"
detail: String(modelData.driver ?? "")
+ (modelData.discrete ? " · the one games use" : " · idle unless something asks for it")
value: Gaming.gpuSummary(modelData)
divider: true
}
}
TextRow {
label: "CPU governor"
detail: "What the cores are scaling to right now"
value: String(Gaming.gameMode?.governorNow ?? "unknown")
divider: false
}
}
// ── What Panama does about it ────────────────────────────────────────────
SettingsCard {
title: "While a game is running"
subtitle: Gaming.gameMode?.hooksInstalled === true
? "Panama reacts when Game Mode engages, and puts everything back when the game exits."
: "Panama can react when Game Mode engages. This needs a hook in gamemode's configuration."
ActionRow {
visible: Gaming.gameMode?.hooksInstalled !== true
label: "Let Panama react to games"
detail: "Adds a start and end hook to your gamemode configuration. Nothing else in that file is touched."
action: "Enable"
enabled: !Gaming.busy && Gaming.gameMode?.available === true
onTriggered: Gaming.installHooks()
}
ToggleRow {
visible: Gaming.gameMode?.hooksInstalled === true
setting: "gamingPerformanceProfile"
}
ToggleRow {
visible: Gaming.gameMode?.hooksInstalled === true
setting: "gamingSilenceNotifications"
}
ToggleRow {
visible: Gaming.gameMode?.hooksInstalled === true
setting: "gamingNotifyOnStart"
}
ActionRow {
visible: Gaming.gameMode?.hooksInstalled === true
label: "Stop reacting to games"
detail: "Removes the hooks. The settings above are kept."
action: "Disable"
enabled: !Gaming.busy
divider: false
onTriggered: Gaming.removeHooks()
}
}
// ── Game Mode itself ─────────────────────────────────────────────────────
SettingsCard {
title: "Game Mode"
subtitle: Gaming.gameMode?.available === true
? "Applied by gamemode to a game while it runs, then undone."
: "gamemode is not installed."
TextRow {
label: "Daemon"
detail: Gaming.gameMode?.daemonRunning === true
? "Running, waiting for a game to ask"
: "Not running, so no game can request it"
value: Gaming.gameMode?.daemonRunning === true ? "Running" : "Stopped"
}
// Said plainly rather than implied: on a machine already running the
// governor gamemode would switch to, its headline effect is nothing.
TextRow {
label: "Governor while gaming"
detail: Gaming.governorAlreadyThere
? "This machine already runs that governor, so Game Mode changes nothing here"
: "Switched for the duration of the game"
value: String(Gaming.gameMode?.governorWhileGaming ?? "unknown")
divider: false
}
}
// ── Overlay ──────────────────────────────────────────────────────────────
SettingsCard {
title: "Performance overlay"
subtitle: Gaming.overlay?.installed === true
? "MangoHud, drawn on top of the game."
: "MangoHud is not installed."
SwitchRow {
label: "Show the overlay in games"
detail: "Takes effect for games launched after your next sign-in, because it is read from the session environment"
checked: Gaming.overlay?.globallyEnabled === true
enabled: !Gaming.busy && Gaming.overlay?.installed === true
onToggled: value => Gaming.setOverlay(value)
}
SegmentRow {
label: "What it shows"
detail: "Frame rate alone, or the full readout with GPU and CPU"
options: [
{ value: "fps", label: "Frame rate" },
{ value: "detailed", label: "Detailed" }
]
value: String(Gaming.overlay?.preset ?? "fps")
enabled: !Gaming.busy && Gaming.overlay?.installed === true
onSelected: value => Gaming.setOverlayPreset(value)
}
TextRow {
label: "Toggle in game"
detail: "Shows and hides the overlay without leaving the game"
value: String(Gaming.overlay?.toggleKey ?? "")
divider: false
}
}
// ── Library ──────────────────────────────────────────────────────────────
SettingsCard {
title: "Library"
subtitle: "Where games live, and what can run them."
TextRow {
label: "Installed games"
detail: String(Gaming.library?.path ?? "")
value: String(Gaming.library?.games ?? 0)
}
// Listed, not chosen. Steam picks the runtime per game in its own
// properties, and a control here would be claiming an authority this
// page does not have.
Repeater {
model: Gaming.library?.protonBuilds ?? []
delegate: TextRow {
required property var modelData
required property int index
width: parent.width
label: String(modelData.name ?? "")
detail: modelData.community === true
? "Community build · chosen per game in Steam"
: "Valve · chosen per game in Steam"
value: "Installed"
divider: true
}
}
TextRow {
label: "gamescope"
detail: "Micro-compositor for scaling and frame limiting, used per game from Steam"
value: Gaming.library?.gamescope === true ? "Available" : "Not installed"
divider: false
}
}
}
@@ -109,6 +109,7 @@ Rectangle {
case "home-phone": return homePhonePage;
case "desktop": return desktopPage;
case "sound": return soundPage;
case "gaming": return gamingPage;
case "notifications": return notificationsPage;
case "screen-intelligence": return screenIntelligencePage;
case "shortcuts": return shortcutsPage;
@@ -179,6 +180,7 @@ Rectangle {
Component { id: homePhonePage; HomePhonePage {} }
Component { id: desktopPage; DesktopPage {} }
Component { id: soundPage; SoundPage {} }
Component { id: gamingPage; GamingPage {} }
Component { id: notificationsPage; NotificationsPage {} }
Component { id: screenIntelligencePage; ScreenIntelligencePage {} }
Component { id: shortcutsPage; ShortcutsPage {} }
@@ -31,6 +31,7 @@ Rectangle {
{ page: "home-phone", label: "Home & Phone", icon: "\u{F02DC}" },
{ page: "desktop", label: "Desktop & Dock", icon: "\u{F04A4}" },
{ page: "sound", label: "Sound", icon: "\u{F057E}" },
{ page: "gaming", label: "Gaming", icon: "\u{F0297}" },
{ page: "notifications", label: "Notifications & Focus", icon: "\u{F009A}" },
{ page: "screen-intelligence", label: "Screen Intelligence", icon: "\u{F05A8}" },
{ page: "shortcuts", label: "Keyboard", icon: "\u{F030C}" },
@@ -3,6 +3,7 @@ AboutPage 1.0 AboutPage.qml
AppearancePage 1.0 AppearancePage.qml
AvatarPicker 1.0 AvatarPicker.qml
ConnectivityPage 1.0 ConnectivityPage.qml
GamingPage 1.0 GamingPage.qml
HomePhonePage 1.0 HomePhonePage.qml
HomeFavoriteCard 1.0 HomeFavoriteCard.qml
AvailableLightRow 1.0 AvailableLightRow.qml
+346
View File
@@ -0,0 +1,346 @@
#!/usr/bin/env python3
"""Gaming: what the machine is doing, and what it should do while you play.
The interesting part is not reporting gamemode's state -- it is reacting to it.
gamemode can run a script when a game asks for it and another when the game
exits, so `hook start` and `hook end` are what let Panama switch the power
profile and silence notifications for exactly the duration of a game, and put
both back afterwards. Everything else here is honest reporting.
panama-gaming snapshot
panama-gaming set-overlay true|false
panama-gaming set-overlay-preset fps|detailed
panama-gaming install-hooks | remove-hooks
panama-gaming hook start|end (called by gamemode, not by a person)
"""
from __future__ import annotations
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
MANGOHUD_CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "MangoHud" / "MangoHud.conf"
GAMEMODE_CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "gamemode.ini"
ENVIRONMENT_CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "environment.d" / "panama-mangohud.conf"
# What the overlay shows. Deliberately two presets rather than exposing every
# MangoHud key: this is a settings page, not a config file with a nicer font.
PRESETS = {
"fps": ["fps", "frametime=0", "no_display=0", "position=top-left",
"font_size=22", "background_alpha=0.4", "toggle_hud=Shift_R+F12"],
"detailed": ["fps", "frametime", "gpu_stats", "gpu_temp", "gpu_power",
"cpu_stats", "cpu_temp", "ram", "vram", "position=top-left",
"font_size=20", "background_alpha=0.4", "toggle_hud=Shift_R+F12"],
}
class BoundaryError(RuntimeError):
"""A user-visible failure."""
def run(command: list[str], timeout: float = 20.0) -> subprocess.CompletedProcess:
try:
return subprocess.run(command, capture_output=True, text=True,
timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as error:
raise BoundaryError(f"{command[0]} did not answer.") from error
def read_int(path: Path) -> int | None:
try:
return int(path.read_text().strip())
except (OSError, ValueError):
return None
def gpus() -> list[dict]:
"""Every AMD/Intel GPU with a hwmon node, warmest first.
Read from sysfs rather than a tool: it costs nothing, needs no daemon, and
a page that polls while it is open should not be spawning processes.
"""
found = []
for hwmon in sorted(Path("/sys/class/hwmon").glob("hwmon*")):
try:
name = (hwmon / "name").read_text().strip()
except OSError:
continue
if name not in ("amdgpu", "i915", "xe", "nouveau"):
continue
device = (hwmon / "device").resolve()
temperature = read_int(hwmon / "temp1_input")
power = read_int(hwmon / "power1_average")
used = read_int(device / "mem_info_vram_used")
total = read_int(device / "mem_info_vram_total")
model = ""
try:
model = (device / "product_name").read_text().strip()
except OSError:
model = ""
found.append({
"driver": name,
"model": model,
"temperatureC": round(temperature / 1000, 1) if temperature else None,
"watts": round(power / 1000000, 1) if power else None,
"vramUsedBytes": used or 0,
"vramTotalBytes": total or 0,
# A card with no VRAM reported is the integrated one sharing system
# memory; saying "0 of 0 GB" would look broken.
"discrete": bool(total and total > 1073741824),
})
found.sort(key=lambda entry: (not entry["discrete"], entry["driver"]))
return found
def governor() -> str:
try:
return Path("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor").read_text().strip()
except OSError:
return ""
def game_mode() -> dict:
available = bool(shutil.which("gamemoded"))
state = {"available": available, "active": False, "daemonRunning": False,
"governorWhileGaming": "", "governorNow": governor()}
if not available:
return state
status = run(["gamemoded", "-s"]).stdout.strip()
state["active"] = "is active" in status
state["daemonRunning"] = "gamemode is" in status
# What it would switch the governor to, from its own configuration.
for path in (GAMEMODE_CONFIG, Path("/usr/share/gamemode/gamemode.ini")):
try:
text = path.read_text()
except OSError:
continue
found = re.search(r"^\s*desiredgov\s*=\s*(\S+)", text, re.M)
if found:
state["governorWhileGaming"] = found.group(1)
break
return state
def hooks_installed() -> bool:
try:
text = GAMEMODE_CONFIG.read_text()
except OSError:
return False
return "panama-gaming hook start" in text
def overlay() -> dict:
installed = bool(shutil.which("mangohud"))
preset = ""
if MANGOHUD_CONFIG.is_file():
try:
body = MANGOHUD_CONFIG.read_text()
preset = "detailed" if "gpu_stats" in body else "fps"
except OSError:
preset = ""
return {
"installed": installed,
"configured": MANGOHUD_CONFIG.is_file(),
"preset": preset or "fps",
# Global enablement is an environment variable read at session start, so
# a change here does not affect anything already running.
"globallyEnabled": ENVIRONMENT_CONFIG.is_file(),
"toggleKey": "Shift_R+F12",
}
def library() -> dict:
root = Path.home() / ".local/share/Steam"
games = len(list((root / "steamapps").glob("*.acf"))) if (root / "steamapps").is_dir() else 0
tools = []
for directory in (root / "compatibilitytools.d", root / "steamapps/common"):
if not directory.is_dir():
continue
for entry in sorted(directory.iterdir()):
if entry.is_dir() and entry.name.lower().startswith("proton"):
tools.append({
"name": entry.name,
"community": directory.name == "compatibilitytools.d",
})
return {
"path": str(root),
"games": games,
"protonBuilds": tools,
"gamescope": bool(shutil.which("gamescope")),
"steam": bool(shutil.which("steam")),
}
def snapshot() -> dict:
return {
"gameMode": {**game_mode(), "hooksInstalled": hooks_installed()},
"gpus": gpus(),
"overlay": overlay(),
"library": library(),
"error": "",
}
def set_overlay_preset(preset: str) -> None:
if preset not in PRESETS:
raise BoundaryError("That is not an overlay preset.")
MANGOHUD_CONFIG.parent.mkdir(parents=True, exist_ok=True)
header = ("# Written by Panama's Gaming settings.\n"
"# Edits here are replaced when the preset changes.\n")
MANGOHUD_CONFIG.write_text(header + "\n".join(PRESETS[preset]) + "\n", encoding="utf-8")
def set_overlay(enabled: bool) -> None:
if not shutil.which("mangohud"):
raise BoundaryError("MangoHud is not installed.")
if enabled:
if not MANGOHUD_CONFIG.is_file():
set_overlay_preset("fps")
ENVIRONMENT_CONFIG.parent.mkdir(parents=True, exist_ok=True)
ENVIRONMENT_CONFIG.write_text(
"# Written by Panama's Gaming settings.\n"
"# Read when the session starts, so this reaches applications\n"
"# launched afterwards rather than ones already running.\n"
"MANGOHUD=1\n", encoding="utf-8")
else:
try:
ENVIRONMENT_CONFIG.unlink()
except OSError:
pass
def install_hooks() -> None:
"""Point gamemode's start and end hooks at this script.
Written by editing rather than replacing: gamemode.ini is the user's file
and may hold settings this page does not manage.
"""
script = str(Path(__file__).resolve())
lines = []
if GAMEMODE_CONFIG.is_file():
lines = [line for line in GAMEMODE_CONFIG.read_text().splitlines()
if "panama-gaming hook" not in line]
text = "\n".join(lines)
if "[custom]" not in text:
text += "\n\n[custom]\n"
text = re.sub(r"\[custom\]\n",
f"[custom]\nstart={script} hook start\nend={script} hook end\n",
text, count=1)
GAMEMODE_CONFIG.parent.mkdir(parents=True, exist_ok=True)
GAMEMODE_CONFIG.write_text(text.strip() + "\n", encoding="utf-8")
def remove_hooks() -> None:
if not GAMEMODE_CONFIG.is_file():
return
lines = [line for line in GAMEMODE_CONFIG.read_text().splitlines()
if "panama-gaming hook" not in line]
GAMEMODE_CONFIG.write_text("\n".join(lines).strip() + "\n", encoding="utf-8")
def hook(phase: str) -> None:
"""Called by gamemode when a game starts and when it stops.
Reads what the user asked for from the settings file directly: the shell may
not be running, and a hook that depends on a running shell would silently do
nothing for someone who restarted it mid-session.
"""
if phase not in ("start", "end"):
raise BoundaryError("That is not a hook phase.")
settings_path = (Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
/ "panama" / "settings.json")
try:
settings = json.loads(settings_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
settings = {}
scripts = Path(__file__).resolve().parent
# What was true before the game started, so ending it restores that rather
# than imposing a default. Without this, finishing a game would silently
# undo a power profile or a Do Not Disturb the user had chosen themselves.
state_path = Path(os.environ.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")) / "panama-gaming.json"
if phase == "start":
before = {}
if settings.get("gamingPerformanceProfile", True):
current = run([str(scripts / "panama-power-profile"), "list"], timeout=15)
try:
before["profile"] = json.loads(current.stdout or "{}").get("active", "")
except json.JSONDecodeError:
before["profile"] = ""
run([str(scripts / "panama-power-profile"), "set", "performance"], timeout=15)
if settings.get("gamingSilenceNotifications", True) and shutil.which("qs"):
was_silent = run(["qs", "ipc", "call", "notifications", "dndState"],
timeout=10).stdout.strip() == "true"
before["silenced"] = was_silent
if not was_silent:
run(["qs", "ipc", "call", "notifications", "setDnd", "true"], timeout=10)
try:
state_path.write_text(json.dumps(before), encoding="utf-8")
except OSError:
pass
if settings.get("gamingNotifyOnStart", False) and shutil.which("notify-send"):
run(["notify-send", "-a", "Panama", "Game Mode",
"Performance profile engaged, notifications silenced."], timeout=10)
return
# end
try:
before = json.loads(state_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
before = {}
if before.get("profile"):
run([str(scripts / "panama-power-profile"), "set", before["profile"]], timeout=15)
# Only un-silence if this turned it on.
if before.get("silenced") is False and shutil.which("qs"):
run(["qs", "ipc", "call", "notifications", "setDnd", "false"], timeout=10)
try:
state_path.unlink()
except OSError:
pass
def main(arguments: list[str]) -> int:
try:
if arguments == ["snapshot"]:
print(json.dumps(snapshot(), separators=(",", ":")))
return 0
if len(arguments) == 2 and arguments[0] == "hook":
hook(arguments[1])
return 0
if len(arguments) == 2 and arguments[0] == "set-overlay":
set_overlay(arguments[1] == "true")
elif len(arguments) == 2 and arguments[0] == "set-overlay-preset":
set_overlay_preset(arguments[1])
elif arguments == ["install-hooks"]:
install_hooks()
elif arguments == ["remove-hooks"]:
remove_hooks()
else:
raise BoundaryError(
"Usage: panama-gaming snapshot | set-overlay true|false | "
"set-overlay-preset fps|detailed | install-hooks | remove-hooks | "
"hook start|end")
except BoundaryError as error:
state = snapshot()
state["error"] = str(error)
print(json.dumps(state, separators=(",", ":")))
return 0
print(json.dumps(snapshot(), separators=(",", ":")))
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
+129
View File
@@ -0,0 +1,129 @@
pragma Singleton
// Gaming: what the machine is doing, and what it should do while you play.
//
// The reporting half is cheap -- GPU sensors come from sysfs, gamemode from its
// own daemon -- so this can poll while its page is open. It only polls then:
// a settings page nobody is looking at has no business waking the CPU twice a
// second.
//
// The acting half is not in this file at all. gamemode runs a script when a
// game starts and another when it exits, and that script reads the preferences
// directly, because the shell may have been restarted since the game launched.
import Quickshell
import Quickshell.Io
import QtQuick
Singleton {
id: root
readonly property string helperPath: Quickshell.shellDir + "/scripts/panama-gaming"
property var gameMode: ({})
property var gpus: []
property var overlay: ({})
property var library: ({})
property bool scanned: false
property string lastError: ""
// Set by the page while it is visible. Nothing polls otherwise.
property bool watching: false
readonly property bool busy: query.running || mutation.running
readonly property bool active: root.gameMode?.active === true
readonly property var primaryGpu: {
for (const gpu of root.gpus) {
if (gpu.discrete)
return gpu;
}
return root.gpus.length > 0 ? root.gpus[0] : null;
}
// The honest version: gamemode's headline trick is switching the governor,
// and it does nothing if the machine already runs that governor.
readonly property bool governorAlreadyThere:
String(root.gameMode?.governorNow ?? "") !== ""
&& root.gameMode?.governorNow === root.gameMode?.governorWhileGaming
function formatBytes(bytes: real): string {
if (!(bytes > 0))
return "0 GB";
return (bytes / 1073741824).toFixed(bytes < 10737418240 ? 1 : 0) + " GB";
}
function gpuSummary(gpu: var): string {
if (!gpu)
return "";
const parts = [];
if (gpu.temperatureC !== null && gpu.temperatureC !== undefined)
parts.push(gpu.temperatureC + " °C");
if (gpu.watts !== null && gpu.watts !== undefined && gpu.watts > 0)
parts.push(gpu.watts + " W");
if (Number(gpu.vramTotalBytes ?? 0) > 0)
parts.push(root.formatBytes(gpu.vramUsedBytes) + " / "
+ root.formatBytes(gpu.vramTotalBytes));
return parts.join(" · ");
}
function refresh(): void {
if (query.running)
return;
query.command = [root.helperPath, "snapshot"];
query.running = true;
}
function absorb(text: string): void {
try {
const parsed = JSON.parse(text);
root.gameMode = parsed.gameMode ?? ({});
root.gpus = Array.isArray(parsed.gpus) ? parsed.gpus : [];
root.overlay = parsed.overlay ?? ({});
root.library = parsed.library ?? ({});
root.lastError = String(parsed.error ?? "");
} catch (error) {
root.lastError = "Could not read the gaming helper's answer.";
console.warn("Gaming: could not parse helper output:", error);
}
root.scanned = true;
}
function run(arguments: var): void {
if (mutation.running)
return;
root.lastError = "";
mutation.command = [root.helperPath].concat(arguments);
mutation.running = true;
}
function setOverlay(enabled: bool): void { root.run(["set-overlay", enabled ? "true" : "false"]); }
function setOverlayPreset(preset: string): void { root.run(["set-overlay-preset", preset]); }
function installHooks(): void { root.run(["install-hooks"]); }
function removeHooks(): void { root.run(["remove-hooks"]); }
Process {
id: query
stdout: StdioCollector { onStreamFinished: root.absorb(this.text) }
stderr: StdioCollector {
onStreamFinished: if (this.text.trim() !== "") root.lastError = this.text.trim()
}
}
Process {
id: mutation
stdout: StdioCollector { onStreamFinished: root.absorb(this.text) }
stderr: StdioCollector {
onStreamFinished: if (this.text.trim() !== "") root.lastError = this.text.trim()
}
}
// Three seconds: fast enough that a temperature reading feels live, slow
// enough that it is not a background task of its own.
Timer {
running: root.watching
interval: 3000
repeat: true
onTriggered: root.refresh()
}
}
@@ -51,7 +51,8 @@ Singleton {
"notices": "desktop",
"weather": "home",
"notifications": "notifications",
"capture": "screen-intelligence"
"capture": "screen-intelligence",
"gaming": "gaming"
})
// Settings that are real but have no schema entry, because the system owns
@@ -78,6 +79,10 @@ Singleton {
{ label: "Remote desktop", detail: "See and control this desktop from elsewhere", page: "sharing" },
{ label: "Network name", detail: "The name other machines see", page: "sharing" },
{ label: "File sharing", detail: "Share folders on the network", page: "sharing" },
{ label: "Game Mode", detail: "What happens while a game is running", page: "gaming" },
{ label: "Performance overlay", detail: "Frame rate and sensors on top of the game", page: "gaming" },
{ label: "Proton", detail: "Compatibility tools available to Steam", page: "gaming" },
{ label: "Graphics card", detail: "Temperature, power draw, and video memory", page: "gaming" },
{ label: "Software update", detail: "Packages, applications, and firmware", page: "updates" },
{ label: "Updates", detail: "What is waiting to be installed", page: "updates" },
{ label: "Firmware", detail: "Updates for the hardware itself", page: "updates" },
@@ -92,7 +92,7 @@ Singleton {
}
function openSettings(page: string): void {
const allowed = ["home", "appearance", "displays", "connectivity", "home-phone", "desktop", "sound", "notifications", "screen-intelligence", "shortcuts", "mouse", "privacy", "region", "accounts", "accessibility", "power", "datetime", "applications", "updates", "storage", "snapshots", "users", "sharing", "printers", "services", "about"];
const allowed = ["home", "appearance", "displays", "connectivity", "home-phone", "desktop", "sound", "gaming", "notifications", "screen-intelligence", "shortcuts", "mouse", "privacy", "region", "accounts", "accessibility", "power", "datetime", "applications", "updates", "storage", "snapshots", "users", "sharing", "printers", "services", "about"];
root.settingsPage = allowed.indexOf(page) >= 0 ? page : "home";
DesktopPreferences.set("lastPage", root.settingsPage);
root.settingsOpen = true;
+10
View File
@@ -467,6 +467,16 @@ ShellRoot {
Notifs.doNotDisturb = !Notifs.doNotDisturb;
return Notifs.doNotDisturb;
}
// Explicit set and read, which a script needs. A toggle is the wrong
// primitive for "silence while a game runs": if notifications were
// already silenced, toggling at game start would UNsilence them.
function setDnd(enabled: bool): bool {
Notifs.doNotDisturb = enabled;
return Notifs.doNotDisturb;
}
function dndState(): bool { return Notifs.doNotDisturb; }
}
IpcHandler {