keyboard.py 8.2 KB

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