#!/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'} COLOR_USE = re.compile(r'(?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) # Qt 6.12's QtQuick exports a Color singleton that hides the kits' # Commons.Color; an older QtQuick version leaves it out. if COLOR_USE.search(new): new = re.sub(r'^(\s*import\s+QtQuick)(\s*)$', r'\g<1> 6.8\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()