common.py 5.2 KB

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