keyboard.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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
  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, json_load
  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(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. # avoid assumptions on macro name by using the first available
  68. first_layout = next(iter(info["layouts"].values()))["layout"]
  69. # guess at width and height now its optional
  70. width, height = (0, 0)
  71. for item in first_layout:
  72. width = max(width, int(item["x"]) + 1)
  73. height = max(height, int(item["y"]) + 1)
  74. info["matrix_pins"] = {
  75. "cols": ["C2"] * width,
  76. "rows": ["D1"] * height,
  77. }
  78. # assume a 1:1 mapping on matrix to electrical
  79. for item in first_layout:
  80. item["matrix"] = [int(item["y"]), int(item["x"])]
  81. # finally write out the updated info.json
  82. dest.write_text(json.dumps(info, cls=InfoJSONEncoder, sort_keys=True))
  83. def _question(*args, **kwargs):
  84. """Ugly workaround until 'milc' learns to display a repromt msg
  85. """
  86. # TODO: Remove this once milc.questions.question handles reprompt messages
  87. reprompt = kwargs["reprompt"]
  88. del kwargs["reprompt"]
  89. validate = kwargs["validate"]
  90. del kwargs["validate"]
  91. prompt = args[0]
  92. ret = None
  93. while not ret:
  94. ret = question(prompt, **kwargs)
  95. if not validate(ret):
  96. ret = None
  97. prompt = reprompt
  98. return ret
  99. def prompt_keyboard():
  100. prompt = """{fg_yellow}Name Your Keyboard Project{style_reset_all}
  101. For more infomation, see:
  102. https://docs.qmk.fm/hardware_keyboard_guidelines#naming-your-keyboard-project
  103. Keyboard Name? """
  104. errmsg = 'Keyboard already exists! Please choose a different name:'
  105. return _question(prompt, reprompt=errmsg, validate=lambda x: not keyboard(x).exists())
  106. def prompt_user():
  107. prompt = """
  108. {fg_yellow}Attribution{style_reset_all}
  109. Used for maintainer, copyright, etc
  110. Your GitHub Username? """
  111. return question(prompt, default=git_get_username())
  112. def prompt_name(def_name):
  113. prompt = """
  114. {fg_yellow}More Attribution{style_reset_all}
  115. Used for maintainer, copyright, etc
  116. Your Real Name? """
  117. return question(prompt, default=def_name)
  118. def prompt_layout():
  119. prompt = """
  120. {fg_yellow}Pick Base Layout{style_reset_all}
  121. As a starting point, one of the common layouts can be used to bootstrap the process
  122. Default Layout? """
  123. # avoid overwhelming user - remove some?
  124. filtered_layouts = [x for x in available_layouts if not any(xs in x for xs in ['_split', '_blocker', '_tsangan', '_f13'])]
  125. filtered_layouts.append("none of the above")
  126. return choice(prompt, filtered_layouts, default=len(filtered_layouts) - 1)
  127. def prompt_mcu():
  128. prompt = """
  129. {fg_yellow}What Powers Your Project{style_reset_all}
  130. For more infomation, see:
  131. https://docs.qmk.fm/#/compatible_microcontrollers
  132. MCU? """
  133. # remove any options strictly used for compatibility
  134. filtered_mcu = [x for x in (dev_boards + mcu_types) if not any(xs in x for xs in ['cortex', 'unknown'])]
  135. return choice(prompt, filtered_mcu, default=filtered_mcu.index("atmega32u4"))
  136. @cli.argument('-kb', '--keyboard', help='Specify the name for the new keyboard directory', arg_only=True, type=keyboard_name)
  137. @cli.argument('-l', '--layout', help='Community layout to bootstrap with', arg_only=True, type=layout_type)
  138. @cli.argument('-t', '--type', help='Specify the keyboard MCU type (or "development_board" preset)', arg_only=True, type=mcu_type)
  139. @cli.argument('-u', '--username', help='Specify your username (default from Git config)', dest='name')
  140. @cli.argument('-n', '--realname', help='Specify your real name if you want to use that. Defaults to username', arg_only=True)
  141. @cli.subcommand('Creates a new keyboard directory')
  142. def new_keyboard(cli):
  143. """Creates a new keyboard.
  144. """
  145. cli.log.info('{style_bright}Generating a new QMK keyboard directory{style_normal}')
  146. cli.echo('')
  147. kb_name = cli.args.keyboard if cli.args.keyboard else prompt_keyboard()
  148. if not validate_keyboard_name(kb_name):
  149. 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.')
  150. return 1
  151. if keyboard(kb_name).exists():
  152. cli.log.error(f'Keyboard {{fg_cyan}}{kb_name}{{fg_reset}} already exists! Please choose a different name.')
  153. return 1
  154. user_name = cli.config.new_keyboard.name if cli.config.new_keyboard.name else prompt_user()
  155. 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)
  156. default_layout = cli.args.layout if cli.args.layout else prompt_layout()
  157. mcu = cli.args.type if cli.args.type else prompt_mcu()
  158. # Preprocess any development_board presets
  159. if mcu in dev_boards:
  160. defaults_map = json_load(Path('data/mappings/defaults.hjson'))
  161. board = defaults_map['development_board'][mcu]
  162. mcu = board['processor']
  163. bootloader = board['bootloader']
  164. else:
  165. bootloader = select_default_bootloader(mcu)
  166. detach_layout = False
  167. if default_layout == 'none of the above':
  168. default_layout = "ortho_4x4"
  169. detach_layout = True
  170. tokens = { # Comment here is to force multiline formatting
  171. 'YEAR': str(date.today().year),
  172. 'KEYBOARD': kb_name,
  173. 'USER_NAME': user_name,
  174. 'REAL_NAME': real_name,
  175. 'LAYOUT': default_layout,
  176. 'MCU': mcu,
  177. 'BOOTLOADER': bootloader
  178. }
  179. if cli.config.general.verbose:
  180. cli.log.info("Creating keyboard with:")
  181. for key, value in tokens.items():
  182. cli.echo(f" {key.ljust(10)}: {value}")
  183. # begin with making the deepest folder in the tree
  184. keymaps_path = keyboard(kb_name) / 'keymaps/'
  185. keymaps_path.mkdir(parents=True)
  186. # copy in keymap.c or keymap.json
  187. community_keymap = Path(COMMUNITY / f'{default_layout}/default_{default_layout}/')
  188. shutil.copytree(community_keymap, keymaps_path / 'default')
  189. # process template files
  190. for file in list(TEMPLATE.iterdir()):
  191. replace_placeholders(file, keyboard(kb_name) / file.name, tokens)
  192. # merge in infos
  193. community_info = Path(COMMUNITY / f'{default_layout}/info.json')
  194. augment_community_info(community_info, keyboard(kb_name) / 'keyboard.json')
  195. # detach community layout and rename to just "LAYOUT"
  196. if detach_layout:
  197. replace_string(keyboard(kb_name) / 'keyboard.json', 'LAYOUT_ortho_4x4', 'LAYOUT')
  198. replace_string(keymaps_path / 'default/keymap.c', 'LAYOUT_ortho_4x4', 'LAYOUT')
  199. cli.log.info(f'{{fg_green}}Created a new keyboard called {{fg_cyan}}{kb_name}{{fg_green}}.{{fg_reset}}')
  200. cli.log.info(f"Build Command: {{fg_yellow}}qmk compile -kb {kb_name} -km default{{fg_reset}}.")
  201. cli.log.info(f'Project Location: {{fg_cyan}}{QMK_FIRMWARE}/{keyboard(kb_name)}{{fg_reset}},')
  202. cli.log.info("{{fg_yellow}}Now update the config files to match the hardware!{{fg_reset}}")