keyboard.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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.commands 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. COMMUNITY = Path('layouts/default/')
  17. TEMPLATE = Path('data/templates/keyboard/')
  18. MCU2BOOTLOADER = {
  19. "MKL26Z64": "halfkay",
  20. "MK20DX128": "halfkay",
  21. "MK20DX256": "halfkay",
  22. "MK66FX1M0": "halfkay",
  23. "STM32F042": "stm32-dfu",
  24. "STM32F072": "stm32-dfu",
  25. "STM32F103": "stm32duino",
  26. "STM32F303": "stm32-dfu",
  27. "STM32F401": "stm32-dfu",
  28. "STM32F405": "stm32-dfu",
  29. "STM32F407": "stm32-dfu",
  30. "STM32F411": "stm32-dfu",
  31. "STM32F446": "stm32-dfu",
  32. "STM32G431": "stm32-dfu",
  33. "STM32G474": "stm32-dfu",
  34. "STM32L412": "stm32-dfu",
  35. "STM32L422": "stm32-dfu",
  36. "STM32L432": "stm32-dfu",
  37. "STM32L433": "stm32-dfu",
  38. "STM32L442": "stm32-dfu",
  39. "STM32L443": "stm32-dfu",
  40. "GD32VF103": "gd32v-dfu",
  41. "WB32F3G71": "wb32-dfu",
  42. "atmega16u2": "atmel-dfu",
  43. "atmega32u2": "atmel-dfu",
  44. "atmega16u4": "atmel-dfu",
  45. "atmega32u4": "atmel-dfu",
  46. "at90usb162": "atmel-dfu",
  47. "at90usb646": "atmel-dfu",
  48. "at90usb647": "atmel-dfu",
  49. "at90usb1286": "atmel-dfu",
  50. "at90usb1287": "atmel-dfu",
  51. "atmega32a": "bootloadhid",
  52. "atmega328p": "usbasploader",
  53. "atmega328": "usbasploader",
  54. }
  55. # defaults
  56. schema = dotty(load_jsonschema('keyboard'))
  57. mcu_types = sorted(schema["properties.processor.enum"], key=str.casefold)
  58. available_layouts = sorted([x.name for x in COMMUNITY.iterdir() if x.is_dir()])
  59. def mcu_type(mcu):
  60. """Callable for argparse validation.
  61. """
  62. if mcu not in mcu_types:
  63. raise ValueError
  64. return mcu
  65. def layout_type(layout):
  66. """Callable for argparse validation.
  67. """
  68. if layout not in available_layouts:
  69. raise ValueError
  70. return layout
  71. def keyboard_name(name):
  72. """Callable for argparse validation.
  73. """
  74. if not validate_keyboard_name(name):
  75. raise ValueError
  76. return name
  77. def validate_keyboard_name(name):
  78. """Returns True if the given keyboard name contains only lowercase a-z, 0-9 and underscore characters.
  79. """
  80. regex = re.compile(r'^[a-z0-9][a-z0-9/_]+$')
  81. return bool(regex.match(name))
  82. def select_default_bootloader(mcu):
  83. """Provide sane defaults for bootloader
  84. """
  85. return MCU2BOOTLOADER.get(mcu, "custom")
  86. def replace_placeholders(src, dest, tokens):
  87. """Replaces the given placeholders in each template file.
  88. """
  89. content = src.read_text()
  90. for key, value in tokens.items():
  91. content = content.replace(f'%{key}%', value)
  92. dest.write_text(content)
  93. def augment_community_info(src, dest):
  94. """Splice in any additional data into info.json
  95. """
  96. info = json.loads(src.read_text())
  97. template = json.loads(dest.read_text())
  98. # merge community with template
  99. deep_update(info, template)
  100. # avoid assumptions on macro name by using the first available
  101. first_layout = next(iter(info["layouts"].values()))["layout"]
  102. # guess at width and height now its optional
  103. width, height = (0, 0)
  104. for item in first_layout:
  105. width = max(width, int(item["x"]) + 1)
  106. height = max(height, int(item["y"]) + 1)
  107. info["matrix_pins"] = {
  108. "cols": ["C2"] * width,
  109. "rows": ["D1"] * height,
  110. }
  111. # assume a 1:1 mapping on matrix to electrical
  112. for item in first_layout:
  113. item["matrix"] = [int(item["y"]), int(item["x"])]
  114. # finally write out the updated info.json
  115. dest.write_text(json.dumps(info, cls=InfoJSONEncoder))
  116. def prompt_keyboard():
  117. prompt = """{fg_yellow}Name Your Keyboard Project{style_reset_all}
  118. For more infomation, see:
  119. https://docs.qmk.fm/#/hardware_keyboard_guidelines?id=naming-your-keyboardproject
  120. keyboard Name? """
  121. return question(prompt, validate=lambda x: not keyboard(x).exists())
  122. def prompt_user():
  123. prompt = """{fg_yellow}Attribution{style_reset_all}
  124. Used for maintainer, copyright, etc
  125. Your GitHub Username? """
  126. return question(prompt, default=git_get_username())
  127. def prompt_name(def_name):
  128. prompt = """{fg_yellow}More Attribution{style_reset_all}
  129. Used for maintainer, copyright, etc
  130. Your Real Name? """
  131. return question(prompt, default=def_name)
  132. def prompt_layout():
  133. prompt = """{fg_yellow}Pick Base Layout{style_reset_all}
  134. As a starting point, one of the common layouts can be used to bootstrap the process
  135. Default Layout? """
  136. # avoid overwhelming user - remove some?
  137. filtered_layouts = [x for x in available_layouts if not any(xs in x for xs in ['_split', '_blocker', '_tsangan', '_f13'])]
  138. filtered_layouts.append("none of the above")
  139. return choice(prompt, filtered_layouts, default=len(filtered_layouts) - 1)
  140. def prompt_mcu():
  141. prompt = """{fg_yellow}What Powers Your Project{style_reset_all}
  142. For more infomation, see:
  143. https://docs.qmk.fm/#/compatible_microcontrollers
  144. MCU? """
  145. # remove any options strictly used for compatibility
  146. filtered_mcu = [x for x in mcu_types if not any(xs in x for xs in ['cortex', 'unknown'])]
  147. return choice(prompt, filtered_mcu, default=filtered_mcu.index("atmega32u4"))
  148. @cli.argument('-kb', '--keyboard', help='Specify the name for the new keyboard directory', arg_only=True, type=keyboard_name)
  149. @cli.argument('-l', '--layout', help='Community layout to bootstrap with', arg_only=True, type=layout_type)
  150. @cli.argument('-t', '--type', help='Specify the keyboard MCU type', arg_only=True, type=mcu_type)
  151. @cli.argument('-u', '--username', help='Specify your username (default from Git config)', arg_only=True)
  152. @cli.argument('-n', '--realname', help='Specify your real name if you want to use that. Defaults to username', arg_only=True)
  153. @cli.subcommand('Creates a new keyboard directory')
  154. def new_keyboard(cli):
  155. """Creates a new keyboard.
  156. """
  157. cli.log.info('{style_bright}Generating a new QMK keyboard directory{style_normal}')
  158. cli.echo('')
  159. kb_name = cli.args.keyboard if cli.args.keyboard else prompt_keyboard()
  160. user_name = cli.args.username if cli.args.username else prompt_user()
  161. real_name = cli.args.realname or cli.args.username if cli.args.realname or cli.args.username else prompt_name(user_name)
  162. default_layout = cli.args.layout if cli.args.layout else prompt_layout()
  163. mcu = cli.args.type if cli.args.type else prompt_mcu()
  164. bootloader = select_default_bootloader(mcu)
  165. if not validate_keyboard_name(kb_name):
  166. 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.')
  167. return 1
  168. if keyboard(kb_name).exists():
  169. cli.log.error(f'Keyboard {{fg_cyan}}{kb_name}{{fg_reset}} already exists! Please choose a different name.')
  170. return 1
  171. tokens = {'YEAR': str(date.today().year), 'KEYBOARD': kb_name, 'USER_NAME': user_name, 'REAL_NAME': real_name, 'LAYOUT': default_layout, 'MCU': mcu, 'BOOTLOADER': bootloader}
  172. if cli.config.general.verbose:
  173. cli.log.info("Creating keyboard with:")
  174. for key, value in tokens.items():
  175. cli.echo(f" {key.ljust(10)}: {value}")
  176. # TODO: detach community layout and rename to just "LAYOUT"
  177. if default_layout == 'none of the above':
  178. default_layout = "ortho_4x4"
  179. # begin with making the deepest folder in the tree
  180. keymaps_path = keyboard(kb_name) / 'keymaps/'
  181. keymaps_path.mkdir(parents=True)
  182. # copy in keymap.c or keymap.json
  183. community_keymap = Path(COMMUNITY / f'{default_layout}/default_{default_layout}/')
  184. shutil.copytree(community_keymap, keymaps_path / 'default')
  185. # process template files
  186. for file in list(TEMPLATE.iterdir()):
  187. replace_placeholders(file, keyboard(kb_name) / file.name, tokens)
  188. # merge in infos
  189. community_info = Path(COMMUNITY / f'{default_layout}/info.json')
  190. augment_community_info(community_info, keyboard(kb_name) / community_info.name)
  191. cli.log.info(f'{{fg_green}}Created a new keyboard called {{fg_cyan}}{kb_name}{{fg_green}}.{{fg_reset}}')
  192. cli.log.info(f'To start working on things, `cd` into {{fg_cyan}}keyboards/{kb_name}{{fg_reset}},')
  193. cli.log.info('or open the directory in your preferred text editor.')
  194. cli.log.info(f"And build with {{fg_yellow}}qmk compile -kb {kb_name} -km default{{fg_reset}}.")