logo

qmk_firmware

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

keyboard.py (9577B)


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