Debian Codegraph @

scripts/update-keysyms-definitions.py

raw
1 #!/usr/bin/env python3
2
3 """
4 Convert X11 keysyms headers into our keysyms header.
5 """
6
7 from __future__ import print_function
8 import re
9 import os
10 from pathlib import Path
11
12 XORG_KEY_PREFIX = "XK_"
13 KEY_PREFIX = "XKB_KEY_"
14 EVDEV_MACRO = "_EVDEVK"
15 EXTRA_SPACES = " " * (len(KEY_PREFIX) - len(XORG_KEY_PREFIX))
16
17 # Expected format:
18 # #define XF86XK_FooBar 0x1234 /* some optional comment */
19 # or:
20 # #define XF86XK_FooBar _EVDEVK(0x123) /* some optional comment */
21 # We also need to match commented evdev entries:
22 # /* Use: XF86XK_FooBar _EVDEVK(0x123) some optional comment */
23 # /* TODO: … _EVDEVK(0x123) some optional comment */
24 keysym_entry_pattern = re.compile(
25 rf"""^
26 (?:(?P<define>\#define)\s+|(?P<use>/\*\s+Use:)\s+|(?P<todo>/\*\s+TODO:))
27 (?(todo)
28 (?P<todo_comment>(?:\s+(?!{EVDEV_MACRO}|0x)\S+)+) |
29 (?:(?P<prefix>\w*){XORG_KEY_PREFIX}|(?=NoSymbol))(?P<name>\w+)
30 )
31 (?P<spacing>\s+)
32 (?P<evdev>{EVDEV_MACRO}\()?(?P<value>0x[0-9A-Fa-f]+)(?(evdev)\))
33 """,
34 re.VERBOSE,
35 )
36
37 # Match keysym guarded by #ifndef
38 keysym_ifndef_pattern = re.compile(
39 rf"^#ifndef\s+(?P<prefix>\w*){XORG_KEY_PREFIX}(?P<name>\w+)\s*$"
40 )
41
42 # Match remaining XK_ references in the comments, e.g we will replace:
43 # XF86XK_CamelCaseKernelName _EVDEVK(kernel value)
44 # #define XKB_KEY_SunCompose 0x0000FF20 /* Same as XK_Multi_key */
45 # with:
46 # XKB_KEY_XF86CamelCaseKernelName _EVDEVK(kernel value)
47 # #define XKB_KEY_SunCompose 0x0000FF20 /* Same as XKB_KEY_Multi_key */
48 xorgproto_keysym_prefix_pattern = re.compile(
49 rf"\b(?P<prefix>\w*){XORG_KEY_PREFIX}(?!KOREAN\b)"
50 )
51
52 alias_pattern = re.compile(
53 rf"(?P<alias>(?:(?:D|d)eprecated )?(?:a|A)lias for ){KEY_PREFIX}(?P<comment>[^\*]+)"
54 )
55
56
57 def make_keysym_name(m: re.Match[str]) -> str:
58 return m.group("prefix") + m.group("name")
59
60
61 def make_keysym_entry(m: re.Match[str]) -> str:
62 """
63 Perform the substitutions
64 """
65 if m.group("evdev"):
66 if m.group("define"):
67 # Replace the xorgproto _EVDEVK macro with the actual value:
68 # 0x10081000 is the base, the evdev hex code is added to that.
69 # We replace to make parsing of the keys later easier.
70 value = 0x10081000 + int(m.group("value"), 16)
71 value_str = f"{value:#x} "
72 else:
73 value_str = f"""{EVDEV_MACRO}({m.group("value")})"""
74 else:
75 value_str = m.group("value")
76 spacing = m.group("spacing")
77 if todo := m.group("todo"):
78 todo_comment = m.group("todo_comment")
79 todo_commentʹ = xorgproto_keysym_prefix_pattern.sub(
80 rf"{KEY_PREFIX}\1", todo_comment
81 )
82 if todo_commentʹ != todo_comment:
83 diff = len(todo_commentʹ) - len(todo_comment)
84 if diff != len(EXTRA_SPACES):
85 raise ValueError()
86 todo_comment = todo_commentʹ
87 else:
88 spacing += EXTRA_SPACES
89 return f"""{todo}{todo_comment}{spacing}{value_str}"""
90 else:
91 prefix = m.group("prefix") or ""
92 name = m.group("name")
93 define = m.group("define") or m.group("use")
94 if m.group("use") and name == "NoSymbol":
95 spacing += EXTRA_SPACES
96 key_prefix = ""
97 else:
98 key_prefix = KEY_PREFIX
99 return f"""{define} {key_prefix}{prefix}{name}{spacing}{value_str}"""
100
101
102 def fix_alias(m: re.Match[str]) -> str:
103 alias = m.group("alias")
104 comment = m.group("comment")
105 if len(comment) - len(comment.rstrip()) > 1:
106 spaces = " " * len(XORG_KEY_PREFIX)
107 else:
108 spaces = ""
109 return f"{alias}{comment}{spaces}"
110
111
112 prefix = Path(os.environ.get("X11_HEADERS_PREFIX", "/usr"))
113 HEADERS = (
114 prefix / "include/X11/keysymdef.h",
115 prefix / "include/X11/XF86keysym.h",
116 prefix / "include/X11/Sunkeysym.h",
117 prefix / "include/X11/DECkeysym.h",
118 prefix / "include/X11/HPkeysym.h",
119 )
120
121 print(
122 f"""#ifndef _XKBCOMMON_KEYSYMS_H
123 #define _XKBCOMMON_KEYSYMS_H
124
125 /* This file is autogenerated; please do not commit directly. */
126
127 /**
128 * @file
129 * Key symbols (keysyms) definitions.
130 */
131
132 #define {KEY_PREFIX}NoSymbol 0x000000 /* Special KeySym */
133 """
134 )
135
136 keysyms: set[str] = set()
137 for path in HEADERS:
138 pending_guarded_keysym: str | None = None
139 with path.open("rt", encoding="utf-8") as header:
140 for line in header:
141 # Duplicate keysym name guard
142 if m := keysym_ifndef_pattern.match(line):
143 if pending_guarded_keysym:
144 raise ValueError(f"Nested #ifndef {pending_guarded_keysym}")
145 pending_guarded_keysym = make_keysym_name(m)
146 continue
147
148 # Ignore C macro #ifdef/#ifndef
149 elif line.startswith("#ifdef") or line.startswith("#ifndef"):
150 if pending_guarded_keysym:
151 raise ValueError(f"Nested C macro {pending_guarded_keysym}")
152 continue
153
154 # Ignore C macro #endif and check end of keysym name guard
155 elif line.startswith("#endif"):
156 if pending_guarded_keysym:
157 pending_guarded_keysym = None
158 continue
159
160 # Ignore C macro #undef
161 elif line.startswith("#undef"):
162 continue
163
164 # Remove #define _OSF_Keysyms and such.
165 elif line.startswith("#define _"):
166 continue
167
168 # Keysym entry: proceed various tests
169 if line.startswith("#") and (m := keysym_entry_pattern.match(line)):
170 name = make_keysym_name(m)
171 # Check expected guarded keysym, if relevant
172 if pending_guarded_keysym and name != pending_guarded_keysym:
173 raise ValueError(f"{path}: Malformed keysym name guard: {line}")
174 # Check if name already defined
175 elif name in keysyms:
176 if pending_guarded_keysym:
177 # Ignore guarded keysym
178 continue
179 else:
180 raise ValueError(f"{path}: Unguarded redefinition: {line}")
181 else:
182 keysyms.add(name)
183
184 # Perform _EVDEV and XK_ substitutions
185 line = keysym_entry_pattern.sub(make_keysym_entry, line)
186 line = xorgproto_keysym_prefix_pattern.sub(rf"{KEY_PREFIX}\1", line)
187 line = alias_pattern.sub(fix_alias, line)
188
189 print(line.rstrip(), end="\n")
190 print()
191 print("#endif")