Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

5.1 KB
Raw Blame
#!/usr/bin/env python3
"""Regenerates the Android agent logos from the desktop app's one-color SVGs.

Each `apps/desktop/src/renderer/assets/agents/<registry>.svg` made only of paths becomes
`app/src/main/res/drawable/agent_<registry>.xml` (tinted at runtime, as the iOS template images
are); logos with other shapes fall back to the terminal glyph. Also writes `AgentIcons.kt`, the
`agentIconRes("claude-acp")` lookup.

Run from apps/android: python3 tools/agent_icons.py (self-check: python3 tools/agent_icons_test.py)
"""
import pathlib
import re
import xml.etree.ElementTree as ET

ROOT = pathlib.Path(__file__).resolve().parent.parent
SOURCE = ROOT.parent / "desktop/src/renderer/assets/agents"
DRAWABLES = ROOT / "app/src/main/res/drawable"
KOTLIN = ROOT / "app/src/main/kotlin/com/codync/android/AgentIcons.kt"
SVG = "{http://www.w3.org/2000/svg}"
IGNORED = {"title", "desc"}


def resource(registry: str) -> str:
    return "agent_" + re.sub(r"[^a-z0-9]", "_", registry.lower())


NUMBER = re.compile(r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?")


def compact(d: str, size: float) -> str:
    """Rounds path numbers to what a 24dp icon can show (lint flags long paths).

    Reads the path argument by argument: in `1.5.5` the second `.5` is its own number, and in an
    arc (`a.3.3 0 01.4-.2`) the two flags are single digits that may touch the next number.
    """
    places = max(1, 4 - len(str(int(size))))
    out = []
    for command, args in re.findall(r"([MmZzLlHhVvCcSsQqTtAa])([^MmZzLlHhVvCcSsQqTtAa]*)", d):
        values, i = [], 0
        while i < len(args):
            if args[i] in " ,\t\r\n":
                i += 1
            elif command in "aA" and len(values) % 7 in (3, 4):
                values.append(args[i])
                i += 1
            else:
                number = NUMBER.match(args, i)
                if number is None:
                    raise ValueError(f"unreadable path at {command}{args[i:]}")
                values.append(f"{float(number.group()):.{places}f}".rstrip("0").rstrip("."))
                i = number.end()
        out.append(command + "".join(v if n == 0 or v.startswith("-") else " " + v for n, v in enumerate(values)))
    return "".join(out)


def convert(svg: pathlib.Path) -> str | None:
    root = ET.parse(svg).getroot()
    shapes = [e for e in root.iter() if e is not root and e.tag.removeprefix(SVG) not in IGNORED]
    if not shapes or any(e.tag.removeprefix(SVG) != "path" or "transform" in e.attrib for e in shapes):
        return None
    x, y, w, h = (float(v) for v in root.attrib["viewBox"].replace(",", " ").split())
    body = []
    for path in shapes:
        fill = path.get("fill", root.get("fill", "black"))
        stroke = path.get("stroke", root.get("stroke", "none"))
        attrs = [f'android:pathData="{compact(path.attrib["d"], max(w, h))}"']
        if fill != "none":
            attrs.append('android:fillColor="#FF000000"')
            if path.get("fill-rule", root.get("fill-rule")) == "evenodd":
                attrs.append('android:fillType="evenOdd"')
            if "fill-opacity" in path.attrib:
                attrs.append(f'android:fillAlpha="{path.attrib["fill-opacity"]}"')
        if stroke != "none":
            attrs.append('android:strokeColor="#FF000000"')
            attrs.append(f'android:strokeWidth="{path.get("stroke-width", root.get("stroke-width", "1"))}"')
            for svg_name, android in (("stroke-linecap", "strokeLineCap"), ("stroke-linejoin", "strokeLineJoin")):
                value = path.get(svg_name, root.get(svg_name))
                if value:
                    attrs.append(f'android:{android}="{value}"')
        body.append("        <path " + " ".join(attrs) + "/>\n")
    group = f'    <group android:translateX="{0.0 - x:g}" android:translateY="{0.0 - y:g}">\n'
    return (
        '<?xml version="1.0" encoding="utf-8"?>\n'
        f"<!-- {svg.name} from the desktop app's agent logos. Generated by tools/agent_icons.py. -->\n"
        '<vector xmlns:android="http://schemas.android.com/apk/res/android"\n'
        f'    android:width="24dp" android:height="24dp" android:viewportWidth="{w:g}" android:viewportHeight="{h:g}">\n'
        f"{group}{''.join(body)}    </group>\n"
        "</vector>\n"
    )


def main() -> None:
    for old in DRAWABLES.glob("agent_*.xml"):
        old.unlink()
    made = []
    for svg in sorted(SOURCE.glob("*.svg")):
        xml = convert(svg)
        if xml is None:
            continue
        (DRAWABLES / f"{resource(svg.stem)}.xml").write_text(xml)
        made.append(svg.stem)
    cases = "\n".join(f'    "{r}" -> R.drawable.{resource(r)}' for r in made)
    KOTLIN.write_text(
        "// Generated by tools/agent_icons.py: the agent logos converted from the desktop app's SVGs.\n"
        "package com.codync.android\n\n"
        "import androidx.annotation.DrawableRes\n\n"
        "/** The logo for an agent's ACP registry id (or Codync's id for agents outside it), or null. */\n"
        "@DrawableRes internal fun agentIconRes(registry: String?): Int? = when (registry) {\n"
        f"{cases}\n"
        "    else -> null\n"
        "}\n"
    )
    print(f"{len(made)} of {len(list(SOURCE.glob('*.svg')))} logos")


if __name__ == "__main__":
    main()