aboutsummaryrefslogtreecommitdiff
path: root/lib/python
diff options
context:
space:
mode:
Diffstat (limited to 'lib/python')
-rw-r--r--lib/python/qmk/cli/__init__.py1
-rwxr-xr-xlib/python/qmk/cli/generate/keyboard_c.py138
-rwxr-xr-xlib/python/qmk/cli/generate/keyboard_h.py19
-rwxr-xr-xlib/python/qmk/cli/new/keymap.py6
-rw-r--r--lib/python/qmk/cli/resolve_alias.py16
-rwxr-xr-xlib/python/qmk/cli/via2json.py32
-rw-r--r--lib/python/qmk/flashers.py7
7 files changed, 182 insertions, 37 deletions
diff --git a/lib/python/qmk/cli/__init__.py b/lib/python/qmk/cli/__init__.py
index 2d63dfb447..bb47ea26ed 100644
--- a/lib/python/qmk/cli/__init__.py
+++ b/lib/python/qmk/cli/__init__.py
@@ -82,6 +82,7 @@ subcommands = [
'qmk.cli.new.keymap',
'qmk.cli.painter',
'qmk.cli.pytest',
+ 'qmk.cli.resolve_alias',
'qmk.cli.test.c',
'qmk.cli.userspace.add',
'qmk.cli.userspace.compile',
diff --git a/lib/python/qmk/cli/generate/keyboard_c.py b/lib/python/qmk/cli/generate/keyboard_c.py
index 228b320942..1978de4a22 100755
--- a/lib/python/qmk/cli/generate/keyboard_c.py
+++ b/lib/python/qmk/cli/generate/keyboard_c.py
@@ -1,5 +1,9 @@
"""Used by the make system to generate keyboard.c from info.json.
"""
+import bisect
+import dataclasses
+from typing import Optional
+
from milc import cli
from qmk.info import info_json
@@ -87,6 +91,7 @@ def _gen_matrix_mask(info_data):
lines.append(f' 0b{"".join(reversed(mask[i]))},')
lines.append('};')
lines.append('#endif')
+ lines.append('')
return lines
@@ -122,6 +127,128 @@ def _gen_joystick_axes(info_data):
lines.append('};')
lines.append('#endif')
+ lines.append('')
+
+ return lines
+
+
+class LayoutKey:
+ """Geometric info for one key in a layout."""
+ row: int
+ col: int
+ x: float
+ y: float
+ w: float = 1.0
+ h: float = 1.0
+ hand: Optional[str] = None
+
+ @staticmethod
+ def from_json(key_json):
+ row, col = key_json['matrix']
+ return LayoutKey(
+ row=row,
+ col=col,
+ x=key_json['x'],
+ y=key_json['y'],
+ w=key_json.get('w', 1.0),
+ h=key_json.get('h', 1.0),
+ hand=key_json.get('hand', None),
+ )
+
+ @property
+ def cx(self):
+ """Center x coordinate of the key."""
+ return self.x + self.w / 2.0
+
+ @property
+ def cy(self):
+ """Center y coordinate of the key."""
+ return self.y + self.h / 2.0
+
+
+class Layout:
+ """Geometric info of a layout."""
+ def __init__(self, layout_json):
+ self.keys = [LayoutKey.from_json(key_json) for key_json in layout_json['layout']]
+ self.x_min = min(key.cx for key in self.keys)
+ self.x_max = max(key.cx for key in self.keys)
+ self.x_mid = (self.x_min + self.x_max) / 2
+ # If there is one key with width >= 6u, it is probably the spacebar.
+ i = [i for i, key in enumerate(self.keys) if key.w >= 6.0]
+ self.spacebar = self.keys[i[0]] if len(i) == 1 else None
+
+ def is_symmetric(self, tol: float = 0.02):
+ """Whether the key positions are symmetric about x_mid."""
+ x = sorted([key.cx for key in self.keys])
+ for i in range(len(x)):
+ x_i_mirrored = 2.0 * self.x_mid - x[i]
+ # Find leftmost x element greater than or equal to (x_i_mirrored - tol).
+ j = bisect.bisect_left(x, x_i_mirrored - tol)
+ if j == len(x) or abs(x[j] - x_i_mirrored) > tol:
+ return False
+
+ return True
+
+ def widest_horizontal_gap(self):
+ """Finds the x midpoint of the widest horizontal gap between keys."""
+ x = sorted([key.cx for key in self.keys])
+ x_mid = self.x_mid
+ max_sep = 0
+ for i in range(len(x) - 1):
+ sep = x[i + 1] - x[i]
+ if sep > max_sep:
+ max_sep = sep
+ x_mid = (x[i + 1] + x[i]) / 2
+
+ return x_mid
+
+
+def _gen_chordal_hold_layout(info_data):
+ """Convert info.json content to chordal_hold_layout
+ """
+ # NOTE: If there are multiple layouts, only the first is read.
+ for layout_name, layout_json in info_data['layouts'].items():
+ layout = Layout(layout_json)
+ break
+
+ if layout.is_symmetric():
+ # If the layout is symmetric (e.g. most split keyboards), guess the
+ # handedness based on the sign of (x - layout.x_mid).
+ hand_signs = [key.x - layout.x_mid for key in layout.keys]
+ elif layout.spacebar is not None:
+ # If the layout has a spacebar, form a dividing line through the spacebar,
+ # nearly vertical but with a slight angle to follow typical row stagger.
+ x0 = layout.spacebar.cx - 0.05
+ y0 = layout.spacebar.cy - 1.0
+ hand_signs = [(key.x - x0) - (key.y - y0) / 3.0 for key in layout.keys]
+ else:
+ # Fallback: assume handedness based on the widest horizontal separation.
+ x_mid = layout.widest_horizontal_gap()
+ hand_signs = [key.x - x_mid for key in layout.keys]
+
+ for key, hand_sign in zip(layout.keys, hand_signs):
+ if key.hand is None:
+ if key == layout.spacebar or abs(hand_sign) <= 0.02:
+ key.hand = '*'
+ else:
+ key.hand = 'L' if hand_sign < 0.0 else 'R'
+
+ lines = []
+ lines.append('#ifdef CHORDAL_HOLD')
+ line = ('__attribute__((weak)) const char chordal_hold_layout[MATRIX_ROWS][MATRIX_COLS] PROGMEM = ' + layout_name + '(')
+
+ x_prev = None
+ for key in layout.keys:
+ if x_prev is None or key.x < x_prev:
+ lines.append(line)
+ line = ' '
+ line += f"'{key.hand}', "
+ x_prev = key.x
+
+ lines.append(line[:-2])
+ lines.append(');')
+ lines.append('#endif')
return lines
@@ -136,11 +263,12 @@ def generate_keyboard_c(cli):
kb_info_json = info_json(cli.args.keyboard)
# Build the layouts.h file.
- keyboard_h_lines = [GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE, '#include QMK_KEYBOARD_H', '']
+ keyboard_c_lines = [GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE, '#include QMK_KEYBOARD_H', '']
- keyboard_h_lines.extend(_gen_led_configs(kb_info_json))
- keyboard_h_lines.extend(_gen_matrix_mask(kb_info_json))
- keyboard_h_lines.extend(_gen_joystick_axes(kb_info_json))
+ keyboard_c_lines.extend(_gen_led_configs(kb_info_json))
+ keyboard_c_lines.extend(_gen_matrix_mask(kb_info_json))
+ keyboard_c_lines.extend(_gen_joystick_axes(kb_info_json))
+ keyboard_c_lines.extend(_gen_chordal_hold_layout(kb_info_json))
# Show the results
- dump_lines(cli.args.output, keyboard_h_lines, cli.args.quiet)
+ dump_lines(cli.args.output, keyboard_c_lines, cli.args.quiet)
diff --git a/lib/python/qmk/cli/generate/keyboard_h.py b/lib/python/qmk/cli/generate/keyboard_h.py
index 5863a0983a..cb9528d96b 100755
--- a/lib/python/qmk/cli/generate/keyboard_h.py
+++ b/lib/python/qmk/cli/generate/keyboard_h.py
@@ -22,6 +22,11 @@ def _generate_layouts(keyboard, kb_info_json):
row_num = kb_info_json['matrix_size']['rows']
lines = []
+ lines.append('')
+ lines.append('// Layout content')
+ lines.append('')
+ lines.append('#define XXX KC_NO')
+
for layout_name, layout_data in kb_info_json['layouts'].items():
if layout_data['c_macro']:
continue
@@ -31,7 +36,7 @@ def _generate_layouts(keyboard, kb_info_json):
continue
layout_keys = []
- layout_matrix = [['KC_NO'] * col_num for _ in range(row_num)]
+ layout_matrix = [['XXX'] * col_num for _ in range(row_num)]
for key_data in layout_data['layout']:
row, col = key_data['matrix']
@@ -46,7 +51,7 @@ def _generate_layouts(keyboard, kb_info_json):
lines.append('')
lines.append(f'#define {layout_name}({", ".join(layout_keys)}) {{ \\')
- rows = ', \\\n'.join(['\t {' + ', '.join(row) + '}' for row in layout_matrix])
+ rows = ', \\\n'.join([' { ' + ', '.join(row) + ' }' for row in layout_matrix])
rows += ' \\'
lines.append(rows)
lines.append('}')
@@ -67,6 +72,9 @@ def _generate_keycodes(kb_info_json):
return []
lines = []
+ lines.append('')
+ lines.append('// Keycode content')
+ lines.append('')
lines.append('enum keyboard_keycodes {')
for index, item in enumerate(kb_info_json.get('keycodes')):
@@ -103,17 +111,14 @@ def generate_keyboard_h(cli):
valid_config = dd_layouts or keyboard_h
# Build the layouts.h file.
- keyboard_h_lines = [GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE, '#pragma once', '#include "quantum.h"']
+ keyboard_h_lines = [GPL2_HEADER_C_LIKE, GENERATED_HEADER_C_LIKE, '#pragma once', '', '#include "quantum.h"']
- keyboard_h_lines.append('')
- keyboard_h_lines.append('// Layout content')
if dd_layouts:
keyboard_h_lines.extend(dd_layouts)
+
if keyboard_h:
keyboard_h_lines.append(f'#include "{Path(keyboard_h).name}"')
- keyboard_h_lines.append('')
- keyboard_h_lines.append('// Keycode content')
if dd_keycodes:
keyboard_h_lines.extend(dd_keycodes)
diff --git a/lib/python/qmk/cli/new/keymap.py b/lib/python/qmk/cli/new/keymap.py
index f1df05636c..8b7160f5f2 100755
--- a/lib/python/qmk/cli/new/keymap.py
+++ b/lib/python/qmk/cli/new/keymap.py
@@ -23,19 +23,17 @@ def validate_keymap_name(name):
def prompt_keyboard():
prompt = """{fg_yellow}Select Keyboard{style_reset_all}
-If you`re unsure you can view a full list of supported keyboards with {fg_yellow}qmk list-keyboards{style_reset_all}.
+If you're unsure you can view a full list of supported keyboards with {fg_yellow}qmk list-keyboards{style_reset_all}.
Keyboard Name? """
-
return question(prompt)
def prompt_user():
prompt = """
{fg_yellow}Name Your Keymap{style_reset_all}
-Used for maintainer, copyright, etc
-Your GitHub Username? """
+Keymap name? """
return question(prompt, default=git_get_username())
diff --git a/lib/python/qmk/cli/resolve_alias.py b/lib/python/qmk/cli/resolve_alias.py
new file mode 100644
index 0000000000..b9ffb46618
--- /dev/null
+++ b/lib/python/qmk/cli/resolve_alias.py
@@ -0,0 +1,16 @@
+from qmk.keyboard import keyboard_folder
+
+from milc import cli
+
+
[email protected]('--allow-unknown', arg_only=True, action='store_true', help="Return original if rule is not a valid keyboard.")
[email protected]('keyboard', arg_only=True, help='The keyboard\'s name')
[email protected]('Resolve DEFAULT_FOLDER and any keyboard_aliases for provided rule')
+def resolve_alias(cli):
+ try:
+ print(keyboard_folder(cli.args.keyboard))
+ except ValueError:
+ if cli.args.allow_unknown:
+ print(cli.args.keyboard)
+ else:
+ raise
diff --git a/lib/python/qmk/cli/via2json.py b/lib/python/qmk/cli/via2json.py
index 537e102640..0997e9ca9f 100755
--- a/lib/python/qmk/cli/via2json.py
+++ b/lib/python/qmk/cli/via2json.py
@@ -9,19 +9,15 @@ import qmk.keyboard
import qmk.path
from qmk.info import info_json
from qmk.json_encoders import KeymapJSONEncoder
-from qmk.commands import parse_configurator_json, dump_lines
-from qmk.keymap import generate_json, list_keymaps, locate_keymap, parse_keymap_c
+from qmk.commands import dump_lines
+from qmk.keymap import generate_json
-def _find_via_layout_macro(keyboard):
- keymap_layout = None
- if 'via' in list_keymaps(keyboard):
- keymap_path = locate_keymap(keyboard, 'via')
- if keymap_path.suffix == '.json':
- keymap_layout = parse_configurator_json(keymap_path)['layout']
- else:
- keymap_layout = parse_keymap_c(keymap_path)['layers'][0]['layout']
- return keymap_layout
+def _find_via_layout_macro(keyboard_data):
+ """Assume layout macro when only 1 is available
+ """
+ layouts = list(keyboard_data['layouts'].keys())
+ return layouts[0] if len(layouts) == 1 else None
def _convert_macros(via_macros):
@@ -130,20 +126,16 @@ def via2json(cli):
This command uses the `qmk.keymap` module to generate a keymap.json from a VIA backup json. The generated keymap is written to stdout, or to a file if -o is provided.
"""
- # Find appropriate layout macro
- keymap_layout = cli.args.layout if cli.args.layout else _find_via_layout_macro(cli.args.keyboard)
- if not keymap_layout:
- cli.log.error(f"Couldn't find LAYOUT macro for keyboard {cli.args.keyboard}. Please specify it with the '-l' argument.")
- return False
-
# Load the VIA backup json
with cli.args.filename.open('r') as fd:
via_backup = json.load(fd)
- # Generate keyboard metadata
keyboard_data = info_json(cli.args.keyboard)
- if not keyboard_data:
- cli.log.error(f'LAYOUT macro {keymap_layout} is not a valid one for keyboard {cli.args.keyboard}!')
+
+ # Find appropriate layout macro
+ keymap_layout = cli.args.layout if cli.args.layout else _find_via_layout_macro(keyboard_data)
+ if not keymap_layout:
+ cli.log.error(f"Couldn't find LAYOUT macro for keyboard {cli.args.keyboard}. Please specify it with the '-l' argument.")
return False
# Get keycode array
diff --git a/lib/python/qmk/flashers.py b/lib/python/qmk/flashers.py
index 7ee1bc8de7..2cca4941d3 100644
--- a/lib/python/qmk/flashers.py
+++ b/lib/python/qmk/flashers.py
@@ -202,6 +202,10 @@ def _flash_mdloader(file):
def _flash_uf2(file):
+ output = cli.run(['util/uf2conv.py', '--info', file]).stdout
+ if 'UF2 File' not in output:
+ return True
+
cli.run(['util/uf2conv.py', '--deploy', file], capture_output=False)
@@ -235,7 +239,8 @@ def flasher(mcu, file):
elif bl == 'md-boot':
_flash_mdloader(file)
elif bl == '_uf2_compatible_':
- _flash_uf2(file)
+ if _flash_uf2(file):
+ return (True, "Flashing only supports uf2 format files.")
else:
return (True, "Known bootloader found but flashing not currently supported!")