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
@@ -161,6 +161,8 @@ Schema 3 preserves existing pins/settings and adds dock defaults.
|
|||||||
Run `./scripts/glassmxrph launcher` to toggle the running shell's launcher.
|
Run `./scripts/glassmxrph launcher` to toggle the running shell's launcher.
|
||||||
Search applications, use Up/Down and Enter, or type `>` for Settings commands such
|
Search applications, use Up/Down and Enter, or type `>` for Settings commands such
|
||||||
as `>dock`, `>appearance`, `>wallpaper` and `>media`. Escape/outside click closes.
|
as `>dock`, `>appearance`, `>wallpaper` and `>media`. Escape/outside click closes.
|
||||||
|
The two round pills beside the search bar switch to Clipboard History and the Emoji
|
||||||
|
picker (click again to go back); `>clipboard` and `>emoji` do the same.
|
||||||
Other future destinations remain explicitly labelled until their phases are implemented. All destinations are also in Settings' page selector.
|
Other future destinations remain explicitly labelled until their phases are implemented. All destinations are also in Settings' page selector.
|
||||||
|
|
||||||
Recent-file indexing is deferred.
|
Recent-file indexing is deferred.
|
||||||
@@ -186,6 +188,10 @@ of the panel lets you drag tiles to any cell, resize them from the corner handle
|
|||||||
Plugins with a Noctalia `controlCenterWidget` entry point appear there as tiles too.
|
Plugins with a Noctalia `controlCenterWidget` entry point appear there as tiles too.
|
||||||
Right-click Sound to extend it with a volume slider per app (the players
|
Right-click Sound to extend it with a volume slider per app (the players
|
||||||
EasyEffects processes); right-click a toggle to open its settings.
|
EasyEffects processes); right-click a toggle to open its settings.
|
||||||
|
**Game Mode** (tile) turns off animations, blur, shadows and HyprGlass, switches to
|
||||||
|
the performance power profile and turns on Do Not Disturb until you switch it off;
|
||||||
|
Settings → Power chooses which. Changed values are journalled and restored exactly,
|
||||||
|
also after a shell crash. `glassmxrph`'s IPC target `gamemode` toggles it.
|
||||||
Logout, reboot and shutdown require explicit confirmation.
|
Logout, reboot and shutdown require explicit confirmation.
|
||||||
|
|
||||||
NetworkManager, BlueZ and PipeWire use native Quickshell models. Other controls reuse
|
NetworkManager, BlueZ and PipeWire use native Quickshell models. Other controls reuse
|
||||||
|
|||||||
@@ -181,6 +181,10 @@
|
|||||||
"id": "profiles",
|
"id": "profiles",
|
||||||
"enabled": true
|
"enabled": true
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"id": "gameMode",
|
||||||
|
"enabled": true
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"id": "output",
|
"id": "output",
|
||||||
"enabled": true
|
"enabled": true
|
||||||
@@ -211,6 +215,11 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
|
"gameMode": {
|
||||||
|
"effects": true,
|
||||||
|
"doNotDisturb": true,
|
||||||
|
"performance": true
|
||||||
|
},
|
||||||
"launcher": {
|
"launcher": {
|
||||||
"recentFiles": false,
|
"recentFiles": false,
|
||||||
"width": 680,
|
"width": 680,
|
||||||
|
|||||||
@@ -100,6 +100,13 @@ Singleton {
|
|||||||
h: 1,
|
h: 1,
|
||||||
source: Qt.resolvedUrl("modules/Caffeine.qml")
|
source: Qt.resolvedUrl("modules/Caffeine.qml")
|
||||||
},
|
},
|
||||||
|
gameMode: {
|
||||||
|
title: "Game Mode",
|
||||||
|
glyph: "",
|
||||||
|
w: 2,
|
||||||
|
h: 1,
|
||||||
|
source: Qt.resolvedUrl("modules/GameMode.qml")
|
||||||
|
},
|
||||||
profiles: {
|
profiles: {
|
||||||
title: "Power profile",
|
title: "Power profile",
|
||||||
glyph: "",
|
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;
|
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(!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.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();
|
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 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");
|
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 ClipboardService 1.0 ClipboardService.qml
|
||||||
singleton EmojiService 1.0 EmojiService.qml
|
singleton EmojiService 1.0 EmojiService.qml
|
||||||
singleton CaffeineService 1.0 CaffeineService.qml
|
singleton CaffeineService 1.0 CaffeineService.qml
|
||||||
|
singleton GameModeService 1.0 GameModeService.qml
|
||||||
@@ -11,6 +11,31 @@ SettingsPage {
|
|||||||
Modules.Profiles {
|
Modules.Profiles {
|
||||||
Layout.fillWidth: true
|
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 {
|
SettingsSection {
|
||||||
title: "Lock screen"
|
title: "Lock screen"
|
||||||
padded: true
|
padded: true
|
||||||
|
|||||||
@@ -166,6 +166,7 @@ Item {
|
|||||||
BluetoothService.backend = root.btBackend;
|
BluetoothService.backend = root.btBackend;
|
||||||
SystemService.helper = "testing/recording_system.py";
|
SystemService.helper = "testing/recording_system.py";
|
||||||
CaffeineService.command = ["sleep", "infinity"];
|
CaffeineService.command = ["sleep", "infinity"];
|
||||||
|
GameModeService.helper = "testing/recording_gamemode.py";
|
||||||
SystemService.refresh();
|
SystemService.refresh();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -292,6 +293,8 @@ Item {
|
|||||||
streams: AudioService.streams.map(n => AudioService.streamName(n)),
|
streams: AudioService.streams.map(n => AudioService.streamName(n)),
|
||||||
streamMuted: root.streamNode.audio.muted,
|
streamMuted: root.streamNode.audio.muted,
|
||||||
caffeine: CaffeineService.active,
|
caffeine: CaffeineService.active,
|
||||||
|
gameMode: GameModeService.active,
|
||||||
|
gameModeApplied: GameModeService.applied,
|
||||||
caffeineRunning: CaffeineService.running,
|
caffeineRunning: CaffeineService.running,
|
||||||
active: ScreenService.active.name,
|
active: ScreenService.active.name,
|
||||||
screens: Quickshell.screens.map(s => s.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'}))
|
||||||
@@ -11,6 +11,7 @@ python3 "$project_dir/tests/providers_test.py"
|
|||||||
python3 "$project_dir/tests/system_providers_test.py"
|
python3 "$project_dir/tests/system_providers_test.py"
|
||||||
python3 "$project_dir/tests/metrics_test.py"
|
python3 "$project_dir/tests/metrics_test.py"
|
||||||
python3 "$project_dir/tests/glass_test.py"
|
python3 "$project_dir/tests/glass_test.py"
|
||||||
|
python3 "$project_dir/tests/gamemode_test.py"
|
||||||
python3 "$project_dir/tests/clipboard_test.py"
|
python3 "$project_dir/tests/clipboard_test.py"
|
||||||
# compat/ holds vendored third-party UI kits (qs.compat.* imports qmllint cannot
|
# compat/ holds vendored third-party UI kits (qs.compat.* imports qmllint cannot
|
||||||
# resolve); they are exercised by the plugin runtime test instead.
|
# resolve); they are exercised by the plugin runtime test instead.
|
||||||
|
|||||||
@@ -104,3 +104,5 @@ assert.equal(settings.dropModule(modules,'a','right','').find(m=>m.id==='a').cus
|
|||||||
assert.throws(()=>api.load(defaults,{hyprglass:{values:{blur_iterations:2.5}}}));
|
assert.throws(()=>api.load(defaults,{hyprglass:{values:{blur_iterations:2.5}}}));
|
||||||
assert.throws(()=>api.load(defaults,{hyprglass:{values:{refraction_strength:99}}}));
|
assert.throws(()=>api.load(defaults,{hyprglass:{values:{refraction_strength:99}}}));
|
||||||
console.log('Drag/drop preserves module options and validates global glass preferences.');
|
console.log('Drag/drop preserves module options and validates global glass preferences.');
|
||||||
|
assert.equal(loaded.gameMode.effects,true);assert.equal(api.update(loaded,'gameMode.performance',false).gameMode.performance,false);for(const v of ['yes',1,null])assert.throws(()=>api.update(loaded,'gameMode.effects',v),/Game Mode/);
|
||||||
|
console.log('Game Mode preferences validate.');
|
||||||
@@ -55,6 +55,13 @@ with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp:
|
|||||||
assert ipc('controlTest','rightClick','outputTile');wait(lambda:not state()['extras'].get('output',0),'Sound folds back')
|
assert ipc('controlTest','rightClick','outputTile');wait(lambda:not state()['extras'].get('output',0),'Sound folds back')
|
||||||
assert ipc('controlTest','click','caffeineToggle');wait(lambda:state()['caffeine'] and state()['caffeineRunning'],'Caffeine on')
|
assert ipc('controlTest','click','caffeineToggle');wait(lambda:state()['caffeine'] and state()['caffeineRunning'],'Caffeine on')
|
||||||
assert ipc('controlTest','click','caffeineToggle');wait(lambda:not state()['caffeine'] and not state()['caffeineRunning'],'Caffeine off')
|
assert ipc('controlTest','click','caffeineToggle');wait(lambda:not state()['caffeine'] and not state()['caffeineRunning'],'Caffeine off')
|
||||||
|
# Game Mode runs its helper on and off (recorded, never the real compositor).
|
||||||
|
gm=events.with_suffix('.gamemode')
|
||||||
|
assert ipc('controlTest','click','gameModeToggle');wait(lambda:state()['gameModeApplied'],'Game Mode on')
|
||||||
|
wait(lambda:gm.exists() and json.loads(gm.read_text().splitlines()[-1])['action']=='on','Game Mode helper on')
|
||||||
|
assert ipc('controlTest','checked','gameModeToggle')
|
||||||
|
assert ipc('controlTest','click','gameModeToggle');wait(lambda:not state()['gameMode'] and not state()['gameModeApplied'],'Game Mode off')
|
||||||
|
wait(lambda:json.loads(gm.read_text().splitlines()[-1])['action']=='off','Game Mode helper off')
|
||||||
assert ipc('controlTest','click','wifiToggle');wait(lambda:not state()['wifi'],'Wi-Fi toggle')
|
assert ipc('controlTest','click','wifiToggle');wait(lambda:not state()['wifi'],'Wi-Fi toggle')
|
||||||
assert ipc('controlTest','click','bluetoothToggle');wait(lambda:not state()['bluetooth'],'Bluetooth toggle')
|
assert ipc('controlTest','click','bluetoothToggle');wait(lambda:not state()['bluetooth'],'Bluetooth toggle')
|
||||||
assert ipc('controlTest','click','bluetoothToggle')
|
assert ipc('controlTest','click','bluetoothToggle')
|
||||||
@@ -160,4 +167,4 @@ with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp:
|
|||||||
shell.terminate();shell.wait(timeout=5)
|
shell.terminate();shell.wait(timeout=5)
|
||||||
if original:subprocess.run(['hyprctl','dispatch','focusmonitor',original],capture_output=True)
|
if original:subprocess.run(['hyprctl','dispatch','focusmonitor',original],capture_output=True)
|
||||||
text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text
|
text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text
|
||||||
print('PASS: native read-only discovery, active-monitor placement, system pill, recording audio/per-app volume/Caffeine/network/Bluetooth/display/DND actions, free grid edit mode (place, push down, air gaps, resize, remove, add, plugin tiles, reset), power confirmation/cancel, outside/Escape/exclusivity, settings, clean logs.')
|
print('PASS: native read-only discovery, active-monitor placement, system pill, recording audio/per-app volume/Caffeine/Game Mode/network/Bluetooth/display/DND actions, free grid edit mode (place, push down, air gaps, resize, remove, add, plugin tiles, reset), power confirmation/cancel, outside/Escape/exclusivity, settings, clean logs.')
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import importlib.util,json,os,tempfile,unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
spec=importlib.util.spec_from_file_location('gamemode',Path(__file__).resolve().parents[1]/'quickshell/helpers/gamemode.py')
|
||||||
|
gm=importlib.util.module_from_spec(spec);spec.loader.exec_module(gm)
|
||||||
|
class GameModeTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
# HyprGlass is not loaded here, and the user has shadows off.
|
||||||
|
self.state={'animations:enabled':1,'decoration:blur:enabled':1,'decoration:shadow:enabled':0}
|
||||||
|
def env(self,temp,sig='fixture'):
|
||||||
|
return patch.dict(os.environ,{'XDG_STATE_HOME':temp,'HYPRLAND_INSTANCE_SIGNATURE':sig})
|
||||||
|
def fakes(self,profile='balanced'):
|
||||||
|
self.profile=profile
|
||||||
|
def setp(name):self.profile=name
|
||||||
|
return patch.multiple(gm,get_many=lambda keys:{k:self.state[k] for k in keys if k in self.state},put_many=lambda values:self.state.update(values),get_profile=lambda:self.profile,set_profile=setp)
|
||||||
|
def test_on_off_restores_exact_values(self):
|
||||||
|
with tempfile.TemporaryDirectory() as temp,self.env(temp):
|
||||||
|
with self.fakes():
|
||||||
|
original=dict(self.state)
|
||||||
|
self.assertTrue(gm.dispatch({'action':'on'})['active'])
|
||||||
|
self.assertEqual(set(self.state.values()),{0})
|
||||||
|
self.assertEqual(self.profile,'performance')
|
||||||
|
self.assertNotIn('plugin:hyprglass:enabled',self.state)
|
||||||
|
self.assertTrue(gm.dispatch({'action':'status'})['active'])
|
||||||
|
self.assertFalse(gm.dispatch({'action':'off'})['active'])
|
||||||
|
self.assertEqual(self.state,original)
|
||||||
|
self.assertEqual(self.profile,'balanced')
|
||||||
|
self.assertFalse(gm.dispatch({'action':'status'})['active'])
|
||||||
|
def test_on_twice_keeps_first_journal(self):
|
||||||
|
with tempfile.TemporaryDirectory() as temp,self.env(temp):
|
||||||
|
with self.fakes():
|
||||||
|
gm.dispatch({'action':'on'});gm.dispatch({'action':'on'})
|
||||||
|
gm.dispatch({'action':'off'})
|
||||||
|
self.assertEqual(self.state['animations:enabled'],1)
|
||||||
|
def test_crash_recovery_and_other_sessions(self):
|
||||||
|
with tempfile.TemporaryDirectory() as temp:
|
||||||
|
with self.fakes():
|
||||||
|
with self.env(temp,'old'):gm.dispatch({'action':'on'})
|
||||||
|
# A new Hyprland session never applies the old journal.
|
||||||
|
with self.env(temp,'new'):
|
||||||
|
self.assertFalse(gm.dispatch({'action':'status'})['active'])
|
||||||
|
gm.dispatch({'action':'off'})
|
||||||
|
self.assertEqual(self.state['animations:enabled'],0)
|
||||||
|
# The same session (shell restarted) restores it.
|
||||||
|
with self.env(temp,'old'):
|
||||||
|
gm.dispatch({'action':'off'})
|
||||||
|
self.assertEqual(self.state['animations:enabled'],1)
|
||||||
|
def test_options_and_no_profiles_daemon(self):
|
||||||
|
with tempfile.TemporaryDirectory() as temp,self.env(temp):
|
||||||
|
with self.fakes(profile=None):
|
||||||
|
gm.dispatch({'action':'on','effects':False,'performance':True})
|
||||||
|
self.assertEqual(self.state['animations:enabled'],1)
|
||||||
|
self.assertIsNone(self.profile)
|
||||||
|
gm.dispatch({'action':'off'})
|
||||||
|
with self.fakes():
|
||||||
|
gm.dispatch({'action':'on','effects':True,'performance':False})
|
||||||
|
self.assertEqual(self.profile,'balanced')
|
||||||
|
gm.dispatch({'action':'off'})
|
||||||
|
self.assertEqual(self.state['animations:enabled'],1)
|
||||||
|
def test_parses_missing_options(self):
|
||||||
|
out='{"option": "animations:enabled", "int": 1, "set": true }\n\n\nno such option\n\n{"option": "decoration:blur:enabled", "int": 0, "set": true }\n'
|
||||||
|
with patch.object(gm,'run',lambda args:out):
|
||||||
|
self.assertEqual(gm.get_many(['animations:enabled','plugin:hyprglass:enabled','decoration:blur:enabled']),{'animations:enabled':1,'decoration:blur:enabled':0})
|
||||||
|
def test_rejected_keyword_raises(self):
|
||||||
|
with patch.object(gm,'run',lambda args:'ok\nconfig option <x> does not exist.'):
|
||||||
|
with self.assertRaises(ValueError):gm.put_many({'x':0,'y':0})
|
||||||
|
def test_unknown_action(self):
|
||||||
|
with tempfile.TemporaryDirectory() as temp,self.env(temp):
|
||||||
|
with self.assertRaises(ValueError):gm.dispatch({'action':'nope'})
|
||||||
|
if __name__=='__main__':unittest.main()
|
||||||
Reference in new issue
Block a user