#!/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()