keyboard.py 8.6 KB

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