Add a manual Game Mode Control Center tile
Turns off animations, blur, shadows and HyprGlass, switches to the performance power profile and turns on Do Not Disturb, each optional in Settings > Power. The helper journals the values it changes per Hyprland session and restores them exactly, also after a shell crash. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9e1ac4efe7
commit
bfbfc8961e
15 files changed
+325
-1
No files matched your search
@@ -181,6 +181,10 @@
|
||||
"id": "profiles",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"id": "gameMode",
|
||||
"enabled": true
|
||||
},
|
||||
{
|
||||
"id": "output",
|
||||
"enabled": true
|
||||
@@ -211,6 +215,11 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"gameMode": {
|
||||
"effects": true,
|
||||
"doNotDisturb": true,
|
||||
"performance": true
|
||||
},
|
||||
"launcher": {
|
||||
"recentFiles": false,
|
||||
"width": 680,
|
||||
|
||||
@@ -100,6 +100,13 @@ Singleton {
|
||||
h: 1,
|
||||
source: Qt.resolvedUrl("modules/Caffeine.qml")
|
||||
},
|
||||
gameMode: {
|
||||
title: "Game Mode",
|
||||
glyph: "",
|
||||
w: 2,
|
||||
h: 1,
|
||||
source: Qt.resolvedUrl("modules/GameMode.qml")
|
||||
},
|
||||
profiles: {
|
||||
title: "Power profile",
|
||||
glyph: "",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
pragma ComponentBehavior: Bound
|
||||
import QtQuick
|
||||
import ".."
|
||||
import "../../services"
|
||||
|
||||
// Game Mode switch; right click opens its options in Settings → Power.
|
||||
CCTile {
|
||||
objectName: "gameModeToggle"
|
||||
title: "Game Mode"
|
||||
detail: GameModeService.error ? GameModeService.error : GameModeService.active ? "On" : "Off"
|
||||
page: "power"
|
||||
glyph: ""
|
||||
fallback: "G"
|
||||
checked: GameModeService.active
|
||||
onClicked: GameModeService.toggle()
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Game Mode system side: turn animations, blur, shadows and HyprGlass off and
|
||||
switch to the performance power profile, remembering the live values in a
|
||||
journal so they come back exactly, even after a shell crash. Options Hyprland
|
||||
does not have (no HyprGlass) and a missing power-profiles-daemon are skipped."""
|
||||
import json,os,subprocess,sys
|
||||
from pathlib import Path
|
||||
|
||||
KEYS=['animations:enabled','decoration:blur:enabled','decoration:shadow:enabled','plugin:hyprglass:enabled']
|
||||
|
||||
|
||||
def run(args):
|
||||
p=subprocess.run(['hyprctl',*args],text=True,capture_output=True,timeout=4)
|
||||
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
|
||||
return p.stdout.strip()
|
||||
|
||||
def get_many(keys):
|
||||
# Missing options (an unloaded plugin) are left out.
|
||||
out=run(['-j','--batch',';'.join('getoption '+k for k in keys)])
|
||||
decoder,pos,found=json.JSONDecoder(),0,{}
|
||||
while pos<len(out):
|
||||
while pos<len(out) and out[pos].isspace():pos+=1
|
||||
if pos>=len(out):break
|
||||
try:data,pos=decoder.raw_decode(out,pos)
|
||||
except ValueError:
|
||||
# Non-JSON error text for a missing option: skip to the next object.
|
||||
nxt=out.find('{',pos+1)
|
||||
if nxt<0:break
|
||||
pos=nxt;continue
|
||||
if isinstance(data,dict) and 'int' in data:found[str(data.get('option',''))]=data['int']
|
||||
return {k:found[k] for k in keys if k in found}
|
||||
|
||||
def put_many(values):
|
||||
if not values:return
|
||||
out=run(['--batch',';'.join('keyword %s %d'%(k,v) for k,v in values.items())])
|
||||
bad=[line for line in out.splitlines() if line.strip() and line.strip()!='ok']
|
||||
if bad:raise ValueError(bad[0][:350])
|
||||
|
||||
PROFILES=('net.hadess.PowerProfiles','/net/hadess/PowerProfiles','net.hadess.PowerProfiles')
|
||||
|
||||
def busctl(*args):
|
||||
p=subprocess.run(['busctl','--system','--auto-start=no','--timeout=3','--json=short',*args],text=True,capture_output=True,timeout=5)
|
||||
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
|
||||
return json.loads(p.stdout)['data'] if p.stdout.strip() else None
|
||||
|
||||
def get_profile():
|
||||
"""The active profile, or None without power-profiles-daemon or a performance profile."""
|
||||
try:
|
||||
names=[p['Profile']['data'] for p in busctl('get-property',*PROFILES,'Profiles')]
|
||||
return busctl('get-property',*PROFILES,'ActiveProfile') if 'performance' in names else None
|
||||
except (ValueError,KeyError,TypeError,subprocess.TimeoutExpired):return None
|
||||
|
||||
def set_profile(name):
|
||||
p=subprocess.run(['busctl','--system','--auto-start=no','--timeout=3','set-property',*PROFILES,'ActiveProfile','s',name],text=True,capture_output=True,timeout=5)
|
||||
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
|
||||
|
||||
def journal_path():
|
||||
# Per Hyprland session: a journal from an older session is never applied.
|
||||
sig=os.environ.get('HYPRLAND_INSTANCE_SIGNATURE','none')
|
||||
return Path(os.environ.get('XDG_STATE_HOME',Path.home()/'.local/state'))/('glassMxrph/gamemode-%s.json'%sig)
|
||||
|
||||
def dispatch(req):
|
||||
path=journal_path();action=req.get('action')
|
||||
if action=='on':
|
||||
if not path.exists():
|
||||
saved={'keywords':get_many(KEYS) if req.get('effects',True) else {},
|
||||
'profile':get_profile() if req.get('performance',True) else None}
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
temp=path.with_suffix('.tmp');temp.write_text(json.dumps(saved));temp.replace(path)
|
||||
saved=json.loads(path.read_text())
|
||||
put_many({k:0 for k in saved['keywords']})
|
||||
if saved['profile'] and saved['profile']!='performance':set_profile('performance')
|
||||
return dict(active=True)
|
||||
if action=='off':
|
||||
if path.exists():
|
||||
saved=json.loads(path.read_text())
|
||||
put_many(saved['keywords'])
|
||||
if saved['profile'] and saved['profile']!='performance':set_profile(saved['profile'])
|
||||
path.unlink()
|
||||
return dict(active=False)
|
||||
if action=='status':
|
||||
return dict(active=path.exists())
|
||||
raise ValueError('Unknown Game Mode action')
|
||||
|
||||
if __name__=='__main__':
|
||||
try:print(json.dumps(dict(ok=True,**dispatch(json.loads(sys.argv[1])))))
|
||||
except (OSError,ValueError,KeyError,subprocess.TimeoutExpired) as e:print(json.dumps(dict(ok=False,error=str(e))))
|
||||
@@ -88,6 +88,7 @@ function validate(c) {
|
||||
const notes=c.notifications;
|
||||
if(!notes || ["enabled","doNotDisturb","criticalInDnd"].some(k=>typeof notes[k]!=="boolean") || !["slide","drop","fade","shrink"].includes(notes.animation) || !["top-right","top-center"].includes(notes.position) || !Number.isInteger(notes.timeout) || notes.timeout<1000 || notes.timeout>30000 || !Number.isInteger(notes.maxPopups) || notes.maxPopups<1 || notes.maxPopups>6)throw Error("Invalid notification preferences");
|
||||
if(c.controlCenter.version !== 2 || !Number.isFinite(c.controlCenter.width) || c.controlCenter.width < 320 || c.controlCenter.width > 600 || !Array.isArray(c.controlCenter.modules))throw Error("Invalid Control Center configuration");
|
||||
if(!c.gameMode || ["effects","doNotDisturb","performance"].some(k=>typeof c.gameMode[k]!=="boolean"))throw Error("Invalid Game Mode preferences");
|
||||
const controlIds=new Set();
|
||||
for(const m of c.controlCenter.modules) { if(!m || typeof m.id!=="string" || controlIds.has(m.id) || typeof m.enabled!=="boolean" || ["w","h"].some(k=>m[k]!==undefined && (!Number.isInteger(m[k]) || m[k]<1 || m[k]>4)) || [["x",3],["y",63]].some(([k,max])=>m[k]!==undefined && (!Number.isInteger(m[k]) || m[k]<0 || m[k]>max)))throw Error("Invalid Control Center module"); controlIds.add(m.id); }
|
||||
for(const group of [c.system.brightness,c.system.nightLight]) for(const key of ["statusCommand","setCommand"])if(!Array.isArray(group[key]) || group[key].some(v=>typeof v!=="string" || !v.length))throw Error("Provider command must be an argument array");
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
pragma Singleton
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import Quickshell.Io
|
||||
|
||||
// Game Mode: compositor effects off, performance power profile and Do Not
|
||||
// Disturb while gaming, switched by hand. The helper journals what it changed,
|
||||
// so effects and the profile come back even after a shell crash.
|
||||
Singleton {
|
||||
id: root
|
||||
property string helper: "helpers/gamemode.py"
|
||||
property bool active: false
|
||||
property string error: ""
|
||||
readonly property var options: ConfigService.ready ? ConfigService.data.gameMode : ({
|
||||
effects: true,
|
||||
doNotDisturb: true,
|
||||
performance: true
|
||||
})
|
||||
// What is applied right now, and the DND state to put back.
|
||||
property bool applied: false
|
||||
property var restoreDnd: null
|
||||
function toggle() {
|
||||
active = !active;
|
||||
return true;
|
||||
}
|
||||
// Debounced, so quick double clicks settle on the last state.
|
||||
onActiveChanged: sync.restart()
|
||||
Timer {
|
||||
id: sync
|
||||
interval: 250
|
||||
onTriggered: root.apply()
|
||||
}
|
||||
function apply() {
|
||||
if (root.active === root.applied)
|
||||
return;
|
||||
if (job.running) {
|
||||
sync.restart();
|
||||
return;
|
||||
}
|
||||
applied = active;
|
||||
job.start({
|
||||
action: active ? "on" : "off",
|
||||
effects: options.effects,
|
||||
performance: options.performance
|
||||
});
|
||||
if (active && options.doNotDisturb && NotificationService.active && !NotificationService.dnd) {
|
||||
restoreDnd = false;
|
||||
NotificationService.setDnd(true);
|
||||
} else if (!active && restoreDnd !== null) {
|
||||
NotificationService.setDnd(restoreDnd);
|
||||
restoreDnd = null;
|
||||
}
|
||||
}
|
||||
// A crash while on left effects off: put back what the journal holds.
|
||||
Component.onCompleted: job.start({
|
||||
action: "off"
|
||||
})
|
||||
ProviderJob {
|
||||
id: job
|
||||
helper: root.helper
|
||||
onFinished: (request, result) => {
|
||||
root.error = result.ok ? "" : result.error || "Game Mode request failed";
|
||||
// A change while the request ran is applied now.
|
||||
if (root.active !== root.applied)
|
||||
sync.restart();
|
||||
}
|
||||
}
|
||||
IpcHandler {
|
||||
target: "gamemode"
|
||||
function toggle(): bool {
|
||||
return root.toggle();
|
||||
}
|
||||
function status(): string {
|
||||
return JSON.stringify({
|
||||
active: root.active,
|
||||
applied: root.applied,
|
||||
error: root.error
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,3 +20,4 @@ singleton NotificationService 1.0 NotificationService.qml
|
||||
singleton ClipboardService 1.0 ClipboardService.qml
|
||||
singleton EmojiService 1.0 EmojiService.qml
|
||||
singleton CaffeineService 1.0 CaffeineService.qml
|
||||
singleton GameModeService 1.0 GameModeService.qml
|
||||
@@ -11,6 +11,31 @@ SettingsPage {
|
||||
Modules.Profiles {
|
||||
Layout.fillWidth: true
|
||||
}
|
||||
SettingsSection {
|
||||
title: "Game Mode"
|
||||
description: "What the Control Center's Game Mode tile changes while it is on"
|
||||
PreferenceToggle {
|
||||
label: "Turn off animations, blur, shadows and glass"
|
||||
icon: ""
|
||||
setting: "gameMode.effects"
|
||||
}
|
||||
PreferenceToggle {
|
||||
label: "Performance power profile"
|
||||
description: "Back to the previous profile afterwards"
|
||||
icon: ""
|
||||
setting: "gameMode.performance"
|
||||
}
|
||||
PreferenceToggle {
|
||||
label: "Do Not Disturb"
|
||||
description: "Built-in notifications only"
|
||||
icon: ""
|
||||
setting: "gameMode.doNotDisturb"
|
||||
}
|
||||
}
|
||||
SettingNote {
|
||||
warning: true
|
||||
text: GameModeService.error
|
||||
}
|
||||
SettingsSection {
|
||||
title: "Lock screen"
|
||||
padded: true
|
||||
|
||||
@@ -166,6 +166,7 @@ Item {
|
||||
BluetoothService.backend = root.btBackend;
|
||||
SystemService.helper = "testing/recording_system.py";
|
||||
CaffeineService.command = ["sleep", "infinity"];
|
||||
GameModeService.helper = "testing/recording_gamemode.py";
|
||||
SystemService.refresh();
|
||||
return true;
|
||||
}
|
||||
@@ -292,6 +293,8 @@ Item {
|
||||
streams: AudioService.streams.map(n => AudioService.streamName(n)),
|
||||
streamMuted: root.streamNode.audio.muted,
|
||||
caffeine: CaffeineService.active,
|
||||
gameMode: GameModeService.active,
|
||||
gameModeApplied: GameModeService.applied,
|
||||
caffeineRunning: CaffeineService.running,
|
||||
active: ScreenService.active.name,
|
||||
screens: Quickshell.screens.map(s => s.name),
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Test-only Game Mode adapter. Records requests; never calls hyprctl or D-Bus."""
|
||||
import json,os,sys
|
||||
from pathlib import Path
|
||||
base=Path(os.environ['GLASSMXRPH_SYSTEM_EVENTS']).with_suffix('.gamemode')
|
||||
req=json.loads(sys.argv[1])
|
||||
with base.open('a') as f:f.write(json.dumps(req)+'\n')
|
||||
print(json.dumps({'ok':True,'active':req.get('action')=='on'}))
|
||||
Reference in new issue
Block a user