logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

json_encoders.py (7832B)


  1. """Class that pretty-prints QMK info.json files.
  2. """
  3. import json
  4. from decimal import Decimal
  5. newline = '\n'
  6. class QMKJSONEncoder(json.JSONEncoder):
  7. """Base class for all QMK JSON encoders.
  8. """
  9. container_types = (list, tuple, dict)
  10. indentation_char = " "
  11. def __init__(self, *args, **kwargs):
  12. super().__init__(*args, **kwargs)
  13. self.indentation_level = 0
  14. if not self.indent:
  15. self.indent = 4
  16. def encode_decimal(self, obj):
  17. """Encode a decimal object.
  18. """
  19. if obj == int(obj): # I can't believe Decimal objects don't have .is_integer()
  20. return int(obj)
  21. return float(obj)
  22. def encode_dict(self, obj, path):
  23. """Encode a dict-like object.
  24. """
  25. if obj:
  26. self.indentation_level += 1
  27. items = sorted(obj.items(), key=self.sort_dict) if self.sort_keys else obj.items()
  28. output = [self.indent_str + f"{json.dumps(key)}: {self.encode(value, path + [key])}" for key, value in items]
  29. self.indentation_level -= 1
  30. return "{\n" + ",\n".join(output) + "\n" + self.indent_str + "}"
  31. else:
  32. return "{}"
  33. def encode_dict_single_line(self, obj, path):
  34. """Encode a dict-like object onto a single line.
  35. """
  36. return "{" + ", ".join(f"{json.dumps(key)}: {self.encode(value, path + [key])}" for key, value in sorted(obj.items(), key=self.sort_layout)) + "}"
  37. def encode_list(self, obj, path):
  38. """Encode a list-like object.
  39. """
  40. if self.primitives_only(obj):
  41. return "[" + ", ".join(self.encode(value, path + [index]) for index, value in enumerate(obj)) + "]"
  42. else:
  43. self.indentation_level += 1
  44. if path[-1] in ('layout', 'rotary'):
  45. # These are part of a LED layout or encoder config, put them on a single line
  46. output = [self.indent_str + self.encode_dict_single_line(value, path + [index]) for index, value in enumerate(obj)]
  47. else:
  48. output = [self.indent_str + self.encode(value, path + [index]) for index, value in enumerate(obj)]
  49. self.indentation_level -= 1
  50. return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
  51. def encode(self, obj, path=[]):
  52. """Encode JSON objects for QMK.
  53. """
  54. if isinstance(obj, Decimal):
  55. return self.encode_decimal(obj)
  56. elif isinstance(obj, (list, tuple)):
  57. return self.encode_list(obj, path)
  58. elif isinstance(obj, dict):
  59. return self.encode_dict(obj, path)
  60. else:
  61. return super().encode(obj)
  62. def primitives_only(self, obj):
  63. """Returns true if the object doesn't have any container type objects (list, tuple, dict).
  64. """
  65. if isinstance(obj, dict):
  66. obj = obj.values()
  67. return not any(isinstance(element, self.container_types) for element in obj)
  68. @property
  69. def indent_str(self):
  70. return self.indentation_char * (self.indentation_level * self.indent)
  71. class InfoJSONEncoder(QMKJSONEncoder):
  72. """Custom encoder to make info.json's a little nicer to work with.
  73. """
  74. def sort_layout(self, item):
  75. """Sorts the hashes in a nice way.
  76. """
  77. key = item[0]
  78. if key == 'label':
  79. return '00label'
  80. elif key == 'matrix':
  81. return '01matrix'
  82. elif key == 'x':
  83. return '02x'
  84. elif key == 'y':
  85. return '03y'
  86. elif key == 'w':
  87. return '04w'
  88. elif key == 'h':
  89. return '05h'
  90. elif key == 'flags':
  91. return '06flags'
  92. return key
  93. def sort_dict(self, item):
  94. """Forces layout to the back of the sort order.
  95. """
  96. key = item[0]
  97. if self.indentation_level == 1:
  98. if key == 'manufacturer':
  99. return '10manufacturer'
  100. elif key == 'keyboard_name':
  101. return '11keyboard_name'
  102. elif key == 'maintainer':
  103. return '12maintainer'
  104. elif key == 'community_layouts':
  105. return '97community_layouts'
  106. elif key == 'layout_aliases':
  107. return '98layout_aliases'
  108. elif key == 'layouts':
  109. return '99layouts'
  110. else:
  111. return '50' + str(key)
  112. return key
  113. class KeymapJSONEncoder(QMKJSONEncoder):
  114. """Custom encoder to make keymap.json's a little nicer to work with.
  115. """
  116. def encode_list(self, obj, path):
  117. """Encode a list-like object.
  118. """
  119. if self.indentation_level == 2:
  120. indent_level = self.indentation_level + 1
  121. # We have a list of keycodes
  122. layer = [[]]
  123. for key in obj:
  124. if key == 'JSON_NEWLINE':
  125. layer.append([])
  126. else:
  127. if isinstance(key, dict):
  128. # We have a macro
  129. # TODO: Add proper support for nicely formatting keymap.json macros
  130. layer[-1].append(f'{self.encode(key)}')
  131. else:
  132. layer[-1].append(f'"{key}"')
  133. layer = [f"{self.indent_str*indent_level}{', '.join(row)}" for row in layer]
  134. return f"{self.indent_str}[\n{newline.join(layer)}\n{self.indent_str*self.indentation_level}]"
  135. elif self.primitives_only(obj):
  136. return "[" + ", ".join(self.encode(element) for element in obj) + "]"
  137. else:
  138. self.indentation_level += 1
  139. output = [self.indent_str + self.encode(element) for element in obj]
  140. self.indentation_level -= 1
  141. return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
  142. def sort_dict(self, item):
  143. """Sorts the hashes in a nice way.
  144. """
  145. key = item[0]
  146. if self.indentation_level == 1:
  147. if key == 'version':
  148. return '00version'
  149. elif key == 'author':
  150. return '01author'
  151. elif key == 'notes':
  152. return '02notes'
  153. elif key == 'layers':
  154. return '98layers'
  155. elif key == 'documentation':
  156. return '99documentation'
  157. else:
  158. return '50' + str(key)
  159. return key
  160. class UserspaceJSONEncoder(QMKJSONEncoder):
  161. """Custom encoder to make userspace qmk.json's a little nicer to work with.
  162. """
  163. def sort_dict(self, item):
  164. """Sorts the hashes in a nice way.
  165. """
  166. key = item[0]
  167. if self.indentation_level == 1:
  168. if key == 'userspace_version':
  169. return '00userspace_version'
  170. if key == 'build_targets':
  171. return '01build_targets'
  172. return key
  173. class CommunityModuleJSONEncoder(QMKJSONEncoder):
  174. """Custom encoder to make qmk_module.json's a little nicer to work with.
  175. """
  176. def sort_dict(self, item):
  177. """Sorts the hashes in a nice way.
  178. """
  179. key = item[0]
  180. if self.indentation_level == 1:
  181. if key == 'module_name':
  182. return '00module_name'
  183. if key == 'maintainer':
  184. return '01maintainer'
  185. if key == 'license':
  186. return '02license'
  187. if key == 'url':
  188. return '03url'
  189. if key == 'features':
  190. return '04features'
  191. if key == 'keycodes':
  192. return '05keycodes'
  193. elif self.indentation_level == 3: # keycodes
  194. if key == 'key':
  195. return '00key'
  196. if key == 'aliases':
  197. return '01aliases'
  198. return key