common.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """This script handles the XAP protocol data files.
  2. """
  3. import os
  4. import hjson
  5. import jsonschema
  6. from pathlib import Path
  7. from typing import OrderedDict
  8. from jinja2 import Environment, FileSystemLoader, select_autoescape
  9. from qmk.casing import to_snake
  10. from qmk.constants import QMK_FIRMWARE
  11. from qmk.json_schema import validate
  12. from qmk.decorators import lru_cache
  13. from qmk.keymap import locate_keymap
  14. from qmk.path import keyboard
  15. XAP_SPEC = 'xap.hjson'
  16. def _get_jinja2_env(data_templates_xap_subdir: str):
  17. templates_dir = os.path.join(QMK_FIRMWARE, 'data', 'templates', 'xap', data_templates_xap_subdir)
  18. j2 = Environment(loader=FileSystemLoader(templates_dir), autoescape=select_autoescape())
  19. return j2
  20. def render_xap_output(data_templates_xap_subdir, file_to_render, defs):
  21. j2 = _get_jinja2_env(data_templates_xap_subdir)
  22. return j2.get_template(file_to_render).render(xap=defs, xap_str=hjson.dumps(defs), to_snake=to_snake)
  23. def _find_kb_spec(kb):
  24. base_path = Path('keyboards')
  25. keyboard_parent = keyboard(kb)
  26. for _ in range(5):
  27. if keyboard_parent == base_path:
  28. break
  29. spec = keyboard_parent / XAP_SPEC
  30. if spec.exists():
  31. return spec
  32. keyboard_parent = keyboard_parent.parent
  33. # Just return something we know doesn't exist
  34. return keyboard(kb) / XAP_SPEC
  35. def _find_km_spec(kb, km):
  36. return locate_keymap(kb, km).parent / XAP_SPEC
  37. def _merge_ordered_dicts(dicts):
  38. """Merges nested OrderedDict objects resulting from reading a hjson file.
  39. Later input dicts overrides earlier dicts for plain values.
  40. Arrays will be appended. If the first entry of an array is "!reset!", the contents of the array will be cleared and replaced with RHS.
  41. Dictionaries will be recursively merged. If any entry is "!reset!", the contents of the dictionary will be cleared and replaced with RHS.
  42. """
  43. result = OrderedDict()
  44. def add_entry(target, k, v):
  45. if k in target and isinstance(v, (OrderedDict, dict)):
  46. if "!reset!" in v:
  47. target[k] = v
  48. else:
  49. target[k] = _merge_ordered_dicts([target[k], v])
  50. if "!reset!" in target[k]:
  51. del target[k]["!reset!"]
  52. elif k in target and isinstance(v, list):
  53. if v[0] == '!reset!':
  54. target[k] = v[1:]
  55. else:
  56. target[k] = target[k] + v
  57. else:
  58. target[k] = v
  59. for d in dicts:
  60. for (k, v) in d.items():
  61. add_entry(result, k, v)
  62. return result
  63. def get_xap_definition_files():
  64. """Get the sorted list of XAP definition files, from <QMK>/data/xap.
  65. """
  66. xap_defs = QMK_FIRMWARE / "data" / "xap"
  67. return list(sorted(xap_defs.glob('**/xap_*.hjson')))
  68. def update_xap_definitions(original, new):
  69. """Creates a new XAP definition object based on an original and the new supplied object.
  70. Both inputs must be of type OrderedDict.
  71. Later input dicts overrides earlier dicts for plain values.
  72. Arrays will be appended. If the first entry of an array is "!reset!", the contents of the array will be cleared and replaced with RHS.
  73. Dictionaries will be recursively merged. If any entry is "!reset!", the contents of the dictionary will be cleared and replaced with RHS.
  74. """
  75. if original is None:
  76. original = OrderedDict()
  77. return _merge_ordered_dicts([original, new])
  78. @lru_cache(timeout=5)
  79. def get_xap_defs(version):
  80. """Gets the required version of the XAP definitions.
  81. """
  82. files = get_xap_definition_files()
  83. # Slice off anything newer than specified version
  84. if version != 'latest':
  85. index = [idx for idx, s in enumerate(files) if version in str(s)][0]
  86. files = files[:(index + 1)]
  87. definitions = [hjson.load(file.open(encoding='utf-8')) for file in files]
  88. return _merge_ordered_dicts(definitions)
  89. def latest_xap_defs():
  90. """Gets the latest version of the XAP definitions.
  91. """
  92. return get_xap_defs('latest')
  93. def merge_xap_defs(kb, km):
  94. """Gets the latest version of the XAP definitions and merges in optional keyboard/keymap specs
  95. """
  96. definitions = [get_xap_defs('latest')]
  97. kb_xap = _find_kb_spec(kb)
  98. if kb_xap.exists():
  99. definitions.append({'routes': {'0x02': hjson.load(kb_xap.open(encoding='utf-8'))}})
  100. km_xap = _find_km_spec(kb, km)
  101. if km_xap.exists():
  102. definitions.append({'routes': {'0x03': hjson.load(km_xap.open(encoding='utf-8'))}})
  103. defs = _merge_ordered_dicts(definitions)
  104. try:
  105. validate(defs, 'qmk.xap.v1')
  106. except jsonschema.ValidationError as e:
  107. print(f'Invalid XAP spec: {e.message}')
  108. exit(1)
  109. return defs
  110. def route_conditions(route_stack):
  111. """Handles building the C preprocessor conditional based on the current route.
  112. """
  113. conditions = []
  114. for route in route_stack:
  115. if 'enable_if_preprocessor' in route:
  116. conditions.append(route['enable_if_preprocessor'])
  117. if len(conditions) == 0:
  118. return None
  119. return "(" + ' && '.join([f'({c})' for c in conditions]) + ")"