common.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. """This script handles the XAP protocol data files.
  2. """
  3. import re
  4. import os
  5. import hjson
  6. import jsonschema
  7. from pathlib import Path
  8. from typing import OrderedDict
  9. from jinja2 import Environment, FileSystemLoader, select_autoescape
  10. from qmk.constants import QMK_FIRMWARE, GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE
  11. from qmk.git import git_get_version
  12. from qmk.json_schema import json_load, validate
  13. from qmk.decorators import lru_cache
  14. from qmk.keymap import locate_keymap
  15. from qmk.path import keyboard
  16. from qmk.xap.jinja2_filters import attach_filters
  17. XAP_SPEC = 'xap.hjson'
  18. def list_lighting_versions(feature):
  19. """Return available versions - sorted newest first
  20. """
  21. ret = []
  22. for file in Path('data/constants/').glob(f'{feature}_[0-9].[0-9].[0-9].json'):
  23. ret.append(file.stem.split('_')[-1])
  24. ret.sort(reverse=True)
  25. return ret
  26. def load_lighting_spec(feature, version='latest'):
  27. """Build lighting data from the requested spec file
  28. """
  29. if version == 'latest':
  30. version = list_lighting_versions(feature)[0]
  31. spec = json_load(Path(f'data/constants/{feature}_{version}.json'))
  32. # preprocess for gross rgblight "mode + n"
  33. for obj in spec.get('effects', {}).values():
  34. define = obj['key']
  35. offset = 0
  36. found = re.match('(.*)_(\\d+)$', define)
  37. if found:
  38. define = found.group(1)
  39. offset = int(found.group(2)) - 1
  40. obj['define'] = define
  41. obj['offset'] = offset
  42. return spec
  43. def _get_jinja2_env(data_templates_xap_subdir: str):
  44. templates_dir = os.path.join(QMK_FIRMWARE, 'data', 'templates', 'xap', data_templates_xap_subdir)
  45. j2 = Environment(loader=FileSystemLoader(templates_dir), autoescape=select_autoescape())
  46. return j2
  47. def render_xap_output(data_templates_xap_subdir, file_to_render, defs=None, **kwargs):
  48. if defs is None:
  49. defs = latest_xap_defs()
  50. j2 = _get_jinja2_env(data_templates_xap_subdir)
  51. attach_filters(j2)
  52. constants = {}
  53. for feature in ['rgblight', 'rgb_matrix', 'led_matrix']:
  54. constants[feature] = load_lighting_spec(feature)
  55. return j2.get_template(file_to_render).render(xap=defs, qmk_version=git_get_version(), xap_str=hjson.dumps(defs), constants=constants, GPL2_HEADER_C_LIKE=GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE=GENERATED_HEADER_C_LIKE, **kwargs)
  56. def _find_kb_spec(kb):
  57. base_path = Path('keyboards')
  58. keyboard_parent = keyboard(kb)
  59. for _ in range(5):
  60. if keyboard_parent == base_path:
  61. break
  62. spec = keyboard_parent / XAP_SPEC
  63. if spec.exists():
  64. return spec
  65. keyboard_parent = keyboard_parent.parent
  66. # Just return something we know doesn't exist
  67. return keyboard(kb) / XAP_SPEC
  68. def _find_km_spec(kb, km):
  69. return locate_keymap(kb, km).parent / XAP_SPEC
  70. def _merge_ordered_dicts(dicts):
  71. """Merges nested OrderedDict objects resulting from reading a hjson file.
  72. Later input dicts overrides earlier dicts for plain values.
  73. 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.
  74. Dictionaries will be recursively merged. If any entry is "!reset!", the contents of the dictionary will be cleared and replaced with RHS.
  75. """
  76. result = OrderedDict()
  77. def add_entry(target, k, v):
  78. if k in target and isinstance(v, (OrderedDict, dict)):
  79. if "!reset!" in v:
  80. target[k] = v
  81. else:
  82. target[k] = _merge_ordered_dicts([target[k], v])
  83. if "!reset!" in target[k]:
  84. del target[k]["!reset!"]
  85. elif k in target and isinstance(v, list):
  86. if v[0] == '!reset!':
  87. target[k] = v[1:]
  88. else:
  89. target[k] = target[k] + v
  90. else:
  91. target[k] = v
  92. for d in dicts:
  93. for (k, v) in d.items():
  94. add_entry(result, k, v)
  95. return result
  96. def get_xap_definition_files():
  97. """Get the sorted list of XAP definition files, from <QMK>/data/xap.
  98. """
  99. xap_defs = QMK_FIRMWARE / "data" / "xap"
  100. return list(sorted(xap_defs.glob('**/xap_*.hjson')))
  101. def update_xap_definitions(original, new):
  102. """Creates a new XAP definition object based on an original and the new supplied object.
  103. Both inputs must be of type OrderedDict.
  104. Later input dicts overrides earlier dicts for plain values.
  105. 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.
  106. Dictionaries will be recursively merged. If any entry is "!reset!", the contents of the dictionary will be cleared and replaced with RHS.
  107. """
  108. if original is None:
  109. original = OrderedDict()
  110. return _merge_ordered_dicts([original, new])
  111. @lru_cache(timeout=5)
  112. def get_xap_defs(version):
  113. """Gets the required version of the XAP definitions.
  114. """
  115. files = get_xap_definition_files()
  116. # Slice off anything newer than specified version
  117. if version != 'latest':
  118. index = [idx for idx, s in enumerate(files) if version in str(s)][0]
  119. files = files[:(index + 1)]
  120. definitions = [hjson.load(file.open(encoding='utf-8')) for file in files]
  121. return _merge_ordered_dicts(definitions)
  122. def latest_xap_defs():
  123. """Gets the latest version of the XAP definitions.
  124. """
  125. return get_xap_defs('latest')
  126. def merge_xap_defs(kb, km):
  127. """Gets the latest version of the XAP definitions and merges in optional keyboard/keymap specs
  128. """
  129. definitions = [get_xap_defs('latest')]
  130. kb_xap = _find_kb_spec(kb)
  131. if kb_xap.exists():
  132. definitions.append({'routes': {'0x02': hjson.load(kb_xap.open(encoding='utf-8'))}})
  133. km_xap = _find_km_spec(kb, km)
  134. if km_xap.exists():
  135. definitions.append({'routes': {'0x03': hjson.load(km_xap.open(encoding='utf-8'))}})
  136. defs = _merge_ordered_dicts(definitions)
  137. try:
  138. validate(defs, 'qmk.xap.v1')
  139. except jsonschema.ValidationError as e:
  140. print(f'Invalid XAP spec: {e.message}')
  141. exit(1)
  142. return defs
  143. def route_conditions(route_stack):
  144. """Handles building the C preprocessor conditional based on the current route.
  145. """
  146. conditions = []
  147. for route in route_stack:
  148. if 'enable_if_preprocessor' in route:
  149. conditions.append(route['enable_if_preprocessor'])
  150. if len(conditions) == 0:
  151. return None
  152. return "(" + ' && '.join([f'({c})' for c in conditions]) + ")"