keyboard.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. """This script automates the creation of new keyboard directories using a starter template.
  2. """
  3. import re
  4. import json
  5. import shutil
  6. from datetime import date
  7. from pathlib import Path
  8. from dotty_dict import dotty
  9. from functools import lru_cache
  10. from milc import cli
  11. from milc.questions import choice, question, yesno
  12. from qmk.git import git_get_username
  13. from qmk.json_schema import load_jsonschema
  14. from qmk.path import keyboard
  15. from qmk.json_encoders import InfoJSONEncoder
  16. from qmk.json_schema import deep_update
  17. from qmk.constants import MCU2BOOTLOADER, QMK_FIRMWARE
  18. COMMUNITY = Path('layouts/default/')
  19. TEMPLATE = Path('data/templates/keyboard/')
  20. @lru_cache(maxsize=1)
  21. def _keyboard_schema():
  22. return dotty(load_jsonschema('keyboard'))
  23. def _processor_types():
  24. return sorted(_keyboard_schema()["properties.processor.enum"], key=str.casefold)
  25. def _dev_boards():
  26. return sorted(_keyboard_schema()["properties.development_board.enum"], key=str.casefold)
  27. def _available_layouts():
  28. return sorted([x.name for x in COMMUNITY.iterdir() if x.is_dir()])
  29. def mcu_type(mcu):
  30. """Callable for argparse validation.
  31. """
  32. if mcu not in (_dev_boards() + _processor_types()):
  33. raise ValueError
  34. return mcu
  35. def layout_type(layout):
  36. """Callable for argparse validation.
  37. """
  38. if layout not in _available_layouts():
  39. raise ValueError
  40. return layout
  41. def keyboard_name(name):
  42. """Callable for argparse validation.
  43. """
  44. if not validate_keyboard_name(name):
  45. raise ValueError
  46. return name
  47. def validate_keyboard_name(name):
  48. """Returns True if the given keyboard name contains only lowercase a-z, 0-9 and underscore characters.
  49. """
  50. regex = re.compile(r'^[a-z0-9][a-z0-9/_]+$')
  51. return bool(regex.match(name))
  52. def select_default_bootloader(mcu):
  53. """Provide sane defaults for bootloader
  54. """
  55. return MCU2BOOTLOADER.get(mcu, "custom")
  56. def replace_placeholders(src, dest, tokens):
  57. """Replaces the given placeholders in each template file.
  58. """
  59. content = src.read_text()
  60. for key, value in tokens.items():
  61. content = content.replace(f'%{key}%', value)
  62. dest.write_text(content)
  63. def replace_string(src, token, value):
  64. src.write_text(src.read_text().replace(token, value))
  65. def augment_community_info(config, src, dest):
  66. """Splice in any additional data into info.json
  67. """
  68. info = json.loads(src.read_text())
  69. template = json.loads(dest.read_text())
  70. # merge community with template
  71. deep_update(info, template)
  72. deep_update(info, config)
  73. # avoid assumptions on macro name by using the first available
  74. first_layout = next(iter(info["layouts"].values()))["layout"]
  75. # guess at width and height now its optional
  76. width, height = (0, 0)
  77. for item in first_layout:
  78. width = max(width, int(item["x"]) + 1)
  79. height = max(height, int(item["y"]) + 1)
  80. info["matrix_pins"] = {
  81. "cols": ["C2"] * width,
  82. "rows": ["D1"] * height,
  83. }
  84. # assume a 1:1 mapping on matrix to electrical
  85. for item in first_layout:
  86. item["matrix"] = [int(item["y"]), int(item["x"])]
  87. # finally write out the updated json
  88. dest.write_text(json.dumps(info, cls=InfoJSONEncoder, sort_keys=True))
  89. def _question(*args, **kwargs):
  90. """Ugly workaround until 'milc' learns to display a repromt msg
  91. """
  92. # TODO: Remove this once milc.questions.question handles reprompt messages
  93. reprompt = kwargs["reprompt"]
  94. del kwargs["reprompt"]
  95. validate = kwargs["validate"]
  96. del kwargs["validate"]
  97. prompt = args[0]
  98. ret = None
  99. while not ret:
  100. ret = question(prompt, **kwargs)
  101. if not validate(ret):
  102. ret = None
  103. prompt = reprompt
  104. return ret
  105. def prompt_heading_subheading(heading, subheading):
  106. cli.log.info(f"{{fg_yellow}}{heading}{{style_reset_all}}")
  107. cli.log.info(subheading)
  108. def prompt_keyboard():
  109. prompt_heading_subheading("Name Your Keyboard Project", """For more information, see:
  110. https://docs.qmk.fm/hardware_keyboard_guidelines#naming-your-keyboard-project""")
  111. errmsg = 'Keyboard already exists! Please choose a different name:'
  112. return _question("Keyboard Name?", reprompt=errmsg, validate=lambda x: not keyboard(x).exists())
  113. def prompt_user():
  114. prompt_heading_subheading("Attribution", "Used for maintainer, copyright, etc.")
  115. return question("Your GitHub Username?", default=git_get_username())
  116. def prompt_name(def_name):
  117. prompt_heading_subheading("More Attribution", "Used for maintainer, copyright, etc.")
  118. return question("Your Real Name?", default=def_name)
  119. def prompt_layout():
  120. prompt_heading_subheading("Pick Base Layout", """As a starting point, one of the common layouts can be used to
  121. bootstrap the process""")
  122. # avoid overwhelming user - remove some?
  123. filtered_layouts = [x for x in _available_layouts() if not any(xs in x for xs in ['_split', '_blocker', '_tsangan', '_f13'])]
  124. filtered_layouts.append("none of the above")
  125. return choice("Default Layout?", filtered_layouts, default=len(filtered_layouts) - 1)
  126. def prompt_mcu_type():
  127. prompt_heading_subheading(
  128. "What Powers Your Project", """Is your board using a separate development board, such as a Pro Micro,
  129. or is the microcontroller integrated onto the PCB?
  130. For more information, see:
  131. https://docs.qmk.fm/compatible_microcontrollers"""
  132. )
  133. return yesno("Using a Development Board?")
  134. def prompt_dev_board():
  135. prompt_heading_subheading("Select Development Board", """For more information, see:
  136. https://docs.qmk.fm/compatible_microcontrollers""")
  137. filtered_dev_boards = _dev_boards()
  138. filtered_dev_boards.append("none of the above")
  139. return choice("Development Board?", filtered_dev_boards, default=len(filtered_dev_boards) - 1)
  140. def prompt_mcu():
  141. prompt_heading_subheading("Select Microcontroller", """For more information, see:
  142. https://docs.qmk.fm/compatible_microcontrollers""")
  143. # remove any options strictly used for compatibility
  144. filtered_mcu = [x for x in _processor_types() if not any(xs in x for xs in ['cortex', 'unknown'])]
  145. return choice("Microcontroller?", filtered_mcu, default=filtered_mcu.index("atmega32u4"))
  146. @cli.argument('-kb', '--keyboard', help='Specify the name for the new keyboard directory', arg_only=True, type=keyboard_name)
  147. @cli.argument('-l', '--layout', help='Community layout to bootstrap with', arg_only=True, type=layout_type)
  148. @cli.argument('-t', '--type', help='Specify the keyboard MCU type (or "development_board" preset)', arg_only=True, type=mcu_type)
  149. @cli.argument('-u', '--username', help='Specify your username (default from Git config)', dest='name')
  150. @cli.argument('-n', '--realname', help='Specify your real name if you want to use that. Defaults to username', arg_only=True)
  151. @cli.subcommand('Creates a new keyboard directory')
  152. def new_keyboard(cli):
  153. """Creates a new keyboard.
  154. """
  155. cli.log.info('{style_bright}Generating a new QMK keyboard directory{style_normal}')
  156. cli.echo('')
  157. kb_name = cli.args.keyboard if cli.args.keyboard else prompt_keyboard()
  158. if not validate_keyboard_name(kb_name):
  159. cli.log.error('Keyboard names must contain only {fg_cyan}lowercase a-z{fg_reset}, {fg_cyan}0-9{fg_reset}, and {fg_cyan}_{fg_reset}! Please choose a different name.')
  160. return 1
  161. if keyboard(kb_name).exists():
  162. cli.log.error(f'Keyboard {{fg_cyan}}{kb_name}{{fg_reset}} already exists! Please choose a different name.')
  163. return 1
  164. user_name = cli.config.new_keyboard.name if cli.config.new_keyboard.name else prompt_user()
  165. real_name = cli.args.realname or cli.config.new_keyboard.name if cli.args.realname or cli.config.new_keyboard.name else prompt_name(user_name)
  166. default_layout = cli.args.layout if cli.args.layout else prompt_layout()
  167. mcu = None
  168. if cli.args.type:
  169. mcu = cli.args.type
  170. else:
  171. if prompt_mcu_type():
  172. mcu = prompt_dev_board()
  173. if not mcu or mcu == "none of the above":
  174. mcu = prompt_mcu()
  175. config = {}
  176. if mcu in _dev_boards():
  177. config['development_board'] = mcu
  178. else:
  179. config['processor'] = mcu
  180. config['bootloader'] = select_default_bootloader(mcu)
  181. detach_layout = False
  182. if default_layout == 'none of the above':
  183. default_layout = "ortho_4x4"
  184. detach_layout = True
  185. tokens = { # Comment here is to force multiline formatting
  186. 'YEAR': str(date.today().year),
  187. 'KEYBOARD': kb_name,
  188. 'USER_NAME': user_name,
  189. 'REAL_NAME': real_name
  190. }
  191. # begin with making the deepest folder in the tree
  192. keymaps_path = keyboard(kb_name) / 'keymaps/'
  193. keymaps_path.mkdir(parents=True)
  194. # copy in keymap.c or keymap.json
  195. community_keymap = Path(COMMUNITY / f'{default_layout}/default_{default_layout}/')
  196. shutil.copytree(community_keymap, keymaps_path / 'default')
  197. # process template files
  198. for file in list(TEMPLATE.iterdir()):
  199. replace_placeholders(file, keyboard(kb_name) / file.name, tokens)
  200. # merge in infos
  201. community_info = Path(COMMUNITY / f'{default_layout}/info.json')
  202. augment_community_info(config, community_info, keyboard(kb_name) / 'keyboard.json')
  203. # detach community layout and rename to just "LAYOUT"
  204. if detach_layout:
  205. replace_string(keyboard(kb_name) / 'keyboard.json', 'LAYOUT_ortho_4x4', 'LAYOUT')
  206. replace_string(keymaps_path / 'default/keymap.c', 'LAYOUT_ortho_4x4', 'LAYOUT')
  207. cli.log.info(f'{{fg_green}}Created a new keyboard called {{fg_cyan}}{kb_name}{{fg_green}}.{{fg_reset}}')
  208. cli.log.info(f"Build Command: {{fg_yellow}}qmk compile -kb {kb_name} -km default{{fg_reset}}.")
  209. cli.log.info(f'Project Location: {{fg_cyan}}{QMK_FIRMWARE}/{keyboard(kb_name)}{{fg_reset}}.')
  210. cli.log.info("{fg_yellow}Now update the config files to match the hardware!{fg_reset}")