summaryrefslogtreecommitdiff
path: root/tools/razer-quirks-lister.py
blob: 6069ade798e31cc7ccc993c983ca3239d26fd16e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
#
# SPDX-License-Identifier: MIT
#
# This utility clones the openrazer repository, extracts the known VID/PID combos
# for "RazerBlade" keyboards and spits out a libinput-compatible quirks file
# with those keyboards listed as "Internal".
#
# Usage:
# $ cd path/to/libinput.git/
# $ ./tools/razer-quirks-list.py

from pathlib import Path
from collections import namedtuple
import tempfile
import shutil
import subprocess
import sys


KeyboardDescriptor = namedtuple("KeyboardDescriptor", ["vid", "pid", "name"])

with tempfile.TemporaryDirectory() as tmpdir:
    # Clone the openrazer directory and add its Python modyle basedir
    # to our sys.path so we can import it
    subprocess.run(
        [
            "git",
            "clone",
            "--quiet",
            "--depth=1",
            "https://github.com/openrazer/openrazer",
        ],
        cwd=tmpdir,
        check=True,
    )
    sys.path.append(str(Path(tmpdir) / "openrazer" / "daemon"))

    import openrazer_daemon.hardware.keyboards as razer_keyboards  # type: ignore

    keyboards: list[KeyboardDescriptor] = []

    # All classnames for the keyboards we care about start with RazerBlade
    for clsname in filter(lambda c: c.startswith("RazerBlade"), dir(razer_keyboards)):
        kbd = getattr(razer_keyboards, clsname)
        try:
            k = KeyboardDescriptor(name=clsname, vid=kbd.USB_VID, pid=kbd.USB_PID)
            keyboards.append(k)
        except AttributeError:
            continue

    tmpfile = Path(tmpdir) / "30-vendor-razer.quirks"
    try:
        quirksfile = next(Path("quirks").glob("30-vendor-razer.quirks"))
    except StopIteration:
        print("Unable to find the razer quirks file.")
        raise SystemExit(1)

    with open(tmpfile, "w") as output:
        with open(quirksfile) as input:
            for line in input:
                output.write(line)
                if line.startswith("# AUTOGENERATED"):
                    output.write("\n")
                    break

        for kbd in sorted(keyboards, key=lambda k: k.vid << 16 | k.pid):
            print(
                "\n".join(
                    (
                        f"[{kbd.name} Keyboard]",
                        "MatchUdevType=keyboard",
                        "MatchBus=usb",
                        f"MatchVendor=0x{kbd.vid:04X}",
                        f"MatchProduct=0x{kbd.pid:04X}",
                        "AttrKeyboardIntegration=internal",
                    )
                ),
                file=output,
            )
            print(file=output)

    shutil.copy(tmpfile, quirksfile)