common.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """This script handles the XAP protocol data files.
  2. """
  3. import hjson
  4. import jsonschema
  5. from pathlib import Path
  6. from typing import OrderedDict
  7. from jinja2 import Environment, FileSystemLoader, select_autoescape
  8. import qmk.constants
  9. from qmk.git import git_get_version
  10. from qmk.lighting import load_lighting_spec
  11. from qmk.json_schema import validate, merge_ordered_dicts
  12. from qmk.makefile import parse_rules_mk_file
  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. USERSPACE_DIR = Path('users')
  18. XAP_SPEC = 'xap.hjson'
  19. def _get_jinja2_env(data_templates_xap_subdir: str):
  20. templates_dir = qmk.constants.QMK_FIRMWARE / 'data/templates/xap' / data_templates_xap_subdir
  21. j2 = Environment(loader=FileSystemLoader(templates_dir), autoescape=select_autoescape(), lstrip_blocks=True, trim_blocks=True)
  22. return j2
  23. def render_xap_output(data_templates_xap_subdir, file_to_render, defs=None, **kwargs):
  24. if defs is None:
  25. defs = latest_xap_defs()
  26. j2 = _get_jinja2_env(data_templates_xap_subdir)
  27. attach_filters(j2)
  28. specs = {}
  29. for feature in ['rgblight', 'rgb_matrix', 'led_matrix']:
  30. specs[feature] = load_lighting_spec(feature)
  31. return j2.get_template(file_to_render).render(xap=defs, qmk_version=git_get_version(), xap_str=hjson.dumps(defs), specs=specs, constants=qmk.constants, **kwargs)
  32. def _find_kb_spec(kb):
  33. base_path = Path('keyboards')
  34. keyboard_parent = keyboard(kb)
  35. for _ in range(5):
  36. if keyboard_parent == base_path:
  37. break
  38. spec = keyboard_parent / XAP_SPEC
  39. if spec.exists():
  40. return spec
  41. keyboard_parent = keyboard_parent.parent
  42. # Just return something we know doesn't exist
  43. return keyboard(kb) / XAP_SPEC
  44. def _find_km_spec(kb, km):
  45. keymap_dir = locate_keymap(kb, km).parent
  46. if not keymap_dir.exists():
  47. return None
  48. # Resolve any potential USER_NAME overrides - default back to keymap name
  49. keymap_rules_mk = parse_rules_mk_file(keymap_dir / 'rules.mk')
  50. username = keymap_rules_mk.get('USER_NAME', km)
  51. keymap_spec = keymap_dir / XAP_SPEC
  52. userspace_spec = USERSPACE_DIR / username / XAP_SPEC
  53. # In the case of both userspace and keymap - keymap wins
  54. return keymap_spec if keymap_spec.exists() else userspace_spec
  55. def get_xap_definition_files():
  56. """Get the sorted list of XAP definition files, from <QMK>/data/xap.
  57. """
  58. xap_defs = qmk.constants.QMK_FIRMWARE / "data" / "xap"
  59. return list(sorted(xap_defs.glob('**/xap_*.hjson')))
  60. def update_xap_definitions(original, new):
  61. """Creates a new XAP definition object based on an original and the new supplied object.
  62. Both inputs must be of type OrderedDict.
  63. Later input dicts overrides earlier dicts for plain values.
  64. 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.
  65. Dictionaries will be recursively merged. If any entry is "!reset!", the contents of the dictionary will be cleared and replaced with RHS.
  66. """
  67. if original is None:
  68. original = OrderedDict()
  69. return merge_ordered_dicts([original, new])
  70. @lru_cache(timeout=5)
  71. def get_xap_defs(version):
  72. """Gets the required version of the XAP definitions.
  73. """
  74. files = get_xap_definition_files()
  75. # Slice off anything newer than specified version
  76. if version != 'latest':
  77. index = [idx for idx, s in enumerate(files) if version in str(s)][0]
  78. files = files[:(index + 1)]
  79. definitions = [hjson.load(file.open(encoding='utf-8')) for file in files]
  80. return merge_ordered_dicts(definitions)
  81. def latest_xap_defs():
  82. """Gets the latest version of the XAP definitions.
  83. """
  84. return get_xap_defs('latest')
  85. def merge_xap_defs(kb, km):
  86. """Gets the latest version of the XAP definitions and merges in optional keyboard/keymap specs
  87. """
  88. definitions = [get_xap_defs('latest')]
  89. kb_xap = _find_kb_spec(kb)
  90. if kb_xap.exists():
  91. definitions.append({'routes': {'0x02': hjson.load(kb_xap.open(encoding='utf-8'))}})
  92. km_xap = _find_km_spec(kb, km)
  93. if km_xap.exists():
  94. definitions.append({'routes': {'0x03': hjson.load(km_xap.open(encoding='utf-8'))}})
  95. defs = merge_ordered_dicts(definitions)
  96. try:
  97. validate(defs, 'qmk.xap.v1')
  98. except jsonschema.ValidationError as e:
  99. print(f'Invalid XAP spec: {e.message}')
  100. exit(1)
  101. return defs