Add glassMxrph shell sources
Initial commit of the Quickshell desktop suite: bar, dock, launcher, settings, Control Center, dashboard, OSD, lock screen, desktop widgets, plugin host with the vendored Noctalia/Omarchy compatibility layer, helpers, packaging, tests and phase documentation. Includes the optimization work so far: usage widgets and dashboard gauges no longer animate continuously, desktop widgets pause while covered, system controls stop flickering on background polls, dock app matching uses an indexed catalog, and workspace ghosts are created only for occupied slots. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
99e64a7713
433 files changed
+57792
No files matched your search
@@ -0,0 +1,98 @@
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('node:path');
|
||||
const root = path.join(__dirname, '..');
|
||||
const api = vm.createContext({});
|
||||
vm.runInContext(fs.readFileSync(path.join(root, 'quickshell/services/ConfigLogic.js'), 'utf8'), api);
|
||||
const defaults = JSON.parse(fs.readFileSync(path.join(root, 'quickshell/config/defaults.json')));
|
||||
const loaded = api.load(defaults, {appearance: {customAccent: '#123456'}, futureOption: 42, dock: {pinnedApps: ['example.desktop']}});
|
||||
assert.equal(loaded.appearance.customAccent, '#123456');
|
||||
assert.equal(loaded.appearance.glassOpacity, defaults.appearance.glassOpacity);
|
||||
assert.equal(loaded.futureOption, 42);
|
||||
assert.equal(loaded.dock.pinnedApps[0], 'example.desktop');
|
||||
assert.throws(() => api.load(defaults, {schemaVersion: 99}));
|
||||
assert.throws(() => api.load(defaults, {appearance: {glassOpacity: 4}}));
|
||||
assert.throws(() => api.load(defaults, {bar: {modules: [{id:'clock',position:'bad',enabled:true}]}}));
|
||||
assert.throws(() => api.load(defaults, []));
|
||||
const edited = api.update(loaded, 'appearance.customAccent', '#abcdef');
|
||||
assert.equal(loaded.appearance.customAccent, '#123456');
|
||||
assert.equal(edited.appearance.customAccent, '#abcdef');
|
||||
assert.equal(loaded.appearance.glassTint, '#000000');
|
||||
assert.equal(loaded.osd.position, 'top-right');assert.equal(loaded.bar.workspaces.style, 'numbers');
|
||||
const widget={id:'w-1',type:'clock',variant:'digital',monitor:'DP-1',x:10,y:20,w:260,h:130,opacity:1,options:{}};
|
||||
assert.deepEqual(loaded.desktopWidgets.items,[]);
|
||||
assert.equal(loaded.lock.backdrop,'wallpaper');assert.equal(loaded.lock.pamService,'');assert.equal(api.update(loaded,'lock.pamService','hyprlock').lock.pamService,'hyprlock');
|
||||
for(const [k,v] of [['lock.backdrop','video'],['lock.pamService','../etc/shadow'],['lock.glass','yes']])assert.throws(()=>api.update(loaded,k,v),/lock screen/);assert.equal(api.update(loaded,'desktopWidgets.items',[widget,Object.assign({},widget,{id:'w-2',type:'future'})]).desktopWidgets.items.length,2);
|
||||
for(const bad of [[widget,widget],[Object.assign({},widget,{w:10})],[Object.assign({},widget,{opacity:2})],[Object.assign({},widget,{id:'Bad id'})],[Object.assign({},widget,{options:[]})]])assert.throws(()=>api.update(loaded,'desktopWidgets.items',bad),/desktop widget/);assert.equal(api.update(loaded, 'bar.workspaces.style', 'pacman').bar.workspaces.style, 'pacman');assert.throws(() => api.update(loaded, 'bar.workspaces.style', 'emoji'), /bar module options/);assert.throws(() => api.update(loaded, 'osd.position', 'left'), /OSD/);assert.throws(() => api.update(loaded, 'osd.timeout', 50), /OSD/);assert.throws(() => api.update(loaded, 'appearance.glassTint', 'grey'), /Glass tint/);
|
||||
assert.throws(() => api.update(loaded, '__proto__.polluted', true));
|
||||
console.log('Configuration preservation, validation and update tests passed.');
|
||||
|
||||
const originalModules = [{id:'clock',position:'left',enabled:false},{id:'system',position:'center',enabled:true}];
|
||||
const migrated = api.load(defaults, {schemaVersion:1,bar:{modules:originalModules},tray:{hoverDelay:650},dock:{pinnedApps:['custom.desktop']}});
|
||||
assert.equal(migrated.schemaVersion, 3);
|
||||
assert.equal(migrated.bar.modules[0].id, 'clock');
|
||||
assert.equal(migrated.bar.modules[0].position, 'left');
|
||||
assert.equal(migrated.bar.modules[0].enabled, false);
|
||||
assert.equal(migrated.bar.modules[1].id, 'tray');
|
||||
assert.equal(migrated.bar.modules[2].position, 'center');
|
||||
assert.equal(originalModules.length, 2);
|
||||
assert.equal(migrated.tray.hoverDelay, 650);
|
||||
assert.equal(migrated.dock.pinnedApps[0], 'custom.desktop');
|
||||
assert.equal(api.load(defaults, migrated).bar.modules.length, 3);
|
||||
const removed = api.load(defaults, {schemaVersion:2,bar:{modules:originalModules}});
|
||||
assert.equal(removed.bar.modules.length, 2); // never re-add a deliberately removed module
|
||||
assert.throws(() => api.load(defaults, {tray:{hoverDelay:-10}}));
|
||||
assert.throws(() => api.load(defaults, {tray:{iconSize:100}}));
|
||||
assert.throws(() => api.load(defaults, {tray:{enabled:'yes'}}));
|
||||
assert.throws(() => api.load(defaults, {tray:{background:'invalid'}}));
|
||||
console.log('Phase 2 migration and tray validation tests passed.');
|
||||
const phase3=api.load(defaults,{schemaVersion:2,dock:{enabled:false,pinnedApps:['my.desktop'],monitor:'external',visibility:'auto'},future:{keep:true}});
|
||||
assert.equal(phase3.schemaVersion,3);assert.equal(phase3.dock.enabled,false);assert.equal(phase3.dock.pinnedApps[0],'my.desktop');assert.equal(phase3.dock.monitor,'external');assert.equal(phase3.dock.iconSize,48);assert(phase3.future.keep);
|
||||
for(const dock of [{position:'top'},{visibility:'bad'},{iconSize:0},{pinnedApps:['a','a.desktop']},{terminalCommand:'sh'},{appOverrides:{a:42}}]) assert.throws(()=>api.load(defaults,{dock}));
|
||||
console.log('Phase 3 migration and dock validation tests passed.');
|
||||
const phase4=api.load(defaults,{schemaVersion:3,launcher:{recentFiles:false,unknown:'keep'},dock:{pinnedApps:['preserved.desktop']}});
|
||||
assert.equal(phase4.launcher.width,680);assert.equal(phase4.launcher.unknown,'keep');assert.equal(phase4.dock.pinnedApps[0],'preserved.desktop');
|
||||
for (const launcher of [{width:10},{maxResults:0},{maxResults:2.5},{showDescriptions:'yes'},{recentFiles:42}]) assert.throws(()=>api.load(defaults,{launcher}));
|
||||
console.log('Launcher default merging and preference validation passed.');
|
||||
const phase5=api.load(defaults,{schemaVersion:3,appearance:{customAccent:'#112233'},wallpaper:{directories:['/pictures'],byMonitor:{screen:'/pictures/a.png'}},media:{showAlbum:false},bar:{modules:originalModules}});
|
||||
assert.equal(phase5.appearance.panelOpacity,0.86);assert.equal(phase5.wallpaper.backend,'native');assert.equal(phase5.wallpaper.byMonitor.screen,'/pictures/a.png');assert.equal(phase5.media.showAlbum,false);assert.equal(phase5.media.showAlbumArt,true);assert.equal(phase5.bar.modules.length,2);
|
||||
for(const data of [{matugen:{contrast:2}},{matugen:{scheme:'invented'}},{wallpaper:{command:'sh -c'}},{media:{showCava:'yes'}},{appearance:{panelOpacity:2}},{bar:{workspaces:{count:0}}}])assert.throws(()=>api.load(defaults,data));
|
||||
const settings=vm.createContext({});vm.runInContext(fs.readFileSync(path.join(root,'quickshell/services/SettingsLogic.js'),'utf8'),settings);
|
||||
const modules=[{id:'a',position:'left',enabled:true,custom:{keep:true}},{id:'middle',position:'center',enabled:true},{id:'b',position:'left',enabled:false}];
|
||||
const moved=settings.moveModule(modules,'b',-1);assert.equal(moved[0].id,'b');assert.equal(moved[1].id,'middle');assert(moved[2].custom.keep);assert.equal(modules[0].id,'a');
|
||||
const withoutMiddle=settings.removeModule(modules,'middle');assert.deepEqual(withoutMiddle.map(m=>m.id),['a','b']);assert.equal(modules.length,3);
|
||||
const assigned=settings.editModule(modules,'a','position','right');assert.equal(assigned[0].position,'right');assert(assigned[0].custom.keep);assert.equal(modules[0].position,'left');
|
||||
console.log('Phase 5 preference merging, validation and immutable bar editing/removal passed.');
|
||||
|
||||
assert.throws(() => api.update(phase5, 'bar.modules', {}), /must be an array/);
|
||||
assert.equal(api.update(phase5, 'bar.modules', [{id:'nowPlaying',position:'right',enabled:true}]).bar.modules[0].id, 'nowPlaying');
|
||||
const phase7=api.load(defaults,{schemaVersion:3,controlCenter:{modules:[]},dock:{pinnedApps:['keep.desktop']},future:{keep:true}});
|
||||
assert.equal(phase7.controlCenter.version,1);assert(phase7.controlCenter.modules.length>0);assert.equal(phase7.dock.pinnedApps[0],'keep.desktop');assert(phase7.future.keep);
|
||||
assert.equal(api.load(defaults,{controlCenter:{version:1,modules:[]}}).controlCenter.modules.length,0);
|
||||
const customCenter=api.load(defaults,{controlCenter:{modules:[{id:'custom',enabled:false,metadata:'preserved'}]}});
|
||||
assert.equal(customCenter.controlCenter.modules[0].metadata,'preserved');assert.equal(customCenter.controlCenter.modules.length,1);
|
||||
for(const controlCenter of [{version:2},{version:1,width:100},{version:1,modules:[{id:'audio',enabled:true},{id:'audio',enabled:false}]}])assert.throws(()=>api.load(defaults,{controlCenter}));
|
||||
for(const system of [{brightness:{setCommand:'sh -c'}},{nightLight:{temperature:0}},{power:{lockCommand:['']}}])assert.throws(()=>api.load(defaults,{system}));
|
||||
console.log('Phase 7 one-time module migration, intentional empty layouts, provider validation and preservation passed.');
|
||||
|
||||
for(const controlCenter of [null,[],{modules:null},{modules:''}])assert.throws(()=>api.load(defaults,{controlCenter}));
|
||||
|
||||
const metricConfig=api.load(defaults,{schemaVersion:3,metrics:{interval:5,networkInterface:'custom',future:42}});
|
||||
assert.equal(metricConfig.metrics.interval,5);
|
||||
assert.equal(metricConfig.metrics.networkInterface,'custom');
|
||||
assert.equal(metricConfig.metrics.future,42);
|
||||
assert.equal(metricConfig.metrics.gpu,'auto');
|
||||
for(const value of [0,31,1.5,'2'])assert.throws(()=>api.update(metricConfig,'metrics.interval',value));
|
||||
for(const value of [['relative'],['/','/'],null])assert.throws(()=>api.update(metricConfig,'metrics.storagePaths',value));
|
||||
assert.equal(api.update(metricConfig,'metrics.storagePaths',[]).metrics.storagePaths.length,0);
|
||||
console.log('Phase 8 metrics defaults, preservation, source and interval validation passed.');
|
||||
const dropped=settings.dropModule(modules,'b','center','middle');
|
||||
assert.equal(dropped.find(m=>m.id==='b').position,'center');
|
||||
assert.equal(dropped.find(m=>m.id==='b').enabled,false);
|
||||
assert.equal(dropped.findIndex(m=>m.id==='b')+1,dropped.findIndex(m=>m.id==='middle'));
|
||||
assert.equal(modules[2].position,'left');
|
||||
assert.equal(settings.dropModule(modules,'a','right','').find(m=>m.id==='a').custom.keep,true);
|
||||
assert.throws(()=>api.load(defaults,{hyprglass:{values:{blur_iterations:2.5}}}));
|
||||
assert.throws(()=>api.load(defaults,{hyprglass:{values:{refraction_strength:99}}}));
|
||||
console.log('Drag/drop preserves module options and validates global glass preferences.');
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real Wayland/read-only native discovery, then recording adapters for all writes."""
|
||||
import json,os,subprocess,tempfile,time
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call']
|
||||
def ipc(target,method,*args):
|
||||
r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True)
|
||||
return json.loads(r.stdout) if r.returncode==0 and r.stdout.strip() else None
|
||||
def state():return ipc('controlTest','snapshot') or {}
|
||||
def wait(check,label):
|
||||
end=time.monotonic()+15
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
if check():return
|
||||
except (TypeError,KeyError,ValueError):pass
|
||||
time.sleep(.08)
|
||||
raise AssertionError(label+': '+str(state()))
|
||||
def pref(key,value):assert ipc('shell','setPreference',key,' '+json.dumps(value)),ipc('shell','status')
|
||||
if ipc('shell','status'):raise SystemExit('Use an isolated source path; instance already active.')
|
||||
log=ROOT/'.cache/controlcenter-runtime.log';log.parent.mkdir(exist_ok=True)
|
||||
monitors=json.loads(subprocess.check_output(['hyprctl','monitors','-j'],text=True));original=next((m['name'] for m in monitors if m['focused']),None)
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-controls-') as tmp:
|
||||
events=Path(tmp)/'events';cfg=Path(tmp)/'config/glassMxrph/config.json';cfg.parent.mkdir(parents=True)
|
||||
cfg.write_text(json.dumps({'schemaVersion':3,'media':{'enabled':False},'dock':{'enabled':False}}))
|
||||
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_CACHE_HOME=tmp+'/cache',GLASSMXRPH_CONTROL_TESTING='1',GLASSMXRPH_SYSTEM_EVENTS=str(events),QT_QPA_PLATFORMTHEME='',QT_NO_XDG_DESKTOP_PORTAL='1')
|
||||
with log.open('w') as output:
|
||||
shell=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=output,stderr=subprocess.STDOUT)
|
||||
try:
|
||||
wait(lambda:ipc('shell','status')['ready'],'ready')
|
||||
time.sleep(.25)
|
||||
assert ipc('controlTest','clickSystem')
|
||||
wait(lambda:ipc('controlcenter','status')['opened'],'system pill opens')
|
||||
wait(lambda:not state()['busy'] and 'power' in state()['state'],'read-only native providers')
|
||||
assert ipc('controlcenter','status')['screen']==state()['active']
|
||||
time.sleep(.4)
|
||||
s=state();assert s['x']>s['screenWidth']/2 and s['x']+s['width']<=s['screenWidth'] and s['y']+s['height']<=s['screenHeight']
|
||||
wait(lambda:ipc('controlTest','inject'),'inject recording adapters')
|
||||
wait(lambda:not state()['busy'] and state()['state']['brightness']['available'],'fixture providers')
|
||||
assert ipc('controlTest','click','volumeMute');wait(lambda:state()['muted'],'mute click')
|
||||
assert ipc('controlTest','slider','volumeSlider');wait(lambda:state()['volume']>.6,'volume slider')
|
||||
assert ipc('controlTest','click','microphoneMute');wait(lambda:state()['microphone'],'microphone click')
|
||||
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')
|
||||
assert ipc('controlTest','connectFixtures')
|
||||
for name,key in [('nightLightToggle','nightLight'),('dndToggle','dnd')]:
|
||||
assert ipc('controlTest','click',name)
|
||||
wait(lambda:not state()['busy'] and state()['state'][key]['enabled'],key+' readback')
|
||||
failure=events.with_suffix('.fail');failure.touch()
|
||||
assert ipc('controlTest','click','dndToggle')
|
||||
wait(lambda:not state()['busy'] and bool(state()['error']),'provider error')
|
||||
assert state()['state']['dnd']['enabled'] and ipc('controlTest','checked','dndToggle'),'Failed request changed displayed real state'
|
||||
assert ipc('controlTest','slider','brightnessSlider')
|
||||
wait(lambda:not state()['busy'] and bool(state()['error']),'brightness error')
|
||||
assert ipc('controlTest','value','brightnessSlider')==state()['state']['brightness']['value'],'Failed brightness request changed display'
|
||||
failure.unlink();assert ipc('controlTest','click','dndToggle')
|
||||
wait(lambda:not state()['busy'] and not state()['error'] and not state()['state']['dnd']['enabled'],'provider recovery')
|
||||
assert ipc('controlTest','slider','brightnessSlider')
|
||||
wait(lambda:not state()['busy'] and state()['state']['brightness']['value']>60,'brightness readback')
|
||||
assert ipc('controlTest','click','power-reboot');assert state()['power']=='reboot'
|
||||
assert not any(json.loads(line)['action']=='power' for line in events.read_text().splitlines())
|
||||
assert ipc('controlTest','click','powerCancel');assert state()['power']==''
|
||||
assert ipc('controlTest','click','power-shutdown');ipc('controlTest','pressEscape');wait(lambda:state()['power']=='','Escape cancels pending power')
|
||||
assert ipc('controlcenter','status')['opened']
|
||||
assert ipc('controlTest','click','power-reboot');assert ipc('controlTest','click','powerConfirm')
|
||||
wait(lambda:not state()['busy'],'recorded confirmation')
|
||||
actions=[json.loads(line) for line in events.read_text().splitlines()]
|
||||
power=[a for a in actions if a['action']=='power'];assert len(power)==1 and power[0]['value']=='reboot' and power[0]['confirmed'] is True
|
||||
ipc('controlcenter','close');time.sleep(.3);ipc('controlcenter','open');time.sleep(.35)
|
||||
assert ipc('controlTest','screenshot',str(ROOT/'.cache/controlcenter-preview.png'))
|
||||
ipc('controlTest','outside');wait(lambda:not state()['windowVisible'],'outside closes')
|
||||
for monitor in monitors:
|
||||
subprocess.run(['hyprctl','dispatch','focusmonitor',monitor['name']],check=True,capture_output=True)
|
||||
wait(lambda:state()['active']==monitor['name'],'active monitor event')
|
||||
ipc('controlcenter','open');wait(lambda:state()['windowVisible'],'mapped on output');time.sleep(.3)
|
||||
assert ipc('controlcenter','status')['screen']==monitor['name']
|
||||
s=state();assert s['x']>=0 and s['x']+s['width']<=s['screenWidth'] and s['y']+s['height']<=s['screenHeight']
|
||||
ipc('controlcenter','close');wait(lambda:not state()['windowVisible'],'close before monitor switch')
|
||||
pref('animation.reducedMotion',True)
|
||||
for _ in range(3):
|
||||
ipc('controlcenter','open');wait(lambda:state()['windowVisible'],'reduced motion open')
|
||||
ipc('controlcenter','close');wait(lambda:not state()['windowVisible'],'reduced motion close')
|
||||
pref('animation.reducedMotion',False)
|
||||
ipc('controlcenter','open');ipc('launcher','open');wait(lambda:not ipc('controlcenter','status')['opened'],'launcher exclusivity');ipc('launcher','close')
|
||||
ipc('shell','openSettings','controlcenter');wait(lambda:state()['settingsVisible'],'module editor opens');time.sleep(.3)
|
||||
assert ipc('controlTest','settingsClick','control-down-connectivity')
|
||||
wait(lambda:state()['modules'][1]['id']=='connectivity','visual module reorder')
|
||||
assert ipc('controlTest','settingsClick','control-enable-audio')
|
||||
wait(lambda:not next(m for m in state()['modules'] if m['id']=='audio')['enabled'],'visual module toggle')
|
||||
ipc('shell','close');wait(lambda:not state()['settingsVisible'],'settings closes')
|
||||
for page in ['controlcenter','audio','network','bluetooth','displays','notifications','power']:
|
||||
ipc('shell','openSettings',page);time.sleep(.3)
|
||||
wait(lambda:not state()['scan'],'network scan released')
|
||||
ipc('shell','close');pref('controlCenter.modules',[])
|
||||
ipc('controlcenter','open');time.sleep(.3);ipc('controlTest','pressEscape');wait(lambda:not ipc('controlcenter','status')['opened'],'Escape closes empty panel')
|
||||
wait(lambda:json.loads(cfg.read_text())['controlCenter']['modules']==[],'module persistence')
|
||||
finally:
|
||||
shell.terminate();shell.wait(timeout=5)
|
||||
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
|
||||
print('PASS: native read-only discovery, active-monitor placement, system pill, recording audio/network/Bluetooth/display/DND actions, power confirmation/cancel, outside/Escape/exclusivity, settings, clean logs.')
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Native wallpaper and DnD on Wayland; global glass writes go to a recording hyprctl."""
|
||||
import importlib.util,json,os,shutil,struct,subprocess,tempfile,time,zlib
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call']
|
||||
def ipc(target,method,*args):
|
||||
p=subprocess.run(BASE+[target,method,*map(str,args)],text=True,capture_output=True,timeout=5)
|
||||
return json.loads(p.stdout) if p.returncode==0 and p.stdout.strip() else None
|
||||
def state():return ipc('settingsTest','snapshot') or {}
|
||||
def wait(fn):
|
||||
end=time.monotonic()+20
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
if fn():return
|
||||
except (TypeError,KeyError,ValueError,FileNotFoundError):pass
|
||||
time.sleep(.1)
|
||||
raise AssertionError(str(state()))
|
||||
def pref(key,value):assert ipc('shell','setPreference',key,' '+json.dumps(value)) is True
|
||||
spec=importlib.util.spec_from_file_location('glass',ROOT/'quickshell/helpers/glass.py');g=importlib.util.module_from_spec(spec);spec.loader.exec_module(g)
|
||||
def png(path,rgb):
|
||||
def chunk(k,d):return struct.pack('!I',len(d))+k+d+struct.pack('!I',zlib.crc32(k+d)&0xffffffff)
|
||||
path.write_bytes(b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!2I5B',64,64,8,2,0,0,0))+chunk(b'IDAT',zlib.compress((b'\x00'+bytes(rgb)*64)*64))+chunk(b'IEND',b''))
|
||||
if ipc('shell','status'):raise SystemExit('Stop the running project preview before this isolated test.')
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-customization-') as tmp:
|
||||
t=Path(tmp);(t/'bin').mkdir();images=t/'images';images.mkdir();png(images/'amber #1.png',(140,90,20));png(images/'blue.png',(20,65,120))
|
||||
initial={k:('liquid' if k=='default_preset' else 'auto' if k=='layers:mask_mode' else '' if isinstance(v,str) else 0) for k,v in g.values({'layers':True,'values':g.GHOSTTY}).items()}
|
||||
initial.update({'layers:namespaces':'','layers:exclude_namespaces':'','layers:namespace_presets':''})
|
||||
record=t/'glass.json';record.write_text(json.dumps(initial))
|
||||
real=shutil.which('hyprctl')
|
||||
fake=t/'bin/hyprctl';fake.write_text('''#!/usr/bin/env python3
|
||||
import json,os,subprocess,sys
|
||||
from pathlib import Path
|
||||
args=sys.argv[1:];p=Path(os.environ['GLASS_TEST_RECORD']);d=json.loads(p.read_text())
|
||||
if 'getoption' in args and args[-1].startswith('plugin:hyprglass:'):
|
||||
k=args[-1].removeprefix('plugin:hyprglass:');v=d[k];print(json.dumps({'str' if isinstance(v,str) else 'float' if isinstance(v,float) else 'int':v,'set':True}))
|
||||
elif args[0]=='keyword' and args[1].startswith('plugin:hyprglass:'):
|
||||
k=args[1].removeprefix('plugin:hyprglass:');v=args[2]
|
||||
if not isinstance(d[k],str):v=float(v);v=int(v) if v.is_integer() else v
|
||||
d[k]=v;p.write_text(json.dumps(d));print('ok')
|
||||
else:os.execv(os.environ['GLASS_REAL_HYPRCTL'],[os.environ['GLASS_REAL_HYPRCTL'],*args])
|
||||
''');fake.chmod(0o755)
|
||||
config=t/'config/glassMxrph/config.json';config.parent.mkdir(parents=True);config.write_text(json.dumps({'schemaVersion':3,'wallpaper':{'backend':'native','directories':[str(images)]},'dock':{'enabled':False},'media':{'enabled':False}}))
|
||||
env=dict(os.environ,PATH=str(t/'bin')+':'+os.environ['PATH'],XDG_CONFIG_HOME=str(t/'config'),XDG_STATE_HOME=str(t/'state'),GLASSMXRPH_SETTINGS_TESTING='1',GLASS_TEST_RECORD=str(record),GLASS_REAL_HYPRCTL=real)
|
||||
log=ROOT/'.cache/customization-runtime.log'
|
||||
with log.open('w') as out:
|
||||
shell=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=out,stderr=subprocess.STDOUT)
|
||||
try:
|
||||
wait(lambda:state().get('data',{}).get('schemaVersion')==3)
|
||||
ipc('shell','openSettings','bar');time.sleep(.35)
|
||||
assert ipc('settingsTest','dragModule','workspaces','right','tray')
|
||||
wait(lambda:next(m for m in state()['data']['bar']['modules'] if m['id']=='workspaces')['position']=='right')
|
||||
assert ipc('settingsTest','dragModule','clock','left','settings')
|
||||
wait(lambda:state()['data']['bar']['modules'][0]['id']=='clock')
|
||||
assert ipc('settingsTest','dragModule','clock','center','')
|
||||
wait(lambda:next(m for m in state()['data']['bar']['modules'] if m['id']=='clock')['position']=='center')
|
||||
assert ipc('settingsTest','screenshot',str(ROOT/'.cache/bar-drag-preview.png'))
|
||||
ipc('shell','openSettings','wallpaper');time.sleep(.25)
|
||||
assert ipc('settingsTest','click','openWallpaperPicker')
|
||||
wait(lambda:state()['picker'] and len(state()['images'])==2)
|
||||
ipc('settingsTest','pickerQuery','amber')
|
||||
assert ipc('settingsTest','pickerSelect',0)
|
||||
wait(lambda:state()['wallpaper'].endswith('amber #1.png') and not ipc('wallpaper','status')['busy'])
|
||||
assert state()['data']['wallpaper']['history'][0].endswith('amber #1.png')
|
||||
layers=json.loads(subprocess.check_output([real,'-j','layers']))
|
||||
assert any(i['namespace']=='glassMxrph-wallpaper' for m in layers.values() for layer in m['levels'].values() for i in layer)
|
||||
assert ipc('settingsTest','pickerScreenshot',str(ROOT/'.cache/wallpaper-picker-preview.png'))
|
||||
ipc('shell','openSettings','appearance');wait(lambda:state()['glass'].get('available'))
|
||||
assert ipc('settingsTest','click','glassMatchGhostty')
|
||||
wait(lambda:state()['data']['appearance']['panelOpacity']==.3)
|
||||
assert ipc('settingsTest','click','glassApply')
|
||||
wait(lambda:not state()['glassBusy'] and state()['data']['hyprglass']['enabled'])
|
||||
assert not state()['glassError'],state()['glassError']
|
||||
applied=json.loads(record.read_text());assert applied['dark:refraction_strength']==3 and applied['default_preset']=='default'
|
||||
assert applied['layers:enabled']==1
|
||||
pref('hyprglass.values.blur_strength',1.25)
|
||||
assert ipc('settingsTest','click','glassApply')
|
||||
wait(lambda:not state()['glassBusy'] and json.loads(record.read_text())['dark:blur_strength']==1.25)
|
||||
pref('hyprglass.effectEnabled',False)
|
||||
assert ipc('settingsTest','click','glassApply')
|
||||
wait(lambda:not state()['glassBusy'] and json.loads(record.read_text())['enabled']==0)
|
||||
assert json.loads(record.read_text())['layers:enabled']==0
|
||||
assert ipc('settingsTest','click','glassRestore')
|
||||
wait(lambda:not state()['glassBusy'] and not state()['data']['hyprglass']['enabled'])
|
||||
assert json.loads(record.read_text())==initial
|
||||
wait(lambda:json.loads(config.read_text())['wallpaper']['history'])
|
||||
finally:shell.terminate();shell.wait(timeout=8)
|
||||
text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text
|
||||
print('PASS: drag across/within/into empty lanes, native picker/search/apply/history/background, Ghostty match, global apply/update/restore via recording compositor, persistence and clean logs.')
|
||||
@@ -0,0 +1,47 @@
|
||||
//@ pragma AppId org.glassMxrph.DockFixture
|
||||
import QtQuick
|
||||
import Quickshell
|
||||
import Quickshell.Io
|
||||
|
||||
ShellRoot {
|
||||
FloatingWindow {
|
||||
id: first
|
||||
visible: true
|
||||
implicitWidth: 320
|
||||
implicitHeight: 200
|
||||
title: "glassMxrph dock test · first"
|
||||
color: "#20252c"
|
||||
Text {
|
||||
anchors.centerIn: parent
|
||||
text: "Dock test window 1"
|
||||
color: "white"
|
||||
}
|
||||
}
|
||||
FloatingWindow {
|
||||
id: second
|
||||
visible: false
|
||||
implicitWidth: 320
|
||||
implicitHeight: 200
|
||||
title: "glassMxrph dock test · second"
|
||||
color: "#20252c"
|
||||
Text {
|
||||
anchors.centerIn: parent
|
||||
text: "Dock test window 2"
|
||||
color: "white"
|
||||
}
|
||||
}
|
||||
IpcHandler {
|
||||
target: "fixture"
|
||||
function two(): void {
|
||||
second.visible = true;
|
||||
}
|
||||
function hide(): void {
|
||||
first.visible = false;
|
||||
second.visible = false;
|
||||
}
|
||||
function fullscreen(value: bool): void {
|
||||
first.visible = true;
|
||||
first.fullscreen = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
const fs=require('node:fs'),vm=require('node:vm'),assert=require('node:assert/strict'),path=require('node:path');
|
||||
const root=path.join(__dirname,'..');
|
||||
function load(file){const context=vm.createContext({});vm.runInContext(fs.readFileSync(path.join(root,file),'utf8'),context);return context;}
|
||||
const app=load('quickshell/services/AppMatching.js'),geo=load('quickshell/dock/DockGeometry.js');
|
||||
const entries=[{id:'org.example.Editor',name:'Editor',startupClass:'editor'},{id:'browser',name:'Browser',startupClass:'web'},{id:'browser-beta',name:'Browser Beta',startupClass:'web'}];
|
||||
assert.equal(app.match('org.example.Editor.desktop','',entries,{}),entries[0]);
|
||||
assert.equal(app.match('EDITOR','',entries,{}),entries[0]);
|
||||
assert.equal(app.match('web','',entries,{}),null); // ambiguous StartupWMClass is not guessed
|
||||
assert.equal(app.match('browser-helper','',entries,{}),null);
|
||||
assert.equal(app.match('web','',entries,{web:'browser.desktop'}),entries[1]);
|
||||
const windows=[{address:'1',appId:'editor',active:false},{address:'2',appId:'editor',active:true},{address:'3',appId:'unknown',active:false}];
|
||||
const groups=app.group(entries,windows,['missing.desktop','org.example.Editor.desktop'],{},true);
|
||||
assert.equal(groups.length,3);assert.equal(groups[0].entry,null);assert.equal(groups[1].windows.length,2);assert.equal(groups[1].focused,true);assert.equal(groups[2].pinned,false);
|
||||
assert.equal(app.group(entries,windows,['org.example.Editor.desktop'],{},false).length,1);
|
||||
const pins=['a.desktop','b.desktop','c.desktop'];
|
||||
assert.equal(JSON.stringify(app.reorder(pins,'a','c')),JSON.stringify(['b.desktop','c.desktop','a.desktop']));assert.equal(pins[0],'a.desktop');
|
||||
const rect={x:100,y:900,width:200,height:80},window={x:90,y:800,width:200,height:150,monitor:'test',workspace:1};
|
||||
assert(geo.obstructed(rect,'test',[window],[1]));
|
||||
assert(!geo.obstructed(rect,'other',[window],[1]));
|
||||
assert(!geo.obstructed(rect,'test',[window],[2]));
|
||||
assert(!geo.obstructed(rect,'test',[{...window,hidden:true}],[1]));
|
||||
assert(!geo.intersects(rect,{x:100,y:820,width:200,height:80}));
|
||||
assert(geo.obstructed(rect,'test',[{...window,x:500,fullscreen:true}],[1]));
|
||||
console.log('Dock matching, ambiguity, pin preservation/reorder, grouping and monitor/workspace overlap tests passed.');
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Opt-in live Hyprland dock test. Uses temporary preferences and disposable windows."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call']
|
||||
FIXTURE=ROOT/'tests/dock-fixture'
|
||||
IDENT='org.glassMxrph.DockFixture'
|
||||
OTHER=IDENT+'Other'
|
||||
def ipc(target,method,*args):
|
||||
result=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True)
|
||||
return json.loads(result.stdout) if result.returncode==0 and result.stdout.strip() else None
|
||||
|
||||
def eventually(check,label,timeout=8):
|
||||
end=time.monotonic()+timeout
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
if check():return
|
||||
except (ValueError,KeyError,TypeError,IndexError,AttributeError,FileNotFoundError):pass
|
||||
time.sleep(.08)
|
||||
raise AssertionError(label+': '+str(ipc('dock','status')))
|
||||
|
||||
def pref(key,value):
|
||||
assert ipc('shell','setPreference','dock.'+key,json.dumps(value)),key
|
||||
|
||||
def fixture_call(method,*args):
|
||||
result=subprocess.run(['quickshell','ipc','--path',str(FIXTURE),'call','fixture',method,*map(str,args)],capture_output=True,text=True)
|
||||
assert result.returncode==0,result.stderr
|
||||
|
||||
def item():return next(i for i in ipc('dock','status')['items'] if i['id']==IDENT)
|
||||
def menu():return ipc('dockTest','rows') or []
|
||||
|
||||
if ipc('shell','status'):
|
||||
raise SystemExit('An instance already uses this source path. Test an isolated copy; do not stop a live shell.')
|
||||
log=ROOT/'.cache/dock-runtime.log';log.parent.mkdir(exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-dock-') as tmp:
|
||||
temp=Path(tmp);apps=temp/'data/applications';apps.mkdir(parents=True)
|
||||
eventfile=temp/'events';helper=temp/'launch.py'
|
||||
helper.write_text('import pathlib,sys\nwith pathlib.Path(sys.argv[1]).open("a") as f:f.write(sys.argv[2]+"\\n")\n')
|
||||
for ident in [IDENT,OTHER]:
|
||||
(apps/(ident+'.desktop')).write_text(f'''[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Dock Fixture {ident[-5:]}
|
||||
Exec=python3 {helper} {eventfile} open
|
||||
Icon=preferences-system
|
||||
StartupWMClass={ident}
|
||||
Actions=NewWindow;
|
||||
|
||||
[Desktop Action NewWindow]
|
||||
Name=New Test Window
|
||||
Exec=python3 {helper} {eventfile} action
|
||||
''')
|
||||
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_DATA_HOME=tmp+'/data',GLASSMXRPH_DOCK_TESTING='1',QT_QPA_PLATFORMTHEME='',QT_NO_XDG_DESKTOP_PORTAL='1')
|
||||
cfg=temp/'config/glassMxrph/config.json';cfg.parent.mkdir(parents=True)
|
||||
cfg.write_text(json.dumps({'schemaVersion':3,'dock':{'showRunningApps':False,'pinnedApps':[IDENT+'.desktop',OTHER+'.desktop']}}))
|
||||
shell=fixture=None
|
||||
try:
|
||||
with log.open('w') as out:
|
||||
shell=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=out,stderr=subprocess.STDOUT)
|
||||
eventually(lambda:ipc('shell','status')['ready'],'config ready')
|
||||
eventually(lambda:len(ipc('dockTest','snapshot')['icons'])==2,'pinned icons')
|
||||
assert item()['running']==0 and item()['matched']
|
||||
assert ipc('dockTest','click',IDENT,1)
|
||||
eventually(lambda:'open' in eventfile.read_text(),'launch desktop entry')
|
||||
assert ipc('dockTest','click',IDENT,2)
|
||||
eventually(lambda:ipc('dock','status')['opened'],'context menu')
|
||||
ipc('launcher','open')
|
||||
eventually(lambda:not ipc('dock','status')['opened'] and ipc('launcher','status')['opened'],'launcher closes dock popup')
|
||||
ipc('launcher','close')
|
||||
time.sleep(.3)
|
||||
assert ipc('dockTest','click',IDENT,2)
|
||||
eventually(lambda:ipc('dock','status')['opened'],'reopen after launcher')
|
||||
eventually(lambda:any(r['id']=='action:NewWindow' for r in menu()),'advertised action')
|
||||
time.sleep(.3)
|
||||
assert ipc('dockTest','row','action:NewWindow')
|
||||
eventually(lambda:'action' in eventfile.read_text(),'desktop action invocation')
|
||||
assert ipc('dockTest','drag',IDENT,OTHER)
|
||||
eventually(lambda:ipc('dock','status')['items'][0]['id']==OTHER,'drag reorder')
|
||||
eventually(lambda:json.loads(cfg.read_text())['dock']['pinnedApps'][0]==OTHER+'.desktop','pin order persisted')
|
||||
assert ipc('dock','move',IDENT,OTHER)
|
||||
fixture=subprocess.Popen(['quickshell','--path',str(FIXTURE)],env=env,stdout=out,stderr=subprocess.STDOUT)
|
||||
eventually(lambda:item()['running']==1,'native window matching')
|
||||
assert ipc('dockTest','click',IDENT,1)
|
||||
eventually(lambda:item()['focused'],'single window focus')
|
||||
fixture_call('two')
|
||||
eventually(lambda:item()['running']==2,'group multiple windows')
|
||||
assert ipc('dockTest','click',IDENT,1)
|
||||
eventually(lambda:ipc('dock','status')['chooser'] and len(menu())==2,'window chooser')
|
||||
time.sleep(.3)
|
||||
first=menu()[0]['id'];assert ipc('dockTest','row',first)
|
||||
eventually(lambda:any(w['address']==first[6:] and w['active'] for w in ipc('dockTest','snapshot')['windows']),'chooser focus')
|
||||
assert ipc('dockTest','click',IDENT,2)
|
||||
eventually(lambda:ipc('dock','status')['opened'] and any(r['id']=='unpin' for r in menu()),'app context')
|
||||
time.sleep(.3)
|
||||
close=next(r['id'] for r in menu() if r['id'].startswith('close:'))
|
||||
assert ipc('dockTest','row',close)
|
||||
eventually(lambda:item()['running']==1,'close requested window')
|
||||
assert ipc('dockTest','click',IDENT,2)
|
||||
eventually(lambda:ipc('dock','status')['opened'],'reopen menu')
|
||||
time.sleep(.3);ipc('dockTest','pressEscape')
|
||||
eventually(lambda:not ipc('dock','status')['opened'],'Escape dismiss')
|
||||
ipc('shell','openSettings','dock')
|
||||
eventually(lambda:ipc('shell','status')['settingsOpen'],'dock settings')
|
||||
time.sleep(.4);ipc('shell','close')
|
||||
pref('visibility','auto');ipc('dockTest','hover','false')
|
||||
eventually(lambda:not ipc('dock','status')['docks'][0]['shown'],'auto hide')
|
||||
assert ipc('dockTest','hover','true')
|
||||
eventually(lambda:ipc('dock','status')['docks'][0]['shown'],'edge reveal')
|
||||
ipc('dockTest','hover','false')
|
||||
pref('monitor',ipc('dockTest','snapshot')['windows'][0]['monitor'])
|
||||
fixture_call('hide')
|
||||
pref('visibility','intelligent')
|
||||
time.sleep(1)
|
||||
baseline=ipc('dock','status')['docks'][0]['overlap']
|
||||
fixture_call('fullscreen','true')
|
||||
eventually(lambda:ipc('dock','status')['docks'][0]['overlap'] and not ipc('dock','status')['docks'][0]['shown'],'intelligent hide behind fullscreen window')
|
||||
fixture_call('hide')
|
||||
eventually(lambda:ipc('dock','status')['docks'][0]['overlap']==baseline and ipc('dock','status')['docks'][0]['shown']!=baseline,'intelligent visibility returns to existing-window baseline')
|
||||
pref('visibility','always');pref('magnification',False)
|
||||
screens=ipc('dockTest','screens')
|
||||
for screen in screens:
|
||||
pref('monitor',screen)
|
||||
for edge in ['bottom','left','right']:
|
||||
pref('position',edge)
|
||||
eventually(lambda:ipc('dock','status')['docks'][0]['screen']==screen and ipc('dock','status')['docks'][0]['position']==edge,'monitor/edge placement')
|
||||
time.sleep(.15)
|
||||
pref('position','bottom');pref('monitor','primary')
|
||||
assert ipc('dockTest','screenshot',str(ROOT/'.cache/dock-preview.png'))
|
||||
pref('enabled',False)
|
||||
eventually(lambda:not ipc('dock','status')['docks'],'disable dock')
|
||||
pref('enabled',True)
|
||||
eventually(lambda:len(ipc('dock','status')['docks'])==1,'enable dock')
|
||||
assert ipc('dockTest','click',OTHER,2)
|
||||
eventually(lambda:ipc('dock','status')['opened'],'unpin context menu')
|
||||
time.sleep(.3)
|
||||
assert ipc('dockTest','row','unpin')
|
||||
eventually(lambda:len(ipc('dock','status')['items'])==1,'unpin')
|
||||
finally:
|
||||
for process in [fixture,shell]:
|
||||
if process and process.poll() is None:
|
||||
process.terminate();process.wait(timeout=5)
|
||||
text=log.read_text()
|
||||
assert 'WARN' not in text and 'ERROR' not in text,text
|
||||
print('PASS: native desktop launch/actions, pin drag/persistence, real window matching/focus/chooser/close, Escape, settings, auto and intelligent hide/reveal, every output/edge, enable/disable, clean logs.')
|
||||
@@ -0,0 +1,38 @@
|
||||
import importlib.util,os,tempfile,unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
spec=importlib.util.spec_from_file_location('glass',Path(__file__).resolve().parents[1]/'quickshell/helpers/glass.py')
|
||||
glass=importlib.util.module_from_spec(spec);spec.loader.exec_module(glass)
|
||||
class GlassTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.options={'layers':True,'values':glass.GHOSTTY.copy()}
|
||||
self.target=glass.values(self.options)
|
||||
self.original={k:('liquid' if k=='default_preset' else 'auto' if k=='layers:mask_mode' else '' if isinstance(v,str) else 0) for k,v in self.target.items()}
|
||||
self.original.update({'layers:namespaces':'other-shell','layers:exclude_namespaces':'wallpaper','layers:namespace_presets':'other-shell:subtle'})
|
||||
self.state=self.original.copy()
|
||||
def fake_put(self,key,value):self.state[key]=value
|
||||
def test_apply_restore_preserves_other_rules(self):
|
||||
with tempfile.TemporaryDirectory() as temp,patch.dict(os.environ,{'XDG_STATE_HOME':temp,'HYPRLAND_INSTANCE_SIGNATURE':'fixture'}),patch.object(glass,'get',lambda k:self.state[k]),patch.object(glass,'put',self.fake_put):
|
||||
self.assertTrue(glass.dispatch({'action':'apply','options':self.options})['available'])
|
||||
self.assertEqual(self.state['default_preset'],'default')
|
||||
self.assertEqual(self.state['layers:namespaces'],'other-shell')
|
||||
glass.dispatch({'action':'restore'})
|
||||
self.assertEqual(self.state,self.original)
|
||||
def test_restore_keeps_external_changes(self):
|
||||
with tempfile.TemporaryDirectory() as temp,patch.dict(os.environ,{'XDG_STATE_HOME':temp,'HYPRLAND_INSTANCE_SIGNATURE':'fixture'}),patch.object(glass,'get',lambda k:self.state[k]),patch.object(glass,'put',self.fake_put):
|
||||
glass.dispatch({'action':'apply','options':self.options})
|
||||
self.state['default_preset']='external'
|
||||
result=glass.dispatch({'action':'restore'})
|
||||
self.assertEqual(self.state['default_preset'],'external');self.assertIn('default_preset',result['notice'])
|
||||
def test_partial_failure_rolls_back(self):
|
||||
def fail(key,value):
|
||||
if key=='dark:brightness' and value!=self.original[key]:raise ValueError('fixture failure')
|
||||
self.fake_put(key,value)
|
||||
with tempfile.TemporaryDirectory() as temp,patch.dict(os.environ,{'XDG_STATE_HOME':temp,'HYPRLAND_INSTANCE_SIGNATURE':'fixture'}),patch.object(glass,'get',lambda k:self.state[k]),patch.object(glass,'put',fail):
|
||||
with self.assertRaises(ValueError):glass.dispatch({'action':'apply','options':self.options})
|
||||
self.assertEqual(self.state,self.original)
|
||||
def test_validation_before_writes(self):
|
||||
for value in [-1,99,'; bad',float('nan')]:
|
||||
o={'layers':True,'values':dict(glass.GHOSTTY,blur_strength=value)}
|
||||
with self.assertRaises(ValueError):glass.values(o)
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,18 @@
|
||||
const fs=require('node:fs'),vm=require('node:vm'),path=require('node:path'),assert=require('node:assert/strict');
|
||||
const root=path.join(__dirname,'..'),search=vm.createContext({});
|
||||
vm.runInContext(fs.readFileSync(path.join(root,'quickshell/launcher/SearchLogic.js'),'utf8'),search);
|
||||
const items=[
|
||||
{id:'edit',title:'Editor',fields:[{text:'Editor'},{text:'Text development',penalty:200}]},
|
||||
{id:'edit-plus',title:'Editor Plus',fields:[{text:'Editor Plus'}]},
|
||||
{id:'photo',title:'Éditeur photo',fields:[{text:'Éditeur photo'}]},
|
||||
{id:'web',title:'Web Browser',fields:[{text:'Web Browser'},{text:'Internet',penalty:200}]}
|
||||
];
|
||||
const index=search.index(items),results=(q,n=50)=>search.rank(index,q,n);
|
||||
assert.equal(results('editor')[0].id,'edit');assert.equal(results('edtr')[0].id,'edit');
|
||||
assert.equal(results('EDITEUR')[0].id,'photo');assert.equal(results('web bro')[0].id,'web');
|
||||
assert.equal(results('internet')[0].id,'web');assert.equal(results('text editor')[0].id,'edit');
|
||||
assert.equal(results('doesnotexist').length,0);assert.equal(results('; rm -rf /').length,0);
|
||||
assert.equal(results('',2).length,2);assert.equal(results(' ').length,4);
|
||||
assert.equal(results('editor impossible').length,0);
|
||||
assert.equal(items[0].title,'Editor');assert(search.score('dock','dock')>search.score('docker','dock'));
|
||||
console.log('Launcher ranking: exact/prefix/fuzzy, accents/case, keywords, multi-token, limits and no-match tests passed.');
|
||||
@@ -0,0 +1,144 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Opt-in live launcher test. Temporary desktop entries/preferences; no real apps launched."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call']
|
||||
ESC,DOWN,UP,ENTER=0x01000000,0x01000015,0x01000013,0x01000004
|
||||
|
||||
def ipc(target,method,*args):
|
||||
p=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True)
|
||||
return json.loads(p.stdout) if p.returncode==0 and p.stdout.strip() else None
|
||||
|
||||
def eventually(check,label,timeout=8):
|
||||
end=time.monotonic()+timeout
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
if check():return
|
||||
except (ValueError,KeyError,TypeError,AttributeError,IndexError,FileNotFoundError):pass
|
||||
time.sleep(.06)
|
||||
raise AssertionError(label+': '+str(ipc('launcherTest','snapshot')))
|
||||
|
||||
def snapshot():return ipc('launcherTest','snapshot') or {}
|
||||
def open_launcher():
|
||||
ipc('launcher','open')
|
||||
eventually(lambda:snapshot()['opened'] and snapshot()['focused'],'launcher focused')
|
||||
# Spotlight style: opens as the bare search bar, listing nothing until typing or browsing.
|
||||
eventually(lambda:abs(snapshot()['width']-680)<1 and abs(snapshot()['height']-60)<1 and not snapshot()['results'],'animation complete')
|
||||
|
||||
def query(text):
|
||||
ipc('launcherTest','query',text)
|
||||
eventually(lambda:snapshot()['query']==text,'query')
|
||||
|
||||
def centered():
|
||||
# Spotlight placement: horizontally centred, top edge in the upper third.
|
||||
s=snapshot()
|
||||
return abs(s['x']+s['width']/2-s['screenWidth']/2)<1 and abs(s['y']-round(s['screenHeight']*0.22))<1
|
||||
|
||||
if ipc('shell','status'):
|
||||
raise SystemExit('This source path is already running. Use an isolated copy; do not replace the active shell.')
|
||||
log=ROOT/'.cache/launcher-runtime.log';log.parent.mkdir(exist_ok=True)
|
||||
monitors=json.loads(subprocess.check_output(['hyprctl','monitors','-j'],text=True))
|
||||
original=next((m['name'] for m in monitors if m['focused']),None)
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-launcher-') as tmp:
|
||||
temp=Path(tmp);apps=temp/'data/applications';apps.mkdir(parents=True)
|
||||
events=temp/'events';helper=temp/'launch.py'
|
||||
helper.write_text('import pathlib,sys\nwith pathlib.Path(sys.argv[1]).open("a") as f:f.write(sys.argv[2]+"\\n")\n')
|
||||
for suffix in ['Alpha','Beta','Hidden','Terminal']:
|
||||
(apps/f'org.glassMxrph.LauncherFixture{suffix}.desktop').write_text(f'''[Desktop Entry]
|
||||
Type=Application
|
||||
Name=GlassMxrph Fixture {suffix}
|
||||
GenericName=Launcher test application
|
||||
Keywords=gmxbrush;painting;
|
||||
Exec=python3 {helper} {events} {suffix}
|
||||
NoDisplay={'true' if suffix=='Hidden' else 'false'}
|
||||
Terminal={'true' if suffix=='Terminal' else 'false'}
|
||||
''')
|
||||
cfg=temp/'config/glassMxrph/config.json';cfg.parent.mkdir(parents=True)
|
||||
# Hermetic: never scan the user's wallpaper folders (and their image formats).
|
||||
cfg.write_text(json.dumps({'schemaVersion':3,'dock':{'enabled':False},'wallpaper':{'directories':[str(temp)]}}))
|
||||
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_DATA_HOME=tmp+'/data',GLASSMXRPH_LAUNCHER_TESTING='1',QT_QPA_PLATFORMTHEME='',QT_NO_XDG_DESKTOP_PORTAL='1')
|
||||
shell=None
|
||||
try:
|
||||
with log.open('w') as out:
|
||||
shell=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=out,stderr=subprocess.STDOUT)
|
||||
eventually(lambda:ipc('shell','status')['ready'],'config ready')
|
||||
for monitor in monitors:
|
||||
subprocess.run(['hyprctl','dispatch','focusmonitor',monitor['name']],check=True,capture_output=True)
|
||||
# With cursor:no_warps and follow_mouse, focus snaps back to the
|
||||
# monitor under the pointer; such monitors cannot be reached here.
|
||||
try:eventually(lambda:snapshot()['activeMonitor']==monitor['name'],'Hyprland focus event',timeout=3)
|
||||
except AssertionError:
|
||||
print('SKIP: cannot focus',monitor['name'],'(pointer-follow focus without cursor warps)');continue
|
||||
open_launcher()
|
||||
assert snapshot()['screen']==monitor['name'] and centered(),snapshot()
|
||||
ipc('launcherTest','outside')
|
||||
eventually(lambda:not snapshot()['visible'],'outside dismissal')
|
||||
# Shell runner toggles the existing instance, never starts another process.
|
||||
subprocess.run([str(ROOT/'scripts/glassmxrph'),'launcher'],env=env,check=True,capture_output=True)
|
||||
eventually(lambda:snapshot()['opened'],'runner IPC toggle')
|
||||
ipc('launcherTest','typeAscii','glass')
|
||||
eventually(lambda:snapshot()['query']=='glass','real keyboard text input')
|
||||
query('GlassMxrph Fixture')
|
||||
eventually(lambda:len(snapshot()['results'])==3,'NoDisplay excluded')
|
||||
assert all(not r['id'].endswith('Hidden') for r in snapshot()['results'])
|
||||
assert ipc('launcherTest','hover',0)
|
||||
ipc('launcherTest','key',DOWN)
|
||||
time.sleep(.3) # Stationary pointer / opening layout must not override selection.
|
||||
assert snapshot()['selected']==1, {k:snapshot()[k] for k in ['selected','focused','width','height','query']}
|
||||
ipc('launcherTest','key',UP);assert snapshot()['selected']==0
|
||||
query('GlassMxrph Fixture Alpha')
|
||||
ipc('launcherTest','key',ENTER)
|
||||
eventually(lambda:events.exists() and 'Alpha' in events.read_text(),'Enter launches native desktop entry')
|
||||
eventually(lambda:not snapshot()['opened'],'launch closes')
|
||||
open_launcher();query('gmfxbt')
|
||||
eventually(lambda:snapshot()['results'][0]['id'].endswith('Beta'),'fuzzy app match')
|
||||
ipc('launcherTest','click',0)
|
||||
eventually(lambda:'Beta' in events.read_text(),'pointer launches result')
|
||||
open_launcher();query('gmxbrush')
|
||||
eventually(lambda:len(snapshot()['results'])==3,'keyword search')
|
||||
query('GlassMxrph Fixture Terminal')
|
||||
ipc('launcherTest','key',ENTER)
|
||||
eventually(lambda:bool(snapshot()['error']) and snapshot()['opened'],'terminal requirement remains visible')
|
||||
assert 'Terminal' not in events.read_text()
|
||||
# Spotlight: the first Escape clears the query, the next one closes.
|
||||
ipc('launcherTest','key',ESC)
|
||||
eventually(lambda:snapshot()['query']=='' and snapshot()['opened'],'Escape clears query')
|
||||
ipc('launcherTest','key',ESC)
|
||||
eventually(lambda:not snapshot()['visible'],'Escape dismiss')
|
||||
open_launcher();query('>')
|
||||
eventually(lambda:{r['id'] for r in snapshot()['results']}=={'about','appearance','audio','bar','tray','bluetooth','controlcenter','display','dock','launcher','media','metrics','network','notifications','power','wallpaper','widgets','osd','lock','dashboard','plugins'},'all commands registered')
|
||||
time.sleep(.3);assert ipc('launcherTest','screenshot',str(ROOT/'.cache/launcher-preview.png'))
|
||||
for text,page in [('>metrics','metrics'),('>wall','wallpaper'),('>dock','dock'),('>media','media'),('>tray','tray'),('>display','displays'),('>launcher','launcher'),('>appearance','appearance'),('>bar','bar'),('>network','network'),('>bluetooth','bluetooth'),('>audio','audio'),('>controlcenter','controlcenter'),('>notifications','notifications'),('>power','power'),('>about','about')]:
|
||||
query(text)
|
||||
ipc('launcherTest','key',ENTER)
|
||||
eventually(lambda:ipc('shell','status')['settingsOpen'] and ipc('shell','status')['settingsPage']==page,'command destination '+page)
|
||||
assert not snapshot()['opened']
|
||||
open_launcher()
|
||||
assert not ipc('shell','status')['settingsOpen']
|
||||
query('>command-that-does-not-exist')
|
||||
assert not snapshot()['results']
|
||||
ipc('launcherTest','key',ENTER);assert snapshot()['opened']
|
||||
assert ipc('launcherTest','extension','true')
|
||||
assert not ipc('launcherTest','extension','true'),'Duplicate command accepted'
|
||||
query('>fixture');ipc('launcherTest','key',ENTER)
|
||||
eventually(lambda:ipc('shell','status')['settingsPage']=='about','extension execution')
|
||||
ipc('launcherTest','extension','false');ipc('shell','close')
|
||||
# Reduced motion and rapid reversals must settle without hidden keyboard grabs.
|
||||
assert ipc('shell','setPreference','animation.reducedMotion','true')
|
||||
for _ in range(6):ipc('launcher','toggle')
|
||||
eventually(lambda:not snapshot()['opened'] and not snapshot()['visible'],'rapid toggle settles')
|
||||
open_launcher();assert centered()
|
||||
ipc('shell','close')
|
||||
eventually(lambda:not snapshot()['opened'],'shared close IPC')
|
||||
finally:
|
||||
if shell and shell.poll() is None:shell.terminate();shell.wait(timeout=5)
|
||||
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
|
||||
print('PASS: centered active-monitor placement, keyboard/text/mouse input, fuzzy/keyword search, NoDisplay filtering, native launch/errors, all commands and extension lifecycle, settings routes, outside/Escape, reduced motion, rapid toggles, clean logs.')
|
||||
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run with dbus-run-session, real Wayland and dbus-python/PyGObject."""
|
||||
import json,os,subprocess,tempfile,time,shutil
|
||||
from pathlib import Path
|
||||
import dbus
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call']
|
||||
def ipc(target,method,*args):
|
||||
r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True)
|
||||
return json.loads(r.stdout) if r.returncode==0 and r.stdout.strip() else None
|
||||
def state():return ipc('media','status') or {}
|
||||
def wait(check,label):
|
||||
end=time.monotonic()+12
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
if check():return
|
||||
except (KeyError,TypeError,ValueError):pass
|
||||
time.sleep(.1)
|
||||
raise AssertionError(label+': '+str(state()))
|
||||
def pref(key,value):assert ipc('shell','setPreference',key,' '+json.dumps(value)), str(ipc('shell','status'))
|
||||
if ipc('shell','status'):raise SystemExit('Use an isolated source path; instance already running.')
|
||||
log=ROOT/'.cache/media-runtime.log';log.parent.mkdir(exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-media-') as tmp:
|
||||
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_CACHE_HOME=tmp+'/cache',GLASSMXRPH_MEDIA_TESTING='1',QT_QPA_PLATFORMTHEME='',QT_NO_XDG_DESKTOP_PORTAL='1')
|
||||
fail=Path(tmp)/'cava-failure';binpath=Path(tmp)/'bin';binpath.mkdir()
|
||||
actual_cava=shutil.which('cava')
|
||||
if not actual_cava:raise SystemExit('Cava must be available for this integration test.')
|
||||
wrapper=binpath/'cava'
|
||||
wrapper.write_text('#!/usr/bin/env python3\nimport os,sys,pathlib\nif pathlib.Path('+repr(str(fail))+').exists():\n print("Synthetic Cava failure",file=sys.stderr)\n sys.exit(127)\nos.execv('+repr(actual_cava)+',['+repr(actual_cava)+']+sys.argv[1:])\n');wrapper.chmod(0o755)
|
||||
env['PATH']=str(binpath)+os.pathsep+env['PATH']
|
||||
events=Path(tmp)/'events';children=[]
|
||||
with log.open('w') as output:
|
||||
shell=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=output,stderr=subprocess.STDOUT)
|
||||
try:
|
||||
wait(lambda:ipc('shell','status')['ready'],'shell ready')
|
||||
wait(lambda:state().get('title')=='Nothing playing','empty state')
|
||||
assert ipc('media','toggle') is False
|
||||
for name in ['fixtureOne','fixtureTwo']:
|
||||
children.append(subprocess.Popen(['python3',str(ROOT/'tests/mpris_fixture.py'),name,str(events)],stdout=output,stderr=subprocess.STDOUT))
|
||||
wait(lambda:len(state()['players'])==2,'discovery')
|
||||
bus=dbus.SessionBus()
|
||||
def update(name,data):dbus.Interface(bus.get_object('org.mpris.MediaPlayer2.'+name,'/org/mpris/MediaPlayer2'),'org.glassMxrph.Test').Update(json.dumps(data))
|
||||
update('fixtureTwo',{'PlaybackStatus':'Playing'})
|
||||
wait(lambda:state()['selected'].endswith('fixtureTwo'),'automatic playing player')
|
||||
assert ipc('media','select','org.mpris.MediaPlayer2.fixtureOne')
|
||||
wait(lambda:state()['selected'].endswith('fixtureOne'),'manual selection')
|
||||
assert state()['length']==180 and state()['artist']=='Fixture artist'
|
||||
assert ipc('media','toggle');assert ipc('media','next');assert ipc('media','previous');assert ipc('media','seek',45)
|
||||
wait(lambda:state()['playing'] and state()['position']>=45,'play and seek seconds')
|
||||
records=[json.loads(s) for s in events.read_text().splitlines()]
|
||||
assert {'play','next','previous','seek'} <= {e['method'] for e in records}
|
||||
assert next(e for e in records if e['method']=='seek')['position']==45000000
|
||||
update('fixtureOne',{'CanSeek':False,'CanGoNext':False,'CanGoPrevious':False,'CanPause':False,'Title':'Updated song'})
|
||||
wait(lambda:state()['title']=='Updated song' and not state()['seekable'],'metadata/capabilities')
|
||||
assert ipc('media','next') is False and ipc('media','previous') is False and ipc('media','seek',10) is False
|
||||
pref('media.preferredPlayer','org.mpris.MediaPlayer2.fixtureTwo')
|
||||
wait(lambda:state()['selected'].endswith('fixtureTwo'),'preferred player')
|
||||
pref('bar.modules',[{'id':'nowPlaying','position':'right','enabled':True}])
|
||||
ipc('shell','openSettings','media');time.sleep(.5)
|
||||
assert ipc('mediaTest','click','mediaToggle')
|
||||
wait(lambda:not state()['playing'],'widget pause click')
|
||||
assert ipc('mediaTest','click','mediaToggle')
|
||||
wait(lambda:state()['playing'],'widget play click')
|
||||
pref('media.showCava',True)
|
||||
wait(lambda:ipc('cava','status')['running'],'Cava starts')
|
||||
wait(lambda:ipc('cava','status')['frames']>2,'Cava frame shape')
|
||||
assert ipc('mediaTest','screenshot',str(ROOT/'.cache/music-preview.png'))
|
||||
time.sleep(.2)
|
||||
update('fixtureTwo',{'PlaybackStatus':'Paused'})
|
||||
wait(lambda:not ipc('cava','status')['running'],'Cava stops on pause')
|
||||
update('fixtureTwo',{'PlaybackStatus':'Playing'})
|
||||
wait(lambda:ipc('cava','status')['running'],'Cava resumes')
|
||||
ipc('shell','close')
|
||||
wait(lambda:not ipc('cava','status')['running'],'Cava stops without visible views')
|
||||
ipc('shell','openSettings','media')
|
||||
wait(lambda:ipc('cava','status')['running'],'Cava restarts with visible card')
|
||||
pref('media.showCava',False)
|
||||
wait(lambda:not ipc('cava','status')['running'],'Cava stops')
|
||||
fail.touch();pref('media.showCava',True)
|
||||
wait(lambda:bool(ipc('cava','status')['error']) and not ipc('cava','status')['running'],'Cava failure fallback')
|
||||
time.sleep(.3);assert not ipc('cava','status')['running'],'Cava restarted after failure'
|
||||
pref('media.showCava',False);fail.unlink();pref('media.showCava',True)
|
||||
wait(lambda:ipc('cava','status')['running'] and not ipc('cava','status')['error'],'Cava recovery')
|
||||
pref('media.showCava',False)
|
||||
pref('media.showAlbumArt',False);pref('media.showProgress',False)
|
||||
update('fixtureTwo',{'NoLength':True})
|
||||
wait(lambda:state()['length']==0 and not state()['seekable'],'unknown length stream')
|
||||
children[1].terminate();children[1].wait(timeout=5)
|
||||
wait(lambda:len(state()['players'])==1 and state()['selected'].endswith('fixtureOne'),'disconnect fallback')
|
||||
children[0].terminate();children[0].wait(timeout=5)
|
||||
wait(lambda:len(state()['players'])==0 and state()['title']=='Nothing playing','last player removal')
|
||||
finally:
|
||||
for proc in children:
|
||||
if proc.poll() is None:proc.terminate();proc.wait(timeout=5)
|
||||
shell.terminate();shell.wait(timeout=5)
|
||||
text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text
|
||||
print('PASS: empty state, two-player discovery/selection/fallback, metadata, capability guards, playback DBus actions, seek units, settings/bar, Cava lifecycle, clean runtime logs.')
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only live metrics integration with isolated preferences; no hardware writes."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
SHELL=ROOT/'quickshell'
|
||||
def ipc(target,method,*args):
|
||||
p=subprocess.run(['quickshell','ipc','--path',str(SHELL),'call',target,method,*args],capture_output=True,text=True,timeout=5)
|
||||
if p.returncode:return None
|
||||
try:return json.loads(p.stdout)
|
||||
except ValueError:return p.stdout.strip()
|
||||
def wait(check,timeout=15):
|
||||
end=time.monotonic()+timeout
|
||||
while time.monotonic()<end:
|
||||
if check():return
|
||||
time.sleep(.15)
|
||||
raise AssertionError('Runtime condition timed out')
|
||||
def state():return ipc('metrics','status') or {}
|
||||
def pref(key,value):
|
||||
result=ipc('shell','setPreference',key,' '+json.dumps(value,separators=(",",":")))
|
||||
assert result is True,(key,result,ipc('shell','status'))
|
||||
if ipc('shell','status'):raise SystemExit('An existing instance is running; stop it before this isolated test.')
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-metrics-') as tmp:
|
||||
env=dict(os.environ,GLASSMXRPH_METRICS_TESTING='1',XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state')
|
||||
log=Path(tmp)/'runtime.log'
|
||||
with log.open('w') as out:
|
||||
p=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=out,stderr=subprocess.STDOUT)
|
||||
try:
|
||||
# Nothing on the desktop samples by default; the collector idles.
|
||||
wait(lambda:state().get('consumers')==0 and not state().get('running'))
|
||||
ipc('shell','openSettings','metrics')
|
||||
wait(lambda:state().get('consumers')==1 and state().get('samples',0)>=2)
|
||||
assert ipc('metricsTest','screenshot',str(ROOT/'.cache/metrics-preview.png')) is True
|
||||
wait(lambda:(ROOT/'.cache/metrics-preview.png').exists())
|
||||
s=state();assert not s['error'] and not s['stale'],s
|
||||
assert 0<=s['snapshot']['cpu']['percent']<=100,s
|
||||
assert s['snapshot']['ram']['total']>0,s
|
||||
ipc('shell','close')
|
||||
wait(lambda:state().get('consumers')==0 and not state().get('running'))
|
||||
before=state()['samples'];time.sleep(2.2);assert state()['samples']==before
|
||||
monitors=json.loads(subprocess.check_output(['hyprctl','-j','monitors']))
|
||||
pref('bar.modules',[{'id':k,'enabled':True,'position':'right'} for k in ['cpu','gpu','ram','storage','cpuTemperature','gpuTemperature','networkThroughput']])
|
||||
wait(lambda:state().get('consumers')==7*len(monitors) and state().get('samples',0)>before)
|
||||
pref('bar.modules',[])
|
||||
ipc('shell','openSettings','metrics')
|
||||
wait(lambda:state().get('consumers')==1)
|
||||
pref('metrics.interval',1)
|
||||
pref('metrics.storagePaths',['/','/missing-glassmxrph-test'])
|
||||
wait(lambda:len(state().get('snapshot',{}).get('storage',[]))==2)
|
||||
assert not state()['snapshot']['storage'][1]['available']
|
||||
pref('metrics.networkInterface','missing-glassmxrph-test')
|
||||
wait(lambda:state().get('snapshot',{}).get('network',{}).get('selected')==['missing-glassmxrph-test'])
|
||||
assert state()['snapshot']['network']['download'] is None
|
||||
pref('controlCenter.modules',[{'id':'metrics','enabled':True}])
|
||||
ipc('controlcenter','open')
|
||||
wait(lambda:state().get('consumers')==1)
|
||||
ipc('controlcenter','close')
|
||||
wait(lambda:state().get('consumers')==0 and not state().get('running'))
|
||||
# Desktop widgets sample only while their desktop is uncovered: no
|
||||
# tiled or fullscreen window on the monitor's active workspace.
|
||||
clients=json.loads(subprocess.check_output(['hyprctl','-j','clients']))
|
||||
active={m['activeWorkspace']['id'] for m in monitors}
|
||||
covered={c['monitor'] for c in clients if c['workspace']['id'] in active and (not c['floating'] or c['fullscreen'])}
|
||||
widget=lambda m:{'version':1,'grid':False,'items':[{'id':'cpu-1','type':'cpu','variant':'','monitor':m['name'],'x':40,'y':40,'w':180,'h':130,'opacity':1}]}
|
||||
hidden=[m for m in monitors if m['id'] in covered]
|
||||
shown=[m for m in monitors if m['id'] not in covered]
|
||||
if hidden:
|
||||
pref('desktopWidgets',widget(hidden[0]))
|
||||
time.sleep(3)
|
||||
assert state().get('consumers')==0 and not state().get('running'),state()
|
||||
if shown:
|
||||
pref('desktopWidgets',widget(shown[0]))
|
||||
wait(lambda:state().get('consumers')>=1 and state().get('running'))
|
||||
config=Path(tmp)/'config/glassMxrph/config.json'
|
||||
wait(lambda:config.exists() and json.loads(config.read_text())['metrics']['interval']==1)
|
||||
finally:
|
||||
p.terminate();p.wait(timeout=8)
|
||||
(ROOT/'.cache/phase8-runtime.log').write_text(log.read_text())
|
||||
text=log.read_text()
|
||||
assert 'WARN' not in text and 'ERROR' not in text,text
|
||||
print('PASS: live counters, shared bar/settings/Control Center consumers, idle shutdown/restart, source changes, unavailable sources, persistence and clean QML/DBus logs.')
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
spec = importlib.util.spec_from_file_location('metrics', Path(__file__).resolve().parents[1] / 'quickshell/helpers/metrics.py')
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
|
||||
class MetricsTests(unittest.TestCase):
|
||||
def test_cpu_guest_not_double_counted_and_resets(self):
|
||||
self.assertEqual(m.cpu_counts('cpu 10 20 30 40 5 6 7 8 100 200'), (126,45))
|
||||
self.assertIsNone(m.cpu_percent(None,(100,20)))
|
||||
self.assertEqual(m.cpu_percent((100,20),(200,70)),50)
|
||||
self.assertIsNone(m.cpu_percent((200,70),(100,20)))
|
||||
self.assertIsNone(m.cpu_percent((100,20),(200,10)))
|
||||
|
||||
def test_ram_available_cache(self):
|
||||
r=m.memory('MemTotal: 100 kB\nMemFree: 10 kB\nMemAvailable: 40 kB')
|
||||
self.assertEqual(r['used'],60*1024)
|
||||
self.assertEqual(r['percent'],60)
|
||||
self.assertFalse(m.memory('MemTotal: 100 kB')['available'])
|
||||
|
||||
def test_network_time_reset_and_new_interface(self):
|
||||
current=m.net_counts(' eth0: 100 0 0 0 0 0 0 0 200 0 0 0 0 0 0 0')
|
||||
self.assertEqual(m.net_rates({'eth0':(50,100)},current,2)['eth0'],{'download':25,'upload':50})
|
||||
self.assertEqual(m.net_rates({'eth0':(500,500)},current,2)['eth0'],{'download':0,'upload':0})
|
||||
self.assertEqual(m.net_rates({},current,2),{})
|
||||
self.assertEqual(m.net_rates(current,current,0),{})
|
||||
|
||||
def test_nvidia_partial_sensor_and_invalid_numbers(self):
|
||||
result=m.nvidia_rows('GPU-1, NVIDIA Example, 30, 60, 1024, 8192, 1200, [N/A]\nGPU-2, Other, N/A, N/A, N/A, N/A, N/A, N/A')
|
||||
self.assertEqual(len(result),2)
|
||||
self.assertEqual(result[0]['used'],1024**3)
|
||||
self.assertIsNone(result[0]['power'])
|
||||
self.assertIsNone(result[1]['percent'])
|
||||
for value in ['nan','inf','-1','N/A']:
|
||||
self.assertIsNone(m.number(value))
|
||||
|
||||
def test_missing_sources_and_storage_path_failure(self):
|
||||
with patch.object(m,'read',return_value=''),patch.object(m.shutil,'which',return_value=None):
|
||||
c=m.Collector({'storagePaths':['/definitely/missing/glassmxrph']})
|
||||
with patch.object(c,'gpu',return_value=[]):
|
||||
result=c.sample()
|
||||
self.assertIsNone(result['cpu']['percent'])
|
||||
self.assertFalse(result['ram']['available'])
|
||||
self.assertFalse(result['storage'][0]['available'])
|
||||
self.assertTrue(result['warnings'])
|
||||
|
||||
def test_amd_units(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
base=Path(temp)/'card1/device';hw=base/'hwmon/hwmon1';hw.mkdir(parents=True)
|
||||
for file,value in {'vendor':'0x1002','gpu_busy_percent':'25','mem_info_vram_used':'1024','mem_info_vram_total':'4096'}.items():
|
||||
(base/file).write_text(value)
|
||||
for file,value in {'temp1_input':'52000','freq1_input':'1500000000','power1_average':'23000000'}.items():
|
||||
(hw/file).write_text(value)
|
||||
c=m.Collector({});c.nvidia=None
|
||||
original=m.Path.glob
|
||||
def glob(p, pattern):
|
||||
return iter([base]) if str(p)=='/sys/class/drm' else original(p,pattern)
|
||||
with patch.object(m.Path,'glob',glob):
|
||||
gpu=c.gpu()[0]
|
||||
self.assertEqual((gpu['temperature'],gpu['frequency'],gpu['power']), (52,1500,23))
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synthetic MPRIS player; run only on the test's private session bus."""
|
||||
import json,sys
|
||||
from pathlib import Path
|
||||
import dbus,dbus.service
|
||||
from dbus.mainloop.glib import DBusGMainLoop
|
||||
from gi.repository import GLib
|
||||
DBusGMainLoop(set_as_default=True)
|
||||
bus=dbus.SessionBus();name=dbus.service.BusName('org.mpris.MediaPlayer2.'+sys.argv[1],bus)
|
||||
ROOT='org.mpris.MediaPlayer2';PLAYER=ROOT+'.Player';PROPS='org.freedesktop.DBus.Properties';TEST='org.glassMxrph.Test'
|
||||
events=Path(sys.argv[2])
|
||||
art=events.parent/'art.svg'
|
||||
art.write_text('<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256"><rect width="256" height="256" fill="#193844"/><circle cx="128" cy="128" r="85" fill="#477d86"/><circle cx="128" cy="128" r="36" fill="#193844"/><circle cx="128" cy="128" r="8" fill="#d4e4d9"/></svg>')
|
||||
def record(method,**args):
|
||||
with events.open('a') as f:f.write(json.dumps(dict(method=method,**args))+'\n')
|
||||
class Player(dbus.service.Object):
|
||||
def __init__(self):
|
||||
super().__init__(bus,'/org/mpris/MediaPlayer2')
|
||||
self.root={'Identity':sys.argv[1],'DesktopEntry':sys.argv[1],'CanQuit':False,'CanRaise':False,'HasTrackList':False,'SupportedUriSchemes':dbus.Array([],signature='s'),'SupportedMimeTypes':dbus.Array([],signature='s')}
|
||||
self.props={'PlaybackStatus':'Paused','LoopStatus':'None','Rate':1.0,'Shuffle':False,'Volume':0.5,'Position':dbus.Int64(12000000),'MinimumRate':1.0,'MaximumRate':1.0,'CanGoNext':True,'CanGoPrevious':True,'CanPlay':True,'CanPause':True,'CanSeek':True,'CanControl':True,'Metadata':self.metadata('Fixture song')}
|
||||
def metadata(self,title):return dbus.Dictionary({'mpris:trackid':dbus.ObjectPath('/track/one'),'mpris:length':dbus.Int64(180000000),'xesam:title':title,'xesam:artist':dbus.Array(['Fixture artist'],signature='s'),'xesam:album':'Fixture album','mpris:artUrl':art.as_uri()},signature='sv')
|
||||
@dbus.service.method(PROPS,in_signature='s',out_signature='a{sv}')
|
||||
def GetAll(self,interface):return self.root if interface==ROOT else self.props if interface==PLAYER else {}
|
||||
@dbus.service.method(PROPS,in_signature='ss',out_signature='v')
|
||||
def Get(self,interface,key):return self.GetAll(interface)[key]
|
||||
@dbus.service.method(PROPS,in_signature='ssv')
|
||||
def Set(self,interface,key,value):self.props[key]=value;self.PropertiesChanged(PLAYER,{key:value},[])
|
||||
@dbus.service.signal(PROPS,signature='sa{sv}as')
|
||||
def PropertiesChanged(self,interface,changed,invalidated):pass
|
||||
@dbus.service.signal(PLAYER,signature='x')
|
||||
def Seeked(self,position):pass
|
||||
@dbus.service.method(PLAYER)
|
||||
def PlayPause(self):
|
||||
record('toggle');self.props['PlaybackStatus']='Paused' if self.props['PlaybackStatus']=='Playing' else 'Playing';self.PropertiesChanged(PLAYER,{'PlaybackStatus':self.props['PlaybackStatus']},[])
|
||||
@dbus.service.method(PLAYER)
|
||||
def Play(self):
|
||||
record('play');self.props['PlaybackStatus']='Playing';self.PropertiesChanged(PLAYER,{'PlaybackStatus':'Playing'},[])
|
||||
@dbus.service.method(PLAYER)
|
||||
def Pause(self):
|
||||
record('pause');self.props['PlaybackStatus']='Paused';self.PropertiesChanged(PLAYER,{'PlaybackStatus':'Paused'},[])
|
||||
@dbus.service.method(PLAYER)
|
||||
def Next(self):record('next')
|
||||
@dbus.service.method(PLAYER)
|
||||
def Previous(self):record('previous')
|
||||
@dbus.service.method(PLAYER,in_signature='ox')
|
||||
def SetPosition(self,track,position):record('seek',track=str(track),position=int(position));self.props['Position']=position;self.Seeked(position)
|
||||
@dbus.service.method(PLAYER,in_signature='x')
|
||||
def Seek(self,offset):self.SetPosition('/track/one',self.props['Position']+offset)
|
||||
@dbus.service.method(TEST,in_signature='s')
|
||||
def Update(self,payload):
|
||||
changes=json.loads(payload)
|
||||
if 'Title' in changes:changes['Metadata']=self.metadata(changes.pop('Title'))
|
||||
if changes.pop('NoLength',False):
|
||||
changes['Metadata']=self.metadata('Live stream');del changes['Metadata']['mpris:length']
|
||||
self.props.update(changes);self.PropertiesChanged(PLAYER,changes,[])
|
||||
player=Player();GLib.MainLoop().run()
|
||||
@@ -0,0 +1,10 @@
|
||||
const fs=require('node:fs'),vm=require('node:vm'),path=require('node:path'),assert=require('node:assert/strict');
|
||||
const color=vm.createContext({});
|
||||
vm.runInContext(fs.readFileSync(path.join(__dirname,'../quickshell/theme/ColorLogic.js'),'utf8'),color);
|
||||
for(let r=0;r<=255;r+=15)for(let g=0;g<=255;g+=15)for(let b=0;b<=255;b+=15){
|
||||
const l=color.luminance(r/255,g/255,b/255),dark=color.darkForeground(r/255,g/255,b/255);
|
||||
assert(color.contrast(l,dark?0:1)>=4.5,`${r},${g},${b}`);
|
||||
}
|
||||
assert.equal(color.luminance(0,0,0),0);
|
||||
assert.equal(color.luminance(1,1,1),1);
|
||||
console.log('Phase 9: accent foreground contrast passes 4.5:1 over RGB grid.');
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Isolated read-only session: motion, palette recovery, output fallback and collector recovery."""
|
||||
import json,os,signal,subprocess,tempfile,time
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def ipc(target,method,*args):
|
||||
p=subprocess.run(['quickshell','ipc','--path',str(ROOT/'quickshell'),'call',target,method,*args],capture_output=True,text=True,timeout=5)
|
||||
return json.loads(p.stdout) if p.returncode==0 and p.stdout.strip() else None
|
||||
def wait(check):
|
||||
end=time.monotonic()+15
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
if check():return
|
||||
except (KeyError,TypeError,ValueError):pass
|
||||
time.sleep(.1)
|
||||
raise AssertionError('Timed out')
|
||||
def pref(key,value):assert ipc('shell','setPreference',key,' '+json.dumps(value)) is True
|
||||
if ipc('shell','status'):raise SystemExit('Stop the project preview before this isolated test.')
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-polish-') as tmp:
|
||||
env=dict(os.environ,GLASSMXRPH_POLISH_TESTING='1',XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state')
|
||||
log=ROOT/'.cache/polish-runtime.log'
|
||||
with log.open('w') as out:
|
||||
proc=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=out,stderr=subprocess.STDOUT)
|
||||
try:
|
||||
wait(lambda:ipc('shell','status')['ready'])
|
||||
pref('animation.reducedMotion',True)
|
||||
wait(lambda:ipc('polishTest','snapshot')['intensity']==0)
|
||||
assert ipc('polishTest','snapshot')['duration']==0
|
||||
assert all(i['influence']==0 and i['magnification']==1 for i in ipc('polishTest','snapshot')['dock'])
|
||||
ipc('shell','openSettings','appearance');ipc('polishTest','staleScreens')
|
||||
wait(lambda:ipc('polishTest','snapshot')['settingsScreen']==ipc('polishTest','snapshot')['active'])
|
||||
ipc('controlcenter','open');ipc('polishTest','staleScreens')
|
||||
wait(lambda:ipc('polishTest','snapshot')['controlScreen']==ipc('polishTest','snapshot')['active'])
|
||||
ipc('shell','close')
|
||||
for _ in range(5):
|
||||
ipc('launcher','toggle');ipc('shell','openSettings','appearance');ipc('controlcenter','open');ipc('shell','close')
|
||||
palette=Path(tmp)/'state/glassMxrph/palette.json'
|
||||
palette.write_text('{broken')
|
||||
wait(lambda:bool(ipc('theme','status')['error']))
|
||||
palette.write_text(json.dumps({'accent':'#889922','accentText':'#889922'}))
|
||||
wait(lambda:not ipc('theme','status')['error'])
|
||||
pref('appearance.accentSource','matugen')
|
||||
wait(lambda:ipc('polishTest','snapshot')['accent']=='#889922')
|
||||
assert ipc('polishTest','snapshot')['foreground'] in ['#000000','#ffffff']
|
||||
pref('appearance.accentSource','custom');pref('appearance.customAccent','#ffffff')
|
||||
wait(lambda:ipc('polishTest','snapshot')['foreground']=='#000000')
|
||||
pref('appearance.customAccent','#000000')
|
||||
wait(lambda:ipc('polishTest','snapshot')['foreground']=='#ffffff')
|
||||
# The collector is demand-driven; the metrics page keeps it running.
|
||||
ipc('shell','openSettings','metrics')
|
||||
wait(lambda:ipc('metrics','status')['samples']>=2)
|
||||
old=ipc('metrics','status');pid=old['processId']
|
||||
assert str(ROOT/'quickshell/helpers/metrics.py').encode() in Path(f'/proc/{pid}/cmdline').read_bytes().split(b'\0')
|
||||
os.kill(pid,signal.SIGTERM)
|
||||
wait(lambda:ipc('metrics','status')['stale'])
|
||||
wait(lambda:ipc('metrics','status')['processId']!=pid and ipc('metrics','status')['samples']>old['samples'])
|
||||
assert not ipc('metrics','status')['error']
|
||||
ipc('shell','close')
|
||||
pref('animation.reducedMotion',False)
|
||||
wait(lambda:ipc('polishTest','snapshot')['duration']>0)
|
||||
ipc('shell','openSettings','appearance');ipc('shell','close')
|
||||
finally:
|
||||
proc.terminate();proc.wait(timeout=8)
|
||||
text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text
|
||||
print('PASS: reduced motion, rapid popup routing, stale-screen fallback, palette error recovery, accent contrast, collector termination/recovery and clean logs.')
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Filesystem and argument safety checks; no real wallpaper service is modified."""
|
||||
import importlib.util,json,subprocess,sys,tempfile,unittest
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('desktop',ROOT/'quickshell/helpers/desktop.py');desktop=importlib.util.module_from_spec(spec);spec.loader.exec_module(desktop)
|
||||
class Providers(unittest.TestCase):
|
||||
def test_scan_and_argument_boundaries(self):
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-provider-') as directory:
|
||||
root=Path(directory);image=root/"a ' quoted ; $(echo nope).png";image.write_bytes(b'fixture')
|
||||
(root/'ignore.txt').write_text('no image')
|
||||
result=desktop.scan({'directories':[directory,directory,str(root/'missing')]})
|
||||
self.assertEqual(len(result['images']),1);self.assertIn('%20',result['images'][0]['url']);self.assertTrue(result['notice'])
|
||||
record=root/'record.json';helper=root/'record.py';helper.write_text('import json,pathlib,sys\npathlib.Path(sys.argv[1]).write_text(json.dumps(sys.argv[2:]))\n')
|
||||
result=desktop.apply({'backend':'custom','monitor':'TEST-1','path':str(image),'command':[sys.executable,str(helper),str(record),'{path}','{monitor}']})
|
||||
self.assertEqual(json.loads(record.read_text()),[str(image),'TEST-1']);self.assertEqual(result['path'],str(image))
|
||||
with self.assertRaises(ValueError):desktop.apply({'backend':'custom','monitor':'TEST-1','path':str(image),'command':['tool']})
|
||||
with self.assertRaises(ValueError):desktop.apply({'backend':'custom','monitor':'bad; command','path':str(image),'command':[]})
|
||||
def test_errors_are_json(self):
|
||||
p=subprocess.run([sys.executable,str(ROOT/'quickshell/helpers/desktop.py'),json.dumps({'action':'palette','executable':'/missing/matugen','path':'/missing'})],capture_output=True,text=True,check=True)
|
||||
self.assertFalse(json.loads(p.stdout)['ok']);self.assertEqual(p.stderr,'')
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Opt-in real Wayland smoke test. Run with no glassMxrph instance active."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SHELL = ROOT / 'quickshell'
|
||||
|
||||
def ipc(method, *args):
|
||||
return subprocess.run(['quickshell', 'ipc', '--path', str(SHELL), 'call', 'shell', method, *args], text=True, capture_output=True)
|
||||
|
||||
def eventually(check, timeout=8):
|
||||
end = time.monotonic() + timeout
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
if check():
|
||||
return
|
||||
except (ValueError, KeyError, FileNotFoundError):
|
||||
pass
|
||||
time.sleep(.1)
|
||||
raise AssertionError('Runtime condition timed out')
|
||||
|
||||
def status():
|
||||
result = ipc('status')
|
||||
return json.loads(result.stdout) if result.returncode == 0 else {}
|
||||
|
||||
if ipc('status').returncode == 0:
|
||||
raise SystemExit('Stop the existing glassMxrph instance before this isolated test.')
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-runtime-') as tmp:
|
||||
env = dict(os.environ, XDG_CONFIG_HOME=tmp + '/config', XDG_STATE_HOME=tmp + '/state')
|
||||
config = Path(tmp) / 'config/glassMxrph/config.json'
|
||||
palette = Path(tmp) / 'state/glassMxrph/palette.json'
|
||||
log = Path(tmp) / 'runtime.log'
|
||||
with log.open('w') as output:
|
||||
proc = subprocess.Popen([str(ROOT / 'scripts/glassmxrph'), 'run'], env=env, stdout=output, stderr=subprocess.STDOUT)
|
||||
try:
|
||||
eventually(lambda: status().get('ready'))
|
||||
duplicate = subprocess.run([str(ROOT / 'scripts/glassmxrph'), 'run'], env=env, capture_output=True, timeout=5)
|
||||
assert duplicate.returncode == 0, duplicate.stderr
|
||||
assert ipc('setPreference', 'appearance.customAccent', '"#167d9a"').stdout.strip() == 'true'
|
||||
assert ipc('setPreference', 'appearance.accentSource', '"custom"').stdout.strip() == 'true'
|
||||
eventually(lambda: config.exists() and json.loads(config.read_text())['appearance']['customAccent'] == '#167d9a')
|
||||
eventually(lambda: status().get('accent') == '#167d9a')
|
||||
palette.write_text(json.dumps({'accent':'#d29442'}))
|
||||
assert ipc('setPreference', 'appearance.accentSource', '"matugen"').stdout.strip() == 'true'
|
||||
eventually(lambda: status().get('accent') == '#d29442')
|
||||
palette.write_text(json.dumps({'accent':'#32966b'}))
|
||||
eventually(lambda: status().get('accent') == '#32966b')
|
||||
ipc('openSettings', 'appearance')
|
||||
eventually(lambda: status().get('settingsOpen'))
|
||||
ipc('close')
|
||||
eventually(lambda: status().get('settingsOpen') is False)
|
||||
# Corrupt external edits must not destroy valid in-memory settings or overwrite the file.
|
||||
eventually(lambda: json.loads(config.read_text())['appearance']['accentSource'] == 'matugen')
|
||||
config.write_text('{broken')
|
||||
eventually(lambda: bool(status().get('error')))
|
||||
assert ipc('setPreference', 'appearance.customAccent', '"#ffffff"').stdout.strip() == 'false'
|
||||
assert config.read_text() == '{broken'
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
text = log.read_text()
|
||||
assert 'WARN' not in text and 'ERROR' not in text, text
|
||||
print('PASS: live Wayland, duplicate prevention, preference persistence, live palette updates, settings IPC, corrupt-file protection, clean runtime logs.')
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real settings/palette integration using disposable images and a recording wallpaper backend."""
|
||||
import json,os,struct,subprocess,tempfile,time,zlib,shutil
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
BASE=['quickshell','ipc','--path',str(ROOT/'quickshell'),'call']
|
||||
def ipc(target,method,*args):
|
||||
r=subprocess.run(BASE+[target,method,*map(str,args)],capture_output=True,text=True)
|
||||
return json.loads(r.stdout) if r.returncode==0 and r.stdout.strip() else None
|
||||
def state():return ipc('settingsTest','snapshot') or {}
|
||||
def eventually(check,label,timeout=12):
|
||||
end=time.monotonic()+timeout
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
if check():return
|
||||
except (ValueError,KeyError,TypeError,AttributeError,FileNotFoundError,IndexError):pass
|
||||
time.sleep(.08)
|
||||
raise AssertionError(label+': '+str(ipc('theme','status'))+' '+str(ipc('wallpaper','status')))
|
||||
def pref(key,value):assert ipc('shell','setPreference',key,json.dumps(value)),key
|
||||
def png(path,rgb):
|
||||
def chunk(kind,data):return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)&0xffffffff)
|
||||
path.write_bytes(b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!2I5B',64,64,8,2,0,0,0))+chunk(b'IDAT',zlib.compress((b'\x00'+bytes(rgb)*64)*64))+chunk(b'IEND',b''))
|
||||
if ipc('shell','status'):raise SystemExit('Use an isolated source path; an instance is already running here.')
|
||||
matugen=shutil.which('matugen')
|
||||
if not matugen:raise SystemExit('Put Matugen 4.2.x on PATH for this integration test.')
|
||||
log=ROOT/'.cache/settings-runtime.log';log.parent.mkdir(exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-settings-') as tmp:
|
||||
temp=Path(tmp);images=temp/'images';images.mkdir()
|
||||
red=images/'red.png';blue=images/'blue name with spaces.png';png(red,(230,30,20));png(blue,(20,50,230))
|
||||
event=temp/'applied.json';helper=temp/'wallpaper.py';helper.write_text('import json,pathlib,sys\npathlib.Path(sys.argv[1]).write_text(json.dumps(sys.argv[2:]))\n')
|
||||
command=['python3',str(helper),str(event),'{path}','{monitor}']
|
||||
cfg=temp/'config/glassMxrph/config.json';cfg.parent.mkdir(parents=True)
|
||||
cfg.write_text(json.dumps({'schemaVersion':3,'dock':{'enabled':False},'wallpaper':{'backend':'custom','command':command,'directories':[str(images)]},'matugen':{'executable':matugen}}))
|
||||
env=dict(os.environ,XDG_CONFIG_HOME=tmp+'/config',XDG_STATE_HOME=tmp+'/state',XDG_CACHE_HOME=tmp+'/cache',GLASSMXRPH_SETTINGS_TESTING='1',QT_QPA_PLATFORMTHEME='',QT_NO_XDG_DESKTOP_PORTAL='1')
|
||||
with log.open('w') as output:
|
||||
proc=subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=output,stderr=subprocess.STDOUT)
|
||||
try:
|
||||
eventually(lambda:ipc('shell','status')['ready'],'ready')
|
||||
ipc('shell','openSettings','appearance');pref('appearance.accentSource','custom')
|
||||
eventually(lambda:ipc('settingsTest','color'),'visual colour picker')
|
||||
eventually(lambda:state()['data']['appearance']['customAccent']!='#a0a0a0','colour persisted')
|
||||
time.sleep(.55);assert ipc('settingsTest','screenshot',str(ROOT/'.cache/appearance-preview.png'))
|
||||
ipc('shell','openSettings','wallpaper')
|
||||
eventually(lambda:len(state()['images'])==2,'gallery images')
|
||||
time.sleep(.3);assert ipc('settingsTest','wallpaper',1)
|
||||
assert ipc('settingsTest','click','wallpaperApply')
|
||||
eventually(lambda:event.exists() and json.loads(event.read_text())[0]==str(red),'wallpaper apply argv')
|
||||
eventually(lambda:state()['wallpaper']==str(red),'current wallpaper')
|
||||
pref('appearance.accentSource','matugen')
|
||||
eventually(lambda:not state()['busy'] and ipc('theme','status')['available'],'initial generated palette')
|
||||
first=state()['palette'];eventually(lambda:state()['theme']==first,'live theme propagated')
|
||||
assert ipc('wallpaper','apply',str(blue))
|
||||
eventually(lambda:state()['wallpaper']==str(blue) and not state()['busy'] and state()['palette']!=first,'automatic regeneration')
|
||||
good=state()['palette']
|
||||
pref('matugen.regenerateOnWallpaperChange',False)
|
||||
assert ipc('wallpaper','apply',str(red));eventually(lambda:state()['wallpaper']==str(red),'second wallpaper')
|
||||
time.sleep(.4);assert state()['palette']==good,'Disabled regeneration changed palette'
|
||||
assert ipc('theme','regenerate')
|
||||
eventually(lambda:not state()['busy'] and state()['palette']==first,'manual regeneration')
|
||||
pref('matugen.executable','/missing/matugen')
|
||||
eventually(lambda:not state()['busy'] and bool(state()['error']),'missing executable error')
|
||||
assert state()['palette']==first,'Failed job destroyed palette'
|
||||
pref('matugen.executable',matugen)
|
||||
eventually(lambda:not state()['busy'] and not state()['error'],'recovery')
|
||||
pref('matugen.regenerateOnWallpaperChange',True)
|
||||
# Rapid changes must leave the newest image as the palette source.
|
||||
for path in [str(red),str(blue),str(red),str(blue)]:ipc('wallpaper','changed',json.loads(event.read_text())[1],path)
|
||||
eventually(lambda:not state()['busy'] and state()['palette']==good,'latest wallpaper wins')
|
||||
# Hold an older real Matugen generation in flight; it must never be published.
|
||||
marker=temp/'slow-started';slow=temp/'slow-matugen'
|
||||
slow.write_text('#!/usr/bin/env python3\nimport os,sys,time,pathlib\nif "--version" not in sys.argv:\n pathlib.Path('+repr(str(marker))+').write_text("started")\n time.sleep(.6)\nos.execv('+repr(matugen)+',['+repr(matugen)+']+sys.argv[1:])\n');slow.chmod(0o755)
|
||||
pref('matugen.regenerateOnWallpaperChange',False)
|
||||
ipc('wallpaper','changed',json.loads(event.read_text())[1],str(red))
|
||||
pref('matugen.executable',str(slow))
|
||||
eventually(lambda:marker.exists(),'older generation running')
|
||||
pref('matugen.regenerateOnWallpaperChange',True)
|
||||
ipc('wallpaper','changed',json.loads(event.read_text())[1],str(blue))
|
||||
end=time.monotonic()+10
|
||||
while state()['busy'] and time.monotonic()<end:
|
||||
assert state()['palette']==good,'Stale in-flight palette was published'
|
||||
time.sleep(.08)
|
||||
assert not state()['busy'] and state()['palette']==good
|
||||
pref('matugen.executable',matugen)
|
||||
eventually(lambda:not state()['busy'],'restore Matugen executable')
|
||||
ipc('shell','openSettings','bar');time.sleep(.3)
|
||||
assert ipc('settingsTest','dragModule','workspaces','left','settings')
|
||||
eventually(lambda:state()['data']['bar']['modules'][0]['id']=='workspaces','visual bar reorder')
|
||||
assert ipc('settingsTest','click','bar-enable-clock')
|
||||
eventually(lambda:not next(m for m in state()['data']['bar']['modules'] if m['id']=='clock')['enabled'],'visual bar toggle')
|
||||
assert ipc('settingsTest','screenshot',str(ROOT/'.cache/bar-editor-preview.png'))
|
||||
for page in ['media','dock','tray','launcher','appearance','wallpaper','displays','about']:
|
||||
ipc('shell','openSettings',page);time.sleep(.15)
|
||||
pref('media.scale',1.25);pref('media.showAlbum',False)
|
||||
eventually(lambda:json.loads(cfg.read_text())['media']['scale']==1.25,'media preferences saved')
|
||||
ipc('shell','close')
|
||||
finally:proc.terminate();proc.wait(timeout=5)
|
||||
text=log.read_text();assert 'WARN' not in text and 'ERROR' not in text,text
|
||||
print('PASS: visual colour picker, wallpaper gallery/apply, real Matugen file generation, automatic/manual live palettes, failure recovery, latest request wins, visual bar reorder/toggle, settings pages/media persistence, clean logs.')
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""System adapter boundaries. All commands and power capabilities are mocked."""
|
||||
import importlib.util,json,subprocess,sys,tempfile,unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('system_provider',ROOT/'quickshell/helpers/system.py')
|
||||
system=importlib.util.module_from_spec(spec);spec.loader.exec_module(system)
|
||||
OPTIONS=json.loads((ROOT/'quickshell/config/defaults.json').read_text())['system']
|
||||
class Providers(unittest.TestCase):
|
||||
def test_power_requires_confirmation_before_any_command(self):
|
||||
with patch.object(system,'run') as run,patch.object(system,'power',return_value={'reboot':True,'shutdown':True,'logout':True}) as capability,patch.object(system,'snapshot',return_value={}):
|
||||
for value in ['reboot','shutdown','logout']:
|
||||
with self.assertRaisesRegex(ValueError,'confirmation'):system.action({'options':OPTIONS,'action':'power','value':value})
|
||||
run.assert_not_called();capability.assert_not_called()
|
||||
system.action({'options':OPTIONS,'action':'power','value':'reboot','confirmed':True})
|
||||
self.assertEqual(run.call_args.args[0][-3:],['Reboot','b','true'])
|
||||
with self.assertRaises(ValueError):system.action({'options':OPTIONS,'action':'power','value':'arbitrary','confirmed':True})
|
||||
def test_validation_and_argv(self):
|
||||
for value in [-1,101,float('nan'),True,'40']:
|
||||
with self.assertRaises(ValueError):system.bounded(value,1,100)
|
||||
self.assertEqual(system.command(['tool','$(echo never); quoted','{value}','{enabled}'],value=40,enabled=False),['tool','$(echo never); quoted','40','false'])
|
||||
with self.assertRaises(ValueError):system.command('sh -c command')
|
||||
with patch.object(system,'run',return_value='{"value":75,"available":"false"}'):
|
||||
with self.assertRaises(ValueError):system.brightness({'statusCommand':['provider']})
|
||||
with patch.object(system,'run',return_value='{"enabled":"false"}'):
|
||||
with self.assertRaises(ValueError):system.night({'statusCommand':['provider']})
|
||||
def test_custom_providers_readback(self):
|
||||
opts=json.loads(json.dumps(OPTIONS));opts['brightness'].update(statusCommand=['status'],setCommand=['setter','--level','{value}'])
|
||||
with patch.object(system,'run',return_value='{"value":73,"available":true}') as run,patch.object(system,'snapshot',return_value={'brightness':{'available':True,'value':73}}):
|
||||
result=system.action({'options':opts,'action':'brightness','value':73})
|
||||
run.assert_called_once_with(['setter','--level','73'])
|
||||
self.assertEqual(result['state']['brightness']['value'],73)
|
||||
def test_missing_providers_do_not_crash_snapshot(self):
|
||||
with patch.object(system,'run',side_effect=FileNotFoundError('missing tool')),patch.object(system,'backlights',return_value=[]),patch.object(system.shutil,'which',return_value=None):
|
||||
state=system.snapshot(OPTIONS)
|
||||
self.assertFalse(state['brightness']['available']);self.assertFalse(state['nightLight']['available']);self.assertFalse(state['profiles']['available']);self.assertFalse(state['dnd']['available']);self.assertFalse(state['power']['shutdown'])
|
||||
def test_unavailable_action_rejected(self):
|
||||
with patch.object(system,'power',return_value={'suspend':False}),patch.object(system,'run') as run:
|
||||
with self.assertRaises(ValueError):system.action({'options':OPTIONS,'action':'power','value':'suspend'})
|
||||
run.assert_not_called()
|
||||
def test_dnd_never_activates_notification_daemon(self):
|
||||
with patch.object(system,'run',return_value='{"type":"b","data":[true]}') as run:
|
||||
self.assertTrue(system.notifications()['enabled'])
|
||||
args=run.call_args.args[0]
|
||||
self.assertIn('--auto-start=no',args);self.assertEqual(args[-1],'GetDnd')
|
||||
with patch.object(system,'notifications',return_value={'available':True}),patch.object(system,'snapshot',return_value={}),patch.object(system,'run') as run:
|
||||
system.action({'options':OPTIONS,'action':'dnd','value':False})
|
||||
self.assertIn('--auto-start=no',run.call_args.args[0]);self.assertEqual(run.call_args.args[0][-3:],['SetDnd','b','false'])
|
||||
def test_cli_errors_are_json(self):
|
||||
p=subprocess.run([sys.executable,str(ROOT/'quickshell/helpers/system.py'),'{"op":"unknown"}'],capture_output=True,text=True)
|
||||
self.assertFalse(json.loads(p.stdout)['ok']);self.assertEqual(p.returncode,1);self.assertEqual(p.stderr,'')
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Synthetic SNI + DBusMenu server. Use only inside a private dbus-run-session."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import dbus
|
||||
import dbus.service
|
||||
from dbus.mainloop.glib import DBusGMainLoop
|
||||
from gi.repository import GLib
|
||||
|
||||
DBusGMainLoop(set_as_default=True)
|
||||
bus = dbus.SessionBus()
|
||||
events = Path(sys.argv[1])
|
||||
icon_path = events.parent / 'fixture.svg'
|
||||
icon_path.write_text('<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"><rect x="2" y="2" width="20" height="20" rx="5" fill="#52b8b0"/></svg>')
|
||||
|
||||
def record(kind, **values):
|
||||
with events.open('a') as file:
|
||||
file.write(json.dumps(dict(kind=kind, **values)) + '\n')
|
||||
|
||||
SNI = 'org.kde.StatusNotifierItem'
|
||||
MENU = 'com.canonical.dbusmenu'
|
||||
PROPS = 'org.freedesktop.DBus.Properties'
|
||||
|
||||
class TrayItem(dbus.service.Object):
|
||||
def __init__(self, path, identifier, menu):
|
||||
super().__init__(bus, path)
|
||||
self.identifier = identifier
|
||||
self.menu = menu
|
||||
|
||||
def properties(self):
|
||||
props = {'Category':'ApplicationStatus', 'Id':self.identifier, 'Title':self.identifier,
|
||||
'Status':'Active', 'IconName':str(icon_path), 'IconPixmap':dbus.Array([], signature='(iiay)'),
|
||||
'AttentionIconName':str(icon_path), 'AttentionIconPixmap':dbus.Array([], signature='(iiay)'),
|
||||
'OverlayIconName':'', 'OverlayIconPixmap':dbus.Array([], signature='(iiay)'),
|
||||
'ItemIsMenu':False,
|
||||
'ToolTip':dbus.Struct((str(icon_path), dbus.Array([], signature='(iiay)'), self.identifier, 'Test fixture'), signature='sa(iiay)ss')}
|
||||
if self.menu: props['Menu'] = dbus.ObjectPath('/Menu')
|
||||
return props
|
||||
|
||||
@dbus.service.method(PROPS, in_signature='s', out_signature='a{sv}')
|
||||
def GetAll(self, interface): return self.properties() if interface == SNI else {}
|
||||
@dbus.service.method(PROPS, in_signature='ss', out_signature='v')
|
||||
def Get(self, interface, name): return self.properties()[name]
|
||||
@dbus.service.method(SNI, in_signature='ii')
|
||||
def Activate(self, x, y): record('activate', item=self.identifier)
|
||||
@dbus.service.method(SNI, in_signature='ii')
|
||||
def SecondaryActivate(self, x, y): record('secondary', item=self.identifier)
|
||||
@dbus.service.method(SNI, in_signature='ii')
|
||||
def ContextMenu(self, x, y): record('context', item=self.identifier)
|
||||
@dbus.service.method(SNI, in_signature='is')
|
||||
def Scroll(self, delta, orientation): record('scroll', delta=delta, orientation=orientation)
|
||||
|
||||
class Menu(dbus.service.Object):
|
||||
def __init__(self):
|
||||
super().__init__(bus, '/Menu')
|
||||
self.props = {
|
||||
0:{'children-display':'submenu'},
|
||||
1:{'label':'&Open fixture', 'icon-name':str(icon_path)},
|
||||
2:{'type':'separator'},
|
||||
3:{'label':'Disabled action', 'enabled':False},
|
||||
4:{'label':'Checked option', 'toggle-type':'checkmark', 'toggle-state':dbus.Int32(1)},
|
||||
5:{'label':'Radio option', 'toggle-type':'radio', 'toggle-state':dbus.Int32(0)},
|
||||
6:{'label':'Submenu', 'children-display':'submenu'},
|
||||
7:{'label':'Nested action'},
|
||||
8:{'label':'Deeper submenu', 'children-display':'submenu'},
|
||||
9:{'label':'Deep action'},
|
||||
10:{'label':'Hidden action', 'visible':False},
|
||||
}
|
||||
self.children = {0:[1,2,3,4,5,6,10],6:[7,8],8:[9]}
|
||||
|
||||
def layout(self, ident, depth):
|
||||
children = [] if depth == 0 else [dbus.Struct(self.layout(i, depth-1 if depth > 0 else -1), signature='ia{sv}av', variant_level=1) for i in self.children.get(ident, [])]
|
||||
return (dbus.Int32(ident), dbus.Dictionary(self.props[ident], signature='sv'), dbus.Array(children, signature='v'))
|
||||
|
||||
@dbus.service.method(PROPS, in_signature='s', out_signature='a{sv}')
|
||||
def GetAll(self, interface): return {'Version':dbus.UInt32(3),'TextDirection':'ltr','Status':'normal','IconThemePath':dbus.Array([],signature='s')}
|
||||
@dbus.service.method(PROPS, in_signature='ss', out_signature='v')
|
||||
def Get(self, interface, name): return self.GetAll(interface)[name]
|
||||
@dbus.service.method(MENU, in_signature='iias', out_signature='u(ia{sv}av)')
|
||||
def GetLayout(self, parent, depth, names): return (dbus.UInt32(1), self.layout(parent, depth))
|
||||
@dbus.service.method(MENU, in_signature='aias', out_signature='a(ia{sv})')
|
||||
def GetGroupProperties(self, ids, names): return [(i, self.props[i]) for i in ids]
|
||||
@dbus.service.method(MENU, in_signature='is', out_signature='v')
|
||||
def GetProperty(self, ident, name): return self.props[ident][name]
|
||||
@dbus.service.method(MENU, in_signature='isvu')
|
||||
def Event(self, ident, event, data, timestamp):
|
||||
record('menu', id=int(ident), event=str(event))
|
||||
if event == 'clicked' and ident in (4,5):
|
||||
self.props[ident]['toggle-state'] = dbus.Int32(1-int(self.props[ident]['toggle-state']))
|
||||
self.ItemsPropertiesUpdated([(ident, {'toggle-state':self.props[ident]['toggle-state']})], [])
|
||||
@dbus.service.method(MENU, in_signature='a(isvu)', out_signature='ai')
|
||||
def EventGroup(self, events):
|
||||
for args in events: self.Event(*args)
|
||||
return []
|
||||
@dbus.service.method(MENU, in_signature='i', out_signature='b')
|
||||
def AboutToShow(self, ident): record('about', id=int(ident)); return False
|
||||
@dbus.service.method(MENU, in_signature='ai', out_signature='aiai')
|
||||
def AboutToShowGroup(self, ids): return ([], [])
|
||||
@dbus.service.signal(MENU, signature='a(ia{sv})a(ias)')
|
||||
def ItemsPropertiesUpdated(self, updated, removed): pass
|
||||
|
||||
menu = Menu()
|
||||
items = [TrayItem('/StatusNotifierItem', 'glassmxrph-fixture', True), TrayItem('/NoMenu', 'glassmxrph-no-menu', False)]
|
||||
|
||||
def register():
|
||||
try:
|
||||
watcher = dbus.Interface(bus.get_object('org.kde.StatusNotifierWatcher', '/StatusNotifierWatcher'), 'org.kde.StatusNotifierWatcher')
|
||||
for path in ['/StatusNotifierItem', '/NoMenu']: watcher.RegisterStatusNotifierItem(path)
|
||||
record('registered')
|
||||
return False
|
||||
except dbus.DBusException: return True
|
||||
|
||||
GLib.timeout_add(100, register)
|
||||
GLib.MainLoop().run()
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run: dbus-run-session -- python3 tests/tray_runtime.py (real Hyprland required)."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import dbus
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE = ['quickshell', 'ipc', '--path', str(ROOT / 'quickshell'), 'call']
|
||||
|
||||
def ipc(target, method, *args):
|
||||
p = subprocess.run(BASE + [target, method, *map(str,args)], text=True, capture_output=True)
|
||||
try: return json.loads(p.stdout) if p.returncode == 0 and p.stdout.strip() else None
|
||||
except ValueError: raise AssertionError(f'IPC failed: {p.stdout} {p.stderr}')
|
||||
|
||||
def eventually(check, timeout=8):
|
||||
end = time.monotonic()+timeout
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
if check(): return
|
||||
except (ValueError, KeyError, TypeError, IndexError, FileNotFoundError, AttributeError): pass
|
||||
time.sleep(.05)
|
||||
raise AssertionError('Tray runtime condition timed out: ' + str(ipc('tray','status')))
|
||||
|
||||
if dbus.SessionBus().name_has_owner('org.kde.StatusNotifierWatcher'):
|
||||
raise SystemExit('Use dbus-run-session: this test must not share a live desktop tray bus.')
|
||||
if ipc('shell','status'):
|
||||
raise SystemExit('Stop the existing glassMxrph instance before running this test.')
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-tray-') as temp:
|
||||
env = dict(os.environ, XDG_CONFIG_HOME=temp+'/config', XDG_STATE_HOME=temp+'/state', GLASSMXRPH_TESTING='1', QT_QPA_PLATFORMTHEME='', QT_NO_XDG_DESKTOP_PORTAL='1')
|
||||
logs = Path(temp)/'shell.log'
|
||||
eventfile = Path(temp)/'events.jsonl'
|
||||
def events(): return [json.loads(line) for line in eventfile.read_text().splitlines()]
|
||||
def state(): return ipc('tray','status') or {}
|
||||
with logs.open('w') as output:
|
||||
shell = subprocess.Popen([str(ROOT/'scripts/glassmxrph'),'run'],env=env,stdout=output,stderr=subprocess.STDOUT)
|
||||
fixture = None
|
||||
try:
|
||||
eventually(lambda: ipc('shell','status').get('ready'))
|
||||
fixture = subprocess.Popen(['python3',str(ROOT/'tests/tray_fixture.py'),str(eventfile)],env=env,stdout=output,stderr=subprocess.STDOUT)
|
||||
eventually(lambda: len(state().get('items',[])) == 2)
|
||||
assert state()['items'][0]['id'].startswith('glassmxrph-'), 'Use a private DBus session'
|
||||
ident = 'glassmxrph-fixture'
|
||||
assert ipc('trayTest','hover',ident,'')
|
||||
time.sleep(.1)
|
||||
assert not state()['opened'], 'Hover opened before intent delay'
|
||||
assert ipc('trayTest','leave',ident,'')
|
||||
time.sleep(.45)
|
||||
assert not state()['opened'], 'Cancelled hover opened a menu'
|
||||
assert ipc('trayTest','hover',ident,'')
|
||||
eventually(lambda: state()['opened'])
|
||||
eventually(lambda: len(state()['menus'][0]['entries']) == 6)
|
||||
time.sleep(.25)
|
||||
layers = json.loads(subprocess.check_output(['hyprctl','-j','layers']))
|
||||
assert any(item['namespace'] == 'glassMxrph-tray'
|
||||
for output in layers.values() for level in output['levels'].values()
|
||||
for item in level), 'Tray menu must be a HyprGlass-compatible layer surface'
|
||||
assert ipc('trayTest','screenshot','/tmp/glassmxrph-tray-preview.png')
|
||||
rows = state()['menus'][0]['entries']
|
||||
assert rows[1]['separator'] and not rows[2]['enabled']
|
||||
assert rows[3]['buttonType'] == 1 and rows[3]['checkState'] == 2
|
||||
assert rows[4]['buttonType'] == 2 and rows[4]['checkState'] == 0
|
||||
assert rows[0]['icon'] and rows[5]['hasChildren']
|
||||
assert ipc('trayTest','row',0,0,'false')
|
||||
time.sleep(.4)
|
||||
assert state()['opened'], 'Moving into menu closed it'
|
||||
assert ipc('trayTest','row',0,5,'false')
|
||||
eventually(lambda: len(state()['menus']) == 2 and len(state()['menus'][1]['entries']) == 2)
|
||||
assert ipc('trayTest','row',1,1,'false')
|
||||
eventually(lambda: len(state()['menus']) == 3)
|
||||
assert ipc('trayTest','row',2,0,'true')
|
||||
eventually(lambda: any(e.get('id') == 9 and e.get('event') == 'clicked' for e in events()))
|
||||
eventually(lambda: not state()['opened'])
|
||||
assert ipc('trayTest','click',ident,2) # Qt.RightButton
|
||||
eventually(lambda: state()['opened'])
|
||||
assert ipc('trayTest','row',0,2,'true')
|
||||
assert not any(e.get('id') == 3 and e.get('event') == 'clicked' for e in events())
|
||||
assert ipc('trayTest','row',0,3,'true')
|
||||
eventually(lambda: any(e.get('id') == 4 and e.get('event') == 'clicked' for e in events()))
|
||||
assert ipc('tray','open',ident,'')
|
||||
eventually(lambda: state()['menus'][0]['entries'][3]['checkState'] == 0)
|
||||
assert ipc('trayTest','row',0,4,'true')
|
||||
eventually(lambda: any(e.get('id') == 5 and e.get('event') == 'clicked' for e in events()))
|
||||
assert ipc('tray','open',ident,'')
|
||||
eventually(lambda: state()['menus'][0]['entries'][4]['checkState'] == 2)
|
||||
ipc('trayTest','pressEscape')
|
||||
eventually(lambda: not state()['opened'])
|
||||
assert ipc('shell','setPreference','tray.hoverMenus','false')
|
||||
assert ipc('trayTest','leave',ident,'')
|
||||
assert ipc('trayTest','hover',ident,'')
|
||||
time.sleep(.5)
|
||||
assert not state()['opened']
|
||||
start = time.monotonic()
|
||||
assert ipc('trayTest','click',ident,2)
|
||||
assert state()['opened'] and time.monotonic() - start < .4, 'Right-click waited for hover delay'
|
||||
ipc('controlcenter','open')
|
||||
eventually(lambda:ipc('controlcenter','status')['opened'] and not state()['opened'])
|
||||
eventually(lambda:not ipc('controlcenter','status')['busy'])
|
||||
assert not dbus.SessionBus().name_has_owner('org.erikreider.swaync.cc'), 'Control Center started a notification daemon'
|
||||
assert ipc('tray','open',ident,'')
|
||||
eventually(lambda:state()['opened'] and not ipc('controlcenter','status')['opened'])
|
||||
ipc('tray','close')
|
||||
assert ipc('trayTest','click',ident,1)
|
||||
assert not ipc('controlcenter','status')['opened'], 'Tray activation opened Control Center'
|
||||
eventually(lambda: any(e['kind'] == 'activate' for e in events()))
|
||||
assert ipc('trayTest','click',ident,4)
|
||||
eventually(lambda: any(e['kind'] == 'secondary' for e in events()))
|
||||
assert ipc('trayTest','hover','glassmxrph-no-menu','')
|
||||
time.sleep(.5)
|
||||
assert not state()['opened'], 'Invented a menu for an item without one'
|
||||
for monitor in ipc('trayTest','screens'):
|
||||
assert ipc('tray','open',ident,monitor)
|
||||
eventually(lambda: state()['menus'][0]['screen'] == monitor and len(state()['menus'][0]['entries']) == 6)
|
||||
ipc('tray','close')
|
||||
assert ipc('tray','open',ident,'')
|
||||
eventually(lambda: len(state()['menus'][0]['entries']) == 6)
|
||||
ipc('launcher','open')
|
||||
eventually(lambda:not state()['opened'] and ipc('launcher','status')['opened'])
|
||||
ipc('launcher','close')
|
||||
time.sleep(.3)
|
||||
assert ipc('tray','open',ident,'')
|
||||
eventually(lambda:len(state()['menus'][0]['entries'])==6)
|
||||
# Caelestia-style handover: a long hover delay proves switches are instant.
|
||||
def popout(): return ipc('popout','status') or {}
|
||||
ipc('tray','close'); eventually(lambda: not state()['opened'])
|
||||
assert ipc('shell','setPreference','bar.modules',' '+json.dumps([{'id':'activeWindow','position':'center','enabled':True},{'id':'tray','position':'right','enabled':True}]))
|
||||
assert ipc('shell','setPreference','tray.hoverMenus','true')
|
||||
assert ipc('shell','setPreference','tray.hoverDelay','1500')
|
||||
eventually(lambda: ipc('trayTest','leaveBar'))
|
||||
assert ipc('trayTest','hover',ident,'')
|
||||
eventually(lambda: state()['opened'], timeout=4)
|
||||
assert not state()['grabbing'], 'Hover-opened menu grabbed keyboard focus'
|
||||
assert ipc('trayTest','hover','glassmxrph-no-menu','')
|
||||
eventually(lambda: popout()['open'] and popout()['kind'] == 'tooltip' and not state()['opened'], timeout=.9)
|
||||
assert ipc('trayTest','hover',ident,'')
|
||||
eventually(lambda: state()['opened'] and not popout()['open'], timeout=.9)
|
||||
# Window previews need a program on the focused workspace (real desktop).
|
||||
if ipc('trayTest','hoverModule','windowItem-0'):
|
||||
eventually(lambda: popout()['open'] and popout()['anchor'] == 'windowItem-0' and not state()['opened'], timeout=.9)
|
||||
time.sleep(.6)
|
||||
assert popout()['visible'] and popout()['width'] > 100, popout()
|
||||
assert ipc('trayTest','popoutScreenshot','/tmp/glassmxrph-popout-preview.png')
|
||||
layers = json.loads(subprocess.check_output(['hyprctl','-j','layers']))
|
||||
assert any(item['namespace'] == 'glassMxrph-popout' for output in layers.values() for level in output['levels'].values() for item in level)
|
||||
assert ipc('trayTest','leaveBar')
|
||||
eventually(lambda: not popout()['open'] and not popout()['visible'])
|
||||
assert ipc('trayTest','hoverModule','windowItem-0')
|
||||
time.sleep(.4); assert not popout()['open'], 'Cold hover ignored the hover delay'
|
||||
eventually(lambda: popout()['open'], timeout=4)
|
||||
assert ipc('trayTest','leaveBar')
|
||||
eventually(lambda: not popout()['open'])
|
||||
else:
|
||||
print('SKIP: no programs on the focused workspace for window previews')
|
||||
# Click-opened menus are sticky and take keyboard focus.
|
||||
assert ipc('trayTest','click',ident,2)
|
||||
eventually(lambda: state()['opened'] and state()['grabbing'] and not popout()['open'])
|
||||
ipc('tray','close'); eventually(lambda: not state()['opened'])
|
||||
fixture.terminate(); fixture.wait(timeout=5)
|
||||
eventually(lambda: len(state()['items']) == 0 and not state()['opened'])
|
||||
finally:
|
||||
if fixture and fixture.poll() is None: fixture.terminate(); fixture.wait(timeout=5)
|
||||
shell.terminate(); shell.wait(timeout=5)
|
||||
output.flush()
|
||||
Path("/tmp/glassmxrph-tray-runtime.log").write_text(logs.read_text())
|
||||
text=logs.read_text()
|
||||
Path('/tmp/glassmxrph-tray-runtime.log').write_text(text)
|
||||
assert 'WARN' not in text and 'ERROR' not in text, text
|
||||
print('PASS: SNI discovery/removal, hover delay/cancellation, pointer handover, menu states/icons, nested menus, DBus actions, disabled entries, live check updates, activation, no-menu tooltips, instant hover handover, active-window preview, hover menus without focus grabs, per-monitor anchoring, clean logs.')
|
||||
@@ -0,0 +1,37 @@
|
||||
const assert = require('assert'), fs = require('fs'), path = require('path'), vm = require('vm');
|
||||
const api = vm.createContext({});
|
||||
vm.runInContext(fs.readFileSync(path.join(__dirname, '../quickshell/services/WidgetLogic.js'), 'utf8'), api);
|
||||
const bounds = {w: 1000, h: 800};
|
||||
// Item edits are immutable.
|
||||
const items = [{id: 'a', x: 0}, {id: 'b', x: 5}];
|
||||
assert.deepEqual(api.updateItem(items, 'b', {x: 9}).map(i => i.x), [0, 9]);
|
||||
assert.equal(items[1].x, 5);
|
||||
assert.deepEqual(api.removeItem(items, 'a').map(i => i.id), ['b']);
|
||||
const id = api.newId(items);
|
||||
assert(/^w-[a-z0-9]+-[a-z0-9]+$/.test(id) && !items.some(i => i.id === id));
|
||||
// Snaps to the screen edge and another widget's edge, with guides.
|
||||
let s = api.snapMove({x: 6, y: 300, w: 100, h: 100}, [], bounds, 0, 10);
|
||||
assert.equal(s.x, 0); assert.deepEqual(s.guides.x, [0]);
|
||||
s = api.snapMove({x: 207, y: 50, w: 100, h: 100}, [{x: 100, y: 400, w: 100, h: 100}], bounds, 0, 10);
|
||||
assert.equal(s.x, 200); assert.equal(s.y, 50);
|
||||
// Centres snap to the screen centre.
|
||||
s = api.snapMove({x: 446, y: 10, w: 100, h: 50}, [], bounds, 0, 10);
|
||||
assert.equal(s.x, 450); assert.deepEqual(s.guides.x, [500]);
|
||||
// Grid wins over guides; rects stay on screen.
|
||||
s = api.snapMove({x: 33, y: 49, w: 100, h: 100}, [], bounds, 20, 10);
|
||||
assert.deepEqual([s.x, s.y], [40, 40]);
|
||||
s = api.snapMove({x: 980, y: -30, w: 100, h: 100}, [], bounds, 0, 0);
|
||||
assert.deepEqual([s.x, s.y], [900, 0]);
|
||||
// Resizing honours minimums from either edge and the output bounds.
|
||||
const limits = {minW: 120, minH: 80, maxW: 600, maxH: 400};
|
||||
let r = api.resizeRect({x: 100, y: 100, w: 200, h: 200}, -150, 0, {right: true}, limits, bounds, 0);
|
||||
assert.deepEqual([r.x, r.w], [100, 120]);
|
||||
r = api.resizeRect({x: 100, y: 100, w: 200, h: 200}, 150, 0, {left: true}, limits, bounds, 0);
|
||||
assert.deepEqual([r.x, r.w], [180, 120]);
|
||||
r = api.resizeRect({x: 100, y: 100, w: 200, h: 200}, 0, 500, {bottom: true}, limits, bounds, 0);
|
||||
assert.equal(r.h, 400);
|
||||
r = api.resizeRect({x: 900, y: 100, w: 90, h: 100}, 500, 0, {right: true}, {minW: 40, minH: 40, maxW: 4000, maxH: 4000}, bounds, 0);
|
||||
assert.equal(r.x + r.w, 1000);
|
||||
r = api.resizeRect({x: 100, y: 100, w: 200, h: 200}, 13, 27, {right: true, bottom: true}, limits, bounds, 20);
|
||||
assert.deepEqual([r.w, r.h], [220, 220]);
|
||||
console.log('Desktop widget snapping, guides, grid, resize limits and immutable edits passed.');
|
||||
Reference in new issue
Block a user