You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

195 lines
5.8 KiB

  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_list(self, obj):
  23. """Encode a list-like object.
  24. """
  25. if self.primitives_only(obj):
  26. return "[" + ", ".join(self.encode(element) for element in obj) + "]"
  27. else:
  28. self.indentation_level += 1
  29. output = [self.indent_str + self.encode(element) for element in obj]
  30. self.indentation_level -= 1
  31. return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
  32. def encode(self, obj):
  33. """Encode keymap.json objects for QMK.
  34. """
  35. if isinstance(obj, Decimal):
  36. return self.encode_decimal(obj)
  37. elif isinstance(obj, (list, tuple)):
  38. return self.encode_list(obj)
  39. elif isinstance(obj, dict):
  40. return self.encode_dict(obj)
  41. else:
  42. return super().encode(obj)
  43. def primitives_only(self, obj):
  44. """Returns true if the object doesn't have any container type objects (list, tuple, dict).
  45. """
  46. if isinstance(obj, dict):
  47. obj = obj.values()
  48. return not any(isinstance(element, self.container_types) for element in obj)
  49. @property
  50. def indent_str(self):
  51. return self.indentation_char * (self.indentation_level * self.indent)
  52. class InfoJSONEncoder(QMKJSONEncoder):
  53. """Custom encoder to make info.json's a little nicer to work with.
  54. """
  55. def encode_dict(self, obj):
  56. """Encode info.json dictionaries.
  57. """
  58. if obj:
  59. if set(("x", "y")).issubset(obj.keys()):
  60. # These are part of a layout/led_config, put them on a single line.
  61. return "{ " + ", ".join(f"{self.encode(key)}: {self.encode(element)}" for key, element in sorted(obj.items())) + " }"
  62. else:
  63. self.indentation_level += 1
  64. output = [self.indent_str + f"{json.dumps(key)}: {self.encode(value)}" for key, value in sorted(obj.items(), key=self.sort_dict)]
  65. self.indentation_level -= 1
  66. return "{\n" + ",\n".join(output) + "\n" + self.indent_str + "}"
  67. else:
  68. return "{}"
  69. def sort_dict(self, key):
  70. """Forces layout to the back of the sort order.
  71. """
  72. key = key[0]
  73. if self.indentation_level == 1:
  74. if key == 'manufacturer':
  75. return '10keyboard_name'
  76. elif key == 'keyboard_name':
  77. return '11keyboard_name'
  78. elif key == 'maintainer':
  79. return '12maintainer'
  80. elif key == 'community_layouts':
  81. return '97community_layouts'
  82. elif key == 'layout_aliases':
  83. return '98layout_aliases'
  84. elif key == 'layouts':
  85. return '99layouts'
  86. else:
  87. return '50' + str(key)
  88. return key
  89. class KeymapJSONEncoder(QMKJSONEncoder):
  90. """Custom encoder to make keymap.json's a little nicer to work with.
  91. """
  92. def encode_dict(self, obj):
  93. """Encode dictionary objects for keymap.json.
  94. """
  95. if obj:
  96. self.indentation_level += 1
  97. output_lines = [f"{self.indent_str}{json.dumps(key)}: {self.encode(value)}" for key, value in sorted(obj.items(), key=self.sort_dict)]
  98. output = ',\n'.join(output_lines)
  99. self.indentation_level -= 1
  100. return f"{{\n{output}\n{self.indent_str}}}"
  101. else:
  102. return "{}"
  103. def encode_list(self, obj):
  104. """Encode a list-like object.
  105. """
  106. if self.indentation_level == 2:
  107. indent_level = self.indentation_level + 1
  108. # We have a list of keycodes
  109. layer = [[]]
  110. for key in obj:
  111. if key == 'JSON_NEWLINE':
  112. layer.append([])
  113. else:
  114. if isinstance(key, dict):
  115. # We have a macro
  116. # TODO: Add proper support for nicely formatting keymap.json macros
  117. layer[-1].append(f'{self.encode(key)}')
  118. else:
  119. layer[-1].append(f'"{key}"')
  120. layer = [f"{self.indent_str*indent_level}{', '.join(row)}" for row in layer]
  121. return f"{self.indent_str}[\n{newline.join(layer)}\n{self.indent_str*self.indentation_level}]"
  122. elif self.primitives_only(obj):
  123. return "[" + ", ".join(self.encode(element) for element in obj) + "]"
  124. else:
  125. self.indentation_level += 1
  126. output = [self.indent_str + self.encode(element) for element in obj]
  127. self.indentation_level -= 1
  128. return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
  129. def sort_dict(self, key):
  130. """Sorts the hashes in a nice way.
  131. """
  132. key = key[0]
  133. if self.indentation_level == 1:
  134. if key == 'version':
  135. return '00version'
  136. elif key == 'author':
  137. return '01author'
  138. elif key == 'notes':
  139. return '02notes'
  140. elif key == 'layers':
  141. return '98layers'
  142. elif key == 'documentation':
  143. return '99documentation'
  144. else:
  145. return '50' + str(key)
  146. return key