aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--common_features.mk5
-rw-r--r--docs/_summary.md1
-rw-r--r--docs/config_options.md4
-rw-r--r--docs/feature_key_overrides.md229
-rw-r--r--docs/syllabus.md1
-rw-r--r--docs/understanding_qmk.md1
-rw-r--r--quantum/process_keycode/process_key_override.c518
-rw-r--r--quantum/process_keycode/process_key_override.h147
-rw-r--r--quantum/process_keycode/process_key_override_private.h24
-rw-r--r--quantum/quantum.c19
-rw-r--r--quantum/quantum.h4
-rw-r--r--quantum/quantum_keycodes.h5
-rw-r--r--show_options.mk1
-rw-r--r--tmk_core/common/action_util.c28
14 files changed, 984 insertions, 3 deletions
diff --git a/common_features.mk b/common_features.mk
index 8080113ef..74b94ecd7 100644
--- a/common_features.mk
+++ b/common_features.mk
@@ -335,6 +335,11 @@ ifeq ($(strip $(PRINTING_ENABLE)), yes)
335 SRC += $(TMK_DIR)/protocol/serial_uart.c 335 SRC += $(TMK_DIR)/protocol/serial_uart.c
336endif 336endif
337 337
338ifeq ($(strip $(KEY_OVERRIDE_ENABLE)), yes)
339 OPT_DEFS += -DKEY_OVERRIDE_ENABLE
340 SRC += $(QUANTUM_DIR)/process_keycode/process_key_override.c
341endif
342
338ifeq ($(strip $(SERIAL_LINK_ENABLE)), yes) 343ifeq ($(strip $(SERIAL_LINK_ENABLE)), yes)
339 SERIAL_SRC := $(wildcard $(SERIAL_PATH)/protocol/*.c) 344 SERIAL_SRC := $(wildcard $(SERIAL_PATH)/protocol/*.c)
340 SERIAL_SRC += $(wildcard $(SERIAL_PATH)/system/*.c) 345 SERIAL_SRC += $(wildcard $(SERIAL_PATH)/system/*.c)
diff --git a/docs/_summary.md b/docs/_summary.md
index 4141e01e7..6c39aeda0 100644
--- a/docs/_summary.md
+++ b/docs/_summary.md
@@ -77,6 +77,7 @@
77 * [Combos](feature_combo.md) 77 * [Combos](feature_combo.md)
78 * [Debounce API](feature_debounce_type.md) 78 * [Debounce API](feature_debounce_type.md)
79 * [Key Lock](feature_key_lock.md) 79 * [Key Lock](feature_key_lock.md)
80 * [Key Overrides](feature_key_overrides.md)
80 * [Layers](feature_layers.md) 81 * [Layers](feature_layers.md)
81 * [One Shot Keys](one_shot_keys.md) 82 * [One Shot Keys](one_shot_keys.md)
82 * [Pointing Device](feature_pointing_device.md) 83 * [Pointing Device](feature_pointing_device.md)
diff --git a/docs/config_options.md b/docs/config_options.md
index 980195ac6..0c98b3101 100644
--- a/docs/config_options.md
+++ b/docs/config_options.md
@@ -195,6 +195,8 @@ If you define these options you will enable the associated feature, which may in
195 * Sets the delay between `register_code` and `unregister_code`, if you're having issues with it registering properly (common on VUSB boards). The value is in milliseconds. 195 * Sets the delay between `register_code` and `unregister_code`, if you're having issues with it registering properly (common on VUSB boards). The value is in milliseconds.
196* `#define TAP_HOLD_CAPS_DELAY 80` 196* `#define TAP_HOLD_CAPS_DELAY 80`
197 * Sets the delay for Tap Hold keys (`LT`, `MT`) when using `KC_CAPSLOCK` keycode, as this has some special handling on MacOS. The value is in milliseconds, and defaults to 80 ms if not defined. For macOS, you may want to set this to 200 or higher. 197 * Sets the delay for Tap Hold keys (`LT`, `MT`) when using `KC_CAPSLOCK` keycode, as this has some special handling on MacOS. The value is in milliseconds, and defaults to 80 ms if not defined. For macOS, you may want to set this to 200 or higher.
198* `#define KEY_OVERRIDE_REPEAT_DELAY 500`
199 * Sets the key repeat interval for [key overrides](feature_key_overrides.md).
198 200
199## RGB Light Configuration 201## RGB Light Configuration
200 202
@@ -400,6 +402,8 @@ Use these to enable or disable building certain features. The more you have enab
400 * USB N-Key Rollover - if this doesn't work, see here: https://github.com/tmk/tmk_keyboard/wiki/FAQ#nkro-doesnt-work 402 * USB N-Key Rollover - if this doesn't work, see here: https://github.com/tmk/tmk_keyboard/wiki/FAQ#nkro-doesnt-work
401* `AUDIO_ENABLE` 403* `AUDIO_ENABLE`
402 * Enable the audio subsystem. 404 * Enable the audio subsystem.
405* `KEY_OVERRIDE_ENABLE`
406 * Enable the key override feature
403* `RGBLIGHT_ENABLE` 407* `RGBLIGHT_ENABLE`
404 * Enable keyboard underlight functionality 408 * Enable keyboard underlight functionality
405* `LEADER_ENABLE` 409* `LEADER_ENABLE`
diff --git a/docs/feature_key_overrides.md b/docs/feature_key_overrides.md
new file mode 100644
index 000000000..861c4bef5
--- /dev/null
+++ b/docs/feature_key_overrides.md
@@ -0,0 +1,229 @@
1# Key Overrides
2
3Key overrides allow you to override modifier-key combinations to send a different modifier-key combination or perform completely custom actions. Don't want `shift` + `1` to type `!` on your computer? Use a key override to make your keyboard type something different when you press `shift` + `1`. The general behavior is like this: If `modifiers w` + `key x` are pressed, replace these keys with `modifiers y` + `key z` in the keyboard report.
4
5You can use key overrides in a similar way to momentary layer/fn keys to activate custom keycodes/shortcuts, with a number of benefits: You completely keep the original use of the modifier keys, while being able to save space by removing fn keys from your keyboard. You can also easily configure _combinations of modifiers_ to trigger different actions than individual modifiers, and much more. The possibilities are quite vast and this documentation contains a few examples for inspiration throughout.
6
7##### A few more examples to get started: You could use key overrides to...
8- Send `brightness up/down` when pressing `ctrl` + `volume up/down`.
9- Send `delete` when pressing `shift` + `backspace`.
10- Create custom shortcuts or change existing ones: E.g. Send `ctrl`+`shift`+`z` when `ctrl`+`y` is pressed.
11- Run custom code when `ctrl` + `alt` + `esc` is pressed.
12
13## Setup
14
15To enable this feature, you need to add `KEY_OVERRIDE_ENABLE = yes` to your `rules.mk`.
16
17Then, in your `keymap.c` file, you'll need to define the array `key_overrides`, which defines all key overrides to be used. Each override is a value of type `key_override_t`. The array `key_overrides` is `NULL`-terminated and contains pointers to `key_override_t` values (`const key_override_t **`).
18
19## Creating Key Overrides
20
21The `key_override_t` struct has many options that allow you to precisely tune your overrides. The full reference is shown below. Instead of manually creating a `key_override_t` value, it is recommended to use these dedicated initializers:
22
23#### `ko_make_basic(modifiers, key, replacement)`
24Returns a `key_override_t`, which sends `replacement` (can be a key-modifer combination), when `key` and `modifiers` are all pressed down. This override still activates if any additional modifiers not specified in `modifiers` are also pressed down. See `ko_make_with_layers_and_negmods` to customize this behavior.
25
26#### `ko_make_with_layers(modifiers, key, replacement, layers)`
27Additionally takes a bitmask `layers` that defines on which layers the override is used.
28
29#### `ko_make_with_layers_and_negmods(modifiers, key, replacement, layers, negative_mods)`
30Additionally takes a bitmask `negative_mods` that defines which modifiers may not be pressed for this override to activate.
31
32#### `ko_make_with_layers_negmods_and_options(modifiers, key, replacement, layers, negative_mods, options)`
33Additionally takes a bitmask `options` that specifies additional options. See `ko_option_t` for available options.
34
35For more customization possibilities, you may directly create a `key_override_t`, which allows you to customize even more behavior. Read further below for details and examples.
36
37## Simple Example
38
39This shows how the mentioned example of sending `delete` when `shift` + `backspace` are pressed is realized:
40
41```c
42const key_override_t delete_key_override = ko_make_basic(MOD_MASK_SHIFT, KC_BSPACE, KC_DELETE);
43
44// This globally defines all key overrides to be used
45const key_override_t **key_overrides = (const key_override_t *[]){
46 &delete_key_override,
47 NULL // Null terminate the array of overrides!
48};
49```
50
51## Intermediate Difficulty Examples
52
53### Media Controls & Screen Brightness
54
55In this example a single key is configured to control media, volume and screen brightness by using key overrides.
56
57- The key is set to send `play/pause` in the keymap.
58
59The following key overrides will be configured:
60
61- `Ctrl` + `play/pause` will send `next track`.
62- `Ctrl` + `Shift` + `play/pause` will send `previous track`.
63- `Alt` + `play/pause` will send `volume up`.
64- `Alt` + `Shift` + `play/pause` will send `volume down`.
65- `Ctrl` + `Alt` + `play/pause` will send `brightness up`.
66- `Ctrl` + `Alt` + `Shift` + `play/pause` will send `brightness down`.
67
68
69```c
70const key_override_t next_track_override =
71 ko_make_with_layers_negmods_and_options(
72 MOD_MASK_CTRL, // Trigger modifiers: ctrl
73 KC_MPLY, // Trigger key: play/pause
74 KC_MNXT, // Replacement key
75 ~0, // Activate on all layers
76 MOD_MASK_SA, // Do not activate when shift or alt are pressed
77 ko_option_no_reregister_trigger); // Specifies that the play key is not registered again after lifting ctrl
78
79const key_override_t prev_track_override = ko_make_with_layers_negmods_and_options(MOD_MASK_CS, KC_MPLY,
80 KC_MPRV, ~0, MOD_MASK_ALT, ko_option_no_reregister_trigger);
81
82const key_override_t vol_up_override = ko_make_with_layers_negmods_and_options(MOD_MASK_ALT, KC_MPLY,
83 KC_VOLU, ~0, MOD_MASK_CS, ko_option_no_reregister_trigger);
84
85const key_override_t vol_down_override = ko_make_with_layers_negmods_and_options(MOD_MASK_SA, KC_MPLY,
86 KC_VOLD, ~0, MOD_MASK_CTRL, ko_option_no_reregister_trigger);
87
88const key_override_t brightness_up_override = ko_make_with_layers_negmods_and_options(MOD_MASK_CA, KC_MPLY,
89 KC_BRIU, ~0, MOD_MASK_SHIFT, ko_option_no_reregister_trigger);
90
91const key_override_t brightness_down_override = ko_make_basic(MOD_MASK_CSA, KC_MPLY, KC_BRID);
92
93// This globally defines all key overrides to be used
94const key_override_t **key_overrides = (const key_override_t *[]){
95 &next_track_override,
96 &prev_track_override,
97 &vol_up_override,
98 &vol_down_override,
99 &brightness_up_override,
100 &brightness_down_override,
101 NULL
102};
103```
104
105### Flexible macOS-friendly Grave Escape
106The [Grave Escape feature](https://docs.qmk.fm/using-qmk/advanced-keycodes/feature_grave_esc) is limited in its configurability and has [bugs when used on macOS](https://docs.qmk.fm/using-qmk/advanced-keycodes/feature_grave_esc#caveats). Key overrides can be used to achieve a similar functionality as Grave Escape, but with more customization and without bugs on macOS.
107
108```c
109// Shift + esc = ~
110const key_override_t tilde_esc_override = ko_make_basic(MOD_MASK_SHIFT, KC_ESC, S(KC_GRAVE));
111
112// GUI + esc = `
113const key_override_t grave_esc_override = ko_make_basic(MOD_MASK_GUI, KC_ESC, KC_GRAVE);
114
115const key_override_t **key_overrides = (const key_override_t *[]){
116 &tilde_esc_override,
117 &grave_esc_override,
118 NULL
119};
120```
121
122In addition to not encountering unexpected bugs on macOS, you can also change the behavior as you wish. Instead setting `GUI` + `ESC` = `` ` `` you may change it to an arbitrary other modifier, for example `Ctrl` + `ESC` = `` ` ``.
123
124## Advanced Examples
125### Modifiers as Layer Keys
126
127Do you really need a dedicated key to toggle your fn layer? With key overrides, perhaps not. This example shows how you can configure to use `rGUI` + `rAlt` (right GUI and right alt) to access a momentary layer like an fn layer. With this you completely eliminate the need to use a dedicated layer key. Of course the choice of modifier keys can be changed as needed, `rGUI` + `rAlt` is just an example here.
128
129```c
130// This is called when the override activates and deactivates. Enable the fn layer on activation and disable on deactivation
131bool momentary_layer(bool key_down, void *layer) {
132 if (key_down) {
133 layer_on((uint8_t)(uintptr_t)layer);
134 } else {
135 layer_off((uint8_t)(uintptr_t)layer);
136 }
137
138 return false;
139}
140
141const key_override_t fn_override = {.trigger_mods = MOD_BIT(KC_RGUI) | MOD_BIT(KC_RCTL), //
142 .layers = ~(1 << LAYER_FN), //
143 .suppressed_mods = MOD_BIT(KC_RGUI) | MOD_BIT(KC_RCTL), //
144 .options = ko_option_no_unregister_on_other_key_down, //
145 .negative_mod_mask = (uint8_t) ~(MOD_BIT(KC_RGUI) | MOD_BIT(KC_RCTL)), //
146 .custom_action = momentary_layer, //
147 .context = (void *)LAYER_FN, //
148 .trigger = KC_NO, //
149 .replacement = KC_NO, //
150 .enabled = NULL};
151```
152
153## Keycodes
154
155You can enable, disable and toggle all key overrides on the fly.
156
157|Keycode |Description |Function Equivalent|
158|----------|---------------------------------|--------|
159|`KEY_OVERRIDE_ON` |Turns on Key Override feature | `key_override_on(void)`|
160|`KEY_OVERRIDE_OFF` |Turns off Key Override feature |`key_override_off(void)`|
161|`KEY_OVERRIDE_TOGGLE` |Toggles Key Override feature on and off |`key_override_toggle(void)`|
162
163## Reference for `key_override_t`
164
165Advanced users may need more customization than what is offered by the simple `ko_make` initializers. For this, directly create a `key_override_t` value and set all members. Below is a reference for all members of `key_override_t`.
166
167| Member | Description |
168|--------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
169| `uint16_t trigger` | The non-modifier keycode that triggers the override. This keycode, and the necessary modifiers (`trigger_mods`) must be pressed to activate this override. Set this to the keycode of the key that should activate the override. Set to `KC_NO` to require only the necessary modifiers to be pressed and no non-modifier. |
170| `uint8_t trigger_mods` | Which mods need to be down for activation. If both sides of a modifier are set (e.g. left ctrl and right ctrl) then only one is required to be pressed (e.g. left ctrl suffices). Use the `MOD_MASK_XXX` and `MOD_BIT()` macros for this. |
171| `layer_state_t layers` | This is a BITMASK (!), defining which layers this override applies to. To use this override on layer i set the ith bit `(1 << i)`. |
172| `uint8_t negative_mod_mask` | Which modifiers cannot be down. It must hold that `(active_modifiers & negative_mod_mask) == 0`, otherwise the key override will not be activated. An active override will be deactivated once this is no longer true. |
173| `uint8_t suppressed_mods` | Modifiers to 'suppress' while the override is active. To suppress a modifier means that even though the modifier key is held down, the host OS sees the modifier as not pressed. Can be used to suppress the trigger modifiers, as a trivial example. |
174| `uint16_t replacement` | The complex keycode to send as replacement when this override is triggered. This can be a simple keycode, a key-modifier combination (e.g. `C(KC_A)`), or `KC_NO` (to register no replacement keycode). Use in combination with suppressed_mods to get the correct modifiers to be sent. |
175| `ko_option_t options` | Options controlling the behavior of the override, such as what actions are allowed to activate the override. |
176| `bool (*custom_action)(bool activated, void *context)` | If not NULL, this function will be called right before the replacement key is registered, along with the provided context and a flag indicating whether the override was activated or deactivated. This function allows you to run some custom actions for specific key overrides. If you return `false`, the replacement key is not registered/unregistered as it would normally. Return `true` to register and unregister the override normally. |
177| `void *context` | A context that will be passed to the custom action function. |
178| `bool *enabled` | If this points to false this override will not be used. Set to NULL to always have this override enabled. |
179
180### Reference for `ko_option_t`
181
182Bitfield with various options controlling the behavior of a key override.
183
184| Value | Description |
185|------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
186| `ko_option_activation_trigger_down` | Allow activating when the trigger key is pressed down. |
187| `ko_option_activation_required_mod_down` | Allow activating when a necessary modifier is pressed down. |
188| `ko_option_activation_negative_mod_up` | Allow activating when a negative modifier is released. |
189| `ko_option_one_mod` | If set, any of the modifiers in `trigger_mods` will be enough to activate the override (logical OR of modifiers). If not set, all the modifiers in `trigger_mods` have to be pressed (logical AND of modifiers). |
190| `ko_option_no_unregister_on_other_key_down` | If set, the override will not deactivate when another key is pressed down. Use only if you really know you need this. |
191| `ko_option_no_reregister_trigger` | If set, the trigger key will never be registered again after the override is deactivated. |
192| `ko_options_default` | The default options used by the `ko_make_xxx` functions |
193
194## For Advanced Users: Inner Workings
195
196This section explains how a key override works in detail, explaining where each member of `key_override_t` comes into play. Understanding this is essential to be able to take full advantage of all the options offered by key overrides.
197
198#### Activation
199
200When the necessary keys are pressed (`trigger_mods` + `trigger`), the override is 'activated' and the replacement key is registered in the keyboard report (`replacement`), while the `trigger` key is removed from the keyboard report. The trigger modifiers may also be removed from the keyboard report upon activation of an override (`suppressed_mods`). The override will not activate if any of the `negative_modifiers` are pressed.
201
202Overrides can activate in three different cases:
203
2041. The trigger key is pressed down and necessary modifiers are already down.
2052. A necessary modifier is pressed down, while the trigger key and other necessary modifiers are already down.
2063. A negative modifier is released, while all necessary modifiers and the trigger key are already down.
207
208Use the `option` member to customize which of these events are allowed to activate your overrides (default: all three).
209
210In any case, a key override can only activate if the `trigger` key is the _last_ non-modifier key that was pressed down. This emulates the behavior of how standard OSes (macOS, Windows, Linux) handle normal key input (to understand: Hold down `a`, then also hold down `b`, then hold down `shift`; `B` will be typed but not `A`).
211
212#### Deactivation
213
214An override is 'deactivated' when one of the trigger keys (`trigger_mods`, `trigger`) is lifted, another non-modifier key is pressed down, or one of the `negative_modifiers` is pressed down. When an override deactivates, the `replacement` key is removed from the keyboard report, while the `suppressed_mods` that are still held down are re-added to the keyboard report. By default, the `trigger` key is re-added to the keyboard report if it is still held down and no other non-modifier key has been pressed since. This again emulates the behavior of how standard OSes handle normal key input (To understand: hold down `a`, then also hold down `b`, then also `shift`, then release `b`; `A` will not be typed even though you are holding the `a` and `shift` keys). Use the `option` field `ko_option_no_reregister_trigger` to prevent re-registering the trigger key in all cases.
215
216#### Key Repeat Delay
217
218A third way in which standard OS-handling of modifier-key input is emulated in key overrides is with a ['key repeat delay'](https://www.dummies.com/computers/pcs/set-your-keyboards-repeat-delay-and-repeat-rate/). To explain what this is, let's look at how normal keyboard input is handled by mainstream OSes again: If you hold down `a`, followed by `shift`, you will see the letter `a` is first typed, then for a short moment nothing is typed and then repeating `A`s are typed. Take note that, although shift is pressed down just after `a` is pressed, it takes a moment until `A` is typed. This is caused by the aforementioned key repeat delay, and it is a feature that prevents unwanted repeated characters from being typed.
219
220This applies equally to releasing a modifier: When you hold `shift`, then press `a`, the letter `A` is typed. Now if you release `shift` first, followed by `a` shortly after, you will not see the letter `a` being typed, even though for a short moment of time you were just holding down the key `a`. This is because no modified characters are typed until the key repeat delay has passed.
221
222 This exact behavior is implemented in key overrides as well: If a key override for `shift` + `a` = `b` exists, and `a` is pressed and held, followed by `shift`, you will not immediately see the letter `b` being typed. Instead, this event is deferred for a short moment, until the key repeat delay has passed, measured from the moment when the trigger key (`a`) was pressed down.
223
224The duration of the key repeat delay is controlled with the `KEY_OVERRIDE_REPEAT_DELAY` macro. Define this value in your `config.h` file to change it. It is 500ms by default.
225
226
227## Difference to Combos
228
229Note that key overrides are very different from [combos](https://docs.qmk.fm/#/feature_combo). Combos require that you press down several keys almost _at the same time_ and can work with any combination of non-modifier keys. Key overrides work like keyboard shortcuts (e.g. `ctrl` + `z`): They take combinations of _multiple_ modifiers and _one_ non-modifier key to then perform some custom action. Key overrides are implemented with much care to behave just like normal keyboard shortcuts would in regards to the order of pressed keys, timing, and interacton with other pressed keys. There are a number of optional settings that can be used to really fine-tune the behavior of each key override as well. Using key overrides also does not delay key input for regular key presses, which inherently happens in combos and may be undesirable.
diff --git a/docs/syllabus.md b/docs/syllabus.md
index ec7f66ba7..b33bd9e72 100644
--- a/docs/syllabus.md
+++ b/docs/syllabus.md
@@ -40,6 +40,7 @@ These topics start to dig into some of the features that QMK supports. You don't
40 * [Tap Dance](feature_tap_dance.md) 40 * [Tap Dance](feature_tap_dance.md)
41 * [Combos](feature_combo.md) 41 * [Combos](feature_combo.md)
42 * [Userspace](feature_userspace.md) 42 * [Userspace](feature_userspace.md)
43 * [Key Overrides](feature_key_overrides.md)
43 44
44# Advanced Topics 45# Advanced Topics
45 46
diff --git a/docs/understanding_qmk.md b/docs/understanding_qmk.md
index 331b1c893..e3dd5cb78 100644
--- a/docs/understanding_qmk.md
+++ b/docs/understanding_qmk.md
@@ -146,6 +146,7 @@ The `process_record()` function itself is deceptively simple, but hidden within
146 * [`bool process_audio(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_audio.c#L19) 146 * [`bool process_audio(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_audio.c#L19)
147 * [`bool process_steno(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_steno.c#L160) 147 * [`bool process_steno(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_steno.c#L160)
148 * [`bool process_music(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_music.c#L114) 148 * [`bool process_music(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_music.c#L114)
149 * [`bool process_key_override(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/5a1b857dea45a17698f6baa7dd1b7a7ea907fb0a/quantum/process_keycode/process_key_override.c#L397)
149 * [`bool process_tap_dance(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_tap_dance.c#L141) 150 * [`bool process_tap_dance(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_tap_dance.c#L141)
150 * [`bool process_unicode_common(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_unicode_common.c#L169) 151 * [`bool process_unicode_common(uint16_t keycode, keyrecord_t *record)`](https://github.com/qmk/qmk_firmware/blob/e1203a222bb12ab9733916164a000ef3ac48da93/quantum/process_keycode/process_unicode_common.c#L169)
151 calls one of: 152 calls one of:
diff --git a/quantum/process_keycode/process_key_override.c b/quantum/process_keycode/process_key_override.c
new file mode 100644
index 000000000..fe43eacc4
--- /dev/null
+++ b/quantum/process_keycode/process_key_override.c
@@ -0,0 +1,518 @@
1/*
2 * Copyright 2021 Jonas Gessner
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "quantum.h"
19#include "report.h"
20#include "timer.h"
21#include "process_key_override_private.h"
22
23#include <debug.h>
24
25#ifndef KEY_OVERRIDE_REPEAT_DELAY
26# define KEY_OVERRIDE_REPEAT_DELAY 500
27#endif
28
29// For benchmarking the time it takes to call process_key_override on every key press (needs keyboard debugging enabled as well)
30// #define BENCH_KEY_OVERRIDE
31
32// For debug output (needs keyboard debugging enabled as well)
33// #define DEBUG_KEY_OVERRIDE
34
35#ifdef DEBUG_KEY_OVERRIDE
36# define key_override_printf dprintf
37#else
38# define key_override_printf(str, ...) \
39 {}
40#endif
41
42// Helpers
43
44// Private functions implemented elsewhere in qmk/tmk
45extern uint8_t extract_mod_bits(uint16_t code);
46extern void set_weak_override_mods(uint8_t mods);
47extern void clear_weak_override_mods(void);
48extern void set_suppressed_override_mods(uint8_t mods);
49extern void clear_suppressed_override_mods(void);
50
51static uint16_t clear_mods_from(uint16_t keycode) {
52 switch (keycode) {
53 case QK_MODS ... QK_MODS_MAX:
54 break;
55 default:
56 return keycode;
57 }
58
59 static const uint16_t all_mods = QK_LCTL | QK_LSFT | QK_LALT | QK_LGUI | QK_RCTL | QK_RSFT | QK_RALT | QK_RGUI;
60
61 return (keycode & ~(all_mods));
62}
63
64// Internal variables
65static const key_override_t *active_override = NULL;
66static bool active_override_trigger_is_down = false;
67
68// Used to keep track of what non-modifier key was last pressed down. We never want to activate an override for a trigger key that is not the last non-mod key that was pressed down. OSes internally completely unregister a key that is held when a different key is held down after. We want to respect this here.
69static uint16_t last_key_down = 0;
70// When was the last key pressed down?
71static uint32_t last_key_down_time = 0;
72
73// What timestamp are we comparing to when waiting to register a deferred key?
74static uint32_t defer_reference_time = 0;
75// What delay should pass until deferred key is registered?
76static uint32_t defer_delay = 0;
77
78// Holds the keycode that should be registered at a later time, in order to not get false key presses
79static uint16_t deferred_register = 0;
80
81// TODO: in future maybe save in EEPROM?
82static bool enabled = true;
83
84// Public variables
85__attribute__((weak)) const key_override_t **key_overrides = NULL;
86
87// Forward decls
88static const key_override_t *clear_active_override(const bool allow_reregister);
89
90void key_override_on(void) {
91 enabled = true;
92 key_override_printf("Key override ON\n");
93}
94
95void key_override_off(void) {
96 enabled = false;
97 clear_active_override(false);
98 key_override_printf("Key override OFF\n");
99}
100
101void key_override_toggle(void) {
102 if (key_override_is_enabled()) {
103 key_override_off();
104 } else {
105 key_override_on();
106 }
107}
108
109bool key_override_is_enabled(void) { return enabled; }
110
111// Returns whether the modifiers that are pressed are such that the override should activate
112static bool key_override_matches_active_modifiers(const key_override_t *override, const uint8_t mods) {
113 // Check that negative keys pass
114 if ((override->negative_mod_mask & mods) != 0) {
115 return false;
116 }
117
118 // Immediately return true if the override requires no mods down
119 if (override->trigger_mods == 0) {
120 return true;
121 }
122
123 if ((override->options & ko_option_one_mod) != 0) {
124 // At least one of the trigger modifiers must be down
125 return (override->trigger_mods & mods) != 0;
126 } else {
127 // All trigger modifiers must be down, but each mod can be active on either side (if both sides are specified).
128
129 // Which mods, regardless of side, are required?
130 uint8_t one_sided_required_mods = (override->trigger_mods & 0b1111) | (override->trigger_mods >> 4);
131
132 // Which of the required modifiers are active?
133 uint8_t active_required_mods = override->trigger_mods & mods;
134
135 // Move the active requird mods to one side
136 uint8_t one_sided_active_required_mods = (active_required_mods & 0b1111) | (active_required_mods >> 4);
137
138 // Check that there is a full match between the required one-sided mods and active required one sided mods
139 return one_sided_active_required_mods == one_sided_required_mods;
140 }
141
142 return false;
143}
144
145static void schedule_deferred_register(const uint16_t keycode) {
146 if (timer_elapsed32(last_key_down_time) < KEY_OVERRIDE_REPEAT_DELAY) {
147 // Defer until KEY_OVERRIDE_REPEAT_DELAY has passed since the trigger key was pressed down. This emulates the behavior as holding down a key x, then holding down shift shortly after. Usually the shifted key X is not immediately produced, but rather a 'key repeat delay' passes before any repeated character is output.
148 defer_reference_time = last_key_down_time;
149 defer_delay = KEY_OVERRIDE_REPEAT_DELAY;
150 } else {
151 // Wait a very short time when a modifier event triggers the override to avoid false activations when e.g. a modifier is pressed just before a key is released (with the intention of pairing the modifier with a different key), or a modifier is lifted shortly before the trigger key is lifted. Operating systems by default reject modifier-events that happen very close to a non-modifier event.
152 defer_reference_time = timer_read32();
153 defer_delay = 50; // 50ms
154 }
155 deferred_register = keycode;
156}
157
158const key_override_t *clear_active_override(const bool allow_reregister) {
159 if (active_override == NULL) {
160 return NULL;
161 }
162
163 key_override_printf("Deactivating override\n");
164
165 deferred_register = 0;
166
167 // Clear the suppressed mods
168 clear_suppressed_override_mods();
169
170 // Unregister the replacement. First remove the weak override mods
171 clear_weak_override_mods();
172
173 const key_override_t *const old = active_override;
174
175 const uint8_t mod_free_replacement = clear_mods_from(active_override->replacement);
176
177 bool unregister_replacement = mod_free_replacement != KC_NO && // KC_NO is never registered
178 mod_free_replacement < SAFE_RANGE; // Custom keycodes are never registered
179
180 // Try firing the custom handler
181 if (active_override->custom_action != NULL) {
182 unregister_replacement &= active_override->custom_action(false, active_override->context);
183 }
184
185 // Then unregister the mod-free replacement key if desired
186 if (unregister_replacement) {
187 if (IS_KEY(mod_free_replacement)) {
188 del_key(mod_free_replacement);
189 } else {
190 key_override_printf("NOT KEY 1\n");
191 send_keyboard_report();
192 unregister_code(mod_free_replacement);
193 }
194 }
195
196 const uint16_t trigger = active_override->trigger;
197
198 const bool reregister_trigger = allow_reregister && // Check if allowed from caller
199 (active_override->options & ko_option_no_reregister_trigger) == 0 && // Check if override allows
200 active_override_trigger_is_down && // Check if trigger is even down
201 trigger != KC_NO && // KC_NO is never registered
202 trigger < SAFE_RANGE; // A custom keycode should not be registered
203
204 // Optionally re-register the trigger if it is still down
205 if (reregister_trigger) {
206 key_override_printf("Re-registering trigger deferred: %u\n", trigger);
207
208 // This will always be a modifier event, so defer always
209 schedule_deferred_register(trigger);
210 }
211
212 send_keyboard_report();
213
214 active_override = NULL;
215 active_override_trigger_is_down = false;
216
217 return old;
218}
219
220/** Checks if the key event is an allowed activation event for the provided override. Does not check things like whether the correct mods or correct trigger key is down. */
221static bool check_activation_event(const key_override_t *override, const bool key_down, const bool is_mod) {
222 ko_option_t options = override->options;
223
224 if ((options & ko_options_all_activations) == 0) {
225 // No activation option provided at all. This is wrong, but let's assume the default activations (ko_options_all_activations) were meant...
226 options = ko_options_all_activations;
227 }
228
229 if (is_mod) {
230 if (key_down) {
231 return (options & ko_option_activation_required_mod_down) != 0;
232 } else {
233 return (options & ko_option_activation_negative_mod_up) != 0;
234 }
235 } else {
236 if (key_down) {
237 return (options & ko_option_activation_trigger_down) != 0;
238 } else {
239 return false;
240 }
241 }
242}
243
244/** Iterates through the list of key overrides and tries activating each, until it finds one that activates or reaches the end of overrides. Returns true if the key action for `keycode` should be sent */
245static bool try_activating_override(const uint16_t keycode, const uint8_t layer, const bool key_down, const bool is_mod, const uint8_t active_mods, bool *activated) {
246 if (key_overrides == NULL) {
247 return true;
248 }
249
250 for (uint8_t i = 0;; i++) {
251 const key_override_t *const override = key_overrides[i];
252
253 // End of array
254 if (override == NULL) {
255 break;
256 }
257
258 // Fast, but not full mods check. Most key presses will not have any mods down, and most overrides will require mods. Hence here we filter overrides that require mods to be down while no mods are down
259 if (active_mods == 0 && override->trigger_mods != 0) {
260 key_override_printf("Not activating override: Modifiers don't match\n");
261 continue;
262 }
263
264 // Check layer
265 if ((override->layers & (1 << layer)) == 0) {
266 key_override_printf("Not activating override: Not set to activate on pressed layer\n");
267 continue;
268 }
269
270 // Check allowed activation events
271 if (!check_activation_event(override, key_down, is_mod)) {
272 key_override_printf("Not activating override: Activation event not allowed\n");
273 continue;
274 }
275
276 const bool is_trigger = override->trigger == keycode;
277
278 // Check if trigger lifted. This is a small optimization in order to skip the remaining checks
279 if (is_trigger && !key_down) {
280 key_override_printf("Not activating override: Trigger lifted\n");
281 continue;
282 }
283
284 // If the trigger is KC_NO it means 'no key', so only the required modifiers need to be down.
285 const bool no_trigger = override->trigger == KC_NO;
286
287 // Check if aleady active
288 if (override == active_override) {
289 key_override_printf("Not activating override: Alerady actived\n");
290 continue;
291 }
292
293 // Check if enabled
294 if (override->enabled != NULL && !((*(override->enabled) & 1))) {
295 key_override_printf("Not activating override: Not enabled\n");
296 continue;
297 }
298
299 // Check mods precisely
300 if (!key_override_matches_active_modifiers(override, active_mods)) {
301 key_override_printf("Not activating override: Modifiers don't match\n");
302 continue;
303 }
304
305 // Check if trigger key is down.
306 const bool trigger_down = is_trigger && key_down;
307
308 // At this point, all requirements for activation are checked, except whether the trigger key is pressed. Now we check if the required trigger is down
309 // If no trigger key is required, yes.
310 // If the trigger was just pressed, yes.
311 // If the last non-mod key that was pressed down is the trigger key, yes.
312 bool should_activate = no_trigger || trigger_down || last_key_down == override->trigger;
313
314 if (!should_activate) {
315 key_override_printf("Not activating override. Trigger not down\n");
316 continue;
317 }
318
319 key_override_printf("Activating override\n");
320
321 clear_active_override(false);
322
323 active_override = override;
324 active_override_trigger_is_down = true;
325
326 set_suppressed_override_mods(override->suppressed_mods);
327
328 if (!trigger_down && !no_trigger) {
329 // When activating a key override the trigger is is always unregistered. In the case where the key that newly pressed is not the trigger key, we have to explicitly remove the trigger key from the keyboard report. If the trigger was just pressed down we simply suppress the event which also has the effect of the trigger key not being registered in the keyboard report.
330 if (IS_KEY(override->trigger)) {
331 del_key(override->trigger);
332 } else {
333 unregister_code(override->trigger);
334 }
335 }
336
337 const uint16_t mod_free_replacement = clear_mods_from(override->replacement);
338
339 bool register_replacement = mod_free_replacement != KC_NO && // KC_NO is never registered
340 mod_free_replacement < SAFE_RANGE; // Custom keycodes are never registered
341
342 // Try firing the custom handler
343 if (override->custom_action != NULL) {
344 register_replacement &= override->custom_action(true, override->context);
345 }
346
347 if (register_replacement) {
348 const uint8_t override_mods = extract_mod_bits(override->replacement);
349 set_weak_override_mods(override_mods);
350
351 // If this is a modifier event that activates the key override we _always_ defer the actual full activation of the override
352 if (is_mod) {
353 key_override_printf("Deferring register replacement key\n");
354 schedule_deferred_register(mod_free_replacement);
355 send_keyboard_report();
356 } else {
357 if (IS_KEY(mod_free_replacement)) {
358 add_key(mod_free_replacement);
359 } else {
360 key_override_printf("NOT KEY 2\n");
361 send_keyboard_report();
362 // On macOS there seems to be a race condition when it comes to the keyboard report and consumer keycodes. It seems the OS may recognize a consumer keycode before an updated keyboard report, even if the keyboard report is actually sent before the consumer key. I assume it is some sort of race condition because it happens infrequently and very irregularly. Waiting for about at least 10ms between sending the keyboard report and sending the consumer code has shown to fix this.
363 wait_ms(10);
364 register_code(mod_free_replacement);
365 }
366 }
367 } else {
368 // If not registering the replacement key send keyboard report to update the unregistered keys.
369 send_keyboard_report();
370 }
371
372 *activated = true;
373
374 // If the trigger is down, suppress the event so that it does not get added to the keyboard report.
375 return !trigger_down;
376 }
377
378 *activated = false;
379
380 return true;
381}
382
383void matrix_scan_key_override(void) {
384 if (deferred_register == 0) {
385 return;
386 }
387
388 if (timer_elapsed32(defer_reference_time) >= defer_delay) {
389 key_override_printf("Registering deferred key\n");
390 register_code16(deferred_register);
391 deferred_register = 0;
392 defer_reference_time = 0;
393 defer_delay = 0;
394 }
395}
396
397bool process_key_override(const uint16_t keycode, const keyrecord_t *const record) {
398#ifdef BENCH_KEY_OVERRIDE
399 uint16_t start = timer_read();
400#endif
401
402 const bool key_down = record->event.pressed;
403 const bool is_mod = IS_MOD(keycode);
404
405 if (key_down) {
406 switch (keycode) {
407 case KEY_OVERRIDE_TOGGLE:
408 key_override_toggle();
409 return false;
410
411 case KEY_OVERRIDE_ON:
412 key_override_on();
413 return false;
414
415 case KEY_OVERRIDE_OFF:
416 key_override_off();
417 return false;
418
419 default:
420 break;
421 }
422 }
423
424 if (!enabled) {
425 return true;
426 }
427
428 uint8_t effective_mods = get_mods();
429
430#ifdef KEY_OVERRIDE_INCLUDE_WEAK_MODS
431 effective_mods |= get_weak_mods();
432#endif
433
434#ifndef NO_ACTION_ONESHOT
435 // Locked one shot mods are added to get_mods(), I think (why??) while oneshot mods are in get_oneshot_mods(). Still OR with get_locked_oneshot_mods because that's where those mods _should_ be saved.
436 effective_mods |= get_oneshot_locked_mods() | get_oneshot_mods();
437#endif
438
439 if (is_mod) {
440 // The mods returned from get_mods() will be updated with this new event _after_ this code runs. Hence we manually update the effective mods here to really know the effective mods.
441 if (key_down) {
442 effective_mods |= MOD_BIT(keycode);
443 } else {
444 effective_mods &= ~MOD_BIT(keycode);
445 }
446 } else {
447 if (key_down) {
448 last_key_down = keycode;
449 last_key_down_time = timer_read32();
450 deferred_register = 0;
451 }
452
453 // The last key that was pressed was just released. No more keys are therefore sending input
454 if (!key_down && keycode == last_key_down) {
455 last_key_down = 0;
456 last_key_down_time = 0;
457 // We also cancel any deferred registers because, again, no keys are sending any input. Only the last key that is pressed creates an input – this key was just lifted.
458 deferred_register = 0;
459 }
460 }
461
462 key_override_printf("key down: %u keycode: %u is mod: %u effective mods: %u\n", key_down, keycode, is_mod, effective_mods);
463
464 bool send_key_action = true;
465 bool activated = false;
466
467 // Non-mod key up events never activate a key override
468 if (is_mod || key_down) {
469 // Get the exact layer that was hit. It will be cached at this point
470 const uint8_t layer = read_source_layers_cache(record->event.key);
471
472 // Use blocked to ensure the same override is not activated again immediately after it is deactivated
473 send_key_action = try_activating_override(keycode, layer, key_down, is_mod, effective_mods, &activated);
474
475 if (!send_key_action) {
476 send_keyboard_report();
477 }
478 }
479
480 if (!activated && active_override != NULL) {
481 if (is_mod) {
482 // Check if necessary modifier of current override goes up or a negative mod goes down
483 if (!key_override_matches_active_modifiers(active_override, effective_mods)) {
484 key_override_printf("Deactivating override because necessary modifier lifted or negative mod pressed\n");
485 clear_active_override(true);
486 }
487 } else {
488 // Check if trigger of current override goes up or if override does not allow additional keys to be down and another key goes down
489 const bool is_trigger = keycode == active_override->trigger;
490 bool should_deactivate = false;
491
492 // Check if trigger key lifted
493 if (is_trigger && !key_down) {
494 should_deactivate = true;
495 active_override_trigger_is_down = false;
496 key_override_printf("Deactivating override because trigger key up\n");
497 }
498
499 // Check if another key was pressed
500 if (key_down && (active_override->options & ko_option_no_unregister_on_other_key_down) == 0) {
501 should_deactivate = true;
502 key_override_printf("Deactivating override because another key was pressed\n");
503 }
504
505 if (should_deactivate) {
506 clear_active_override(false);
507 }
508 }
509 }
510
511#ifdef BENCH_KEY_OVERRIDE
512 uint16_t elapsed = timer_elapsed(start);
513
514 dprintf("Processing key overrides took: %u ms\n", elapsed);
515#endif
516
517 return send_key_action;
518}
diff --git a/quantum/process_keycode/process_key_override.h b/quantum/process_keycode/process_key_override.h
new file mode 100644
index 000000000..9ba59e4e9
--- /dev/null
+++ b/quantum/process_keycode/process_key_override.h
@@ -0,0 +1,147 @@
1/*
2 * Copyright 2021 Jonas Gessner
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19
20#include <stdbool.h>
21#include <stddef.h>
22#include <stdint.h>
23
24#include "action_layer.h"
25
26/**
27 * Key overrides allow you to send a different key-modifier combination or perform a custom action when a certain modifier-key combination is pressed.
28 *
29 * For example, you may configure a key override to send the delete key when shift + backspace are pressed together, or that your volume keys become screen brightness keys when holding ctrl. The possibilities are quite vast and the documentation contains a few examples for inspiration.
30 *
31 * See the documentation and examples here: https://docs.qmk.fm/#/feature_key_overrides
32 */
33
34/** Bitfield with various options controlling the behavior of a key override. */
35typedef enum {
36 /** Allow activating when the trigger key is pressed down. */
37 ko_option_activation_trigger_down = (1 << 0),
38 /** Allow activating when a necessary modifier is pressed down. */
39 ko_option_activation_required_mod_down = (1 << 1),
40 /** Allow activating when a negative modifier is released. */
41 ko_option_activation_negative_mod_up = (1 << 2),
42
43 ko_options_all_activations = ko_option_activation_negative_mod_up | ko_option_activation_required_mod_down | ko_option_activation_trigger_down,
44
45 /** If set, any of the modifiers in trigger_mods will be enough to activate the override (logical OR of modifiers). If not set, all the modifiers in trigger_mods have to be pressed (logical AND of modifiers). */
46 ko_option_one_mod = (1 << 3),
47
48 /** If set, the trigger key will never be registered again after the override is deactivated. */
49 ko_option_no_reregister_trigger = (1 << 4),
50
51 /** If set, the override will not deactivate when another key is pressed down. Use only if you really know you need this. */
52 ko_option_no_unregister_on_other_key_down = (1 << 5),
53
54 /** The default options used by the ko_make_xxx functions. */
55 ko_options_default = ko_options_all_activations,
56} ko_option_t;
57
58/** Defines a single key override */
59typedef struct {
60 // The non-modifier keycode that triggers the override. This keycode, and the necessary modifiers (trigger_mods) must be pressed to activate this override. Set this to the keycode of the key that should activate the override. Set to KC_NO to require only the necessary modifiers to be pressed and no non-modifier.
61 uint16_t trigger;
62
63 // Which mods need to be down for activation. If both sides of a modifier are set (e.g. left ctrl and right ctrl) then only one is required to be pressed (e.g. left ctrl suffices). Use the MOD_MASK_XXX and MOD_BIT() macros for this.
64 uint8_t trigger_mods;
65
66 // This is a BITMASK (!), defining which layers this override applies to. To use this override on layer i set the ith bit (1 << i).
67 layer_state_t layers;
68
69 // Which modifiers cannot be down. It must hold that (active_mods & negative_mod_mask) == 0, otherwise the key override will not be activated. An active override will be deactivated once this is no longer true.
70 uint8_t negative_mod_mask;
71
72 // Modifiers to 'suppress' while the override is active. To suppress a modifier means that even though the modifier key is held down, the host OS sees the modifier as not pressed. Can be used to suppress the trigger modifiers, as a trivial example.
73 uint8_t suppressed_mods;
74
75 // The complex keycode to send as replacement when this override is triggered. This can be a simple keycode, a key-modifier combination (e.g. C(KC_A)), or KC_NO (to register no replacement keycode). Use in combination with suppressed_mods to get the correct modifiers to be sent.
76 uint16_t replacement;
77
78 // Options controlling the behavior of the override, such as what actions are allowed to activate the override.
79 ko_option_t options;
80
81 // If not NULL, this function will be called right before the replacement key is registered, along with the provided context and a flag indicating whether the override was activated or deactivated. This function allows you to run some custom actions for specific key overrides. If you return `false`, the replacement key is not registered/unregistered as it would normally. Return `true` to register and unregister the override normally.
82 bool (*custom_action)(bool activated, void *context);
83
84 // A context that will be passed to the custom action function.
85 void *context;
86
87 // If this points to false this override will not be used. Set to NULL to always have this override enabled.
88 bool *enabled;
89} key_override_t;
90
91/** Define this as a null-terminated array of pointers to key overrides. These key overrides will be used by qmk. */
92extern const key_override_t **key_overrides;
93
94/** Turns key overrides on */
95extern void key_override_on(void);
96
97/** Turns key overrides off */
98extern void key_override_off(void);
99
100/** Toggles key overrides on */
101extern void key_override_toggle(void);
102
103/** Returns whether key overrides are enabled */
104extern bool key_override_is_enabled(void);
105
106/**
107 * Preferrably use these macros to create key overrides. They fix many of the options to a standard setting that should satisfy most basic use-cases. Only directly create a key_override_t struct when you really need to.
108 */
109
110// clang-format off
111
112/**
113 * Convenience initializer to create a basic key override. Activates the override on all layers.
114 */
115#define ko_make_basic(trigger_mods, trigger_key, replacement_key) \
116 ko_make_with_layers(trigger_mods, trigger_key, replacement_key, ~0)
117
118/**
119 * Convenience initializer to create a basic key override. Provide a bitmap (of type layer_state_t) with the bits set for each layer on which the override should activate.
120 */
121#define ko_make_with_layers(trigger_mods, trigger_key, replacement_key, layers) \
122 ko_make_with_layers_and_negmods(trigger_mods, trigger_key, replacement_key, layers, 0)
123
124/**
125 * Convenience initializer to create a basic key override. Provide a bitmap with the bits set for each layer on which the override should activate. Also provide a negative modifier mask, that is used to define which modifiers may not be pressed.
126 */
127#define ko_make_with_layers_and_negmods(trigger_mods, trigger_key, replacement_key, layers, negative_mask) \
128 ko_make_with_layers_negmods_and_options(trigger_mods, trigger_key, replacement_key, layers, negative_mask, ko_options_default)
129
130 /**
131 * Convenience initializer to create a basic key override. Provide a bitmap with the bits set for each layer on which the override should activate. Also provide a negative modifier mask, that is used to define which modifiers may not be pressed. Provide options for additional control of the behavior of the override.
132 */
133#define ko_make_with_layers_negmods_and_options(trigger_mods_, trigger_key, replacement_key, layer_mask, negative_mask, options_) \
134 ((const key_override_t){ \
135 .trigger_mods = (trigger_mods_), \
136 .layers = (layer_mask), \
137 .suppressed_mods = (trigger_mods_), \
138 .options = (options_), \
139 .negative_mod_mask = (negative_mask), \
140 .custom_action = NULL, \
141 .context = NULL, \
142 .trigger = (trigger_key), \
143 .replacement = (replacement_key), \
144 .enabled = NULL \
145 })
146
147// clang-format on
diff --git a/quantum/process_keycode/process_key_override_private.h b/quantum/process_keycode/process_key_override_private.h
new file mode 100644
index 000000000..1d0e134a1
--- /dev/null
+++ b/quantum/process_keycode/process_key_override_private.h
@@ -0,0 +1,24 @@
1/*
2 * Copyright 2021 Jonas Gessner
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19
20#include <stdint.h>
21#include "action.h"
22
23bool process_key_override(const uint16_t keycode, const keyrecord_t *const record);
24void matrix_scan_key_override(void);
diff --git a/quantum/quantum.c b/quantum/quantum.c
index b4cfa28d7..9cfffd931 100644
--- a/quantum/quantum.c
+++ b/quantum/quantum.c
@@ -58,12 +58,16 @@ float bell_song[][2] = SONG(TERMINAL_SOUND);
58# include "process_auto_shift.h" 58# include "process_auto_shift.h"
59#endif 59#endif
60 60
61static void do_code16(uint16_t code, void (*f)(uint8_t)) { 61#ifdef KEY_OVERRIDE_ENABLE
62# include "process_key_override_private.h"
63#endif
64
65uint8_t extract_mod_bits(uint16_t code) {
62 switch (code) { 66 switch (code) {
63 case QK_MODS ... QK_MODS_MAX: 67 case QK_MODS ... QK_MODS_MAX:
64 break; 68 break;
65 default: 69 default:
66 return; 70 return 0;
67 } 71 }
68 72
69 uint8_t mods_to_send = 0; 73 uint8_t mods_to_send = 0;
@@ -80,9 +84,11 @@ static void do_code16(uint16_t code, void (*f)(uint8_t)) {
80 if (code & QK_LGUI) mods_to_send |= MOD_BIT(KC_LGUI); 84 if (code & QK_LGUI) mods_to_send |= MOD_BIT(KC_LGUI);
81 } 85 }
82 86
83 f(mods_to_send); 87 return mods_to_send;
84} 88}
85 89
90static void do_code16(uint16_t code, void (*f)(uint8_t)) { f(extract_mod_bits(code)); }
91
86void register_code16(uint16_t code) { 92void register_code16(uint16_t code) {
87 if (IS_MOD(code) || code == KC_NO) { 93 if (IS_MOD(code) || code == KC_NO) {
88 do_code16(code, register_mods); 94 do_code16(code, register_mods);
@@ -243,6 +249,9 @@ bool process_record_quantum(keyrecord_t *record) {
243#if (defined(AUDIO_ENABLE) || (defined(MIDI_ENABLE) && defined(MIDI_BASIC))) && !defined(NO_MUSIC_MODE) 249#if (defined(AUDIO_ENABLE) || (defined(MIDI_ENABLE) && defined(MIDI_BASIC))) && !defined(NO_MUSIC_MODE)
244 process_music(keycode, record) && 250 process_music(keycode, record) &&
245#endif 251#endif
252#ifdef KEY_OVERRIDE_ENABLE
253 process_key_override(keycode, record) &&
254#endif
246#ifdef TAP_DANCE_ENABLE 255#ifdef TAP_DANCE_ENABLE
247 process_tap_dance(keycode, record) && 256 process_tap_dance(keycode, record) &&
248#endif 257#endif
@@ -408,6 +417,10 @@ void matrix_scan_quantum() {
408 matrix_scan_music(); 417 matrix_scan_music();
409#endif 418#endif
410 419
420#ifdef KEY_OVERRIDE_ENABLE
421 matrix_scan_key_override();
422#endif
423
411#ifdef SEQUENCER_ENABLE 424#ifdef SEQUENCER_ENABLE
412 matrix_scan_sequencer(); 425 matrix_scan_sequencer();
413#endif 426#endif
diff --git a/quantum/quantum.h b/quantum/quantum.h
index 66ba96fde..673796e6b 100644
--- a/quantum/quantum.h
+++ b/quantum/quantum.h
@@ -118,6 +118,10 @@ extern layer_state_t layer_state;
118# include "process_unicodemap.h" 118# include "process_unicodemap.h"
119#endif 119#endif
120 120
121#ifdef KEY_OVERRIDE_ENABLE
122# include "process_key_override.h"
123#endif
124
121#ifdef TAP_DANCE_ENABLE 125#ifdef TAP_DANCE_ENABLE
122# include "process_tap_dance.h" 126# include "process_tap_dance.h"
123#endif 127#endif
diff --git a/quantum/quantum_keycodes.h b/quantum/quantum_keycodes.h
index c361dd670..3d2dbde92 100644
--- a/quantum/quantum_keycodes.h
+++ b/quantum/quantum_keycodes.h
@@ -514,6 +514,11 @@ enum quantum_keycodes {
514 // RGB underglow/matrix (continued) 514 // RGB underglow/matrix (continued)
515 RGB_MODE_TWINKLE, 515 RGB_MODE_TWINKLE,
516 516
517 // Key Overrides
518 KEY_OVERRIDE_TOGGLE,
519 KEY_OVERRIDE_ON,
520 KEY_OVERRIDE_OFF,
521
517 // Start of custom keycode range for keyboards and keymaps - always leave at the end 522 // Start of custom keycode range for keyboards and keymaps - always leave at the end
518 SAFE_RANGE 523 SAFE_RANGE
519}; 524};
diff --git a/show_options.mk b/show_options.mk
index af38bcb24..dd1ad5171 100644
--- a/show_options.mk
+++ b/show_options.mk
@@ -44,6 +44,7 @@ OTHER_OPTION_NAMES = \
44 AUTO_SHIFT_MODIFIERS \ 44 AUTO_SHIFT_MODIFIERS \
45 COMBO_ENABLE \ 45 COMBO_ENABLE \
46 KEY_LOCK_ENABLE \ 46 KEY_LOCK_ENABLE \
47 KEY_OVERRIDE_ENABLE \
47 LEADER_ENABLE \ 48 LEADER_ENABLE \
48 PRINTING_ENABLE \ 49 PRINTING_ENABLE \
49 STENO_ENABLE \ 50 STENO_ENABLE \
diff --git a/tmk_core/common/action_util.c b/tmk_core/common/action_util.c
index a57c8bf66..2b3c00cba 100644
--- a/tmk_core/common/action_util.c
+++ b/tmk_core/common/action_util.c
@@ -27,6 +27,10 @@ extern keymap_config_t keymap_config;
27static uint8_t real_mods = 0; 27static uint8_t real_mods = 0;
28static uint8_t weak_mods = 0; 28static uint8_t weak_mods = 0;
29static uint8_t macro_mods = 0; 29static uint8_t macro_mods = 0;
30#ifdef KEY_OVERRIDE_ENABLE
31static uint8_t weak_override_mods = 0;
32static uint8_t suppressed_mods = 0;
33#endif
30 34
31#ifdef USB_6KRO_ENABLE 35#ifdef USB_6KRO_ENABLE
32# define RO_ADD(a, b) ((a + b) % KEYBOARD_REPORT_KEYS) 36# define RO_ADD(a, b) ((a + b) % KEYBOARD_REPORT_KEYS)
@@ -229,6 +233,7 @@ void send_keyboard_report(void) {
229 keyboard_report->mods = real_mods; 233 keyboard_report->mods = real_mods;
230 keyboard_report->mods |= weak_mods; 234 keyboard_report->mods |= weak_mods;
231 keyboard_report->mods |= macro_mods; 235 keyboard_report->mods |= macro_mods;
236
232#ifndef NO_ACTION_ONESHOT 237#ifndef NO_ACTION_ONESHOT
233 if (oneshot_mods) { 238 if (oneshot_mods) {
234# if (defined(ONESHOT_TIMEOUT) && (ONESHOT_TIMEOUT > 0)) 239# if (defined(ONESHOT_TIMEOUT) && (ONESHOT_TIMEOUT > 0))
@@ -244,6 +249,13 @@ void send_keyboard_report(void) {
244 } 249 }
245 250
246#endif 251#endif
252
253#ifdef KEY_OVERRIDE_ENABLE
254 // These need to be last to be able to properly control key overrides
255 keyboard_report->mods &= ~suppressed_mods;
256 keyboard_report->mods |= weak_override_mods;
257#endif
258
247 host_keyboard_send(keyboard_report); 259 host_keyboard_send(keyboard_report);
248} 260}
249 261
@@ -299,6 +311,22 @@ void set_weak_mods(uint8_t mods) { weak_mods = mods; }
299 */ 311 */
300void clear_weak_mods(void) { weak_mods = 0; } 312void clear_weak_mods(void) { weak_mods = 0; }
301 313
314#ifdef KEY_OVERRIDE_ENABLE
315/** \brief set weak mods used by key overrides. DO not call this manually
316 */
317void set_weak_override_mods(uint8_t mods) { weak_override_mods = mods; }
318/** \brief clear weak mods used by key overrides. DO not call this manually
319 */
320void clear_weak_override_mods(void) { weak_override_mods = 0; }
321
322/** \brief set suppressed mods used by key overrides. DO not call this manually
323 */
324void set_suppressed_override_mods(uint8_t mods) { suppressed_mods = mods; }
325/** \brief clear suppressed mods used by key overrides. DO not call this manually
326 */
327void clear_suppressed_override_mods(void) { suppressed_mods = 0; }
328#endif
329
302/* macro modifier */ 330/* macro modifier */
303/** \brief get macro mods 331/** \brief get macro mods
304 * 332 *