apc_parsers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #!/usr/bin/env python
  2. # License: GPLv3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
  3. import os
  4. import subprocess
  5. import sys
  6. from collections import defaultdict
  7. from typing import Any, DefaultDict, Union
  8. if __name__ == '__main__' and not __package__:
  9. import __main__
  10. __main__.__package__ = 'gen'
  11. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  12. KeymapType = dict[str, tuple[str, Union[frozenset[str], str]]]
  13. def resolve_keys(keymap: KeymapType) -> DefaultDict[str, list[str]]:
  14. ans: DefaultDict[str, list[str]] = defaultdict(list)
  15. for ch, (attr, atype) in keymap.items():
  16. if isinstance(atype, str) and atype in ('int', 'uint'):
  17. q = atype
  18. else:
  19. q = 'flag'
  20. ans[q].append(ch)
  21. return ans
  22. def enum(keymap: KeymapType) -> str:
  23. lines = []
  24. for ch, (attr, atype) in keymap.items():
  25. lines.append(f"{attr}='{ch}'")
  26. return '''
  27. enum KEYS {{
  28. {}
  29. }};
  30. '''.format(',\n'.join(lines))
  31. def parse_key(keymap: KeymapType) -> str:
  32. lines = []
  33. for attr, atype in keymap.values():
  34. vs = atype.upper() if isinstance(atype, str) and atype in ('uint', 'int') else 'FLAG'
  35. lines.append(f'case {attr}: value_state = {vs}; break;')
  36. return ' \n'.join(lines)
  37. def parse_flag(keymap: KeymapType, type_map: dict[str, Any], command_class: str) -> str:
  38. lines = []
  39. for ch in type_map['flag']:
  40. attr, allowed_values = keymap[ch]
  41. q = ' && '.join(f"g.{attr} != '{x}'" for x in sorted(allowed_values))
  42. lines.append(f'''
  43. case {attr}: {{
  44. g.{attr} = parser_buf[pos++];
  45. if ({q}) {{
  46. REPORT_ERROR("Malformed {command_class} control block, unknown flag value for {attr}: 0x%x", g.{attr});
  47. return;
  48. }};
  49. }}
  50. break;
  51. ''')
  52. return ' \n'.join(lines)
  53. def parse_number(keymap: KeymapType) -> tuple[str, str]:
  54. int_keys = [f'I({attr})' for attr, atype in keymap.values() if atype == 'int']
  55. uint_keys = [f'U({attr})' for attr, atype in keymap.values() if atype == 'uint']
  56. return '; '.join(int_keys), '; '.join(uint_keys)
  57. def cmd_for_report(report_name: str, keymap: KeymapType, type_map: dict[str, Any], payload_allowed: bool) -> str:
  58. def group(atype: str, conv: str) -> tuple[str, str]:
  59. flag_fmt, flag_attrs = [], []
  60. cv = {'flag': 'c', 'int': 'i', 'uint': 'I'}[atype]
  61. for ch in type_map[atype]:
  62. flag_fmt.append(f's{cv}')
  63. attr = keymap[ch][0]
  64. flag_attrs.append(f'"{attr}", {conv}g.{attr}')
  65. return ' '.join(flag_fmt), ', '.join(flag_attrs)
  66. flag_fmt, flag_attrs = group('flag', '')
  67. int_fmt, int_attrs = group('int', '(int)')
  68. uint_fmt, uint_attrs = group('uint', '(unsigned int)')
  69. fmt = f'{flag_fmt} {uint_fmt} {int_fmt}'
  70. if payload_allowed:
  71. ans = [f'REPORT_VA_COMMAND("K s {{{fmt} sI}} y#", self->window_id, "{report_name}", ']
  72. else:
  73. ans = [f'REPORT_VA_COMMAND("K s {{{fmt}}}", self->window_id, "{report_name}", ']
  74. ans.append(',\n '.join((flag_attrs, uint_attrs, int_attrs)))
  75. if payload_allowed:
  76. ans.append(', "payload_sz", g.payload_sz, parser_buf, g.payload_sz')
  77. ans.append(');')
  78. return '\n'.join(ans)
  79. def generate(
  80. function_name: str,
  81. callback_name: str,
  82. report_name: str,
  83. keymap: KeymapType,
  84. command_class: str,
  85. initial_key: str = 'a',
  86. payload_allowed: bool = True
  87. ) -> str:
  88. type_map = resolve_keys(keymap)
  89. keys_enum = enum(keymap)
  90. handle_key = parse_key(keymap)
  91. flag_keys = parse_flag(keymap, type_map, command_class)
  92. int_keys, uint_keys = parse_number(keymap)
  93. report_cmd = cmd_for_report(report_name, keymap, type_map, payload_allowed)
  94. if payload_allowed:
  95. payload_after_value = "case ';': state = PAYLOAD; break;"
  96. payload = ', PAYLOAD'
  97. payload_case = f'''
  98. case PAYLOAD: {{
  99. sz = parser_buf_pos - pos;
  100. g.payload_sz = MAX(BUF_EXTRA, sz);
  101. if (!base64_decode8(parser_buf + pos, sz, parser_buf, &g.payload_sz)) {{
  102. g.payload_sz = MAX(BUF_EXTRA, sz);
  103. REPORT_ERROR("Failed to parse {command_class} command payload with error: \
  104. invalid base64 data in chunk of size: %zu with output buffer size: %zu", sz, g.payload_sz); return; }}
  105. pos = parser_buf_pos;
  106. }}
  107. break;
  108. '''
  109. callback = f'{callback_name}(self->screen, &g, parser_buf)'
  110. else:
  111. payload_after_value = payload = payload_case = ''
  112. callback = f'{callback_name}(self->screen, &g)'
  113. return f'''
  114. #include "base64.h"
  115. static inline void
  116. {function_name}(PS *self, uint8_t *parser_buf, const size_t parser_buf_pos) {{
  117. unsigned int pos = 1;
  118. enum PARSER_STATES {{ KEY, EQUAL, UINT, INT, FLAG, AFTER_VALUE {payload} }};
  119. enum PARSER_STATES state = KEY, value_state = FLAG;
  120. static {command_class} g;
  121. unsigned int i, code;
  122. uint64_t lcode; int64_t accumulator;
  123. bool is_negative;
  124. memset(&g, 0, sizeof(g));
  125. size_t sz;
  126. {keys_enum}
  127. enum KEYS key = '{initial_key}';
  128. if (parser_buf[pos] == ';') state = AFTER_VALUE;
  129. while (pos < parser_buf_pos) {{
  130. switch(state) {{
  131. case KEY:
  132. key = parser_buf[pos++];
  133. state = EQUAL;
  134. switch(key) {{
  135. {handle_key}
  136. default:
  137. REPORT_ERROR("Malformed {command_class} control block, invalid key character: 0x%x", key);
  138. return;
  139. }}
  140. break;
  141. case EQUAL:
  142. if (parser_buf[pos++] != '=') {{
  143. REPORT_ERROR("Malformed {command_class} control block, no = after key, found: 0x%x instead", parser_buf[pos-1]);
  144. return;
  145. }}
  146. state = value_state;
  147. break;
  148. case FLAG:
  149. switch(key) {{
  150. {flag_keys}
  151. default:
  152. break;
  153. }}
  154. state = AFTER_VALUE;
  155. break;
  156. case INT:
  157. #define READ_UINT \\
  158. for (i = pos, accumulator=0; i < MIN(parser_buf_pos, pos + 10); i++) {{ \\
  159. int64_t n = parser_buf[i] - '0'; if (n < 0 || n > 9) break; \\
  160. accumulator += n * digit_multipliers[i - pos]; \\
  161. }} \\
  162. if (i == pos) {{ REPORT_ERROR("Malformed {command_class} control block, expecting an integer value for key: %c", key & 0xFF); return; }} \\
  163. lcode = accumulator / digit_multipliers[i - pos - 1]; pos = i; \\
  164. if (lcode > UINT32_MAX) {{ REPORT_ERROR("Malformed {command_class} control block, number is too large"); return; }} \\
  165. code = lcode;
  166. is_negative = false;
  167. if(parser_buf[pos] == '-') {{ is_negative = true; pos++; }}
  168. #define I(x) case x: g.x = is_negative ? 0 - (int32_t)code : (int32_t)code; break
  169. READ_UINT;
  170. switch(key) {{
  171. {int_keys};
  172. default: break;
  173. }}
  174. state = AFTER_VALUE;
  175. break;
  176. #undef I
  177. case UINT:
  178. READ_UINT;
  179. #define U(x) case x: g.x = code; break
  180. switch(key) {{
  181. {uint_keys};
  182. default: break;
  183. }}
  184. state = AFTER_VALUE;
  185. break;
  186. #undef U
  187. #undef READ_UINT
  188. case AFTER_VALUE:
  189. switch (parser_buf[pos++]) {{
  190. default:
  191. REPORT_ERROR("Malformed {command_class} control block, expecting a comma or semi-colon after a value, found: 0x%x",
  192. parser_buf[pos - 1]);
  193. return;
  194. case ',':
  195. state = KEY;
  196. break;
  197. {payload_after_value}
  198. }}
  199. break;
  200. {payload_case}
  201. }} // end switch
  202. }} // end while
  203. switch(state) {{
  204. case EQUAL:
  205. REPORT_ERROR("Malformed {command_class} control block, no = after key"); return;
  206. case INT:
  207. case UINT:
  208. REPORT_ERROR("Malformed {command_class} control block, expecting an integer value"); return;
  209. case FLAG:
  210. REPORT_ERROR("Malformed {command_class} control block, expecting a flag value"); return;
  211. default:
  212. break;
  213. }}
  214. {report_cmd}
  215. {callback};
  216. }}
  217. '''
  218. def write_header(text: str, path: str) -> None:
  219. with open(path, 'w') as f:
  220. print(f'// This file is generated by {os.path.basename(__file__)} do not edit!', file=f, end='\n\n')
  221. print('#pragma once', file=f)
  222. print(text, file=f)
  223. subprocess.check_call(['clang-format', '-i', path])
  224. def graphics_parser() -> None:
  225. flag = frozenset
  226. keymap: KeymapType = {
  227. 'a': ('action', flag('tTqpdfac')),
  228. 'd': ('delete_action', flag('aAiIcCfFnNpPqQrRxXyYzZ')),
  229. 't': ('transmission_type', flag('dfts')),
  230. 'o': ('compressed', flag('z')),
  231. 'f': ('format', 'uint'),
  232. 'm': ('more', 'uint'),
  233. 'i': ('id', 'uint'),
  234. 'I': ('image_number', 'uint'),
  235. 'p': ('placement_id', 'uint'),
  236. 'q': ('quiet', 'uint'),
  237. 'w': ('width', 'uint'),
  238. 'h': ('height', 'uint'),
  239. 'x': ('x_offset', 'uint'),
  240. 'y': ('y_offset', 'uint'),
  241. 'v': ('data_height', 'uint'),
  242. 's': ('data_width', 'uint'),
  243. 'S': ('data_sz', 'uint'),
  244. 'O': ('data_offset', 'uint'),
  245. 'c': ('num_cells', 'uint'),
  246. 'r': ('num_lines', 'uint'),
  247. 'X': ('cell_x_offset', 'uint'),
  248. 'Y': ('cell_y_offset', 'uint'),
  249. 'z': ('z_index', 'int'),
  250. 'C': ('cursor_movement', 'uint'),
  251. 'U': ('unicode_placement', 'uint'),
  252. 'P': ('parent_id', 'uint'),
  253. 'Q': ('parent_placement_id', 'uint'),
  254. 'H': ('offset_from_parent_x', 'int'),
  255. 'V': ('offset_from_parent_y', 'int'),
  256. }
  257. text = generate('parse_graphics_code', 'screen_handle_graphics_command', 'graphics_command', keymap, 'GraphicsCommand')
  258. write_header(text, 'kitty/parse-graphics-command.h')
  259. def main(args: list[str]=sys.argv) -> None:
  260. graphics_parser()
  261. if __name__ == '__main__':
  262. import runpy
  263. m = runpy.run_path(os.path.dirname(os.path.abspath(__file__)))
  264. m['main']([sys.executable, 'apc-parsers'])