1
0

update-keysyms-definitions.py 6.4 KB

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