Files
zmk/app/src/physical_layouts.c
Pete Johanson c06fa48ce5 feat!: Move to zephyr v4.1 (#3060)
refactor: Move to Zephyr v4.1.0

Move to Zephyr v4.1.0, with various build/compilation fixes needed for
basic use.

refactor(tests): Move to native_sim for tests.

feat(core): (Optionally) use Zephyr keyboard input devices

Add ability to assign a keyboard `input` device to a physical layout,
or use a chosen `zmk,matrix-input`.

fix(pointing): Refactor for changes to input API

Pass NULL user_data to input callbacks.

fix(tests): Fix BLE test to account for Zephyr changes

Handle additional read callback invocation once all matching
characteristic have been read.

fix(sensors): Initialize sensor data to 0 before fetching.

Be sure we don't get back any uninitialized data by initializing
the channel data to 0 before calling into the sensor API.

refactor(input): Adjust split input to input API changes.

Input callbacks now have a user_data parameter, adjust accordingly.

chore(bluetooth): Minor cleanup of split BT code after refactor

Small fixes and remove commented dead code left after the split
refactor.

refactor: Fix up BLE tests after Zephyr upgrade.

Minor changes to snapshots based on newer Zephyr version.

refactor(boards): Move to upstream xiao_ble board ID.

Move to official upstream board definition for the Seeed XIAO BLE.

refactor: Adjust metadata schema for HWMv2 board IDs w/ qualifiers

Adjust our ZMK metadata to allow for board IDs that include qualifiers
with slash delimeters.

refactor!(boards): Move nice!nano to HWMv2, and proper revisioning

Upgrade the nice!nano board to HWMv2, under the proper nicekeyboards
vendor directory, and with proper revisions. Includes a breaking change
to default the `2.0.0` version instead of the much older v1 (`1.0.0`).

fix: Disable Nordic dt-bindings header checks.

Disable the recently added Nordic dt-bindings header checks, which cause
issues for our HID related headers.

fix(studio): Correct `memset` usage.

Use the correct memset call to clear our RPC memory.

fix: Refactor for new Zephyr PM API

Adjustments to our PM code to match Zephyr PM APIs.

refactor(ble): Use correct BT opt for connectable.

Adjust for upstream Zephyr BT API changes for advertising options.

refactor(boards): Move MakerDiary M2 board to HWMv2.

Run the HWMv2 script to convert the MakerDiary M2 board.

fix(studio): Correct usage of thread analyzer API

Fix up the RPC code that invoke the thread analyzer API to account for
API changes.

chore: Remove nanopb module override.

Leverage nanopb version that's used by Zephyr.

feat(core): mapper for magic bootloader values.

To trigger bootloaders that use a magic value in RAM to trigger
bootloader mode, add a mapping retained memory driver that maps
write/read of boot mode values to a special magic value stored
in the actually backing RAM.

feat(behaviors): Add retention boot mode to reset.

Support new generic Zephyr retention boot mode API in the reset
behavior.

feat: Add double tap to enter bootloader functionality

Add ability to enter the bootloader if double tapping reset within the
specified window.

refactor(CI): Move to 4.1 container tags.

Move to the new 4.1 tagged container, to ensure updated SDK, Python
packages, etc.

refactor(boards): Move nRFMicro to HWMv2

Refactor nRFMicro to HWMv2, using proper SoC, revisions, and variants
(for flipped). Also move to devicetree setup of DCDC/HV DCDC.

refactor(boards): Move QMK Proton-C to HWMv2

Move Proton-C to HWMv2 for use with Zephyr 4.1.

chore(ci): Adjust core coverage for new board IDs.

Use correct board IDs, with qualifiers, for our core coverage testing.

refactor(boards): Move BDN9 to HWMv2

Move BDN9 to HWMv2, using the base `bdn9` ID, no longer including the
`_rev2` suffix in the ID.

refactor(boards): Move nice!60 to HWMv2

Migrate nice!60 to HWMv2.

refactor: Adjust how we're searching/loading keymap files

Use new post_boards_shields extension point for loading keymap files
from board/shield directories.

refactor(boards): Move planck rev6 to HWMv2.

Move Planck board definition to HWMv2, including versioning tweaks.

refactor(boards): Move OLKB Preonic to HWMv2

Move Preonic board definition to HWMv2 and remove `_rev3` variant
suffix in favor of board versioning with `3.0.0` as the default.

chore(deps): Pull in Zephyr optional group for nanopb.

Ensure we enable nanopb by adding +optional group filter.

fix(ci): Prevent slash characters in artifact names.

Move to HWMv2 means board IDs often include slashes, so replace those
with underscores when doing file uploads.

fix(usb): Adjust Kconfig settings for USB.

* Ensure USB isn't initialized automatically before we do, which can
  happen if USB CDC logging is used/enabled for a given board.
* Adjust USB HID to initialize the USB class/interface before we enable
  the USB device itself.

fix(display): Fix setting the small font for the mono theme.

Adjust for modified mono theme init function to pass the small font.

chore(ci): Fix changed board IDs for core coverage.

Adjust board IDs for our core coverage after move to HWMv2 and board
versioning consistently.

* planck_rev6 -> planck
* bdn9_rev2 -> bdn9

fix(underglow): Remove use of removed Kconfig WS2812 symbol

refactor(boards): Move PW CKP boards to HWMv2

Migrate the bt60, bt65, and bt75 to HWMv2.

refactor(boards): Move Puchi BLE to HWMv2

Migrate the Puchi BLE to HWMv2.

refactor(boards): Migrate Ferris rev02 to HWMv2.

Move Ferris rev02 to HMWv2, and remove the revision from the ID.

refactor(boards): Move Pillbug to HWMv2

Migrate the MechWild PillBug board to HWMv2.

refactor(boards): Migrate s40nc to HWMv2

Move the ShortyFortyNoCordy (s40nc) to HWMv2.

refactor(boards): Move bluemicro840 board to HWMv2.

Migrate bluemicro840 board to HWMv2, set up boot mode retention.

fix(boards): Retore bootloader support on XIAO BLE.

Set up necessary boot mode/retention to properly set GPREGRET to trigger
Adafruit bootloader to run on the XIAO BLE.

refactor(boards): Move Adv360 Pro to HWMv2.

Migrate Adv360 Pro left/right to HWMv2.

refactor(boards): Move Glove80 to HMWv2

Refactor the MoErgo Glove80 left/right to HWMv2.

refactor(boards): Move Mikoto to HMWv2.

Migrate Mikoto to HWMv2, with non-exact matching, tweaks to I2C
selection to imply it for the 7.2.0 revision for the fuel gauge.

refactor(boards): Move kbdfans Tofu65 2.0 to HMWv2

Move Tofu65 2.0 to HMWv2, with ID of just `tofu65`.

refactor(boards): Remove dz60rgb board

Remove dz60rgb, it's no longer readily available and we have other
current stm32 reference designs for testing.

refactor(boards): Move Corneish Zen to HMWv2

Move Corneish Zen to HMWv2, with IDs of
`corneish_zen_left`/`corneish_zen_right`.

refactor(boards): Migrate Corne-ish Zen status screen

* refactor(boards): Add boot mode to the nice!nano using common dtsi

* Add a new .dtsi for setting up nRF52 boot mode/retained memory
  settings
* Adjust XIAO BLE to use the new include file
* Add boot mode to to the nice!nano

refactor(boards): Add boot mode support to nice!60 board

Enable boot mode for nice!60 board.

refactor(boards): Adjust Zephyr board metadata file locations

Move the ZMK metadata files for upstream Zephyr boards to align with the
HWMv2 directory structure that uses the vendor ID for the parent
directory for a board directory.

fix: Don't enable ZMK Display by default for a few shields

By convention, avoid enabling ZMK Display by default on shields that may
be built with under-resourced controllers (e.g. nRF52833 based ones).

fix: Remove usage of renamed Kconfig from core coverage.

Avoid using WS2812_LED_STRIP, since that Kconfig was renamed/split into
SPI/GPIO/I2S symbols.

refactor(boards): Adjust XIAO RP2040 override names, bootloader support

Adjust the .conf/.overlay files to match the proper naming for the
XIAO rp2040 board. Also add the necessary Kconfig/DTS bits for
supporting bootloader using retained memory/boot mode retention.

fix(display): Adjust stack sizes for display usage.

Updated LVGL is bumping our stack size, so adjust the system work queue
and dedicated display queue stack sizes as needed to account for this.

feat(display): Add thread name to dedicated display queue.

When thread names are enabled, pass a name to the dedicated display
queue for better tracibility when using the thread analyzer.

docs(blog): Add Zephyr upgrade post

docs: Add bootloader integration page

Add a dedicated page to outline steps to set up bootloader integration
using the boot retention mechanism in newer Zephyr versions.

fix(display): port nice!view display code

* remove `lv_` prefix from old LVGL methods

doc: Update local setup docs to use `west packages pip`

Install Zephyr deps using the newer `west packages pip --install`.

Signed-off-by: Peter Johanson <peter@peterjohanson.com>

refactor(split): Adjust BT split code for newer Zephyr APIs.

refactor(boards): Adjust upstream RP2040 boards for boot mode retention

Add necessary DTS/Kconfig settings to upstream RP2040 boards so they can
use the ZMK bootloader functionality using the boot mode retention
infrastructure.

docs: Update Zephyr docs links to 4.1.0 version.

Update all links to the Zephyr docs to the 4.1.0 versions to match our
Zephyr version in use.

docs: Add a note about using CMake v3 for maximum compatibility.

Some optional modules, like libmetal, which is used on nRF5340,
specifically require CMake v3, so add a note in the native toolchain
setup about this.

feat(pointing): Handle INPUT_BTN_TOUCH codes for mouse buttons

Translate INPUT_BTN_TOUCH input codes into button 0 press/release for
HID layer.

chore(pointing): Clean up some warning messages.

Properly check return code from queue-ing messages, and fix up some type
warnings in our logging calls.

* Fix input event codes line numbers

fix(studio): Properly serialize GATT RPC indications.

fix(core): Set a system work queue stack size of 2048 by default

We use a fair amount of stack even without BLE or RP2040, so default to
2048 by default everywhere, and constrained platforms can lowes this if
they really need.

refactor(core): Move away from deprecated DIS Kconfig symbols

Use the correct Device Information Service Kconfig symbols for our model
number and manufacturer.

refactor: Move upstream Zephyr board overrides to extensions dirs

Newer Zephyr supports "board extensions" to formally do what we've added
in ourselves via some hacks, so move all our board overlay/config file
overrides for upstream Zephyr boards into that correct structure.

fix(boards): Add xiao_ble sd_partition label for nosd snippet compat

Upstream xiao_ble uses different naming convention for the partition
labels, so add an additional label for the SD range, so the existing
nrf52840-nosd snippet will still work with the board.

fix(core): Don't force CBPRINTF_NANO, for proper formatting.

The nano CBPRINTF implementation lacks some padded formatting needed to
ensure consistent formatting of BLE addresses, which we use to store
keys as strings in a few places, so use the complete CBPRINTF by default
now.

fix(boards): Remove some references to old nice_nano_v2 board ID.

The nice!nano board definition now properly uses versioning, so avoid
referring to it with old `nice_nano_v2` board ID.

fix(boards): Remove nano overlays for old nice_nano_v2 board ID.

With board versioning in place, we can remove the unused
`nice_nano_v2.overlay` files from shields.

---------

Signed-off-by: Peter Johanson <peter@peterjohanson.com>
Co-authored-by: Cem Aksoylar <caksoylar@users.noreply.github.com>
Co-authored-by: Nicolas Munnich <munnich@lipn.univ-paris13.fr>
Co-authored-by: snoyer <noyer.stephane@gmail.com>
2025-12-09 19:43:22 -05:00

575 lines
21 KiB
C

/*
* Copyright (c) 2024 The ZMK Contributors
*
* SPDX-License-Identifier: MIT
*/
#include <zephyr/devicetree.h>
#include <zephyr/device.h>
#include <zephyr/pm/device.h>
#include <zephyr/pm/device_runtime.h>
#include <zephyr/drivers/kscan.h>
#include <zephyr/input/input.h>
#if IS_ENABLED(CONFIG_SETTINGS)
#include <zephyr/settings/settings.h>
#endif
#include <zephyr/logging/log.h>
LOG_MODULE_DECLARE(zmk, CONFIG_ZMK_LOG_LEVEL);
#include <zmk/matrix.h>
#include <zmk/physical_layouts.h>
#include <zmk/event_manager.h>
#include <zmk/events/position_state_changed.h>
ZMK_EVENT_IMPL(zmk_physical_layout_selection_changed);
#define DT_DRV_COMPAT zmk_physical_layout
#define MATRIX_INPUT_SUPPORT \
UTIL_AND(IS_ENABLED(CONFIG_INPUT), \
UTIL_OR(DT_ANY_INST_HAS_PROP_STATUS_OKAY(input), DT_HAS_CHOSEN(zmk_matrix_input)))
#if MATRIX_INPUT_SUPPORT
static void zmk_physical_layout_input_event_cb(struct input_event *evt, void *user_data);
#endif
#define USE_PHY_LAYOUTS \
(DT_HAS_COMPAT_STATUS_OKAY(DT_DRV_COMPAT) && !DT_HAS_CHOSEN(zmk_matrix_transform))
BUILD_ASSERT(
!IS_ENABLED(CONFIG_ZMK_STUDIO) || USE_PHY_LAYOUTS,
"ISSUE FOUND: Keyboards require additional configuration to allow for firmware with ZMK "
"Studio enabled. You have attempted to build a keyboard lacking such configuration. Please see "
"https://zmk.dev/docs/features/studio#adding-zmk-studio-support-to-a-keyboard for "
"more information on how to resolve this error, or contact the maintainer of your keyboard's "
"firmware for assistance.");
#if USE_PHY_LAYOUTS
#define ZKPA_INIT(i, n) \
(const struct zmk_key_physical_attrs) { \
.width = (int16_t)(int32_t)DT_INST_PHA_BY_IDX(n, keys, i, width), \
.height = (int16_t)(int32_t)DT_INST_PHA_BY_IDX(n, keys, i, height), \
.x = (int16_t)(int32_t)DT_INST_PHA_BY_IDX(n, keys, i, x), \
.y = (int16_t)(int32_t)DT_INST_PHA_BY_IDX(n, keys, i, y), \
COND_CODE_1(IS_ENABLED(CONFIG_ZMK_PHYSICAL_LAYOUT_KEY_ROTATION), \
(.rx = (int16_t)(int32_t)DT_INST_PHA_BY_IDX(n, keys, i, rx), \
.ry = (int16_t)(int32_t)DT_INST_PHA_BY_IDX(n, keys, i, ry), \
.r = (int16_t)(int32_t)DT_INST_PHA_BY_IDX(n, keys, i, r), ), \
()) \
}
#define INPUT_FOR_INST(n) \
DEVICE_DT_GET(COND_CODE_1(DT_INST_PROP_LEN(n, input), (DT_INST_PHANDLE(n, input)), \
(DT_CHOSEN(zmk_matrix_input))))
#define ZMK_LAYOUT_INST(n) \
BUILD_ASSERT(!IS_ENABLED(CONFIG_ZMK_STUDIO) || DT_INST_NODE_HAS_PROP(n, keys), \
"ZMK Studio requires physical layouts with key positions. See " \
"https://zmk.dev/docs/development/hardware-integration/studio-setup"); \
static const struct zmk_key_physical_attrs const _CONCAT( \
_zmk_physical_layout_keys_, n)[DT_INST_PROP_LEN_OR(n, keys, 0)] = { \
LISTIFY(DT_INST_PROP_LEN_OR(n, keys, 0), ZKPA_INIT, (, ), n)}; \
ZMK_MATRIX_TRANSFORM_EXTERN(DT_INST_PHANDLE(n, transform)); \
static const struct zmk_physical_layout const _CONCAT(_zmk_physical_layout_, \
DT_DRV_INST(n)) = { \
.display_name = DT_INST_PROP_OR(n, display_name, "Layout #" #n), \
.matrix_transform = ZMK_MATRIX_TRANSFORM_T_FOR_NODE(DT_INST_PHANDLE(n, transform)), \
.keys = _CONCAT(_zmk_physical_layout_keys_, n), \
.keys_len = DT_INST_PROP_LEN_OR(n, keys, 0), \
COND_CODE_1(UTIL_AND(MATRIX_INPUT_SUPPORT, DT_INST_PROP_LEN(n, input)), \
(.input = INPUT_FOR_INST(n)), ()) \
COND_CODE_1(UTIL_OR(DT_HAS_CHOSEN(zmk_kscan), DT_INST_PROP_LEN(n, kscan)), \
(.kscan = DEVICE_DT_GET(COND_CODE_1(DT_INST_PROP_LEN(n, kscan), \
(DT_INST_PHANDLE(n, kscan)), \
(DT_CHOSEN(zmk_kscan))))), \
())}; \
COND_CODE_1( \
UTIL_AND(MATRIX_INPUT_SUPPORT, DT_INST_PROP_LEN(n, input)), \
(INPUT_CALLBACK_DEFINE(INPUT_FOR_INST(n), zmk_physical_layout_input_event_cb, \
(void *)&(_CONCAT(_zmk_physical_layout_, DT_DRV_INST(n))));), \
())
DT_INST_FOREACH_STATUS_OKAY(ZMK_LAYOUT_INST)
#define POS_MAP_COMPAT zmk_physical_layout_position_map
#define HAVE_POS_MAP DT_HAS_COMPAT_STATUS_OKAY(POS_MAP_COMPAT)
#define POS_MAP_COMPLETE (HAVE_POS_MAP && DT_PROP(DT_INST(0, POS_MAP_COMPAT), complete))
#if HAVE_POS_MAP
// Using sizeof + union trick to calculate the "positions" length statically.
#define ZMK_POS_MAP_POSITIONS_ARRAY(node_id) \
uint8_t _CONCAT(prop_, node_id)[DT_PROP_LEN(node_id, positions)];
#define ZMK_POS_MAP_LEN \
sizeof(union {DT_FOREACH_CHILD(DT_INST(0, POS_MAP_COMPAT), ZMK_POS_MAP_POSITIONS_ARRAY)})
struct position_map_entry {
const struct zmk_physical_layout *layout;
const uint32_t positions[ZMK_POS_MAP_LEN];
};
#define ZMK_POS_MAP_LEN_CHECK(node_id) \
BUILD_ASSERT(ZMK_POS_MAP_LEN == DT_PROP_LEN(node_id, positions), \
"Position maps must all have the same number of entries")
DT_FOREACH_CHILD_SEP(DT_INST(0, POS_MAP_COMPAT), ZMK_POS_MAP_LEN_CHECK, (;));
#define ZMK_POS_MAP_ENTRY(node_id) \
{ \
.layout = COND_CODE_1( \
UTIL_AND(DT_NODE_HAS_COMPAT(DT_PHANDLE(node_id, physical_layout), DT_DRV_COMPAT), \
DT_NODE_HAS_STATUS(DT_PHANDLE(node_id, physical_layout), okay)), \
(&_CONCAT(_zmk_physical_layout_, DT_PHANDLE(node_id, physical_layout))), (NULL)), \
.positions = DT_PROP(node_id, positions), \
}
static const struct position_map_entry positions_maps[] = {
DT_FOREACH_CHILD_SEP(DT_INST(0, POS_MAP_COMPAT), ZMK_POS_MAP_ENTRY, (, ))};
#endif
#define ZMK_LAYOUT_REF(n) &_CONCAT(_zmk_physical_layout_, DT_DRV_INST(n)),
static const struct zmk_physical_layout *const layouts[] = {
DT_INST_FOREACH_STATUS_OKAY(ZMK_LAYOUT_REF)};
#elif DT_HAS_CHOSEN(zmk_matrix_transform)
#if DT_HAS_COMPAT_STATUS_OKAY(DT_DRV_COMPAT)
#warning \
"Ignoring the physical layouts and using the chosen matrix transform. Consider setting a chosen physical layout instead."
#endif
ZMK_MATRIX_TRANSFORM_EXTERN(DT_CHOSEN(zmk_matrix_transform));
static const struct zmk_physical_layout _CONCAT(_zmk_physical_layout_, chosen) = {
.display_name = "Default",
.matrix_transform = ZMK_MATRIX_TRANSFORM_T_FOR_NODE(DT_CHOSEN(zmk_matrix_transform)),
COND_CODE_1(DT_HAS_CHOSEN(zmk_kscan), (.kscan = DEVICE_DT_GET(DT_CHOSEN(zmk_kscan)), ), ())};
static const struct zmk_physical_layout *const layouts[] = {
&_CONCAT(_zmk_physical_layout_, chosen)};
#elif UTIL_OR(DT_HAS_CHOSEN(zmk_kscan), DT_HAS_CHOSEN(zmk_matrix_input))
#if DT_HAS_COMPAT_STATUS_OKAY(DT_DRV_COMPAT)
#warning \
"Ignoring the physical layouts and using the chosen kscan/matrix-input with a synthetic transform. Consider setting a chosen physical layout instead."
#endif
ZMK_MATRIX_TRANSFORM_DEFAULT_EXTERN();
static const struct zmk_physical_layout _CONCAT(_zmk_physical_layout_, chosen) = {
.display_name = "Default",
.matrix_transform = &zmk_matrix_transform_default,
#if DT_HAS_CHOSEN(zmk_matrix_input)
.input = DEVICE_DT_GET(DT_CHOSEN(zmk_matrix_input)),
#elif DT_HAS_CHOSEN(zmk_kscan)
.kscan = DEVICE_DT_GET(DT_CHOSEN(zmk_kscan)),
#endif
};
#if DT_HAS_CHOSEN(zmk_matrix_input)
INPUT_CALLBACK_DEFINE(DEVICE_DT_GET(DT_CHOSEN(zmk_matrix_input)),
zmk_physical_layout_input_event_cb,
(void *)&(_CONCAT(_zmk_physical_layout_, chosen)));
#endif
static const struct zmk_physical_layout *const layouts[] = {
&_CONCAT(_zmk_physical_layout_, chosen)};
#endif
const struct zmk_physical_layout *active;
size_t zmk_physical_layouts_get_list(struct zmk_physical_layout const *const **dest_layouts) {
*dest_layouts = &layouts[0];
return ARRAY_SIZE(layouts);
}
#define ZMK_KSCAN_EVENT_STATE_PRESSED 0
#define ZMK_KSCAN_EVENT_STATE_RELEASED 1
struct zmk_kscan_event {
uint32_t row;
uint32_t column;
uint32_t state;
};
static struct zmk_kscan_msg_processor {
struct k_work work;
} msg_processor;
K_MSGQ_DEFINE(physical_layouts_kscan_msgq, sizeof(struct zmk_kscan_event),
CONFIG_ZMK_KSCAN_EVENT_QUEUE_SIZE, 4);
#if MATRIX_INPUT_SUPPORT
static struct zmk_kscan_event pending_input_event;
static void zmk_physical_layout_input_event_cb(struct input_event *evt, void *user_data) {
const struct zmk_physical_layout *layout = (const struct zmk_physical_layout *)user_data;
if (layout != active) {
LOG_WRN("Ignoring input event from non-active layout");
return;
}
switch (evt->type) {
case INPUT_EV_ABS:
switch (evt->code) {
case INPUT_ABS_X:
pending_input_event.column = evt->value;
break;
case INPUT_ABS_Y:
pending_input_event.row = evt->value;
break;
default:
LOG_WRN("Unknown abs code");
return;
}
break;
case INPUT_EV_KEY:
switch (evt->code) {
case INPUT_BTN_TOUCH:
pending_input_event.state =
(evt->value ? ZMK_KSCAN_EVENT_STATE_PRESSED : ZMK_KSCAN_EVENT_STATE_RELEASED);
break;
default:
LOG_WRN("Unknown key code");
return;
}
break;
default:
LOG_WRN("Unknown type");
return;
}
if (evt->sync) {
k_msgq_put(&physical_layouts_kscan_msgq, &pending_input_event, K_NO_WAIT);
k_work_submit(&msg_processor.work);
}
}
#endif
static void zmk_physical_layout_kscan_callback(const struct device *dev, uint32_t row,
uint32_t column, bool pressed) {
if (dev != active->kscan) {
return;
}
struct zmk_kscan_event ev = {
.row = row,
.column = column,
.state = (pressed ? ZMK_KSCAN_EVENT_STATE_PRESSED : ZMK_KSCAN_EVENT_STATE_RELEASED)};
k_msgq_put(&physical_layouts_kscan_msgq, &ev, K_NO_WAIT);
k_work_submit(&msg_processor.work);
}
static void zmk_physical_layouts_kscan_process_msgq(struct k_work *item) {
struct zmk_kscan_event ev;
while (k_msgq_get(&physical_layouts_kscan_msgq, &ev, K_NO_WAIT) == 0) {
bool pressed = (ev.state == ZMK_KSCAN_EVENT_STATE_PRESSED);
int32_t position = zmk_matrix_transform_row_column_to_position(active->matrix_transform,
ev.row, ev.column);
if (position < 0) {
LOG_WRN("Not found in transform: row: %d, col: %d, pressed: %s", ev.row, ev.column,
(pressed ? "true" : "false"));
continue;
}
LOG_DBG("Row: %d, col: %d, position: %d, pressed: %s", ev.row, ev.column, position,
(pressed ? "true" : "false"));
raise_zmk_position_state_changed(
(struct zmk_position_state_changed){.source = ZMK_POSITION_STATE_CHANGE_SOURCE_LOCAL,
.state = pressed,
.position = position,
.timestamp = k_uptime_get()});
}
}
static const struct zmk_physical_layout *get_default_layout(void) {
const struct zmk_physical_layout *initial;
#if USE_PHY_LAYOUTS && DT_HAS_CHOSEN(zmk_physical_layout)
initial = &_CONCAT(_zmk_physical_layout_, DT_CHOSEN(zmk_physical_layout));
#else
initial = layouts[0];
#endif
return initial;
}
static int get_index_of_layout(const struct zmk_physical_layout *layout) {
for (int i = 0; i < ARRAY_SIZE(layouts); i++) {
if (layouts[i] == layout) {
return i;
}
}
return -ENODEV;
}
static uint32_t selected_to_stock_map[ZMK_KEYMAP_LEN];
int zmk_physical_layouts_get_selected_to_stock_position_map(uint32_t const **map) {
*map = selected_to_stock_map;
return ZMK_KEYMAP_LEN;
}
int zmk_physical_layouts_select_layout(const struct zmk_physical_layout *dest_layout) {
if (!dest_layout) {
return -ENODEV;
}
if (dest_layout == active) {
return 0;
}
if (active) {
if (active->kscan) {
kscan_disable_callback(active->kscan);
#if IS_ENABLED(CONFIG_PM_DEVICE_RUNTIME)
pm_device_runtime_put(active->kscan);
#elif IS_ENABLED(CONFIG_PM_DEVICE)
pm_device_action_run(active->kscan, PM_DEVICE_ACTION_SUSPEND);
#endif
}
}
int new_idx = get_index_of_layout(dest_layout);
int stock_idx = get_index_of_layout(get_default_layout());
int ret = zmk_physical_layouts_get_position_map(stock_idx, new_idx, ZMK_KEYMAP_LEN,
selected_to_stock_map);
if (ret < 0) {
LOG_ERR("Failed to refresh the selected to stock mapping (%d)", ret);
return ret;
}
active = dest_layout;
if (active->kscan) {
#if IS_ENABLED(CONFIG_PM_DEVICE_RUNTIME)
int err = pm_device_runtime_get(active->kscan);
if (err < 0) {
LOG_WRN("PM runtime get of kscan device to enable it %d", err);
return err;
}
#elif IS_ENABLED(CONFIG_PM_DEVICE)
pm_device_action_run(active->kscan, PM_DEVICE_ACTION_RESUME);
#endif
kscan_config(active->kscan, zmk_physical_layout_kscan_callback);
kscan_enable_callback(active->kscan);
}
return 0;
}
int zmk_physical_layouts_select(uint8_t index) {
if (index >= ARRAY_SIZE(layouts)) {
return -EINVAL;
}
int ret = zmk_physical_layouts_select_layout(layouts[index]);
if (ret >= 0) {
raise_zmk_physical_layout_selection_changed(
(struct zmk_physical_layout_selection_changed){.selection = index});
}
return ret;
}
int zmk_physical_layouts_get_selected(void) {
for (int i = 0; i < ARRAY_SIZE(layouts); i++) {
if (layouts[i] == active) {
return i;
}
}
return -ENODEV;
}
#if IS_ENABLED(CONFIG_SETTINGS)
static int8_t saved_selected_index = -1;
#endif
int zmk_physical_layouts_select_initial(void) {
int ret = zmk_physical_layouts_select_layout(get_default_layout());
return ret;
}
int zmk_physical_layouts_check_unsaved_selection(void) {
#if IS_ENABLED(CONFIG_SETTINGS)
return saved_selected_index < 0 ||
saved_selected_index == (uint8_t)zmk_physical_layouts_get_selected()
? 0
: 1;
#else
return -ENOTSUP;
#endif
}
int zmk_physical_layouts_save_selected(void) {
#if IS_ENABLED(CONFIG_SETTINGS)
uint8_t val = (uint8_t)zmk_physical_layouts_get_selected();
return settings_save_one("physical_layouts/selected", &val, sizeof(val));
#else
return -ENOTSUP;
#endif
}
int zmk_physical_layouts_revert_selected(void) { return zmk_physical_layouts_select_initial(); }
int zmk_physical_layouts_get_position_map(uint8_t source, uint8_t dest, size_t map_size,
uint32_t map[map_size]) {
if (source >= ARRAY_SIZE(layouts) || dest >= ARRAY_SIZE(layouts)) {
return -EINVAL;
}
if (source == dest) {
for (int i = 0; i < map_size; i++) {
map[i] = i;
}
return 0;
}
const struct zmk_physical_layout *src_layout = layouts[source];
const struct zmk_physical_layout *dest_layout = layouts[dest];
int max_kp = dest_layout->keys_len;
#if HAVE_POS_MAP
const struct position_map_entry *src_pos_map = NULL;
const struct position_map_entry *dest_pos_map = NULL;
for (int pm = 0; pm < ARRAY_SIZE(positions_maps); pm++) {
if (positions_maps[pm].layout == src_layout) {
src_pos_map = &positions_maps[pm];
}
if (positions_maps[pm].layout == dest_layout) {
dest_pos_map = &positions_maps[pm];
}
}
// Maps can place items "off the end" of other layouts so they are
// preserved but not visible, so adjust our max here if that is being used.
if (src_pos_map && dest_pos_map) {
for (int mp = 0; mp < ZMK_POS_MAP_LEN; mp++) {
max_kp =
MAX(max_kp, MAX(src_pos_map->positions[mp] + 1, dest_pos_map->positions[mp] + 1));
}
}
#endif
if (map_size < max_kp) {
return -EINVAL;
}
memset(map, UINT32_MAX, map_size);
for (int b = 0; b < max_kp; b++) {
bool found = false;
#if HAVE_POS_MAP
if (src_pos_map && dest_pos_map) {
for (int m = 0; m < ZMK_POS_MAP_LEN; m++) {
if (dest_pos_map->positions[m] == b) {
map[b] = src_pos_map->positions[m];
found = true;
break;
}
}
}
#endif
#if !POS_MAP_COMPLETE
if (!found) {
const struct zmk_key_physical_attrs *key = &dest_layout->keys[b];
for (int old_b = 0; old_b < src_layout->keys_len; old_b++) {
const struct zmk_key_physical_attrs *candidate_key = &src_layout->keys[old_b];
if (candidate_key->x == key->x && candidate_key->y == key->y) {
map[b] = old_b;
found = true;
break;
}
}
}
#endif
}
return max_kp;
}
#if IS_ENABLED(CONFIG_SETTINGS)
static int physical_layouts_handle_set(const char *name, size_t len, settings_read_cb read_cb,
void *cb_arg) {
const char *next;
if (settings_name_steq(name, "selected", &next) && !next) {
if (len != sizeof(saved_selected_index)) {
return -EINVAL;
}
int err = read_cb(cb_arg, &saved_selected_index, len);
if (err <= 0) {
LOG_ERR("Failed to handle selected physical dest_layout from settings (err %d)", err);
return err;
}
return zmk_physical_layouts_select(saved_selected_index);
}
return 0;
};
SETTINGS_STATIC_HANDLER_DEFINE(physical_layouts, "physical_layouts", NULL,
physical_layouts_handle_set, NULL, NULL);
#endif // IS_ENABLED(CONFIG_SETTINGS)
static int zmk_physical_layouts_init(void) {
k_work_init(&msg_processor.work, zmk_physical_layouts_kscan_process_msgq);
#if IS_ENABLED(CONFIG_PM_DEVICE)
for (int l = 0; l < ARRAY_SIZE(layouts); l++) {
const struct zmk_physical_layout *pl = layouts[l];
if (pl->kscan && pm_device_wakeup_is_capable(pl->kscan) &&
!pm_device_wakeup_enable(pl->kscan, true)) {
LOG_WRN("Failed to wakeup enable %s", pl->kscan->name);
}
}
#endif // IS_ENABLED(CONFIG_PM_DEVICE)
// Initialize a sane mapping
for (int i = 0; i < ZMK_KEYMAP_LEN; i++) {
selected_to_stock_map[i] = i;
}
return zmk_physical_layouts_select_initial();
}
SYS_INIT(zmk_physical_layouts_init, APPLICATION, CONFIG_APPLICATION_INIT_PRIORITY);