summaryrefslogtreecommitdiffstats
path: root/lib/python/qmk
diff options
context:
space:
mode:
Diffstat (limited to 'lib/python/qmk')
-rw-r--r--lib/python/qmk/c_parse.py4
-rw-r--r--lib/python/qmk/cli/__init__.py3
-rwxr-xr-xlib/python/qmk/cli/compile.py57
-rw-r--r--lib/python/qmk/cli/flash.py99
-rwxr-xr-xlib/python/qmk/cli/generate/api.py35
-rw-r--r--lib/python/qmk/cli/generate/autocorrect_data.py289
-rwxr-xr-xlib/python/qmk/cli/generate/config_h.py156
-rwxr-xr-xlib/python/qmk/cli/generate/keyboard_h.py69
-rw-r--r--lib/python/qmk/cli/generate/keycodes.py88
-rwxr-xr-xlib/python/qmk/cli/generate/layouts.py90
-rwxr-xr-xlib/python/qmk/cli/generate/rules_mk.py31
-rw-r--r--lib/python/qmk/cli/new/keyboard.py2
-rw-r--r--lib/python/qmk/cli/painter/convert_graphics.py7
-rw-r--r--lib/python/qmk/cli/painter/make_font.py12
-rw-r--r--lib/python/qmk/commands.py44
-rw-r--r--lib/python/qmk/info.py56
-rw-r--r--lib/python/qmk/json_schema.py15
-rw-r--r--lib/python/qmk/keyboard.py2
-rw-r--r--lib/python/qmk/keycodes.py57
-rw-r--r--lib/python/qmk/keymap.py4
-rw-r--r--lib/python/qmk/tests/test_cli_commands.py30
21 files changed, 775 insertions, 375 deletions
diff --git a/lib/python/qmk/c_parse.py b/lib/python/qmk/c_parse.py
index c14eb490fa..3d73e66091 100644
--- a/lib/python/qmk/c_parse.py
+++ b/lib/python/qmk/c_parse.py
@@ -216,9 +216,9 @@ def _validate_led_config(matrix, matrix_rows, matrix_indexes, position, position
if len(matrix) != matrix_rows and len(matrix) != (matrix_rows / 2):
raise ValueError("Unable to parse g_led_config matrix data")
if len(position) != len(flags):
- raise ValueError("Unable to parse g_led_config position data")
+ raise ValueError(f"Number of g_led_config physical positions ({len(position)}) does not match number of flags ({len(flags)})")
if len(matrix_indexes) and (max(matrix_indexes) >= len(flags)):
- raise ValueError("OOB within g_led_config matrix data")
+ raise ValueError(f"LED index {max(matrix_indexes)} is OOB in g_led_config - should be < {len(flags)}")
if not all(isinstance(n, int) for n in matrix_indexes):
raise ValueError("matrix indexes are not all ints")
if (len(position_raw) % 2) != 0:
diff --git a/lib/python/qmk/cli/__init__.py b/lib/python/qmk/cli/__init__.py
index 98e212c47b..9190af4e50 100644
--- a/lib/python/qmk/cli/__init__.py
+++ b/lib/python/qmk/cli/__init__.py
@@ -47,6 +47,7 @@ subcommands = [
'qmk.cli.format.python',
'qmk.cli.format.text',
'qmk.cli.generate.api',
+ 'qmk.cli.generate.autocorrect_data',
'qmk.cli.generate.compilation_database',
'qmk.cli.generate.config_h',
'qmk.cli.generate.develop_pr_list',
@@ -55,7 +56,7 @@ subcommands = [
'qmk.cli.generate.info_json',
'qmk.cli.generate.keyboard_c',
'qmk.cli.generate.keyboard_h',
- 'qmk.cli.generate.layouts',
+ 'qmk.cli.generate.keycodes',
'qmk.cli.generate.rgb_breathe_table',
'qmk.cli.generate.rules_mk',
'qmk.cli.generate.version_h',
diff --git a/lib/python/qmk/cli/compile.py b/lib/python/qmk/cli/compile.py
index 95118e6687..9e7629906f 100755
--- a/lib/python/qmk/cli/compile.py
+++ b/lib/python/qmk/cli/compile.py
@@ -2,14 +2,13 @@
You can compile a keymap already in the repo or using a QMK Configurator export.
"""
-from subprocess import DEVNULL
-
from argcomplete.completers import FilesCompleter
+
from milc import cli
import qmk.path
from qmk.decorators import automagic_keyboard, automagic_keymap
-from qmk.commands import compile_configurator_json, create_make_command, parse_configurator_json
+from qmk.commands import compile_configurator_json, create_make_command, parse_configurator_json, build_environment
from qmk.keyboard import keyboard_completer, keyboard_folder
from qmk.keymap import keymap_completer
@@ -31,48 +30,32 @@ def compile(cli):
If a keyboard and keymap are provided this command will build a firmware based on that.
"""
- if cli.args.clean and not cli.args.filename and not cli.args.dry_run:
- if cli.config.compile.keyboard and cli.config.compile.keymap:
- command = create_make_command(cli.config.compile.keyboard, cli.config.compile.keymap, 'clean')
- cli.run(command, capture_output=False, stdin=DEVNULL)
-
# Build the environment vars
- envs = {}
- for env in cli.args.env:
- if '=' in env:
- key, value = env.split('=', 1)
- envs[key] = value
- else:
- cli.log.warning('Invalid environment variable: %s', env)
+ envs = build_environment(cli.args.env)
# Determine the compile command
- command = None
+ commands = []
if cli.args.filename:
# If a configurator JSON was provided generate a keymap and compile it
user_keymap = parse_configurator_json(cli.args.filename)
- command = compile_configurator_json(user_keymap, parallel=cli.config.compile.parallel, **envs)
+ commands = [compile_configurator_json(user_keymap, parallel=cli.config.compile.parallel, clean=cli.args.clean, **envs)]
- else:
- if cli.config.compile.keyboard and cli.config.compile.keymap:
- # Generate the make command for a specific keyboard/keymap.
- command = create_make_command(cli.config.compile.keyboard, cli.config.compile.keymap, parallel=cli.config.compile.parallel, **envs)
+ elif cli.config.compile.keyboard and cli.config.compile.keymap:
+ # Generate the make command for a specific keyboard/keymap.
+ if cli.args.clean:
+ commands.append(create_make_command(cli.config.compile.keyboard, cli.config.compile.keymap, 'clean', **envs))
+ commands.append(create_make_command(cli.config.compile.keyboard, cli.config.compile.keymap, parallel=cli.config.compile.parallel, **envs))
- elif not cli.config.compile.keyboard:
- cli.log.error('Could not determine keyboard!')
- elif not cli.config.compile.keymap:
- cli.log.error('Could not determine keymap!')
-
- # Compile the firmware, if we're able to
- if command:
- cli.log.info('Compiling keymap with {fg_cyan}%s', ' '.join(command))
- if not cli.args.dry_run:
- cli.echo('\n')
- # FIXME(skullydazed/anyone): Remove text=False once milc 1.0.11 has had enough time to be installed everywhere.
- compile = cli.run(command, capture_output=False, text=False)
- return compile.returncode
-
- else:
+ if not commands:
cli.log.error('You must supply a configurator export, both `--keyboard` and `--keymap`, or be in a directory for a keyboard or keymap.')
- cli.echo('usage: qmk compile [-h] [-b] [-kb KEYBOARD] [-km KEYMAP] [filename]')
+ cli.print_help()
return False
+
+ cli.log.info('Compiling keymap with {fg_cyan}%s', ' '.join(commands[-1]))
+ if not cli.args.dry_run:
+ cli.echo('\n')
+ for command in commands:
+ ret = cli.run(command, capture_output=False)
+ if ret.returncode:
+ return ret.returncode
diff --git a/lib/python/qmk/cli/flash.py b/lib/python/qmk/cli/flash.py
index c39f4b36d4..40bfbdab56 100644
--- a/lib/python/qmk/cli/flash.py
+++ b/lib/python/qmk/cli/flash.py
@@ -3,15 +3,13 @@
You can compile a keymap already in the repo or using a QMK Configurator export.
A bootloader must be specified.
"""
-from subprocess import DEVNULL
-import sys
-
from argcomplete.completers import FilesCompleter
+
from milc import cli
import qmk.path
from qmk.decorators import automagic_keyboard, automagic_keymap
-from qmk.commands import compile_configurator_json, create_make_command, parse_configurator_json
+from qmk.commands import compile_configurator_json, create_make_command, parse_configurator_json, build_environment
from qmk.keyboard import keyboard_completer, keyboard_folder
from qmk.flashers import flasher
@@ -75,59 +73,40 @@ def flash(cli):
return False
except KeyboardInterrupt:
cli.log.info('Ctrl-C was pressed, exiting...')
- sys.exit(0)
-
- else:
- if cli.args.clean and not cli.args.filename and not cli.args.dry_run:
- if cli.config.flash.keyboard and cli.config.flash.keymap:
- command = create_make_command(cli.config.flash.keyboard, cli.config.flash.keymap, 'clean')
- cli.run(command, capture_output=False, stdin=DEVNULL)
-
- # Build the environment vars
- envs = {}
- for env in cli.args.env:
- if '=' in env:
- key, value = env.split('=', 1)
- envs[key] = value
- else:
- cli.log.warning('Invalid environment variable: %s', env)
-
- # Determine the compile command
- command = ''
-
- if cli.args.bootloaders:
- # Provide usage and list bootloaders
- cli.echo('usage: qmk flash [-h] [-b] [-n] [-kb KEYBOARD] [-km KEYMAP] [-bl BOOTLOADER] [filename]')
- print_bootloader_help()
- return False
-
- if cli.args.filename:
- # Handle compiling a configurator JSON
- user_keymap = parse_configurator_json(cli.args.filename)
- keymap_path = qmk.path.keymap(user_keymap['keyboard'])
- command = compile_configurator_json(user_keymap, cli.args.bootloader, parallel=cli.config.flash.parallel, **envs)
-
- cli.log.info('Wrote keymap to {fg_cyan}%s/%s/keymap.c', keymap_path, user_keymap['keymap'])
-
- else:
- if cli.config.flash.keyboard and cli.config.flash.keymap:
- # Generate the make command for a specific keyboard/keymap.
- command = create_make_command(cli.config.flash.keyboard, cli.config.flash.keymap, cli.args.bootloader, parallel=cli.config.flash.parallel, **envs)
-
- elif not cli.config.flash.keyboard:
- cli.log.error('Could not determine keyboard!')
- elif not cli.config.flash.keymap:
- cli.log.error('Could not determine keymap!')
-
- # Compile the firmware, if we're able to
- if command:
- cli.log.info('Compiling keymap with {fg_cyan}%s', ' '.join(command))
- if not cli.args.dry_run:
- cli.echo('\n')
- compile = cli.run(command, capture_output=False, stdin=DEVNULL)
- return compile.returncode
-
- else:
- cli.log.error('You must supply a configurator export, both `--keyboard` and `--keymap`, or be in a directory for a keyboard or keymap.')
- cli.echo('usage: qmk flash [-h] [-b] [-n] [-kb KEYBOARD] [-km KEYMAP] [-bl BOOTLOADER] [filename]')
- return False
+ return True
+
+ if cli.args.bootloaders:
+ # Provide usage and list bootloaders
+ cli.print_help()
+ print_bootloader_help()
+ return False
+
+ # Build the environment vars
+ envs = build_environment(cli.args.env)
+
+ # Determine the compile command
+ commands = []
+
+ if cli.args.filename:
+ # If a configurator JSON was provided generate a keymap and compile it
+ user_keymap = parse_configurator_json(cli.args.filename)
+ commands = [compile_configurator_json(user_keymap, cli.args.bootloader, parallel=cli.config.flash.parallel, clean=cli.args.clean, **envs)]
+
+ elif cli.config.flash.keyboard and cli.config.flash.keymap:
+ # Generate the make command for a specific keyboard/keymap.
+ if cli.args.clean:
+ commands.append(create_make_command(cli.config.flash.keyboard, cli.config.flash.keymap, 'clean', **envs))
+ commands.append(create_make_command(cli.config.flash.keyboard, cli.config.flash.keymap, cli.args.bootloader, parallel=cli.config.flash.parallel, **envs))
+
+ if not commands:
+ cli.log.error('You must supply a configurator export, both `--keyboard` and `--keymap`, or be in a directory for a keyboard or keymap.')
+ cli.print_help()
+ return False
+
+ cli.log.info('Compiling keymap with {fg_cyan}%s', ' '.join(commands[-1]))
+ if not cli.args.dry_run:
+ cli.echo('\n')
+ for command in commands:
+ ret = cli.run(command, capture_output=False)
+ if ret.returncode:
+ return ret.returncode
diff --git a/lib/python/qmk/cli/generate/api.py b/lib/python/qmk/cli/generate/api.py
index 8d8ca3cd41..a98a12b628 100755
--- a/lib/python/qmk/cli/generate/api.py
+++ b/lib/python/qmk/cli/generate/api.py
@@ -11,12 +11,40 @@ from qmk.info import info_json
from qmk.json_encoders import InfoJSONEncoder
from qmk.json_schema import json_load
from qmk.keyboard import find_readme, list_keyboards
+from qmk.keycodes import load_spec, list_versions
DATA_PATH = Path('data')
TEMPLATE_PATH = DATA_PATH / 'templates/api/'
BUILD_API_PATH = Path('.build/api_data/')
+def _resolve_keycode_specs(output_folder):
+ """To make it easier for consumers, publish pre-merged spec files
+ """
+ for version in list_versions():
+ overall = load_spec(version)
+
+ output_file = output_folder / f'constants/keycodes_{version}.json'
+ output_file.write_text(json.dumps(overall, indent=4), encoding='utf-8')
+
+ # Purge files consumed by 'load_spec'
+ shutil.rmtree(output_folder / 'constants/keycodes/')
+
+
+def _filtered_copy(src, dst):
+ src = Path(src)
+ dst = Path(dst)
+
+ if dst.suffix == '.hjson':
+ data = json_load(src)
+
+ dst = dst.with_suffix('.json')
+ dst.write_text(json.dumps(data, indent=4), encoding='utf-8')
+ return dst
+
+ return shutil.copy2(src, dst)
+
+
def _filtered_keyboard_list():
"""Perform basic filtering of list_keyboards
"""
@@ -47,7 +75,7 @@ def generate_api(cli):
shutil.rmtree(BUILD_API_PATH)
shutil.copytree(TEMPLATE_PATH, BUILD_API_PATH)
- shutil.copytree(DATA_PATH, v1_dir)
+ shutil.copytree(DATA_PATH, v1_dir, copy_function=_filtered_copy)
# Filter down when required
keyboard_list = _filtered_keyboard_list()
@@ -87,7 +115,7 @@ def generate_api(cli):
# Generate data for the global files
keyboard_list = sorted(kb_all)
- keyboard_aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
+ keyboard_aliases = json_load(Path('data/mappings/keyboard_aliases.hjson'))
keyboard_metadata = {
'last_updated': current_datetime(),
'keyboards': keyboard_list,
@@ -95,6 +123,9 @@ def generate_api(cli):
'usb': usb_list,
}
+ # Feature specific handling
+ _resolve_keycode_specs(v1_dir)
+
# Write the global JSON files
keyboard_all_json = json.dumps({'last_updated': current_datetime(), 'keyboards': kb_all}, cls=InfoJSONEncoder)
usb_json = json.dumps({'last_updated': current_datetime(), 'usb': usb_list}, cls=InfoJSONEncoder)
diff --git a/lib/python/qmk/cli/generate/autocorrect_data.py b/lib/python/qmk/cli/generate/autocorrect_data.py
new file mode 100644
index 0000000000..00ab6180ab
--- /dev/null
+++ b/lib/python/qmk/cli/generate/autocorrect_data.py
@@ -0,0 +1,289 @@
+# Copyright 2021 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Python program to make autocorrect_data.h.
+This program reads from a prepared dictionary file and generates a C source file
+"autocorrect_data.h" with a serialized trie embedded as an array. Run this
+program and pass it as the first argument like:
+$ qmk generate-autocorrect-data autocorrect_dict.txt
+Each line of the dict file defines one typo and its correction with the syntax
+"typo -> correction". Blank lines or lines starting with '#' are ignored.
+Example:
+ :thier -> their
+ fitler -> filter
+ lenght -> length
+ ouput -> output
+ widht -> width
+For full documentation, see QMK Docs
+"""
+
+import sys
+import textwrap
+from typing import Any, Dict, Iterator, List, Tuple
+
+from milc import cli
+
+import qmk.path
+from qmk.keyboard import keyboard_completer, keyboard_folder
+from qmk.keymap import keymap_completer, locate_keymap
+
+KC_A = 4
+KC_SPC = 0x2c
+KC_QUOT = 0x34
+
+TYPO_CHARS = dict([
+ ("'", KC_QUOT),
+ (':', KC_SPC), # "Word break" character.
+] + [(chr(c), c + KC_A - ord('a')) for c in range(ord('a'),
+ ord('z') + 1)]) # Characters a-z.
+
+
+def parse_file(file_name: str) -> List[Tuple[str, str]]:
+ """Parses autocorrections dictionary file.
+ Each line of the file defines one typo and its correction with the syntax
+ "typo -> correction". Blank lines or lines starting with '#' are ignored. The
+ function validates that typos only have characters a-z and that typos are not
+ substrings of other typos, otherwise the longer typo would never trigger.
+ Args:
+ file_name: String, path of the autocorrections dictionary.
+ Returns:
+ List of (typo, correction) tuples.
+ """
+
+ try:
+ from english_words import english_words_lower_alpha_set as correct_words
+ except ImportError:
+ cli.echo('Autocorrection will falsely trigger when a typo is a substring of a correctly spelled word.')
+ cli.echo('To check for this, install the english_words package and rerun this script:')
+ cli.echo(' {fg_cyan}python3 -m pip install english_words')
+ # Use a minimal word list as a fallback.
+ correct_words = ('information', 'available', 'international', 'language', 'loosest', 'reference', 'wealthier', 'entertainment', 'association', 'provides', 'technology', 'statehood')
+
+ autocorrections = []
+ typos = set()
+ for line_number, typo, correction in parse_file_lines(file_name):
+ if typo in typos:
+ cli.log.warning('{fg_red}Error:%d:{fg_reset} Ignoring duplicate typo: "{fg_cyan}%s{fg_reset}"', line_number, typo)
+ continue
+
+ # Check that `typo` is valid.
+ if not (all([c in TYPO_CHARS for c in typo])):
+ cli.log.error('{fg_red}Error:%d:{fg_reset} Typo "{fg_cyan}%s{fg_reset}" has characters other than a-z, \' and :.', line_number, typo)
+ sys.exit(1)
+ for other_typo in typos:
+ if typo in other_typo or other_typo in typo:
+ cli.log.error('{fg_red}Error:%d:{fg_reset} Typos may not be substrings of one another, otherwise the longer typo would never trigger: "{fg_cyan}%s{fg_reset}" vs. "{fg_cyan}%s{fg_reset}".', line_number, typo, other_typo)
+ sys.exit(1)
+ if len(typo) < 5:
+ cli.log.warning('{fg_yellow}Warning:%d:{fg_reset} It is suggested that typos are at least 5 characters long to avoid false triggers: "{fg_cyan}%s{fg_reset}"', line_number, typo)
+ if len(typo) > 127:
+ cli.log.error('{fg_red}Error:%d:{fg_reset} Typo exceeds 127 chars: "{fg_cyan}%s{fg_reset}"', line_number, typo)
+ sys.exit(1)
+
+ check_typo_against_dictionary(typo, line_number, correct_words)
+
+ autocorrections.append((typo, correction))
+ typos.add(typo)
+
+ return autocorrections
+
+
+def make_trie(autocorrections: List[Tuple[str, str]]) -> Dict[str, Any]:
+ """Makes a trie from the the typos, writing in reverse.
+ Args:
+ autocorrections: List of (typo, correction) tuples.
+ Returns:
+ Dict of dict, representing the trie.
+ """
+ trie = {}
+ for typo, correction in autocorrections:
+ node = trie
+ for letter in typo[::-1]:
+ node = node.setdefault(letter, {})
+ node['LEAF'] = (typo, correction)
+
+ return trie
+
+
+def parse_file_lines(file_name: str) -> Iterator[Tuple[int, str, str]]:
+ """Parses lines read from `file_name` into typo-correction pairs."""
+
+ line_number = 0
+ for line in open(file_name, 'rt'):
+ line_number += 1
+ line = line.strip()
+ if line and line[0] != '#':
+ # Parse syntax "typo -> correction", using strip to ignore indenting.
+ tokens = [token.strip() for token in line.split('->', 1)]
+ if len(tokens) != 2 or not tokens[0]:
+ print(f'Error:{line_number}: Invalid syntax: "{line}"')
+ sys.exit(1)
+
+ typo, correction = tokens
+ typo = typo.lower() # Force typos to lowercase.
+ typo = typo.replace(' ', ':')
+
+ yield line_number, typo, correction
+
+
+def check_typo_against_dictionary(typo: str, line_number: int, correct_words) -> None:
+ """Checks `typo` against English dictionary words."""
+
+ if typo.startswith(':') and typo.endswith(':'):
+ if typo[1:-1] in correct_words:
+ cli.log.warning('{fg_yellow}Warning:%d:{fg_reset} Typo "{fg_cyan}%s{fg_reset}" is a correctly spelled dictionary word.', line_number, typo)
+ elif typo.startswith(':') and not typo.endswith(':'):
+ for word in correct_words:
+ if word.startswith(typo[1:]):
+ cli.log.warning('{fg_yellow}Warning:%d: {fg_reset}Typo "{fg_cyan}%s{fg_reset}" would falsely trigger on correctly spelled word "{fg_cyan}%s{fg_reset}".', line_number, typo, word)
+ elif not typo.startswith(':') and typo.endswith(':'):
+ for word in correct_words:
+ if word.endswith(typo[:-1]):
+ cli.log.warning('{fg_yellow}Warning:%d:{fg_reset} Typo "{fg_cyan}%s{fg_reset}" would falsely trigger on correctly spelled word "{fg_cyan}%s{fg_reset}".', line_number, typo, word)
+ elif not typo.startswith(':') and not typo.endswith(':'):
+ for word in correct_words:
+ if typo in word:
+ cli.log.warning('{fg_yellow}Warning:%d:{fg_reset} Typo "{fg_cyan}%s{fg_reset}" would falsely trigger on correctly spelled word "{fg_cyan}%s{fg_reset}".', line_number, typo, word)
+
+
+def serialize_trie(autocorrections: List[Tuple[str, str]], trie: Dict[str, Any]) -> List[int]:
+ """Serializes trie and correction data in a form readable by the C code.
+ Args:
+ autocorrections: List of (typo, correction) tuples.
+ trie: Dict of dicts.
+ Returns:
+ List of ints in the range 0-255.
+ """
+ table = []
+
+ # Traverse trie in depth first order.
+ def traverse(trie_node):
+ if 'LEAF' in trie_node: # Handle a leaf trie node.
+ typo, correction = trie_node['LEAF']
+ word_boundary_ending = typo[-1] == ':'
+ typo = typo.strip(':')
+ i = 0 # Make the autocorrection data for this entry and serialize it.
+ while i < min(len(typo), len(correction)) and typo[i] == correction[i]:
+ i += 1
+ backspaces = len(typo) - i - 1 + word_boundary_ending
+ assert 0 <= backspaces <= 63
+ correction = correction[i:]
+ bs_count = [backspaces + 128]
+ data = bs_count + list(bytes(correction, 'ascii')) + [0]
+
+ entry = {'data': data, 'links': [], 'byte_offset': 0}
+ table.append(entry)
+ elif len(trie_node) == 1: # Handle trie node with a single child.
+ c, trie_node = next(iter(trie_node.items()))
+ entry = {'chars': c, 'byte_offset': 0}
+
+ # It's common for a trie to have long chains of single-child nodes. We
+ # find the whole chain so that we can serialize it more efficiently.
+ while len(trie_node) == 1 and 'LEAF' not in trie_node:
+ c, trie_node = next(iter(trie_node.items()))
+ entry['chars'] += c
+
+ table.append(entry)
+ entry['links'] = [traverse(trie_node)]
+ else: # Handle trie node with multiple children.
+ entry = {'chars': ''.join(sorted(trie_node.keys())), 'byte_offset': 0}
+ table.append(entry)
+ entry['links'] = [traverse(trie_node[c]) for c in entry['chars']]
+ return entry
+
+ traverse(trie)
+
+ def serialize(e: Dict[str, Any]) -> List[int]:
+ if not e['links']: # Handle a leaf table entry.
+ return e['data']
+ elif len(e['links']) == 1: # Handle a chain table entry.
+ return [TYPO_CHARS[c] for c in e['chars']] + [0] # + encode_link(e['links'][0]))
+ else: # Handle a branch table entry.
+ data = []
+ for c, link in zip(e['chars'], e['links']):
+ data += [TYPO_CHARS[c] | (0 if data else 64)] + encode_link(link)
+ return data + [0]
+
+ byte_offset = 0
+ for e in table: # To encode links, first compute byte offset of each entry.
+ e['byte_offset'] = byte_offset
+ byte_offset += len(serialize(e))
+ assert 0 <= byte_offset <= 0xffff
+
+ return [b for e in table for b in serialize(e)] # Serialize final table.
+
+
+def encode_link(link: Dict[str, Any]) -> List[int]:
+ """Encodes a node link as two bytes."""
+ byte_offset = link['byte_offset']
+ if not (0 <= byte_offset <= 0xffff):
+ cli.log.error('{fg_red}Error:{fg_reset} The autocorrection table is too large, a node link exceeds 64KB limit. Try reducing the autocorrection dict to fewer entries.')
+ sys.exit(1)
+ return [byte_offset & 255, byte_offset >> 8]
+
+
+def write_generated_code(autocorrections: List[Tuple[str, str]], data: List[int], file_name: str) -> None:
+ """Writes autocorrection data as generated C code to `file_name`.
+ Args:
+ autocorrections: List of (typo, correction) tuples.
+ data: List of ints in 0-255, the serialized trie.
+ file_name: String, path of the output C file.
+ """
+ assert all(0 <= b <= 255 for b in data)
+
+ def typo_len(e: Tuple[str, str]) -> int:
+ return len(e[0])
+
+ min_typo = min(autocorrections, key=typo_len)[0]
+ max_typo = max(autocorrections, key=typo_len)[0]
+ generated_code = ''.join([
+ '// Generated code.\n\n', f'// Autocorrection dictionary ({len(autocorrections)} entries):\n', ''.join(sorted(f'// {typo:<{len(max_typo)}} -> {correction}\n' for typo, correction in autocorrections)),
+ f'\n#define AUTOCORRECT_MIN_LENGTH {len(min_typo)} // "{min_typo}"\n', f'#define AUTOCORRECT_MAX_LENGTH {len(max_typo)} // "{max_typo}"\n\n', f'#define DICTIONARY_SIZE {len(data)}\n\n',
+ textwrap.fill('static const uint8_t autocorrect_data[DICTIONARY_SIZE] PROGMEM = {%s};' % (', '.join(map(str, data))), width=120, subsequent_indent=' '), '\n\n'
+ ])
+
+ with open(file_name, 'wt') as f:
+ f.write(generated_code)
+
+
+@cli.argument('filename', default='autocorrect_dict.txt', help='The autocorrection database file')
+@cli.argument('-kb', '--keyboard', type=keyboard_folder, completer=keyboard_completer, help='The keyboard to build a firmware for. Ignored when a configurator export is supplied.')
+@cli.argument('-km', '--keymap', completer=keymap_completer, help='The keymap to build a firmware for. Ignored when a configurator export is supplied.')
+@cli.argument('-o', '--output', arg_only=True, type=qmk.path.normpath, help='File to write to')
+@cli.subcommand('Generate the autocorrection data file from a dictionary file.')
+def generate_autocorrect_data(cli):
+ autocorrections = parse_file(cli.args.filename)
+ trie = make_trie(autocorrections)
+ data = serialize_trie(autocorrections, trie)
+ # Environment processing
+ if cli.args.output == '-':
+ cli.args.output = None
+
+ if cli.args.output:
+ cli.args.output.parent.mkdir(parents=True, exist_ok=True)
+ cli.log.info('Creating autocorrect database at {fg_cyan}%s', cli.args.output)
+ write_generated_code(autocorrections, data, cli.args.output)
+
+ else:
+ current_keyboard = cli.args.keyboard or cli.config.user.keyboard or cli.config.generate_autocorrect_data.keyboard
+ current_keymap = cli.args.keymap or cli.config.user.keymap or cli.config.generate_autocorrect_data.keymap
+
+ if current_keyboard and current_keymap:
+ filename = locate_keymap(current_keyboard, current_keymap).parent / 'autocorrect_data.h'
+ cli.log.info('Creating autocorrect database at {fg_cyan}%s', filename)
+ write_generated_code(autocorrections, data, filename)
+
+ else:
+ write_generated_code(autocorrections, data, 'autocorrect_data.h')
+
+ cli.log.info('Processed %d autocorrection entries to table with %d bytes.', len(autocorrections), len(data))
diff --git a/lib/python/qmk/cli/generate/config_h.py b/lib/python/qmk/cli/generate/config_h.py
index a26dcdf7d7..31b8d70635 100755
--- a/lib/python/qmk/cli/generate/config_h.py
+++ b/lib/python/qmk/cli/generate/config_h.py
@@ -1,18 +1,27 @@
"""Used by the make system to generate info_config.h from info.json.
"""
from pathlib import Path
-
from dotty_dict import dotty
+
+from argcomplete.completers import FilesCompleter
from milc import cli
-from qmk.info import info_json, keymap_json_config
+from qmk.info import info_json
from qmk.json_schema import json_load
from qmk.keyboard import keyboard_completer, keyboard_folder
-from qmk.commands import dump_lines
-from qmk.path import normpath
+from qmk.commands import dump_lines, parse_configurator_json
+from qmk.path import normpath, FileType
from qmk.constants import GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE
+def generate_define(define, value=None):
+ value = f' {value}' if value is not None else ''
+ return f"""
+#ifndef {define}
+# define {define}{value}
+#endif // {define}"""
+
+
def direct_pins(direct_pins, postfix):
"""Return the config.h lines that set the direct pins.
"""
@@ -22,11 +31,7 @@ def direct_pins(direct_pins, postfix):
cols = ','.join(map(str, [col or 'NO_PIN' for col in row]))
rows.append('{' + cols + '}')
- return f"""
-#ifndef DIRECT_PINS{postfix}
-# define DIRECT_PINS{postfix} {{ {", ".join(rows)} }}
-#endif // DIRECT_PINS{postfix}
-"""
+ return generate_define(f'DIRECT_PINS{postfix}', f'{{ {", ".join(rows)} }}')
def pin_array(define, pins, postfix):
@@ -34,11 +39,7 @@ def pin_array(define, pins, postfix):
"""
pin_array = ', '.join(map(str, [pin or 'NO_PIN' for pin in pins]))
- return f"""
-#ifndef {define}_PINS{postfix}
-# define {define}_PINS{postfix} {{ {pin_array} }}
-#endif // {define}_PINS{postfix}
-"""
+ return generate_define(f'{define}_PINS{postfix}', f'{{ {pin_array} }}')
def matrix_pins(matrix_pins, postfix=''):
@@ -62,24 +63,14 @@ def generate_matrix_size(kb_info_json, config_h_lines):
"""Add the matrix size to the config.h.
"""
if 'matrix_pins' in kb_info_json:
- col_count = kb_info_json['matrix_size']['cols']
- row_count = kb_info_json['matrix_size']['rows']
-
- config_h_lines.append(f"""
-#ifndef MATRIX_COLS
-# define MATRIX_COLS {col_count}
-#endif // MATRIX_COLS
-
-#ifndef MATRIX_ROWS
-# define MATRIX_ROWS {row_count}
-#endif // MATRIX_ROWS
-""")
+ config_h_lines.append(generate_define('MATRIX_COLS', kb_info_json['matrix_size']['cols']))
+ config_h_lines.append(generate_define('MATRIX_ROWS', kb_info_json['matrix_size']['rows']))
def generate_config_items(kb_info_json, config_h_lines):
"""Iterate through the info_config map to generate basic config values.
"""
- info_config_map = json_load(Path('data/mappings/info_config.json'))
+ info_config_map = json_load(Path('data/mappings/info_config.hjson'))
for config_key, info_dict in info_config_map.items():
info_key = info_dict['info_key']
@@ -95,43 +86,23 @@ def generate_config_items(kb_info_json, config_h_lines):
continue
if key_type.startswith('array.array'):
- config_h_lines.append('')
- config_h_lines.append(f'#ifndef {config_key}')
- config_h_lines.append(f'# define {config_key} {{ {", ".join(["{" + ",".join(list(map(str, x))) + "}" for x in config_value])} }}')
- config_h_lines.append(f'#endif // {config_key}')
+ config_h_lines.append(generate_define(config_key, f'{{ {", ".join(["{" + ",".join(list(map(str, x))) + "}" for x in config_value])} }}'))
elif key_type.startswith('array'):
- config_h_lines.append('')
- config_h_lines.append(f'#ifndef {config_key}')
- config_h_lines.append(f'# define {config_key} {{ {", ".join(map(str, config_value))} }}')
- config_h_lines.append(f'#endif // {config_key}')
+ config_h_lines.append(generate_define(config_key, f'{{ {", ".join(map(str, config_value))} }}'))
elif key_type == 'bool':
if config_value:
- config_h_lines.append('')
- config_h_lines.append(f'#ifndef {config_key}')
- config_h_lines.append(f'# define {config_key}')
- config_h_lines.append(f'#endif // {config_key}')
+ config_h_lines.append(generate_define(config_key))
elif key_type == 'mapping':
for key, value in config_value.items():
- config_h_lines.append('')
- config_h_lines.append(f'#ifndef {key}')
- config_h_lines.append(f'# define {key} {value}')
- config_h_lines.append(f'#endif // {key}')
+ config_h_lines.append(generate_define(key, value))
elif key_type == 'str':
- config_h_lines.append('')
- config_h_lines.append(f'#ifndef {config_key}')
- config_h_lines.append(f'# define {config_key} "{config_value}"')
- config_h_lines.append(f'#endif // {config_key}')
+ escaped_str = config_value.replace('\\', '\\\\').replace('"', '\\"')
+ config_h_lines.append(generate_define(conf