From 25c059ab6adac30fe651c11f9fc2ee47d5209d5f Mon Sep 17 00:00:00 2001 From: Belfagor2005 <72314956+Belfagor2005@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:07:13 +0000 Subject: [PATCH] Add nightly Enigma2 skin catalogs Add a catalog builder that reads the public enigma2 sources of each image (openATV, OpenPLi, OpenViX, OpenBH, teamBlue) and writes one JSON catalog per image: skin.py attributes and accepted values, legacy aliases, XML tags, renderers, converters with their arguments, screens with expected widgets, skin parameters, fonts and colors. - catalogs/images.json: editable list of images, branches and plugin repos - catalogs/build_catalogs.py: fetches the sources and builds every catalog - catalogs/e2catalog.py, catalogs/e2compare.py: extractor and comparison - .github/workflows/catalogs.yml: nightly and manual run; publishes to the "catalogs" branch from main only, pull requests just build and upload the result as an artifact OpenSkin Designer will read these catalogs in a follow-up change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EVc11N8zrA7gm5kdSWgpH9 --- .github/workflows/catalogs.yml | 63 ++++ .gitignore | 5 + catalogs/README.md | 63 ++++ catalogs/build_catalogs.py | 94 +++++ catalogs/e2catalog.py | 641 +++++++++++++++++++++++++++++++++ catalogs/e2compare.py | 138 +++++++ catalogs/images.json | 12 + 7 files changed, 1016 insertions(+) create mode 100644 .github/workflows/catalogs.yml create mode 100644 catalogs/README.md create mode 100644 catalogs/build_catalogs.py create mode 100644 catalogs/e2catalog.py create mode 100644 catalogs/e2compare.py create mode 100644 catalogs/images.json diff --git a/.github/workflows/catalogs.yml b/.github/workflows/catalogs.yml new file mode 100644 index 0000000..7c3b6bb --- /dev/null +++ b/.github/workflows/catalogs.yml @@ -0,0 +1,63 @@ +name: Skin catalogs + +# Rebuilds the Enigma2 skin catalogs from the public enigma2 sources +# and publishes them to the "catalogs" branch. +on: + schedule: + - cron: "17 3 * * *" + workflow_dispatch: + pull_request: + paths: + - "catalogs/**" + - ".github/workflows/catalogs.yml" + +permissions: + contents: write + +concurrency: + group: skin-catalogs-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Build catalogs + id: build + run: | + if ! python catalogs/build_catalogs.py --out out; then + echo "partial=true" >> "$GITHUB_OUTPUT" + fi + test -s out/index.json + + - name: Upload catalogs as artifact + uses: actions/upload-artifact@v4 + with: + name: skin-catalogs + path: out/ + retention-days: 14 + + # Publishing only happens from main (nightly run or manual run), never from a pull request. + - name: Publish to the catalogs branch + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + run: | + cd out + git init -q -b catalogs + git add . + git -c user.name="github-actions[bot]" \ + -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -q -m "Skin catalogs $(date -u +%F)" + git push -f "https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git" catalogs + + - name: Report images that failed + if: steps.build.outputs.partial == 'true' + run: | + echo "::warning::Some images could not be built; the others were published. See the Build catalogs step." + exit 1 diff --git a/.gitignore b/.gitignore index 3fa586b..022d1ab 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,8 @@ Source/e2skinner2/bin/ Source/e2skinner2/obj/ *.suo /Source/.vs + +# Skin catalog builder (local runs) +catalogs/cache/ +catalogs/out/ +__pycache__/ diff --git a/catalogs/README.md b/catalogs/README.md new file mode 100644 index 0000000..70488a7 --- /dev/null +++ b/catalogs/README.md @@ -0,0 +1,63 @@ +# Enigma2 skin catalogs + +Machine-readable catalogs that tell OpenSkin Designer what each Enigma2 image supports: +skin attributes and their accepted values, XML tags, renderers, converters (with their +arguments), screens with the widgets they expect, skin parameters, fonts and colors. + +They are generated from the public enigma2 source repositories, so they stay current +without manual work. + +## Where the catalogs are published + +A GitHub Action (`.github/workflows/catalogs.yml`) rebuilds them every night and on demand, +and publishes them to the **`catalogs`** branch of this repository: + +``` +https://raw.githubusercontent.com/OwnerPlugins/OpenSkin-Designer/catalogs/index.json +https://raw.githubusercontent.com/OwnerPlugins/OpenSkin-Designer/catalogs/.json +``` + +| File | Content | +| --- | --- | +| `index.json` | The images available, with branch and file name | +| `.json` | The catalog of one image (used by OpenSkin Designer) | +| `.md` | The same catalog in readable form | +| `compare.md` / `compare.json` | What differs between the images | + +## Images + +The list lives in `images.json`. Each entry has an `id`, a display `name`, the git `repo` +URL, the `branch` and the plugin repositories scanned with it. + +- **Add** an image: copy an entry and change `id`, `name`, `repo` and `branch`. +- **Change** an image: edit its `repo` or `branch`. +- **Remove** an image: set `"enabled": false`, or delete the entry. +- **Plugins**: list them under `plugins`; an empty `branch` means the default branch. + +## Running it locally + +Needs git and Python 3.10 or newer (3.12+ recommended). Nothing is written to GitHub. + +``` +python catalogs/build_catalogs.py # all enabled images +python catalogs/build_catalogs.py --only openatv # one image +``` + +Sources are cached in `catalogs/cache`, results go to `catalogs/out` (both git-ignored). + +## Scripts + +| Script | Purpose | +| --- | --- | +| `build_catalogs.py` | Downloads the sources listed in `images.json` and builds every catalog | +| `e2catalog.py` | Builds the catalog of one enigma2 source tree | +| `e2compare.py` | Compares several catalogs | + +## Limits + +The catalogs come from static analysis of the Python code: + +- skin names computed at runtime and widgets created in loops are not seen; +- `Setup` screens take their layout from `setup.xml`, which is not read yet; +- converter arguments and renderer attributes are best-effort: roughly one converter in + three reads its arguments in a way the script does not recognize. diff --git a/catalogs/build_catalogs.py b/catalogs/build_catalogs.py new file mode 100644 index 0000000..5522918 --- /dev/null +++ b/catalogs/build_catalogs.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""build_catalogs.py - build the skin catalogs from images.json. + +Usage: python build_catalogs.py [--images images.json] [--cache cache] [--out out] [--only openatv openpli] + +For every enabled image: download (or update) its enigma2 repository and plugin +repositories into the cache folder, then write out/.json and out/.md, +and finally out/compare.* and out/index.json. +Needs only git and Python 3.10 or newer. Writes nothing to GitHub. +""" +import argparse, json, os, subprocess, sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import e2catalog # noqa: E402 + +SPARSE = ["lib/python", "lib/gui", "data"] + + +def git(args, cwd=None): + r = subprocess.run(["git"] + args, cwd=cwd, capture_output=True, text=True) + if r.returncode != 0: + raise RuntimeError(f"git {' '.join(args)}: {r.stderr.strip()}") + return r.stdout.strip() + + +def fetch(repo, branch, dest, sparse): + """Shallow clone, or update an existing one. Only the folders the catalog needs.""" + if os.path.isdir(os.path.join(dest, ".git")): + ref = branch or "HEAD" + git(["fetch", "--depth", "1", "--filter=blob:none", "origin", ref], cwd=dest) + git(["checkout", "-q", "--force", "FETCH_HEAD"], cwd=dest) + else: + args = ["clone", "-q", "--depth", "1", "--filter=blob:none"] + if sparse: + args.append("--sparse") + if branch: + args += ["-b", branch] + git(args + [repo, dest]) + if sparse: + git(["sparse-checkout", "set"] + SPARSE, cwd=dest) + return git(["log", "-1", "--format=%ad", "--date=short"], cwd=dest) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--images", default=os.path.join(HERE, "images.json")) + ap.add_argument("--cache", default=os.path.join(HERE, "cache")) + ap.add_argument("--out", default=os.path.join(HERE, "out")) + ap.add_argument("--only", nargs="*", help="only these image ids") + a = ap.parse_args() + + cfg = json.load(open(a.images, encoding="utf-8")) + os.makedirs(a.cache, exist_ok=True) + os.makedirs(a.out, exist_ok=True) + done, failed = [], [] + for img in cfg["images"]: + if not img.get("enabled", True) or (a.only and img["id"] not in a.only): + continue + print(f"== {img['name']} ({img.get('branch') or 'default'})", flush=True) + try: + root = os.path.join(a.cache, img["id"]) + print(" image updated on", fetch(img["repo"], img.get("branch"), root, True), flush=True) + plugin_dirs = [] + for p in img.get("plugins", []): + pdir = os.path.join(a.cache, img["id"] + "__" + p["name"]) + print(f" plugin {p['name']}:", fetch(p["repo"], p.get("branch"), pdir, False), flush=True) + plugin_dirs.append(pdir) + cat = e2catalog.build(root, img["id"], plugin_dirs) + cat["displayName"] = img["name"] + with open(os.path.join(a.out, img["id"] + ".json"), "w", encoding="utf-8") as f: + json.dump(cat, f, indent=1, ensure_ascii=False) + with open(os.path.join(a.out, img["id"] + ".md"), "w", encoding="utf-8") as f: + f.write(e2catalog.to_markdown(cat)) + print(f" {len(cat['screens'])} screens, {len(cat['skinEngine']['attributes'])} attributes, " + f"{len(cat['parseErrors'])} unreadable files", flush=True) + done.append(img["id"]) + except Exception as exc: # one broken image does not stop the others + print(" ERROR:", exc, flush=True) + failed.append(img["id"]) + + if len(done) > 1: + files = [os.path.join(a.out, i + ".json") for i in done] + subprocess.run([sys.executable, os.path.join(HERE, "e2compare.py")] + files + + ["--md", os.path.join(a.out, "compare.md"), "--json", os.path.join(a.out, "compare.json")]) + with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f: + json.dump({"images": [{"id": i["id"], "name": i["name"], "branch": i.get("branch"), "file": i["id"] + ".json"} + for i in cfg["images"] if i["id"] in done]}, f, indent=1) + print(f"\nDone: {len(done)} ok, {len(failed)} failed {failed if failed else ''}. Output in {a.out}") + sys.exit(1 if failed else 0) + + +if __name__ == "__main__": + main() diff --git a/catalogs/e2catalog.py b/catalogs/e2catalog.py new file mode 100644 index 0000000..3f13294 --- /dev/null +++ b/catalogs/e2catalog.py @@ -0,0 +1,641 @@ +#!/usr/bin/env python3 +"""e2catalog - build a skin-author catalog from an enigma2 source tree. + +Given the root of an enigma2 repository (openATV, OpenPLi, OpenViX, OpenBH, ...) +and optionally extra plugin repositories, it extracts everything a skin designer +needs to know about that image: + + * skin engine: attributes accepted by skin.py (AttributeParser) and the XML + sections/tags skin.py reads + * components: Renderer, Converter and Sources modules (with converter + arguments when they can be read from the code) + * screens: every class that inherits (directly or not) from Screen, with the + skin names it looks up (class name + self.skinName) and the widgets it + creates (self["name"] = Component(...)), inherited widgets included + * default skins: screens defined in the XML files shipped in data/ + +Output: one JSON file (machine readable, for the editor) and an optional +Markdown summary (for humans). + +Usage: + e2catalog.py --name openatv [--plugins DIR ...] [-o out.json] [--md out.md] +""" + +import argparse +import warnings +warnings.filterwarnings("ignore", category=SyntaxWarning) +import ast +import datetime +import json +import os +import re +import subprocess +import sys +from collections import defaultdict + +ACTIONMAP_RE = re.compile(r"ActionMap$") +SCREEN_TAG_RE = re.compile(r"]*?\bname\s*=\s*[\"']([^\"']+)[\"']", re.S) + + +# ---------------------------------------------------------------- skin.py +def parse_skin_py(path): + """Return (attributes, xml_tags) supported by a skin.py.""" + try: + text = open(path, encoding="utf-8", errors="replace").read() + except OSError: + return [], [] + attributes = set() + try: + tree = ast.parse(text) + for node in tree.body: + if isinstance(node, ast.ClassDef) and node.name == "AttributeParser": + for item in node.body: + if isinstance(item, ast.FunctionDef) and not item.name.startswith("_") \ + and item.name not in ("applyAll", "applyOne", "applySingleAttribute", + "applyHorizontalScale", "applyVerticalScale", + "attribDeprecationWarning", "applyAllAttributes"): + attributes.add(item.name) + except SyntaxError: + # fallback for syntax newer than the running Python + block = re.search(r"^class AttributeParser.*?(?=^class |\Z)", text, re.S | re.M) + if block: + attributes.update(re.findall(r"^\tdef ([a-zA-Z]\w*)\(self, value\)", block.group(0), re.M)) + tags = set(re.findall(r"""findall\(["']([A-Za-z-]+)["']\)""", text)) + tags.update(re.findall(r"""tag == ["']([A-Za-z-]+)["']""", text)) + return sorted(attributes, key=str.lower), sorted(tags) + + +VALUE_RE = re.compile(r"^[A-Za-z_][\w.;-]{0,39}$") + + +def enum_strings(node): + """String values a piece of code accepts: keys of all-string dicts, members of + `x in ("a", "b")` tuples, `x == "a"` comparisons and `case "a":` patterns.""" + found = set() + for sub in ast.walk(node): + if isinstance(sub, ast.Dict) and sub.keys: + keys = [k.value for k in sub.keys if isinstance(k, ast.Constant) and isinstance(k.value, str)] + if len(keys) == len(sub.keys): + found.update(keys) + elif isinstance(sub, ast.Compare): + for op, comp in zip(sub.ops, sub.comparators): + if isinstance(op, (ast.In, ast.NotIn)) and isinstance(comp, (ast.Tuple, ast.List, ast.Set)): + found.update(e.value for e in comp.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)) + elif isinstance(op, (ast.Eq, ast.NotEq)) and isinstance(comp, ast.Constant) and isinstance(comp.value, str): + found.add(comp.value) + elif isinstance(sub, ast.MatchValue) and isinstance(sub.value, ast.Constant) \ + and isinstance(sub.value.value, str): + found.add(sub.value.value) + return {v for v in found if VALUE_RE.match(v)} + + +def parse_skin_py_deep(path): + """Accepted values per attribute, coordinate tokens and parser functions of a skin.py.""" + out = {"attributeValues": {}, "aliases": {}, "coordinateTokens": [], "parsers": []} + try: + tree = ast.parse(open(path, encoding="utf-8", errors="replace").read()) + except (OSError, SyntaxError): + return out + funcs = {n.name: n for n in tree.body if isinstance(n, ast.FunctionDef)} + out["parsers"] = sorted(n for n in funcs if n.startswith("parse")) + coord = funcs.get("parseCoordinate") + if coord is not None: + src = ast.unparse(coord) + tokens = [] + for token, probe in (("e", r"""['"]e['"]|\be\b"""), ("center", r"center"), ("c", r"""['"]c['"]"""), + ("w", r"""['"]w['"]"""), ("h", r"""['"]h['"]"""), ("%", r"%"), + ("f", r"""['"]f['"]"""), ("*", r"""['"]\*['"]""")): + if re.search(probe, src): + tokens.append(token) + out["coordinateTokens"] = tokens + for node in tree.body: + if isinstance(node, ast.ClassDef) and node.name == "AttributeParser": + for item in node.body: + if not isinstance(item, ast.FunctionDef) or item.name.startswith("_"): + continue + values = enum_strings(item) + for call in ast.walk(item): + if isinstance(call, ast.Call) and isinstance(call.func, ast.Name) \ + and call.func.id in funcs and call.func.id.startswith("parse") \ + and call.func.id not in ("parseColor", "parseCoordinate", "parsePosition", "parseSize", + "parseValuePair", "parseFont", "parseInteger"): + values |= enum_strings(funcs[call.func.id]) + values.discard(item.name) + if values: + out["attributeValues"][item.name] = sorted(values, key=str.lower) + # legacy alias: a method whose only job is self.otherName(value) + calls = [c for c in ast.walk(item) if isinstance(c, ast.Call) and isinstance(c.func, ast.Attribute) + and isinstance(c.func.value, ast.Name) and c.func.value.id == "self"] + if len(item.body) <= 2 and len(calls) == 1 and calls[0].func.attr != item.name \ + and not calls[0].func.attr.startswith("apply") and not item.name.startswith("apply"): + out.setdefault("aliases", {})[item.name] = calls[0].func.attr + for alias, target in out.get("aliases", {}).items(): + if target in out["attributeValues"] and alias not in out["attributeValues"]: + out["attributeValues"][alias] = out["attributeValues"][target] + out["attributeValues"] = dict(sorted(out["attributeValues"].items(), key=lambda i: i[0].lower())) + return out + + +def parse_colors(root, skin_py_path, screens, parameters): + """How an image handles colours: built-in names, window style slots, overlays, buttons.""" + out = {} + try: + text = open(skin_py_path, encoding="utf-8", errors="replace").read() + tree = ast.parse(text) + except (OSError, SyntaxError): + return out + for node in tree.body: + if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "colors" for t in node.targets) \ + and isinstance(node.value, ast.Dict): + out["builtInNames"] = sorted(k.value for k in node.value.keys if isinstance(k, ast.Constant)) + for sub in ast.walk(tree): + if isinstance(sub, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "colorNameConversions" + for t in sub.targets) and isinstance(sub.value, ast.Dict): + out["windowStyleRenames"] = {k.value: v.value for k, v in zip(sub.value.keys, sub.value.values) + if isinstance(k, ast.Constant) and isinstance(v, ast.Constant)} + header = os.path.join(root, "lib", "gui", "ewindowstyleskinned.h") + if os.path.isfile(header): + slots = set(re.findall(r"\bcol([A-Z]\w+)", open(header, encoding="utf-8", errors="replace").read())) + slots.discard("Max") + out["windowStyleColors"] = sorted(slots) + out["namedGradients"] = bool(re.search(r"gradients\[name\]\s*=", text)) + out["userSkinOverlay"] = "skin_user_%s.xml" if "USER_SKIN_TEMPLATE" in text else None + skinconfig = os.path.join(root, "lib", "python", "Plugins", "SystemPlugins", "SkinConfig", "plugin.py") + if os.path.isfile(skinconfig) and "color_scheme" in open(skinconfig, encoding="utf-8", errors="replace").read(): + out["colorSchemes"] = "SkinConfig: /Layouts/Colors/*.xml (+ Layouts/Screens//*.xml with .png preview)" + out["colorParameters"] = [p for p in parameters if re.search(r"colou?r", p, re.I)] + buttons = defaultdict(int) + for sc in screens: + for key in ("key_red", "key_green", "key_yellow", "key_blue"): + if key in sc["widgets"]: + buttons[sc["widgets"][key]] += 1 + out["colorButtonWidgetTypes"] = dict(sorted(buttons.items(), key=lambda i: -i[1])) + out["screensWithColorButtons"] = sum(1 for sc in screens if any( + k in sc["widgets"] for k in ("key_red", "key_green", "key_yellow", "key_blue"))) + return out + + +def code_expectations(roots): + """Skin parameters and font aliases that Python code reads from the skin.""" + params, fonts = defaultdict(set), defaultdict(set) + p_re = re.compile(r"""parameters(?:\.get\(|\[)\s*["']([A-Za-z0-9_]+)["']""") + f_re = re.compile(r"""fonts(?:\.get\(|\[)\s*["']([A-Za-z0-9_]+)["']""") + for root, label in roots: + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [d for d in dirnames if not d.startswith(".")] + for fn in filenames: + if not fn.endswith(".py"): + continue + full = os.path.join(dirpath, fn) + try: + text = open(full, encoding="utf-8", errors="replace").read() + except OSError: + continue + rel = f"{label}:{os.path.relpath(full, root)}" + # only the skin's own dictionaries: skin.parameters / skin.fonts, or names imported from skin + imported = set() + for m in re.finditer(r"^\s*from\s+skin\s+import\s+\(?([^\n)]*)", text, re.M): + imported.update(x.strip().split(" as ")[0] for x in m.group(1).split(",")) + if os.path.basename(full) == "skin.py": + imported.update(("parameters", "fonts")) + for regex, target, name in ((p_re, params, "parameters"), (f_re, fonts, "fonts")): + for m in regex.finditer(text): + before = text[max(0, m.start() - 5):m.start()] + if before.endswith("skin.") or (name in imported and not before.endswith(".")): + target[m.group(1)].add(rel) + return ({k: sorted(v) for k, v in sorted(params.items(), key=lambda i: i[0].lower())}, + {k: sorted(v) for k, v in sorted(fonts.items(), key=lambda i: i[0].lower())}) + + +def renderer_info(path): + """GUI widget, base class and the extra skin attributes a renderer reads in applySkin.""" + info = {} + try: + tree = ast.parse(open(path, encoding="utf-8", errors="replace").read()) + except (OSError, SyntaxError): + return info + for cls in tree.body: + if not isinstance(cls, ast.ClassDef): + continue + bases = [b for b in (attr_name(x) for x in cls.bases) if b] + attrs = set() + for item in cls.body: + if isinstance(item, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "GUI_WIDGET" for t in item.targets): + info["guiWidget"] = attr_name(item.value) + if isinstance(item, ast.FunctionDef) and item.name == "applySkin": + names = {"attrib"} + for loop in ast.walk(item): + if isinstance(loop, ast.For) and isinstance(loop.target, ast.Tuple) and loop.target.elts \ + and isinstance(loop.target.elts[0], ast.Name): + names.add(loop.target.elts[0].id) + for sub in ast.walk(item): + if isinstance(sub, ast.Compare) and isinstance(sub.left, ast.Name) and sub.left.id in names: + for op, comp in zip(sub.ops, sub.comparators): + if isinstance(op, ast.Eq) and isinstance(comp, ast.Constant) and isinstance(comp.value, str): + attrs.add(comp.value) + elif isinstance(op, ast.In) and isinstance(comp, (ast.Tuple, ast.List, ast.Set)): + attrs.update(e.value for e in comp.elts if isinstance(e, ast.Constant) + and isinstance(e.value, str)) + elif isinstance(sub, ast.Match) and isinstance(sub.subject, ast.Name) and sub.subject.id in names: + for case in sub.cases: + attrs |= {p.value.value for p in ast.walk(case.pattern) + if isinstance(p, ast.MatchValue) and isinstance(p.value, ast.Constant) + and isinstance(p.value.value, str)} + if "guiWidget" in info or attrs or "Renderer" in bases: + info["class"] = cls.name + info["bases"] = bases + if attrs: + info["skinAttributes"] = sorted(attrs, key=str.lower) + break + return info + + +# ---------------------------------------------------------------- components +def parse_components(components_dir): + result = {} + for kind, folder in (("renderers", "Renderer"), ("converters", "Converter"), ("sources", "Sources")): + items = {} + base = os.path.join(components_dir, folder) + if os.path.isdir(base): + for fn in sorted(os.listdir(base)): + if not fn.endswith(".py") or fn.startswith("__"): + continue + name = fn[:-3] + entry = {} + if kind == "renderers": + entry = renderer_info(os.path.join(base, fn)) + if kind == "converters": + args = converter_arguments(os.path.join(base, fn)) + if args: + entry["arguments"] = args + items[name] = entry + if kind == "converters": + # a converter that only wraps another one (EventName -> EventInfo) takes its arguments + for name, entry in items.items(): + if entry.get("arguments"): + continue + try: + text = open(os.path.join(base, name + ".py"), encoding="utf-8", errors="replace").read() + except OSError: + continue + m = re.search(r"^class\s+\w+\(\s*(\w+)", text, re.M) + parent = m.group(1) if m else None + if parent and parent != "Converter" and items.get(parent, {}).get("arguments"): + entry["arguments"] = items[parent]["arguments"] + entry["inheritsFrom"] = parent + result[kind] = items + return result + + +def converter_arguments(path): + """Best effort: string literals compared with the converter's type/argument.""" + try: + text = open(path, encoding="utf-8", errors="replace").read() + except OSError: + return [] + found = set() + # class-level option tables: TIME_OPTIONS = {"Date": ..., "Time": ...} + # and match/case on the argument inside __init__ + try: + tree = ast.parse(text) + for sub in ast.walk(tree): + # "Invert" in args + if isinstance(sub, ast.Compare) and isinstance(sub.left, ast.Constant) and isinstance(sub.left.value, str) \ + and any(isinstance(op, ast.In) for op in sub.ops): + found.add(sub.left.value) + # option tables built inside __init__ + if isinstance(sub, ast.FunctionDef) and sub.name == "__init__": + for d in ast.walk(sub): + if isinstance(d, ast.Dict) and len(d.keys) >= 2 and all( + isinstance(k, ast.Constant) and isinstance(k.value, str) for k in d.keys): + found.update(k.value for k in d.keys) + if isinstance(sub, ast.Match): + found.update(p.value.value for p in ast.walk(sub) + if isinstance(p, ast.MatchValue) and isinstance(p.value, ast.Constant) + and isinstance(p.value.value, str) and 0 < len(p.value.value) <= 40) + for cls in tree.body: + if isinstance(cls, ast.ClassDef): + for item in cls.body: + if isinstance(item, ast.Assign) and isinstance(item.value, ast.Dict): + keys = [k.value for k in item.value.keys + if isinstance(k, ast.Constant) and isinstance(k.value, str)] + if len(keys) >= 2 and len(keys) == len(item.value.keys): + found.update(k for k in keys if k and len(k) <= 40) + except SyntaxError: + pass + # dict style: { "Name": self.NAME, ... } + for m in re.finditer(r"""(?:if|elif)\s+(?:type|args?|arg|self\.type|token|x)\s*==\s*["']([^"']{1,40})["']""", text): + found.add(m.group(1)) + for m in re.finditer(r"""(?:type|arg|args)\s+in\s+\(([^)]*)\)""", text): + found.update(re.findall(r"""["']([^"']{1,40})["']""", m.group(1))) + for m in re.finditer(r"""^\s*["']([A-Za-z][\w ]{0,39})["']\s*:\s*\(?\s*self\.""", text, re.M): + found.add(m.group(1)) + # drop noise: 1-2 character codes and pure numbers (rating tables, indexes) + found = {f for f in found if len(f) >= 3 and not f.isdigit() and VALUE_RE.match(f.replace(" ", "_"))} + return sorted(found, key=str.lower) + + +# ---------------------------------------------------------------- screens +def attr_name(node): + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + if isinstance(node, ast.Call): + return attr_name(node.func) + if isinstance(node, ast.Subscript): + return attr_name(node.value) + return None + + +def literal_strings(node): + """String(s) held by a constant / list / tuple / simple concatenation.""" + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return [node.value] + if isinstance(node, (ast.List, ast.Tuple)): + out = [] + for elt in node.elts: + out.extend(literal_strings(elt)) + return out + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + return literal_strings(node.left) + literal_strings(node.right) + if isinstance(node, ast.JoinedStr): + return ["".join(v.value for v in node.values if isinstance(v, ast.Constant))] + return [] + + +class ClassInfo: + __slots__ = ("name", "bases", "file", "widgets", "skin_names", "embedded_screens", "plugin") + + def __init__(self, name, bases, file, plugin): + self.name, self.bases, self.file, self.plugin = name, bases, file, plugin + self.widgets = {} + self.skin_names = [] + self.embedded_screens = [] + + +def scan_python_file(path, rel, plugin, classes, errors): + try: + source = open(path, encoding="utf-8", errors="replace").read() + tree = ast.parse(source) + except (SyntaxError, ValueError) as exc: + errors.append(f"{rel}: {exc.__class__.__name__}") + return + for node in ast.walk(tree): + if not isinstance(node, ast.ClassDef): + continue + info = ClassInfo(node.name, [b for b in (attr_name(x) for x in node.bases) if b], rel, plugin) + for sub in ast.walk(node): + if isinstance(sub, ast.Assign): + for target in sub.targets: + # class attribute: skin = """""" + if isinstance(target, ast.Name) and target.id == "skin": + for s in literal_strings(sub.value): + info.embedded_screens.extend(SCREEN_TAG_RE.findall(s)) + # self.skin = ... + if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name) \ + and target.value.id == "self": + if target.attr == "skinName": + info.skin_names.extend(s for s in literal_strings(sub.value) if s) + elif target.attr == "skin": + for s in literal_strings(sub.value): + info.embedded_screens.extend(SCREEN_TAG_RE.findall(s)) + # self["name"] = Component(...) + if isinstance(target, ast.Subscript) and isinstance(target.value, ast.Name) \ + and target.value.id == "self": + key = target.slice + if isinstance(key, ast.Constant) and isinstance(key.value, str): + comp = attr_name(sub.value) if isinstance(sub.value, ast.Call) else None + if comp and not ACTIONMAP_RE.search(comp): + info.widgets.setdefault(key.value, comp) + # self.skinName.insert(0, "X") / append + elif isinstance(sub, ast.Call) and isinstance(sub.func, ast.Attribute) \ + and sub.func.attr in ("insert", "append") \ + and isinstance(sub.func.value, ast.Attribute) and sub.func.value.attr == "skinName": + for arg in sub.args: + info.skin_names.extend(s for s in literal_strings(arg) if s) + classes.append(info) + + +def collect_python(roots): + classes, errors = [], [] + for root, label in roots: + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [d for d in dirnames if not d.startswith(".") and d not in ("test", "tests")] + for fn in filenames: + if fn.endswith(".py"): + full = os.path.join(dirpath, fn) + rel = os.path.relpath(full, root) + plugin = None + parts = rel.split(os.sep) + if "Plugins" in parts: + i = parts.index("Plugins") + if len(parts) > i + 2: + plugin = "/".join(parts[i + 1:i + 3]) + if label != "image" and not plugin: + plugin = f"{label}/{parts[0]}" if len(parts) > 1 else label + scan_python_file(full, f"{label}:{rel}", plugin, classes, errors) + return classes, errors + + +def resolve_screens(classes): + by_name = defaultdict(list) + for c in classes: + by_name[c.name].append(c) + + memo = {} + + def is_screen(name, seen=()): + if name == "Screen": + return True + if name in memo: + return memo[name] + if name in seen or name not in by_name: + return False + result = any(is_screen(b, seen + (name,)) for c in by_name[name] for b in c.bases) + memo[name] = result + return result + + def inherited_widgets(c, seen=()): + widgets = {} + for b in c.bases: + if b in seen: + continue + for parent in by_name.get(b, []): + widgets.update(inherited_widgets(parent, seen + (c.name,))) + widgets.update(c.widgets) + return widgets + + screens = [] + for c in classes: + if c.name == "Screen" or not any(is_screen(b) for b in c.bases): + continue + names = list(dict.fromkeys(c.skin_names + [c.name])) + screens.append({ + "class": c.name, + "file": c.file, + "plugin": c.plugin, + "skinNames": names, + "embeddedSkin": sorted(set(c.embedded_screens)), + "widgets": dict(sorted(inherited_widgets(c).items())), + }) + screens.sort(key=lambda s: (s["plugin"] or "", s["class"].lower())) + return screens + + +# ---------------------------------------------------------------- default XML skins +def scan_data_xml(data_dir): + main, display = defaultdict(list), defaultdict(list) + if not os.path.isdir(data_dir): + return {}, {} + for dirpath, _, filenames in os.walk(data_dir): + for fn in filenames: + if not fn.endswith(".xml"): + continue + full = os.path.join(dirpath, fn) + rel = os.path.relpath(full, data_dir) + try: + text = open(full, encoding="utf-8", errors="replace").read() + except OSError: + continue + target = display if ("display" in rel.lower() or "vfd" in rel.lower() + or fn.startswith(("skin_text", "skin_display", "skin_lcd"))) else main + for name in SCREEN_TAG_RE.findall(text): + target[name].append(rel) + return ({k: sorted(set(v)) for k, v in sorted(main.items())}, + {k: sorted(set(v)) for k, v in sorted(display.items())}) + + +# ---------------------------------------------------------------- main +def git_info(path): + try: + out = subprocess.run(["git", "-C", path, "log", "-1", "--format=%H %ad", "--date=short"], + capture_output=True, text=True, timeout=20).stdout.split() + branch = subprocess.run(["git", "-C", path, "rev-parse", "--abbrev-ref", "HEAD"], + capture_output=True, text=True, timeout=20).stdout.strip() + return {"commit": out[0], "date": out[1], "branch": branch} + except Exception: + return {} + + +def build(root, name, plugin_dirs): + py = os.path.join(root, "lib", "python") + attributes, tags = parse_skin_py(os.path.join(py, "skin.py")) + components = parse_components(os.path.join(py, "Components")) + roots = [(py, "image")] + [(d, os.path.basename(os.path.normpath(d))) for d in plugin_dirs] + classes, errors = collect_python(roots) + screens = resolve_screens(classes) + main_xml, display_xml = scan_data_xml(os.path.join(root, "data")) + deep = parse_skin_py_deep(os.path.join(py, "skin.py")) + parameters, fonts = code_expectations(roots) + + covered = set(main_xml) + for s in screens: + covered.update(s["embeddedSkin"]) + for s in screens: + s["hasDefaultSkin"] = any(n in covered for n in s["skinNames"]) + + colours = parse_colors(root, os.path.join(py, "skin.py"), screens, parameters) + + return { + "image": name, + "generated": datetime.date.today().isoformat(), + "source": git_info(root), + "extraPluginRepos": [os.path.basename(os.path.normpath(d)) for d in plugin_dirs], + "skinEngine": {"attributes": attributes, "xmlTags": tags, + "attributeValues": deep["attributeValues"], + "legacyAliases": deep["aliases"], + "coordinateTokens": deep["coordinateTokens"], + "parsers": deep["parsers"]}, + "skinExpectedByCode": {"parameters": parameters, "fonts": fonts}, + "colors": colours, + "components": components, + "screens": screens, + "defaultSkin": {"main": main_xml, "display": display_xml}, + "parseErrors": errors, + } + + +def to_markdown(cat): + s = cat["screens"] + core = [x for x in s if not x["plugin"]] + plug = [x for x in s if x["plugin"]] + lines = [ + f"# Skin catalog - {cat['image']}", + "", + f"Source: branch `{cat['source'].get('branch', '?')}`, commit of {cat['source'].get('date', '?')}", + "", + "| Item | Count |", "|---|---|", + f"| skin.py attributes | {len(cat['skinEngine']['attributes'])} |", + f"| XML tags read by skin.py | {len(cat['skinEngine']['xmlTags'])} |", + f"| Renderer | {len(cat['components']['renderers'])} |", + f"| Converter | {len(cat['components']['converters'])} |", + f"| Sources | {len(cat['components']['sources'])} |", + f"| Screens (core) | {len(core)} |", + f"| Screens (plugins) | {len(plug)} |", + f"| Screens with a default skin | {sum(1 for x in s if x['hasDefaultSkin'])} |", + f"| Screens in data/ XML files (TV) | {len(cat['defaultSkin']['main'])} |", + f"| Screens in data/ XML files (display/LCD) | {len(cat['defaultSkin']['display'])} |", + "", + "## skin.py attributes", "", ", ".join(f"`{a}`" for a in cat["skinEngine"]["attributes"]), "", + "## Accepted values per attribute", "", + "| Attribute | Values |", "|---|---|", + *[f"| `{a}` | {', '.join(v)} |" for a, v in cat["skinEngine"]["attributeValues"].items()], + "", + "Legacy aliases (old name -> current name): " + ", ".join(f"`{a}` -> `{b}`" for a, b in cat["skinEngine"]["legacyAliases"].items()), "", + "Accepted coordinate tokens: " + " ".join(f"`{t}`" for t in cat["skinEngine"]["coordinateTokens"]), "", + f"## Skin parameters read by the code ({len(cat['skinExpectedByCode']['parameters'])})", "", + "| Parameter | Used in |", "|---|---|", + *[f"| `{k}` | {', '.join(v[:3])}{' ...' if len(v) > 3 else ''} |" for k, v in cat["skinExpectedByCode"]["parameters"].items()], + "", + f"## Font aliases read by the code ({len(cat['skinExpectedByCode']['fonts'])})", "", + ", ".join(f"`{k}`" for k in cat["skinExpectedByCode"]["fonts"]), "", + "## Colors", "", + f"- Built-in names: {', '.join(cat['colors'].get('builtInNames', []))}", + f"- Window style colors: {', '.join(cat['colors'].get('windowStyleColors', []))}", + f"- Converted window style names: {cat['colors'].get('windowStyleRenames', {})}", + f"- Named gradients in : {'yes' if cat['colors'].get('namedGradients') else 'no'}", + f"- User overlay: {cat['colors'].get('userSkinOverlay')}", + f"- Native color schemes: {cat['colors'].get('colorSchemes', 'no')}", + f"- Color parameters: {', '.join(cat['colors'].get('colorParameters', []))}", + f"- Screens with color buttons: {cat['colors'].get('screensWithColorButtons')}, widget types: {cat['colors'].get('colorButtonWidgetTypes')}", + "", + "## Renderer", "", + "| Renderer | GUI widget | Own attributes |", "|---|---|---|", + *[f"| {k} | {v.get('guiWidget', '')} | {', '.join(v.get('skinAttributes', []))} |" for k, v in cat["components"]["renderers"].items()], + "", + "## Converter", "", + "| Converter | Recognized arguments |", "|---|---|", + *[f"| {k} | {', '.join(v.get('arguments', []))} |" for k, v in cat["components"]["converters"].items()], + "", + "## Screens", "", + "| Class | Skin names looked up | Widgets | Plugin |", "|---|---|---|---|", + ] + for x in s: + w = ", ".join(f"{k} ({v})" for k, v in x["widgets"].items()) + lines.append(f"| {x['class']} | {', '.join(x['skinNames'])} | {w} | {x['plugin'] or ''} |") + return "\n".join(lines) + "\n" + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("root", help="root of the enigma2 repository") + ap.add_argument("--name", required=True, help="image name, e.g. openatv") + ap.add_argument("--plugins", nargs="*", default=[], help="extra plugin repositories to scan") + ap.add_argument("-o", "--output", help="JSON output (default: .json)") + ap.add_argument("--md", help="optional Markdown summary") + a = ap.parse_args() + cat = build(a.root, a.name, a.plugins) + out = a.output or f"{a.name}.json" + with open(out, "w", encoding="utf-8") as f: + json.dump(cat, f, indent=1, ensure_ascii=False) + if a.md: + with open(a.md, "w", encoding="utf-8") as f: + f.write(to_markdown(cat)) + print(f"{a.name}: {len(cat['skinEngine']['attributes'])} attributes, " + f"{len(cat['components']['renderers'])} renderers, {len(cat['components']['converters'])} converters, " + f"{len(cat['screens'])} screens, {len(cat['parseErrors'])} parse errors -> {out}", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/catalogs/e2compare.py b/catalogs/e2compare.py new file mode 100644 index 0000000..8bfe854 --- /dev/null +++ b/catalogs/e2compare.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""e2compare - compare the catalogs produced by e2catalog.py. + +Usage: e2compare.py out/openatv.json out/openpli.json ... [--md compare.md] [--json compare.json] + +Answers the question "if I start a skin on image X, what breaks on image Y?": +attributes, renderers, converters and screen names that exist in one image and +not in another, plus what is common to all of them (the safe subset). +""" + +import argparse +import json + + +def load(path): + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def sets(cat): + screens = set() + for s in cat["screens"]: + if not s["plugin"]: + screens.update(s["skinNames"]) + return { + "attributes": set(cat["skinEngine"]["attributes"]), + "xmlTags": set(cat["skinEngine"]["xmlTags"]), + "renderers": set(cat["components"]["renderers"]), + "converters": set(cat["components"]["converters"]), + "sources": set(cat["components"]["sources"]), + "screenNames": screens, + } + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("catalogs", nargs="+") + ap.add_argument("--md") + ap.add_argument("--json") + a = ap.parse_args() + + cats = [load(p) for p in a.catalogs] + names = [c["image"] for c in cats] + data = {c["image"]: sets(c) for c in cats} + keys = ["attributes", "xmlTags", "renderers", "converters", "sources", "screenNames"] + + result = {"images": names, "common": {}, "onlyIn": {}, "matrix": {}} + for k in keys: + common = set.intersection(*(data[n][k] for n in names)) + result["common"][k] = sorted(common, key=str.lower) + result["onlyIn"][k] = {} + for n in names: + others = set.union(*(data[m][k] for m in names if m != n)) if len(names) > 1 else set() + result["onlyIn"][k][n] = sorted(data[n][k] - others, key=str.lower) + # union matrix: item -> list of images that have it + union = set.union(*(data[n][k] for n in names)) + result["matrix"][k] = {i: [n for n in names if i in data[n][k]] for i in sorted(union, key=str.lower)} + + if a.json: + with open(a.json, "w", encoding="utf-8") as f: + json.dump(result, f, indent=1, ensure_ascii=False) + + labels = {"attributes": "skin.py attributes", "xmlTags": "XML tags", "renderers": "Renderer", + "converters": "Converter", "sources": "Sources", "screenNames": "Screen names (core)"} + lines = ["# Image comparison", "", + "| Item | " + " | ".join(names) + " | Common to all |", + "|---|" + "---|" * (len(names) + 1)] + for k in keys: + lines.append(f"| {labels[k]} | " + " | ".join(str(len(data[n][k])) for n in names) + + f" | {len(result['common'][k])} |") + lines.append("") + for k in ("attributes", "xmlTags", "renderers", "converters"): + lines.append(f"## {labels[k]}: only in one image") + lines.append("") + for n in names: + only = result["onlyIn"][k][n] + lines.append(f"- **{n}** ({len(only)}): " + (", ".join(f"`{x}`" for x in only) if only else "-")) + lines.append("") + lines.append(f"Common to all ({len(result['common'][k])}): " + ", ".join(f"`{x}`" for x in result["common"][k])) + lines.append("") + # deeper differences: same name, different accepted values + def per_image(getter): + table = {} + for c in cats: + for key, vals in getter(c).items(): + table.setdefault(key, {})[c["image"]] = set(vals) + return {k: v for k, v in table.items() if len(v) > 1 and len({frozenset(x) for x in v.values()}) > 1} + + sections = ( + ("Attributes with different values between images", lambda c: c["skinEngine"].get("attributeValues", {})), + ("Converters with different arguments between images", + lambda c: {k: v.get("arguments", []) for k, v in c["components"]["converters"].items() if v.get("arguments")}), + ("Renderers with different own attributes between images", + lambda c: {k: v.get("skinAttributes", []) for k, v in c["components"]["renderers"].items() if v.get("skinAttributes")}), + ) + result["differentValues"] = {} + for title, getter in sections: + diff = per_image(getter) + result["differentValues"][title] = {k: {n: sorted(v, key=str.lower) for n, v in imgs.items()} for k, imgs in diff.items()} + lines.append(f"## {title} ({len(diff)})") + lines.append("") + for key, imgs in sorted(diff.items(), key=lambda i: i[0].lower()): + common = set.intersection(*imgs.values()) + extra = "; ".join(f"{n}: +" + ", ".join(sorted(v - common, key=str.lower)) + for n, v in imgs.items() if v - common) + lines.append(f"- `{key}` (in common: {len(common)}) {extra}") + lines.append("") + + params = {c["image"]: set(c.get("skinExpectedByCode", {}).get("parameters", {})) for c in cats} + if all(params.values()): + common = set.intersection(*params.values()) + lines.append(f"## Skin parameters read by the code") + lines.append("") + lines.append("| Image | Parameters | Only in this one |") + lines.append("|---|---|---|") + for n in names: + others = set.union(*(params[m] for m in names if m != n)) if len(names) > 1 else set() + only = sorted(params[n] - others, key=str.lower) + lines.append(f"| {n} | {len(params[n])} | {', '.join(only) if only else '-'} |") + lines.append("") + lines.append(f"Common to all ({len(common)}): " + ", ".join(f"`{x}`" for x in sorted(common, key=str.lower))) + lines.append("") + result["parameters"] = {"common": sorted(common), "perImage": {n: sorted(v) for n, v in params.items()}} + + if a.json: + with open(a.json, "w", encoding="utf-8") as f: + json.dump(result, f, indent=1, ensure_ascii=False) + + text = "\n".join(lines) + "\n" + if a.md: + with open(a.md, "w", encoding="utf-8") as f: + f.write(text) + else: + print(text) + + +if __name__ == "__main__": + main() diff --git a/catalogs/images.json b/catalogs/images.json new file mode 100644 index 0000000..4cafdf7 --- /dev/null +++ b/catalogs/images.json @@ -0,0 +1,12 @@ +{ + "_info": "Images used to build the catalogs. Set enabled=false to skip an entry. plugins = plugin repositories scanned together with the image; an empty branch means the default branch.", + "images": [ + {"id": "openatv", "name": "openATV", "enabled": true, "repo": "https://github.com/openatv/enigma2.git", "branch": "master", + "plugins": [{"name": "oe-alliance-plugins", "repo": "https://github.com/oe-alliance/oe-alliance-plugins.git", "branch": ""}]}, + {"id": "openpli", "name": "OpenPLi", "enabled": true, "repo": "https://github.com/OpenPLi/enigma2.git", "branch": "scarthgap", + "plugins": [{"name": "enigma2-plugins", "repo": "https://github.com/OpenPLi/enigma2-plugins.git", "branch": ""}]}, + {"id": "openvix", "name": "OpenViX", "enabled": true, "repo": "https://github.com/OpenViX/enigma2.git", "branch": "Developer", "plugins": []}, + {"id": "openbh", "name": "OpenBH", "enabled": true, "repo": "https://github.com/BlackHole/enigma2.git", "branch": "Python3.14", "plugins": []}, + {"id": "teamblue", "name": "teamBlue", "enabled": true, "repo": "https://github.com/teamblue-e2/enigma2.git", "branch": "8.0", "plugins": []} + ] +}