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,9 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exec the optional visualizer; report an absent executable without a QML warning."""
|
||||
import os
|
||||
import sys
|
||||
try:
|
||||
os.execvp('cava', ['cava', '-p', sys.argv[1]])
|
||||
except OSError as error:
|
||||
print('Cava unavailable: ' + str(error), file=sys.stderr)
|
||||
sys.exit(127)
|
||||
@@ -0,0 +1,118 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot filesystem/provider adapter. JSON in argv, JSON out; never shell-evaluates input."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
SCHEMES=['scheme-content','scheme-expressive','scheme-fidelity','scheme-fruit-salad','scheme-monochrome','scheme-neutral','scheme-rainbow','scheme-tonal-spot','scheme-vibrant','scheme-smart']
|
||||
IMAGES={'.png','.jpg','.jpeg','.webp','.bmp'}
|
||||
|
||||
def run(argv,timeout=15):
|
||||
p=subprocess.run(argv,capture_output=True,text=True,timeout=timeout,stdin=subprocess.DEVNULL)
|
||||
if p.returncode:raise ValueError((p.stderr or p.stdout or 'Provider failed').strip()[-700:])
|
||||
return p.stdout.strip()
|
||||
|
||||
def image_path(value):
|
||||
path=Path(value).expanduser().resolve(strict=True)
|
||||
if not path.is_file() or path.suffix.lower() not in IMAGES:raise ValueError('Select a supported still image')
|
||||
return path
|
||||
|
||||
def probe_matugen(executable):
|
||||
version=run([executable,'--version'])
|
||||
if not re.search(r'\b4\.2\.\d+\b',version):raise ValueError('This adapter supports Matugen 4.2.x; found '+version)
|
||||
return version
|
||||
|
||||
def palette(req):
|
||||
executable=req.get('executable','matugen');version=probe_matugen(executable)
|
||||
path=image_path(req['path']);scheme=req.get('scheme','scheme-tonal-spot');contrast=req.get('contrast',0)
|
||||
if scheme not in SCHEMES or not isinstance(contrast,(int,float)) or not -1<=contrast<=1:raise ValueError('Unsupported Matugen options')
|
||||
# The dedicated config has no hooks, app templates or wallpaper command.
|
||||
with tempfile.TemporaryDirectory(prefix='glassmxrph-matugen-') as tmp:
|
||||
base=Path(tmp);template=base/'palette.json';output=base/'generated.json';config=base/'config.toml'
|
||||
template.write_text('{"accent":"{{colors.primary.default.hex}}","accentText":"{{colors.on_primary.default.hex}}","accentContainer":"{{colors.primary_container.default.hex}}"}')
|
||||
config.write_text('[config]\n\n[templates.glassmxrph]\ninput_path = '+json.dumps(str(template))+'\noutput_path = '+json.dumps(str(output))+'\n')
|
||||
run([executable,'--config',str(config),'--mode','dark','--type',scheme,'--contrast='+str(contrast),'--source-color-index','0','image',str(path)],timeout=60)
|
||||
result=json.loads(output.read_text())
|
||||
if not all(re.fullmatch(r'#[0-9a-fA-F]{6}',result.get(k,'')) for k in ['accent','accentText','accentContainer']):raise ValueError('Matugen generated an invalid palette')
|
||||
return {'palette':result,'version':version,'path':str(path)}
|
||||
|
||||
def current(backend,monitor):
|
||||
if backend=='serpantinum':return run(['serpantinum','ipc','call','wallpaper','getWallpaperPath',monitor],5)
|
||||
if backend=='awww':
|
||||
for line in run(['awww','query'],5).splitlines():
|
||||
if line.startswith(monitor+':') and 'image: ' in line:return line.split('image: ',1)[1]
|
||||
return ''
|
||||
return ''
|
||||
|
||||
def provider(req):
|
||||
backend=req.get('backend','auto');monitor=req.get('monitor','')
|
||||
if backend=='auto':
|
||||
for candidate in ['serpantinum','awww']:
|
||||
if shutil.which(candidate):
|
||||
try:return {'backend':candidate,'current':current(candidate,monitor)}
|
||||
except (ValueError,subprocess.TimeoutExpired):pass
|
||||
return {'backend':'none','current':'','notice':'No supported running wallpaper provider. Choose a custom command or start your existing wallpaper service.'}
|
||||
if backend in ['serpantinum','awww']:return {'backend':backend,'current':current(backend,monitor)}
|
||||
if backend=='native':return {'backend':'native','current':req.get('current','')}
|
||||
if backend=='custom':return {'backend':'custom','current':req.get('current','')}
|
||||
raise ValueError('Unsupported wallpaper backend')
|
||||
|
||||
def apply(req):
|
||||
path=image_path(req['path']);monitor=req['monitor']
|
||||
if not re.fullmatch(r'[\w.-]+',monitor):raise ValueError('Invalid output name')
|
||||
backend=provider(req)['backend']
|
||||
if backend=='native':return {'backend':'native','path':str(path),'url':path.as_uri(),'providerPath':str(path)}
|
||||
if backend=='serpantinum':
|
||||
# This provider interpolates filenames into shell commands. Pass a safe owned copy.
|
||||
base=Path(os.environ.get('XDG_CACHE_HOME',Path.home()/'.cache'))/'glassMxrph/wallpapers'
|
||||
base.mkdir(parents=True,exist_ok=True)
|
||||
if "'" in str(base) or '\n' in str(base):raise ValueError('Serpantinum cannot safely handle this cache path')
|
||||
dest=base/(hashlib.sha256(path.read_bytes()).hexdigest()+path.suffix.lower())
|
||||
if not dest.exists():shutil.copyfile(path,dest)
|
||||
run(['serpantinum','ipc','call','wallpaper','setWallpaper',monitor,str(dest),'fade'])
|
||||
# IPC only acknowledges dispatch: poll read-only state for provider acceptance.
|
||||
import time
|
||||
for _ in range(20):
|
||||
if current(backend,monitor)==str(dest):return {'backend':backend,'path':str(path),'providerPath':str(dest)}
|
||||
time.sleep(.1)
|
||||
raise ValueError('Wallpaper provider did not acknowledge the selected image')
|
||||
if backend=='awww':run(['awww','img','--outputs',monitor,'--transition-type','fade',str(path)])
|
||||
elif backend=='custom':
|
||||
command=req.get('command',[])
|
||||
if not isinstance(command,list) or not command or not all(isinstance(x,str) for x in command):raise ValueError('Custom command must be an argument array')
|
||||
if not any('{path}' in x for x in command):raise ValueError('Custom command needs a {path} argument')
|
||||
run([x.replace('{path}',str(path)).replace('{monitor}',monitor) for x in command])
|
||||
else:raise ValueError('No active wallpaper provider')
|
||||
return {'backend':backend,'path':str(path),'providerPath':str(path)}
|
||||
|
||||
def scan(req):
|
||||
found={};errors=[]
|
||||
for directory in (req.get('directories') or [str(Path.home()/'Pictures/Wallpapers')]):
|
||||
base=Path(directory).expanduser()
|
||||
try:
|
||||
for entry in base.iterdir():
|
||||
if entry.is_file() and entry.suffix.lower() in IMAGES:
|
||||
resolved=entry.resolve();found[str(resolved)]={'path':str(resolved),'url':resolved.as_uri(),'name':entry.name}
|
||||
if len(found)>=1000:break
|
||||
except OSError as error:errors.append(str(error))
|
||||
if len(found)>=1000:break
|
||||
return {'images':sorted(found.values(),key=lambda x:x['name'].casefold()),'notice':'; '.join(errors),'limited':len(found)>=1000}
|
||||
|
||||
def dispatch(req):
|
||||
action=req['action']
|
||||
if action=='palette':return palette(req)
|
||||
if action=='matugen-probe':return {'version':probe_matugen(req.get('executable','matugen')),'schemes':SCHEMES}
|
||||
if action=='provider':return provider(req)
|
||||
if action=='apply':return apply(req)
|
||||
if action=='scan':return scan(req)
|
||||
raise ValueError('Unknown adapter request')
|
||||
|
||||
if __name__=='__main__':
|
||||
try:print(json.dumps({'ok':True,**dispatch(json.loads(sys.argv[1]))}))
|
||||
except (ValueError,OSError,KeyError,subprocess.TimeoutExpired) as error:print(json.dumps({'ok':False,'error':str(error)}))
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
"""EasyEffects 10-band equalizer bridge. Prints one JSON status object.
|
||||
|
||||
status installed/running/bypass plus the saved equalizer
|
||||
apply GAINS NAME save gains (JSON list of 10 dB values) and load them as the
|
||||
"glassmxrph_eq" output preset, starting the service if needed
|
||||
bypass on|off global EasyEffects bypass
|
||||
"""
|
||||
import json, os, re, shutil, subprocess, sys, time
|
||||
from pathlib import Path
|
||||
|
||||
PRESET = 'glassmxrph_eq'
|
||||
FREQUENCIES = [32, 63, 125, 250, 500, 1000, 2000, 4000, 8000, 16000]
|
||||
STATE = Path(os.environ.get('XDG_STATE_HOME') or Path.home() / '.local/state') / 'glassMxrph/equalizer.json'
|
||||
|
||||
|
||||
def binary():
|
||||
return os.environ.get('GLASSMXRPH_EASYEFFECTS') or shutil.which('easyeffects')
|
||||
|
||||
|
||||
def run(*args, timeout=4):
|
||||
try:
|
||||
return subprocess.run([binary(), *args], capture_output=True, text=True, timeout=timeout)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return None
|
||||
|
||||
|
||||
def version():
|
||||
p = run('--version')
|
||||
m = re.search(r'(\d+)\.(\d+)', (p.stdout + p.stderr) if p else '')
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (8, 0)
|
||||
|
||||
|
||||
def running():
|
||||
# Nix wraps the binary as .easyeffects-wrapped; match the executable name only.
|
||||
for proc in Path('/proc').glob('[0-9]*'):
|
||||
try:
|
||||
argv0 = (proc / 'cmdline').read_bytes().split(b'\0', 1)[0].decode(errors='ignore')
|
||||
except OSError:
|
||||
continue
|
||||
if re.fullmatch(r'\.?easyeffects(-wrapped)?', os.path.basename(argv0)):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def load_state():
|
||||
try:
|
||||
data = json.loads(STATE.read_text())
|
||||
bands = [max(-12.0, min(12.0, float(v))) for v in data['bands']][:10]
|
||||
if len(bands) == 10:
|
||||
return dict(bands=bands, preset=str(data.get('preset', 'Custom')))
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
pass
|
||||
return dict(bands=[0.0] * 10, preset='Flat')
|
||||
|
||||
|
||||
def preset_dir():
|
||||
# EasyEffects 8 keeps presets under XDG data; 7.x used XDG config.
|
||||
if version() >= (8, 0):
|
||||
return Path(os.environ.get('XDG_DATA_HOME') or Path.home() / '.local/share') / 'easyeffects/output'
|
||||
return Path(os.environ.get('XDG_CONFIG_HOME') or Path.home() / '.config') / 'easyeffects/output'
|
||||
|
||||
|
||||
def write_preset(bands):
|
||||
band = lambda f, g: dict(frequency=f, gain=g, mode='Bell', mute=False, q=1.41, solo=False, width=1.0, slope='x1')
|
||||
channel = {f'band{i}': band(f, bands[i]) for i, f in enumerate(FREQUENCIES)}
|
||||
preset = {'output': {'blocklist': [], 'plugins_order': ['equalizer'], 'equalizer': {
|
||||
'bypass': False, 'input-gain': 0.0, 'output-gain': 0.0, 'left': channel, 'right': channel,
|
||||
'mode': 'IIR', 'num-bands': len(FREQUENCIES), 'split-channels': False}}}
|
||||
directory = preset_dir()
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
tmp = directory / f'.{PRESET}.json.tmp'
|
||||
tmp.write_text(json.dumps(preset, indent=4))
|
||||
tmp.replace(directory / f'{PRESET}.json')
|
||||
|
||||
|
||||
def ensure_service():
|
||||
if running():
|
||||
return True
|
||||
# Service mode keeps it in the background; loading a preset without a running
|
||||
# instance would open the full window instead.
|
||||
flag = '--service-mode' if version() >= (8, 0) else '--gapplication-service'
|
||||
try:
|
||||
subprocess.Popen([binary(), flag, '-w'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
|
||||
except OSError:
|
||||
return False
|
||||
for _ in range(30):
|
||||
if running():
|
||||
time.sleep(0.6)
|
||||
return True
|
||||
time.sleep(0.1)
|
||||
return False
|
||||
|
||||
|
||||
def bypassed():
|
||||
if not running():
|
||||
return False
|
||||
p = run('-b', '3')
|
||||
text = (p.stdout if p else '').strip().lower()
|
||||
return text in ('1', 'true', 'on', 'enabled')
|
||||
|
||||
|
||||
def status(error=''):
|
||||
installed = bool(binary())
|
||||
state = load_state()
|
||||
alive = installed and running()
|
||||
return dict(installed=installed, running=alive, bypass=installed and alive and bypassed(), bands=state['bands'],
|
||||
preset=state['preset'], frequencies=FREQUENCIES, error=error)
|
||||
|
||||
|
||||
def main():
|
||||
command = sys.argv[1] if len(sys.argv) > 1 else 'status'
|
||||
error = ''
|
||||
if command == 'apply' and binary():
|
||||
try:
|
||||
bands = [max(-12.0, min(12.0, float(v))) for v in json.loads(sys.argv[2])][:10]
|
||||
if len(bands) != 10:
|
||||
raise ValueError('expected 10 bands')
|
||||
STATE.parent.mkdir(parents=True, exist_ok=True)
|
||||
STATE.write_text(json.dumps(dict(bands=bands, preset=sys.argv[3] if len(sys.argv) > 3 else 'Custom')))
|
||||
write_preset(bands)
|
||||
if not ensure_service():
|
||||
error = 'EasyEffects did not start'
|
||||
elif not (p := run('-l', PRESET)) or p.returncode != 0:
|
||||
error = 'EasyEffects rejected the preset'
|
||||
except (ValueError, IndexError, OSError) as e:
|
||||
error = str(e)
|
||||
elif command == 'bypass' and binary():
|
||||
if running():
|
||||
run('-b', '1' if (sys.argv[2:] or ['on'])[0] == 'on' else '2')
|
||||
else:
|
||||
error = 'EasyEffects is not running'
|
||||
print(json.dumps(status(error)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Global HyprGlass controls using verified live scalar options, with a restore journal."""
|
||||
import json,math,os,subprocess,sys
|
||||
from pathlib import Path
|
||||
|
||||
PREFIX='plugin:hyprglass:'
|
||||
RANGES={'blur_strength':(0,5),'blur_iterations':(1,5),'refraction_strength':(0,8),
|
||||
'chromatic_aberration':(0,1),'fresnel_strength':(0,1),'specular_strength':(0,1),
|
||||
'edge_thickness':(0,.15),'lens_distortion':(0,1),'brightness':(.2,2),
|
||||
'contrast':(.2,2),'saturation':(0,2),'vibrancy':(0,1),'adaptive_dim':(0,1)}
|
||||
GHOSTTY={'blur_strength':.45,'blur_iterations':2,'refraction_strength':3,
|
||||
'chromatic_aberration':.45,'fresnel_strength':.5,'specular_strength':.8,
|
||||
'edge_thickness':.065,'lens_distortion':.25,'brightness':.95,
|
||||
'contrast':1,'saturation':1,'vibrancy':.15,'adaptive_dim':.2}
|
||||
|
||||
|
||||
def run(args):
|
||||
p=subprocess.run(['hyprctl',*args],text=True,capture_output=True,timeout=4)
|
||||
if p.returncode:raise ValueError((p.stderr or p.stdout).strip()[:350])
|
||||
return p.stdout.strip()
|
||||
|
||||
def get(key):
|
||||
data=json.loads(run(['-j','getoption',PREFIX+key]))
|
||||
for field in ['str','int','float']:
|
||||
if field in data:return data[field]
|
||||
raise ValueError('HyprGlass option unavailable: '+key)
|
||||
|
||||
def put(key,value):
|
||||
result=run(['keyword',PREFIX+key,str(value)])
|
||||
if result!='ok':raise ValueError(result[:350])
|
||||
if get(key)!=value:raise ValueError('HyprGlass did not accept '+key)
|
||||
|
||||
def values(options):
|
||||
controls=options.get('values',{})
|
||||
if set(controls)!=set(RANGES):raise ValueError('Incomplete glass settings')
|
||||
for key,(low,high) in RANGES.items():
|
||||
v=controls[key]
|
||||
if type(v) not in (int,float) or not math.isfinite(v) or not low<=v<=high:raise ValueError('Invalid '+key)
|
||||
if not float(controls['blur_iterations']).is_integer():raise ValueError('Blur passes must be an integer')
|
||||
if type(options.get('layers')) is not bool or type(options.get('effectEnabled',True)) is not bool:raise ValueError('Invalid glass toggle')
|
||||
# "default" is the plugin's documented fallback: custom presets otherwise
|
||||
# override scalar sliders, and live preset definitions are only committed at reload.
|
||||
result={}
|
||||
for key,v in controls.items():
|
||||
result['dark:'+key]=v
|
||||
result['light:'+key]=v
|
||||
result.update({'dark:tint_color':0xffffff08,'light:tint_color':0xffffff08,
|
||||
'dark:glass_opacity':1,'light:glass_opacity':1,
|
||||
'default_preset':'default','default_theme':'dark','layers:preset':'default','layers:mask_mode':'alpha',
|
||||
'layers:enabled':int(options['layers'] and options.get('effectEnabled',True)),'enabled':int(options.get('effectEnabled',True))})
|
||||
return result
|
||||
|
||||
def journal_path():
|
||||
return Path(os.environ.get('XDG_STATE_HOME',Path.home()/'.local/state'))/'glassMxrph/glass-restore.json'
|
||||
|
||||
def save(path,data):
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
temp=path.with_suffix('.tmp');temp.write_text(json.dumps(data));temp.replace(path)
|
||||
|
||||
def probe():
|
||||
try:
|
||||
return dict(available=True,preset=get('default_preset'),enabled=bool(get('enabled')),layers=bool(get('layers:enabled')),
|
||||
namespaces=get('layers:namespaces'),exclusions=get('layers:exclude_namespaces'),overrides=get('layers:namespace_presets'))
|
||||
except (OSError,ValueError,subprocess.TimeoutExpired):return dict(available=False)
|
||||
|
||||
def dispatch(req):
|
||||
action=req.get('action')
|
||||
if action=='probe':return probe()
|
||||
path=journal_path();session=os.environ.get('HYPRLAND_INSTANCE_SIGNATURE','')
|
||||
journal=json.loads(path.read_text()) if path.exists() else {}
|
||||
if journal.get('session')!=session or req.get('reloaded'):journal={}
|
||||
if action=='restore':
|
||||
skipped=[]
|
||||
for key,old in reversed(list(journal.get('before',{}).items())):
|
||||
if get(key)==journal['after'].get(key):put(key,old)
|
||||
else:skipped.append(key)
|
||||
path.unlink(missing_ok=True)
|
||||
return dict(**probe(),notice='Restored previous glass settings.' if not skipped else 'Preserved externally changed options: '+', '.join(skipped))
|
||||
if action!='apply':raise ValueError('Unknown glass request')
|
||||
target=values(req['options'])
|
||||
current={key:get(key) for key in target}
|
||||
before=journal.get('before',current)
|
||||
# Persist before writing so a partial operation can be restored after a crash.
|
||||
record=dict(session=session,before=before,after=target)
|
||||
save(path,record)
|
||||
changed=[]
|
||||
try:
|
||||
for key,value in target.items():
|
||||
if current[key]!=value:
|
||||
changed.append(key);put(key,value)
|
||||
except Exception:
|
||||
rollback_failed=False
|
||||
for key in reversed(changed):
|
||||
try:put(key,current[key])
|
||||
except Exception:rollback_failed=True
|
||||
if not rollback_failed:
|
||||
if journal:save(path,journal)
|
||||
else:path.unlink(missing_ok=True)
|
||||
raise
|
||||
return dict(**probe(),notice='Global glass applied. Explicit per-application and per-layer preset rules still take priority.')
|
||||
|
||||
if __name__=='__main__':
|
||||
try:print(json.dumps(dict(ok=True,**dispatch(json.loads(sys.argv[1])))))
|
||||
except (OSError,ValueError,KeyError,subprocess.TimeoutExpired) as e:print(json.dumps(dict(ok=False,error=str(e))))
|
||||
@@ -0,0 +1,151 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Plugin marketplace browser. Prints one JSON object.
|
||||
|
||||
search [QUERY] [CATEGORY] [SORT] [OFFSET] [LIMIT] [VERIFIED_ONLY] [SOURCE]
|
||||
page of listings; SORT is popular | recent | name; SOURCE is
|
||||
omarchy (plugins.omarchy.org) or noctalia (noctalia-plugins registry)
|
||||
refresh download the catalog again
|
||||
|
||||
The catalog and the registry's automated security review are cached in
|
||||
$XDG_CACHE_HOME/glassMxrph and refreshed every six hours. Installs use the
|
||||
commit the marketplace last validated, not the repository's current HEAD.
|
||||
"""
|
||||
import json, os, sys, time, urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
CATALOG_URL = 'https://plugins.omarchy.org/catalog.json'
|
||||
REGISTRY_URL = 'https://raw.githubusercontent.com/omacom/omarchy-plugin-marketplace/main/registry.json'
|
||||
SITE = 'https://plugins.omarchy.org/'
|
||||
CACHE = Path(os.environ.get('XDG_CACHE_HOME') or Path.home() / '.cache') / 'glassMxrph'
|
||||
INDEX = CACHE / 'omarchy-marketplace.json'
|
||||
NOCTALIA_REGISTRY = 'https://raw.githubusercontent.com/noctalia-dev/noctalia-plugins/main/registry.json'
|
||||
NOCTALIA_REPO = 'https://github.com/noctalia-dev/noctalia-plugins'
|
||||
NOCTALIA_INDEX = CACHE / 'noctalia-marketplace.json'
|
||||
MAX_AGE = 6 * 3600
|
||||
# What glassMxrph can host today (see compat/omarchy).
|
||||
SUPPORT = {'Bar widget': 'supported', 'Panel': 'supported', 'Service': 'supported', 'Plugin': 'supported',
|
||||
'Overlay': 'partial', 'Menu': 'partial', 'Bar': 'unsupported', 'Suite': 'unsupported'}
|
||||
|
||||
|
||||
def download(url):
|
||||
request = urllib.request.Request(url, headers={'User-Agent': 'glassMxrph'})
|
||||
with urllib.request.urlopen(request, timeout=60) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def build_index():
|
||||
catalog = download(CATALOG_URL)
|
||||
review = {}
|
||||
try:
|
||||
for source in download(REGISTRY_URL).get('sources', []):
|
||||
baseline = source.get('automatedSecurityBaseline') or {}
|
||||
review[source.get('repo', '').rstrip('/').removesuffix('.git').lower()] = dict(
|
||||
outcome=baseline.get('outcome', ''), capabilities=baseline.get('capabilities', []))
|
||||
except (OSError, ValueError):
|
||||
pass # The security review is extra detail; browsing works without it.
|
||||
items = []
|
||||
for p in catalog.get('plugins', []):
|
||||
repo = p.get('repo', '')
|
||||
sec = review.get(repo.rstrip('/').removesuffix('.git').lower(), {})
|
||||
kind = p.get('kind') or 'Plugin'
|
||||
builtin = p.get('id', '').startswith('omarchy.')
|
||||
items.append(dict(
|
||||
id=p.get('id', ''), name=p.get('name') or p.get('id', ''), description=p.get('description', ''),
|
||||
author=p.get('author', ''), version=p.get('version', ''), category=p.get('category', 'Other'),
|
||||
tags=p.get('tags', []), kind=kind,
|
||||
# Omarchy's own built-ins use the reserved omarchy.* ids and are not installable.
|
||||
support='unsupported' if builtin else SUPPORT.get(kind, 'partial'),
|
||||
stars=p.get('stars', 0) or 0, verified=p.get('verificationStatus') == 'verified',
|
||||
installable=bool(p.get('installAvailable')) and not builtin,
|
||||
note='Built into Omarchy' if builtin else p.get('installNote', ''),
|
||||
repo=repo, commit=p.get('upstreamValidatedCommit') or p.get('listingValidatedCommit') or '',
|
||||
manifestPath=p.get('manifestPath', ''), license=p.get('license', ''),
|
||||
accent=p.get('accent', ''), initials=p.get('initials', ''),
|
||||
updated=p.get('versionUpdatedAt') or p.get('repositoryUpdatedAt') or p.get('listedAt') or '',
|
||||
review=sec.get('outcome', ''), capabilities=sec.get('capabilities', []),
|
||||
page=SITE + '#' + p.get('id', '')))
|
||||
CACHE.mkdir(parents=True, exist_ok=True)
|
||||
tmp = INDEX.with_suffix('.tmp')
|
||||
tmp.write_text(json.dumps(dict(fetchedAt=int(time.time()), items=items)))
|
||||
tmp.replace(INDEX)
|
||||
|
||||
|
||||
def build_noctalia_index():
|
||||
"""Noctalia v4's registry: one repository, a folder per plugin id."""
|
||||
registry = download(NOCTALIA_REGISTRY)
|
||||
items = []
|
||||
for p in registry.get('plugins', []):
|
||||
tags = p.get('tags') or []
|
||||
items.append(dict(
|
||||
id=p.get('id', ''), name=p.get('name') or p.get('id', ''), description=p.get('description', ''),
|
||||
author=p.get('author', ''), version=p.get('version', ''), category=tags[0] if tags else 'Other',
|
||||
tags=tags, kind='Noctalia v4', support='partial', stars=0, verified=bool(p.get('official')),
|
||||
installable=True, note='Noctalia v4 plugin, run through the compatibility layer',
|
||||
repo=p.get('repository') or NOCTALIA_REPO, commit='', manifestPath=p.get('id', '') + '/manifest.json',
|
||||
license=p.get('license', ''), accent='', initials='', updated=p.get('lastUpdated', ''),
|
||||
review='', capabilities=[], official=bool(p.get('official')),
|
||||
page=NOCTALIA_REPO + '/tree/main/' + p.get('id', '')))
|
||||
CACHE.mkdir(parents=True, exist_ok=True)
|
||||
tmp = NOCTALIA_INDEX.with_suffix('.tmp')
|
||||
tmp.write_text(json.dumps(dict(fetchedAt=int(time.time()), items=items)))
|
||||
tmp.replace(NOCTALIA_INDEX)
|
||||
|
||||
|
||||
def load(force=False, source='omarchy'):
|
||||
index, build = (NOCTALIA_INDEX, build_noctalia_index) if source == 'noctalia' else (INDEX, build_index)
|
||||
fresh = index.is_file() and time.time() - index.stat().st_mtime < MAX_AGE
|
||||
if force or not fresh:
|
||||
try:
|
||||
build()
|
||||
except (OSError, ValueError) as e:
|
||||
if not index.is_file():
|
||||
raise
|
||||
stale = json.loads(index.read_text())
|
||||
stale['warning'] = 'Showing the cached catalog: ' + str(e)
|
||||
return stale
|
||||
return json.loads(index.read_text())
|
||||
|
||||
|
||||
def search(data, query, category, sort, offset, limit, verified_only):
|
||||
words = [w for w in query.lower().split() if w]
|
||||
items = data['items']
|
||||
if category and category != 'all':
|
||||
items = [i for i in items if i['category'] == category]
|
||||
if verified_only:
|
||||
items = [i for i in items if i['verified']]
|
||||
if words:
|
||||
def score(i):
|
||||
hay = ' '.join([i['name'], i['id'], i['description'], i['author'], ' '.join(i['tags'])]).lower()
|
||||
if not all(w in hay for w in words):
|
||||
return -1
|
||||
return sum(3 if w in i['name'].lower() else 1 for w in words)
|
||||
scored = [(score(i), i) for i in items]
|
||||
items = [i for s, i in sorted(scored, key=lambda x: (-x[0], -x[1]['stars'])) if s >= 0]
|
||||
elif sort == 'recent':
|
||||
items = sorted(items, key=lambda i: i['updated'], reverse=True)
|
||||
elif sort == 'name':
|
||||
items = sorted(items, key=lambda i: i['name'].lower())
|
||||
else:
|
||||
items = sorted(items, key=lambda i: (i['verified'], i['stars']), reverse=True)
|
||||
categories = sorted({i['category'] for i in data['items']})
|
||||
return dict(ok=True, total=len(items), offset=offset, items=items[offset:offset + limit],
|
||||
categories=categories, fetchedAt=data.get('fetchedAt', 0), warning=data.get('warning', ''))
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:] or ['search']
|
||||
try:
|
||||
if args[0] == 'refresh':
|
||||
data = load(force=True, source=args[1] if len(args) > 1 else 'omarchy')
|
||||
result = dict(ok=True, total=len(data['items']), fetchedAt=data.get('fetchedAt', 0))
|
||||
else:
|
||||
get = lambda n, d: args[n] if len(args) > n and args[n] != '' else d
|
||||
result = search(load(source=get(7, 'omarchy')), get(1, ''), get(2, 'all'), get(3, 'popular'), int(get(4, '0')),
|
||||
min(100, int(get(5, '30'))), get(6, 'false') == 'true')
|
||||
except (OSError, ValueError) as e:
|
||||
result = dict(ok=False, error='Could not load the plugin catalog: ' + str(e), items=[], total=0, categories=[])
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only Linux telemetry. One streaming process owns all sampling/deltas."""
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def read(path):
|
||||
try:
|
||||
return Path(path).read_text().strip()
|
||||
except OSError:
|
||||
return ''
|
||||
|
||||
|
||||
def number(value, divisor=1):
|
||||
try:
|
||||
result = float(value) / divisor
|
||||
return result if math.isfinite(result) and result >= 0 else None
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def cpu_counts(text):
|
||||
row = next(line for line in text.splitlines() if line.startswith('cpu '))
|
||||
v = [int(n) for n in row.split()[1:9]] # guest already included in user/nice
|
||||
return sum(v), v[3] + (v[4] if len(v) > 4 else 0)
|
||||
|
||||
|
||||
def cpu_percent(previous, current):
|
||||
if previous is None:
|
||||
return None
|
||||
total, idle = current[0] - previous[0], current[1] - previous[1]
|
||||
return max(0, min(100, 100 * (total - idle) / total)) if total > 0 and idle >= 0 else None
|
||||
|
||||
|
||||
def memory(text):
|
||||
v = {line.split(':')[0]: int(line.split()[1]) * 1024 for line in text.splitlines() if ':' in line}
|
||||
total, available = v.get('MemTotal', 0), v.get('MemAvailable')
|
||||
if not total or available is None:
|
||||
return {'available': False}
|
||||
used = max(0, total - available)
|
||||
return dict(available=True, total=total, used=used, free=available, percent=100 * used / total)
|
||||
|
||||
|
||||
def net_counts(text):
|
||||
result = {}
|
||||
for line in text.splitlines():
|
||||
if ':' not in line:
|
||||
continue
|
||||
name, data = line.rsplit(':', 1)
|
||||
fields = data.split()
|
||||
if len(fields) >= 16:
|
||||
result[name.strip()] = (int(fields[0]), int(fields[8]))
|
||||
return result
|
||||
|
||||
|
||||
def net_rates(previous, current, elapsed):
|
||||
return {name: {'download': max(0, values[0] - previous[name][0]) / elapsed,
|
||||
'upload': max(0, values[1] - previous[name][1]) / elapsed}
|
||||
for name, values in current.items() if name in previous and elapsed > 0}
|
||||
|
||||
|
||||
def nvidia_rows(text):
|
||||
result = []
|
||||
for row in csv.reader(text.splitlines(), skipinitialspace=True):
|
||||
if len(row) != 8:
|
||||
continue
|
||||
uid, name, busy, temp, used, total, clock, power = row
|
||||
result.append(dict(id=uid, name=name, provider='nvidia-smi', percent=number(busy),
|
||||
temperature=number(temp), used=number(used, 1 / 1048576),
|
||||
total=number(total, 1 / 1048576), frequency=number(clock), power=number(power)))
|
||||
return result
|
||||
|
||||
|
||||
class Collector:
|
||||
def __init__(self, options):
|
||||
self.options = options
|
||||
self.previous_cpu = None
|
||||
self.previous_net = {}
|
||||
self.previous_time = None
|
||||
self.gpus = []
|
||||
self.gpu_time = -100
|
||||
self.storage = []
|
||||
self.storage_time = -100
|
||||
self.nvidia = shutil.which('nvidia-smi')
|
||||
self.cpu_name = next((line.split(':', 1)[1].strip() for line in read('/proc/cpuinfo').splitlines()
|
||||
if line.startswith('model name')), 'CPU')
|
||||
|
||||
def gpu(self):
|
||||
result = []
|
||||
if self.nvidia:
|
||||
try:
|
||||
p = subprocess.run([self.nvidia, '--query-gpu=uuid,name,utilization.gpu,temperature.gpu,memory.used,memory.total,clocks.gr,power.draw',
|
||||
'--format=csv,noheader,nounits'], capture_output=True, text=True, timeout=2)
|
||||
if p.returncode == 0:
|
||||
result.extend(nvidia_rows(p.stdout))
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
pass
|
||||
for device in sorted(Path('/sys/class/drm').glob('card[0-9]*/device')):
|
||||
if not re.fullmatch(r'card\d+', device.parent.name):
|
||||
continue
|
||||
vendor = read(device / 'vendor')
|
||||
if vendor == '0x10de':
|
||||
continue # NVIDIA handled above, no duplicate device
|
||||
hwm = next(iter(device.glob('hwmon/hwmon*')), None)
|
||||
def sensor(name, divisor=1):
|
||||
return number(read(hwm / name), divisor) if hwm else None
|
||||
result.append(dict(id=str(device.resolve()), name=read(device / 'product_name') or
|
||||
('AMD' if vendor == '0x1002' else 'Intel' if vendor == '0x8086' else 'GPU') + ' · ' + device.parent.name,
|
||||
provider='sysfs', percent=number(read(device / 'gpu_busy_percent')),
|
||||
temperature=sensor('temp1_input', 1000), used=number(read(device / 'mem_info_vram_used')),
|
||||
total=number(read(device / 'mem_info_vram_total')), frequency=sensor('freq1_input', 1000000),
|
||||
power=sensor('power1_average', 1000000)))
|
||||
return result
|
||||
|
||||
def sample(self):
|
||||
now = time.monotonic()
|
||||
warnings = []
|
||||
cpu = dict(name=self.cpu_name, percent=None, temperature=None, frequency=None, power=None)
|
||||
try:
|
||||
counts = cpu_counts(read('/proc/stat'))
|
||||
cpu['percent'] = cpu_percent(self.previous_cpu, counts)
|
||||
self.previous_cpu = counts
|
||||
except (ValueError, StopIteration, IndexError):
|
||||
warnings.append('CPU counters unavailable')
|
||||
frequencies = [number(line.split(':', 1)[1]) for line in read('/proc/cpuinfo').splitlines() if line.startswith('cpu MHz')]
|
||||
frequencies = [v for v in frequencies if v is not None]
|
||||
cpu['frequency'] = sum(frequencies) / len(frequencies) if frequencies else None
|
||||
temperatures = []
|
||||
for hw in Path('/sys/class/hwmon').glob('hwmon*'):
|
||||
if read(hw / 'name') in ('k10temp', 'coretemp', 'zenpower', 'cpu_thermal'):
|
||||
temperatures += [number(read(p), 1000) for p in hw.glob('temp*_input')]
|
||||
temperatures = [v for v in temperatures if v is not None]
|
||||
cpu['temperature'] = max(temperatures) if temperatures else None
|
||||
try:
|
||||
ram = memory(read('/proc/meminfo'))
|
||||
except (ValueError, IndexError):
|
||||
ram = {'available': False}
|
||||
current = net_counts(read('/proc/net/dev'))
|
||||
rates = net_rates(self.previous_net, current, now - self.previous_time) if self.previous_time else {}
|
||||
interfaces = []
|
||||
for name in sorted(current):
|
||||
if name == 'lo':
|
||||
continue
|
||||
values = rates.get(name, {'download': None, 'upload': None})
|
||||
interfaces.append(dict(name=name, **values))
|
||||
selected = self.options.get('networkInterface', 'auto')
|
||||
# Auto uses physical interfaces; excludes VPN/bridge/veth double counting.
|
||||
names = [i['name'] for i in interfaces if (Path('/sys/class/net') / i['name'] / 'device').exists()] if selected == 'auto' else [selected]
|
||||
valid = [rates[n] for n in names if n in rates]
|
||||
network = dict(interfaces=interfaces, selected=names,
|
||||
download=sum(v['download'] for v in valid) if valid else None,
|
||||
upload=sum(v['upload'] for v in valid) if valid else None)
|
||||
self.previous_net, self.previous_time = current, now
|
||||
if now - self.gpu_time >= max(5, self.options.get('interval', 2)):
|
||||
self.gpus, self.gpu_time = self.gpu(), now
|
||||
if now - self.storage_time >= 15:
|
||||
self.storage = []
|
||||
for path in self.options.get('storagePaths', ['/']):
|
||||
try:
|
||||
s = os.statvfs(path)
|
||||
total, free, available = s.f_blocks * s.f_frsize, s.f_bfree * s.f_frsize, s.f_bavail * s.f_frsize
|
||||
used = total - free
|
||||
self.storage.append(dict(path=path, available=True, total=total, used=used, free=free,
|
||||
availableBytes=available, percent=100 * used / total if total else 0))
|
||||
except OSError:
|
||||
self.storage.append(dict(path=path, available=False))
|
||||
self.storage_time = now
|
||||
return dict(cpu=cpu, ram=ram, gpus=self.gpus, storage=self.storage, network=network,
|
||||
timestamp=time.time(), warnings=warnings)
|
||||
|
||||
|
||||
def main():
|
||||
options = json.loads(sys.argv[1]) if len(sys.argv) > 1 else {}
|
||||
interval = min(30, max(1, float(options.get('interval', 2))))
|
||||
collector = Collector(options)
|
||||
while True:
|
||||
started = time.monotonic()
|
||||
print(json.dumps(collector.sample(), allow_nan=False), flush=True)
|
||||
time.sleep(max(.1, interval - (time.monotonic() - started)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (BrokenPipeError, KeyboardInterrupt):
|
||||
pass
|
||||
@@ -0,0 +1,265 @@
|
||||
#!/usr/bin/env python3
|
||||
"""glassMxrph plugin store. Prints one JSON object.
|
||||
|
||||
list installed plugins with validation results
|
||||
install SOURCE [COMMIT] [ID] git URL (cloned, optionally pinned) or a local folder;
|
||||
a repository may hold several plugins (ID picks one)
|
||||
remove ID delete an installed plugin
|
||||
|
||||
Omarchy plugins are copied into the store and their `import qs.Ui` /
|
||||
`import qs.Commons` lines are pointed at glassMxrph's compatibility layer
|
||||
(qs.compat.omarchy.*). Plugins run unsandboxed inside the shell, like in
|
||||
Omarchy: nothing here makes them safe, it only checks they are well formed.
|
||||
"""
|
||||
import json, os, re, shutil, subprocess, sys, tempfile, time
|
||||
from pathlib import Path
|
||||
|
||||
STORE = Path(os.environ.get('XDG_DATA_HOME') or Path.home() / '.local/share') / 'glassMxrph/plugins'
|
||||
KINDS = {'bar-widget': 'barWidget', 'panel': 'panel', 'overlay': 'overlay', 'menu': 'menu', 'service': 'service', 'bar': 'bar'}
|
||||
# Noctalia v4 entry points -> plugin kinds (main.qml is a headless service).
|
||||
NOCTALIA_KINDS = {'barWidget': 'bar-widget', 'panel': 'panel', 'main': 'service', 'settings': 'settings',
|
||||
'desktopWidget': 'desktop-widget', 'desktopWidgetSettings': 'desktop-widget-settings',
|
||||
'controlCenterWidget': 'control-center-widget', 'launcherProvider': 'launcher-provider'}
|
||||
COMPAT = Path(__file__).resolve().parent.parent / 'compat'
|
||||
ID_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$')
|
||||
META = '.glassmxrph.json'
|
||||
REWRITES = {'qs.Ui': 'qs.compat.omarchy.Ui', 'qs.Commons': 'qs.compat.omarchy.Commons'}
|
||||
|
||||
|
||||
def ecosystem(manifest):
|
||||
if not isinstance(manifest, dict):
|
||||
return 'omarchy'
|
||||
if 'schemaVersion' in manifest or 'kinds' in manifest:
|
||||
return 'omarchy'
|
||||
entry = manifest.get('entryPoints')
|
||||
if 'minNoctaliaVersion' in manifest or (isinstance(entry, dict) and set(entry) & set(NOCTALIA_KINDS)):
|
||||
return 'noctalia'
|
||||
return 'omarchy'
|
||||
|
||||
|
||||
def plugin_kinds(manifest):
|
||||
"""(kind, entry file) pairs for either format."""
|
||||
entry = (manifest or {}).get('entryPoints') or {}
|
||||
if ecosystem(manifest) == 'noctalia':
|
||||
return [(NOCTALIA_KINDS[k], v) for k, v in entry.items() if k in NOCTALIA_KINDS]
|
||||
return [(k, entry.get(KINDS[k])) for k in (manifest or {}).get('kinds') or [] if k in KINDS]
|
||||
|
||||
|
||||
def compat_modules(eco):
|
||||
"""qs.* module names the compatibility layer provides for an ecosystem."""
|
||||
root = COMPAT / eco
|
||||
mods = set()
|
||||
for d in root.rglob('*'):
|
||||
if d.is_dir() and any(f.suffix == '.qml' for f in d.iterdir()):
|
||||
mods.add('qs.compat.' + eco + '.' + '.'.join(d.relative_to(root).parts))
|
||||
return mods
|
||||
HEX = re.compile(r'["\']#[0-9A-Fa-f]{6}(?:[0-9A-Fa-f]{2})?["\']')
|
||||
|
||||
|
||||
def safe_rel(path):
|
||||
p = Path(path)
|
||||
return bool(path) and not p.is_absolute() and '..' not in p.parts
|
||||
|
||||
|
||||
def validate(directory):
|
||||
"""Problems with a plugin folder (Omarchy's `plugin validate` rules, or
|
||||
Noctalia's manifest rules)."""
|
||||
problems = []
|
||||
try:
|
||||
manifest = json.loads((directory / 'manifest.json').read_text())
|
||||
except (OSError, ValueError) as e:
|
||||
return None, ['manifest.json does not parse: ' + str(e)]
|
||||
eco = ecosystem(manifest)
|
||||
if eco == 'omarchy' and manifest.get('schemaVersion') != 1:
|
||||
problems.append('schemaVersion must be 1')
|
||||
pid = manifest.get('id')
|
||||
if not isinstance(pid, str) or not ID_RE.match(pid):
|
||||
problems.append('invalid id')
|
||||
elif pid.startswith('omarchy.') or pid.startswith('glassmxrph.'):
|
||||
problems.append('reserved id prefix')
|
||||
for key in ('name', 'version'):
|
||||
if not isinstance(manifest.get(key), str) or not manifest.get(key):
|
||||
problems.append('missing ' + key)
|
||||
if eco == 'omarchy':
|
||||
kinds = manifest.get('kinds')
|
||||
if not isinstance(kinds, list) or not kinds or any(k not in KINDS for k in kinds):
|
||||
problems.append('kinds must be a non-empty list of ' + ', '.join(KINDS))
|
||||
elif not plugin_kinds(manifest):
|
||||
problems.append('entryPoints must name at least one of ' + ', '.join(NOCTALIA_KINDS))
|
||||
for kind, rel in plugin_kinds(manifest):
|
||||
if not isinstance(rel, str) or not safe_rel(rel):
|
||||
problems.append(f'entry point for {kind} must be a safe relative path')
|
||||
elif not (directory / rel).is_file():
|
||||
problems.append(f'entry point file missing: {rel}')
|
||||
for path in directory.rglob('*'):
|
||||
if '.git' in path.parts:
|
||||
continue
|
||||
if path.is_symlink():
|
||||
problems.append('symlinks are not allowed: ' + str(path.relative_to(directory)))
|
||||
return manifest, problems
|
||||
|
||||
|
||||
COMPAT_BIN = Path(__file__).resolve().parent.parent / 'compat/omarchy/bin'
|
||||
|
||||
|
||||
def scan_sources(directory, eco='omarchy'):
|
||||
"""Imports the compatibility layer lacks and hard-coded colors, for the report."""
|
||||
supported = compat_modules(eco)
|
||||
unsupported, custom_colors = set(), 0
|
||||
for path in directory.rglob('*'):
|
||||
if path.suffix not in ('.qml', '.js') or '.git' in path.parts:
|
||||
continue
|
||||
text = path.read_text(errors='ignore')
|
||||
for m in re.finditer(r'^\s*import\s+(qs\.[A-Za-z0-9_.]+)', text, re.M):
|
||||
if m.group(1) not in supported:
|
||||
unsupported.add(m.group(1))
|
||||
custom_colors += len(HEX.findall(text))
|
||||
return sorted(unsupported), custom_colors
|
||||
|
||||
|
||||
def missing_commands(directory):
|
||||
"""omarchy-* helper commands the plugin runs that glassMxrph does not provide."""
|
||||
used = set()
|
||||
for path in directory.rglob('*'):
|
||||
if path.is_file() and '.git' not in path.parts and path.suffix in ('.qml', '.js', '.sh', '.py', ''):
|
||||
used |= set(re.findall(r'\b(omarchy-[a-z0-9-]+)\b', path.read_text(errors='ignore')))
|
||||
return sorted(c for c in used if not (COMPAT_BIN / c).is_file() and not shutil.which(c))
|
||||
|
||||
|
||||
SHEBANGS = re.compile(r'^#!\s*/(?:usr/)?bin/(bash|zsh|python3?|perl|node)\b')
|
||||
|
||||
|
||||
def portable_shebangs(directory):
|
||||
"""NixOS has no /bin/bash or /usr/bin/python3: run interpreters from PATH."""
|
||||
for path in directory.rglob('*'):
|
||||
if not path.is_file() or path.is_symlink() or '.git' in path.parts:
|
||||
continue
|
||||
try:
|
||||
with path.open('rb') as f:
|
||||
head = f.read(64)
|
||||
if not head.startswith(b'#!'):
|
||||
continue
|
||||
text = path.read_text()
|
||||
except (OSError, UnicodeDecodeError):
|
||||
continue
|
||||
new = SHEBANGS.sub(lambda m: '#!/usr/bin/env ' + m.group(1), text, count=1)
|
||||
if new != text:
|
||||
mode = path.stat().st_mode
|
||||
path.write_text(new)
|
||||
path.chmod(mode)
|
||||
|
||||
|
||||
def rewrite_imports(directory, eco='omarchy'):
|
||||
for path in directory.rglob('*'):
|
||||
if path.suffix != '.qml' or '.git' in path.parts:
|
||||
continue
|
||||
text = path.read_text(errors='ignore')
|
||||
new = text
|
||||
if eco == 'noctalia':
|
||||
new = re.sub(r'^(\s*import\s+)qs\.(Commons|Widgets|Services|Modules)\b', r'\g<1>qs.compat.noctalia.\g<2>', new, flags=re.M)
|
||||
else:
|
||||
for old, compat in REWRITES.items():
|
||||
new = re.sub(r'^(\s*import\s+)' + re.escape(old) + r'(\s*)$', r'\g<1>' + compat + r'\g<2>', new, flags=re.M)
|
||||
if new != text:
|
||||
path.write_text(new)
|
||||
|
||||
|
||||
def describe(directory):
|
||||
manifest, problems = validate(directory)
|
||||
meta = {}
|
||||
try:
|
||||
meta = json.loads((directory / META).read_text())
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
pairs = plugin_kinds(manifest)
|
||||
urls = {kind: (directory / rel).as_uri() for kind, rel in pairs if isinstance(rel, str) and safe_rel(rel)}
|
||||
preview = directory / 'preview.png'
|
||||
return dict(id=(manifest or {}).get('id') or directory.name, dir=str(directory), manifest=manifest or {},
|
||||
kinds=[kind for kind, _ in pairs],
|
||||
problems=problems, entryUrls=urls, preview=preview.as_uri() if preview.is_file() else '',
|
||||
ecosystem=meta.get('ecosystem', ecosystem(manifest)), source=meta.get('source', ''), commit=meta.get('commit', ''),
|
||||
installedAt=meta.get('installedAt', 0), unsupportedImports=meta.get('unsupportedImports', []),
|
||||
customColors=meta.get('customColors', 0), missingCommands=missing_commands(directory))
|
||||
|
||||
|
||||
def plugin_dirs(root):
|
||||
if (root / 'manifest.json').is_file():
|
||||
return [root]
|
||||
return sorted(p.parent for p in root.rglob('manifest.json') if '.git' not in p.parts and len(p.relative_to(root).parts) <= 3)
|
||||
|
||||
|
||||
def install(source, commit='', only_id=''):
|
||||
STORE.mkdir(parents=True, exist_ok=True)
|
||||
work = Path(tempfile.mkdtemp(prefix='glassmxrph-plugin-'))
|
||||
try:
|
||||
if re.match(r'^(https://|git@|ssh://)', source):
|
||||
subprocess.run(['git', 'clone', '--quiet', '--filter=blob:none', source, str(work / 'src')], check=True,
|
||||
capture_output=True, text=True, timeout=180)
|
||||
if commit:
|
||||
subprocess.run(['git', '-C', str(work / 'src'), 'checkout', '--quiet', commit], check=True,
|
||||
capture_output=True, text=True, timeout=60)
|
||||
commit = subprocess.run(['git', '-C', str(work / 'src'), 'rev-parse', 'HEAD'], capture_output=True,
|
||||
text=True).stdout.strip()
|
||||
root = work / 'src'
|
||||
else:
|
||||
root = Path(source).expanduser().resolve()
|
||||
if not root.is_dir():
|
||||
raise ValueError('not a folder or git URL: ' + source)
|
||||
found = plugin_dirs(root)
|
||||
if not found:
|
||||
raise ValueError('no manifest.json found')
|
||||
installed, rejected = [], []
|
||||
for directory in found:
|
||||
manifest, problems = validate(directory)
|
||||
if only_id and (manifest or {}).get('id') != only_id:
|
||||
continue
|
||||
if problems:
|
||||
rejected.append(dict(dir=str(directory.relative_to(root)) or '.', problems=problems))
|
||||
continue
|
||||
target = STORE / manifest['id']
|
||||
staging = STORE / ('.staging-' + manifest['id'])
|
||||
if staging.exists():
|
||||
shutil.rmtree(staging)
|
||||
shutil.copytree(directory, staging, ignore=shutil.ignore_patterns('.git'), symlinks=True)
|
||||
eco = ecosystem(manifest)
|
||||
_, colors = scan_sources(staging, eco)
|
||||
rewrite_imports(staging, eco)
|
||||
portable_shebangs(staging)
|
||||
unsupported, _ = scan_sources(staging, eco)
|
||||
(staging / META).write_text(json.dumps(dict(ecosystem=eco, source=source, commit=commit,
|
||||
installedAt=int(time.time()), unsupportedImports=unsupported,
|
||||
customColors=colors), indent=2))
|
||||
if target.exists():
|
||||
shutil.rmtree(target)
|
||||
staging.rename(target)
|
||||
installed.append(manifest['id'])
|
||||
missing = 'plugin ' + only_id + ' not found in ' + source if only_id and not installed and not rejected else ''
|
||||
return dict(ok=bool(installed), installed=installed, rejected=rejected,
|
||||
error='' if installed else missing or 'no valid plugin in ' + source)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def main():
|
||||
command = sys.argv[1] if len(sys.argv) > 1 else 'list'
|
||||
try:
|
||||
if command == 'install':
|
||||
result = install(sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else '', sys.argv[4] if len(sys.argv) > 4 else '')
|
||||
elif command == 'remove':
|
||||
pid = sys.argv[2]
|
||||
if not ID_RE.match(pid) or not (STORE / pid).is_dir():
|
||||
raise ValueError('not installed: ' + pid)
|
||||
shutil.rmtree(STORE / pid)
|
||||
result = dict(ok=True, removed=pid)
|
||||
else:
|
||||
result = dict(ok=True)
|
||||
result['plugins'] = [describe(d) for d in sorted(STORE.iterdir()) if d.is_dir() and not d.name.startswith('.')] if STORE.is_dir() else []
|
||||
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
|
||||
result = dict(ok=False, error=(getattr(e, 'stderr', '') or str(e)).strip()[-400:], plugins=[])
|
||||
except (OSError, ValueError, IndexError) as e:
|
||||
result = dict(ok=False, error=str(e), plugins=[])
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Small system adapters. JSON protocol, argv-only execution, no daemon installation."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
def run(args, timeout=4):
|
||||
result = subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout, env=dict(os.environ, LC_ALL='C'))
|
||||
if result.returncode:
|
||||
raise ValueError((result.stderr or result.stdout or 'Command failed').strip()[-500:])
|
||||
return result.stdout.strip()
|
||||
|
||||
def bus(scope, *args):
|
||||
return json.loads(run(['busctl', '--'+scope, '--auto-start=no', '--timeout=3', '--json=short', *args]))['data']
|
||||
|
||||
def command(args, **values):
|
||||
if not isinstance(args, list) or not args or any(not isinstance(a, str) or not a for a in args):
|
||||
raise ValueError('Configure a nonempty command argument array')
|
||||
return [re.sub(r'\{(value|enabled)\}', lambda m: str(values.get(m[1], m[0])).lower(), a) for a in args]
|
||||
|
||||
def bounded(value, minimum, maximum):
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not minimum <= value <= maximum:
|
||||
raise ValueError('Value outside supported range')
|
||||
return value
|
||||
|
||||
def backlights():
|
||||
result=[]
|
||||
for path in sorted(Path('/sys/class/backlight').glob('*')):
|
||||
maximum=int((path/'max_brightness').read_text())
|
||||
if maximum > 0:
|
||||
result.append({'id':path.name, 'value':100*int((path/'brightness').read_text())/maximum})
|
||||
return result
|
||||
|
||||
def brightness(options):
|
||||
if options.get('statusCommand'):
|
||||
data=json.loads(run(command(options['statusCommand'])))
|
||||
bounded(data['value'], 0, 100)
|
||||
if 'available' in data and type(data['available']) is not bool:raise ValueError('Provider availability must be a boolean')
|
||||
return dict(data, available=bool(data.get('available', True)), provider='custom', devices=[])
|
||||
devices=backlights()
|
||||
device=next((d for d in devices if d['id']==options.get('device')), devices[0] if devices and options.get('device','auto')=='auto' else None)
|
||||
return {'available':bool(device) and bool(shutil.which('brightnessctl')), 'value':device['value'] if device else 0, 'device':device['id'] if device else '', 'devices':devices, 'provider':'brightnessctl', 'notice':'' if device else 'No selected backlight device. External displays need a configured brightness provider.'}
|
||||
|
||||
def night(options):
|
||||
if options.get('statusCommand'):
|
||||
data=json.loads(run(command(options['statusCommand'])))
|
||||
if 'available' in data and type(data['available']) is not bool:raise ValueError('Provider availability must be a boolean')
|
||||
if type(data.get('enabled')) is not bool:raise ValueError('Night Light status must include enabled: true/false')
|
||||
return dict(data, available=bool(data.get('available',True)), provider='custom')
|
||||
temp=bus('user','get-property','rs.wl-gammarelay','/','rs.wl.gammarelay','Temperature')
|
||||
return {'available':True,'enabled':temp<6500,'temperature':temp,'provider':'wl-gammarelay'}
|
||||
|
||||
def notifications():
|
||||
value=bus('user','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','GetDnd')[0]
|
||||
if type(value) is not bool:raise ValueError('SwayNC did not return a DND state')
|
||||
return {'available':True,'enabled':value}
|
||||
|
||||
def profiles():
|
||||
service='net.hadess.PowerProfiles';path='/net/hadess/PowerProfiles'
|
||||
values=bus('system','get-property',service,path,service,'Profiles')
|
||||
current=bus('system','get-property',service,path,service,'ActiveProfile')
|
||||
return {'available':True,'current':current,'profiles':[p['Profile']['data'] for p in values]}
|
||||
|
||||
def lock_command(options):
|
||||
if options.get('lockCommand'):return command(options['lockCommand'])
|
||||
if shutil.which('serpantinum'):return ['serpantinum','lock']
|
||||
if shutil.which('hyprlock'):return ['hyprlock']
|
||||
return []
|
||||
|
||||
def power(options):
|
||||
result={'available':True,'lock':bool(lock_command(options)),'logout':bool(os.environ.get('HYPRLAND_INSTANCE_SIGNATURE')) and bool(shutil.which('hyprctl'))}
|
||||
for key,method in [('suspend','CanSuspend'),('reboot','CanReboot'),('shutdown','CanPowerOff')]:
|
||||
try:result[key]=bus('system','call','org.freedesktop.login1','/org/freedesktop/login1','org.freedesktop.login1.Manager',method)[0] in ['yes','challenge']
|
||||
except (ValueError,OSError,subprocess.TimeoutExpired):result[key]=False
|
||||
return result
|
||||
|
||||
def safely(fn):
|
||||
try:return fn()
|
||||
except (ValueError,OSError,KeyError,TypeError,subprocess.TimeoutExpired) as error:return {'available':False,'notice':str(error)}
|
||||
|
||||
def snapshot(options, features=None):
|
||||
jobs={'brightness':lambda:brightness(options['brightness']), 'nightLight':lambda:night(options['nightLight']), 'dnd':notifications, 'profiles':profiles, 'power':lambda:power(options['power'])}
|
||||
if features is not None:jobs={key:fn for key,fn in jobs.items() if key in features}
|
||||
if not jobs:return {}
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=len(jobs)) as pool:
|
||||
return dict(zip(jobs,pool.map(safely,jobs.values())))
|
||||
|
||||
def action(req):
|
||||
options=req['options'];kind=req['action'];value=req.get('value')
|
||||
if kind=='brightness':
|
||||
value=round(bounded(value,1,100))
|
||||
spec=options['brightness']
|
||||
if spec.get('setCommand'):run(command(spec['setCommand'],value=value))
|
||||
else:
|
||||
state=brightness(spec)
|
||||
if not state['available'] or state['provider']!='brightnessctl':raise ValueError('No writable brightness provider')
|
||||
run(['brightnessctl','--class=backlight','--device='+state['device'],'set',str(value)+'%'])
|
||||
elif kind=='nightLight':
|
||||
if type(value) is not bool:raise ValueError('Night Light expects a boolean')
|
||||
spec=options['nightLight']
|
||||
if spec.get('setCommand'):run(command(spec['setCommand'],enabled=value,value=spec['temperature'] if value else 6500))
|
||||
else:
|
||||
night(spec) # Require a running provider; never auto-start a second gamma daemon.
|
||||
temperature=round(bounded(spec['temperature'],1000,6500)) if value else 6500
|
||||
run(['busctl','--user','--auto-start=no','--timeout=3','set-property','rs.wl-gammarelay','/','rs.wl.gammarelay','Temperature','q',str(temperature)])
|
||||
elif kind=='dnd':
|
||||
if type(value) is not bool:raise ValueError('DND expects a boolean')
|
||||
notifications()
|
||||
run(['busctl','--user','--auto-start=no','--timeout=3','call','org.erikreider.swaync.cc','/org/erikreider/swaync/cc','org.erikreider.swaync.cc','SetDnd','b',str(value).lower()])
|
||||
elif kind=='profile':
|
||||
if value not in profiles()['profiles']:raise ValueError('Unsupported power profile')
|
||||
run(['busctl','--system','--auto-start=no','--timeout=3','set-property','net.hadess.PowerProfiles','/net/hadess/PowerProfiles','net.hadess.PowerProfiles','ActiveProfile','s',value])
|
||||
elif kind=='power':
|
||||
if value not in ['lock','logout','suspend','reboot','shutdown']:raise ValueError('Unsupported power action')
|
||||
if value in ['logout','reboot','shutdown'] and req.get('confirmed') is not True:raise ValueError('Explicit confirmation required')
|
||||
if not power(options['power']).get(value):raise ValueError('Power action unavailable')
|
||||
if value=='lock':subprocess.Popen(lock_command(options['power']),stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
|
||||
elif value=='logout':run(['hyprctl','dispatch','exit'])
|
||||
else:run(['busctl','--system','--auto-start=no','--timeout=10','call','org.freedesktop.login1','/org/freedesktop/login1','org.freedesktop.login1.Manager',{'suspend':'Suspend','reboot':'Reboot','shutdown':'PowerOff'}[value],'b','true'],15)
|
||||
elif kind=='manager':
|
||||
executable={'network':'nm-connection-editor','bluetooth':'blueman-manager'}.get(value)
|
||||
if not executable or not shutil.which(executable):raise ValueError('The existing connection manager is not installed')
|
||||
subprocess.Popen([executable],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,start_new_session=True)
|
||||
else:raise ValueError('Unsupported action')
|
||||
return {'state':snapshot(options)}
|
||||
|
||||
def main(req):
|
||||
if req.get('op')=='status':return {'state':snapshot(req['options'],req.get('features'))}
|
||||
if req.get('op')=='action':return action(req)
|
||||
raise ValueError('Unsupported operation')
|
||||
|
||||
if __name__=='__main__':
|
||||
try:print(json.dumps(dict(ok=True,**main(json.loads(sys.argv[1])))))
|
||||
except (ValueError,OSError,KeyError,TypeError,subprocess.TimeoutExpired) as error:
|
||||
print(json.dumps({'ok':False,'error':str(error)}))
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Current weather from wttr.in as compact JSON: {ok, place, temperature, feels, code, description}."""
|
||||
import json, sys, urllib.parse, urllib.request
|
||||
|
||||
def main():
|
||||
location = sys.argv[1] if len(sys.argv) > 1 else ''
|
||||
url = 'https://wttr.in/' + urllib.parse.quote(location) + '?format=j1'
|
||||
try:
|
||||
with urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': 'glassMxrph'}), timeout=12) as response:
|
||||
data = json.load(response)
|
||||
now = data['current_condition'][0]
|
||||
area = (data.get('nearest_area') or [{}])[0]
|
||||
place = (area.get('areaName') or [{'value': ''}])[0]['value']
|
||||
print(json.dumps(dict(ok=True, place=place or location, celsius=float(now['temp_C']), feelsCelsius=float(now['FeelsLikeC']),
|
||||
code=int(now['weatherCode']), description=now['weatherDesc'][0]['value'].strip(),
|
||||
humidity=int(now['humidity']), wind=float(now['windspeedKmph']))))
|
||||
except Exception as error: # Network, HTTP and format errors all surface as a message.
|
||||
print(json.dumps(dict(ok=False, error=str(error))))
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user