process_key_override.c (21418B)
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 "process_key_override.h" 19 #include "report.h" 20 #include "timer.h" 21 #include "debug.h" 22 #include "wait.h" 23 #include "action_util.h" 24 #include "quantum.h" 25 #include "quantum_keycodes.h" 26 #include "keymap_introspection.h" 27 28 #ifndef KEY_OVERRIDE_REPEAT_DELAY 29 # define KEY_OVERRIDE_REPEAT_DELAY 500 30 #endif 31 32 // For benchmarking the time it takes to call process_key_override on every key press (needs keyboard debugging enabled as well) 33 // #define BENCH_KEY_OVERRIDE 34 35 // For debug output (needs keyboard debugging enabled as well) 36 // #define DEBUG_KEY_OVERRIDE 37 38 #ifdef DEBUG_KEY_OVERRIDE 39 # define key_override_printf dprintf 40 #else 41 # define key_override_printf(str, ...) \ 42 { \ 43 } 44 #endif 45 46 // Helpers 47 48 // Private functions implemented elsewhere in qmk/tmk 49 extern uint8_t extract_mod_bits(uint16_t code); 50 extern void set_weak_override_mods(uint8_t mods); 51 extern void clear_weak_override_mods(void); 52 extern void set_suppressed_override_mods(uint8_t mods); 53 extern void clear_suppressed_override_mods(void); 54 55 static uint16_t clear_mods_from(uint16_t keycode) { 56 switch (keycode) { 57 case QK_MODS ... QK_MODS_MAX: 58 break; 59 default: 60 return keycode; 61 } 62 63 static const uint16_t all_mods = QK_LCTL | QK_LSFT | QK_LALT | QK_LGUI | QK_RCTL | QK_RSFT | QK_RALT | QK_RGUI; 64 65 return (keycode & ~(all_mods)); 66 } 67 68 // Internal variables 69 static const key_override_t *active_override = NULL; 70 static bool active_override_trigger_is_down = false; 71 72 // 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. 73 static uint16_t last_key_down = 0; 74 // When was the last key pressed down? 75 static uint32_t last_key_down_time = 0; 76 77 // What timestamp are we comparing to when waiting to register a deferred key? 78 static uint32_t defer_reference_time = 0; 79 // What delay should pass until deferred key is registered? 80 static uint32_t defer_delay = 0; 81 82 // Holds the keycode that should be registered at a later time, in order to not get false key presses 83 static uint16_t deferred_register = 0; 84 85 // TODO: in future maybe save in EEPROM? 86 static bool enabled = true; 87 88 // Forward decls 89 static const key_override_t *clear_active_override(const bool allow_reregister); 90 91 void key_override_on(void) { 92 enabled = true; 93 key_override_printf("Key override ON\n"); 94 } 95 96 void key_override_off(void) { 97 enabled = false; 98 clear_active_override(false); 99 key_override_printf("Key override OFF\n"); 100 } 101 102 void key_override_toggle(void) { 103 if (key_override_is_enabled()) { 104 key_override_off(); 105 } else { 106 key_override_on(); 107 } 108 } 109 110 bool key_override_is_enabled(void) { 111 return enabled; 112 } 113 114 // Returns whether the modifiers that are pressed are such that the override should activate 115 static bool key_override_matches_active_modifiers(const key_override_t *override, const uint8_t mods) { 116 // Check that negative keys pass 117 if ((override->negative_mod_mask & mods) != 0) { 118 return false; 119 } 120 121 // Immediately return true if the override requires no mods down 122 if (override->trigger_mods == 0) { 123 return true; 124 } 125 126 if ((override->options & ko_option_one_mod) != 0) { 127 // At least one of the trigger modifiers must be down 128 return (override->trigger_mods & mods) != 0; 129 } else { 130 // All trigger modifiers must be down, but each mod can be active on either side (if both sides are specified). 131 132 // Which mods, regardless of side, are required? 133 uint8_t one_sided_required_mods = (override->trigger_mods & 0b1111) | (override->trigger_mods >> 4); 134 135 // Which of the required modifiers are active? 136 uint8_t active_required_mods = override->trigger_mods & mods; 137 138 // Move the active requird mods to one side 139 uint8_t one_sided_active_required_mods = (active_required_mods & 0b1111) | (active_required_mods >> 4); 140 141 // Check that there is a full match between the required one-sided mods and active required one sided mods 142 return one_sided_active_required_mods == one_sided_required_mods; 143 } 144 145 return false; 146 } 147 148 static void schedule_deferred_register(const uint16_t keycode) { 149 if (timer_elapsed32(last_key_down_time) < KEY_OVERRIDE_REPEAT_DELAY) { 150 // 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. 151 defer_reference_time = last_key_down_time; 152 defer_delay = KEY_OVERRIDE_REPEAT_DELAY; 153 } else { 154 // 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. 155 defer_reference_time = timer_read32(); 156 defer_delay = 50; // 50ms 157 } 158 deferred_register = keycode; 159 } 160 161 const key_override_t *clear_active_override(const bool allow_reregister) { 162 if (active_override == NULL) { 163 return NULL; 164 } 165 166 key_override_printf("Deactivating override\n"); 167 168 deferred_register = 0; 169 170 // Clear the suppressed mods 171 clear_suppressed_override_mods(); 172 173 // Unregister the replacement. First remove the weak override mods 174 clear_weak_override_mods(); 175 176 const key_override_t *const old = active_override; 177 178 const uint8_t mod_free_replacement = clear_mods_from(active_override->replacement); 179 180 bool unregister_replacement = mod_free_replacement != KC_NO && // KC_NO is never registered 181 mod_free_replacement < SAFE_RANGE; // Custom keycodes are never registered 182 183 // Try firing the custom handler 184 if (active_override->custom_action != NULL) { 185 unregister_replacement &= active_override->custom_action(false, active_override->context); 186 } 187 188 // Then unregister the mod-free replacement key if desired 189 if (unregister_replacement) { 190 if (IS_BASIC_KEYCODE(mod_free_replacement)) { 191 del_key(mod_free_replacement); 192 } else { 193 key_override_printf("NOT KEY 1\n"); 194 send_keyboard_report(); 195 unregister_code(mod_free_replacement); 196 } 197 } 198 199 const uint16_t trigger = active_override->trigger; 200 201 const bool reregister_trigger = allow_reregister && // Check if allowed from caller 202 (active_override->options & ko_option_no_reregister_trigger) == 0 && // Check if override allows 203 active_override_trigger_is_down && // Check if trigger is even down 204 trigger != KC_NO && // KC_NO is never registered 205 trigger < SAFE_RANGE; // A custom keycode should not be registered 206 207 // Optionally re-register the trigger if it is still down 208 if (reregister_trigger) { 209 key_override_printf("Re-registering trigger deferred: %u\n", trigger); 210 211 // This will always be a modifier event, so defer always 212 schedule_deferred_register(trigger); 213 } 214 215 send_keyboard_report(); 216 217 active_override = NULL; 218 active_override_trigger_is_down = false; 219 220 return old; 221 } 222 223 /** 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. */ 224 static bool check_activation_event(const key_override_t *override, const bool key_down, const bool is_mod) { 225 ko_option_t options = override->options; 226 227 if ((options & ko_options_all_activations) == 0) { 228 // No activation option provided at all. This is wrong, but let's assume the default activations (ko_options_all_activations) were meant... 229 options = ko_options_all_activations; 230 } 231 232 if (is_mod) { 233 if (key_down) { 234 return (options & ko_option_activation_required_mod_down) != 0; 235 } else { 236 return (options & ko_option_activation_negative_mod_up) != 0; 237 } 238 } else { 239 if (key_down) { 240 return (options & ko_option_activation_trigger_down) != 0; 241 } else { 242 return false; 243 } 244 } 245 } 246 247 /** 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 */ 248 static 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) { 249 if (key_override_count() == 0) { 250 return true; 251 } 252 253 for (uint8_t i = 0; i < key_override_count(); i++) { 254 const key_override_t *const override = key_override_get(i); 255 256 // End of array 257 if (override == NULL) { 258 break; 259 } 260 261 // 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 262 if (active_mods == 0 && override->trigger_mods != 0) { 263 key_override_printf("Not activating override: Modifiers don't match\n"); 264 continue; 265 } 266 267 // Check layer 268 if ((override->layers & (1 << layer)) == 0) { 269 key_override_printf("Not activating override: Not set to activate on pressed layer\n"); 270 continue; 271 } 272 273 // Check allowed activation events 274 if (!check_activation_event(override, key_down, is_mod)) { 275 key_override_printf("Not activating override: Activation event not allowed\n"); 276 continue; 277 } 278 279 const bool is_trigger = override->trigger == keycode; 280 281 // Check if trigger lifted. This is a small optimization in order to skip the remaining checks 282 if (is_trigger && !key_down) { 283 key_override_printf("Not activating override: Trigger lifted\n"); 284 continue; 285 } 286 287 // If the trigger is KC_NO it means 'no key', so only the required modifiers need to be down. 288 const bool no_trigger = override->trigger == KC_NO; 289 290 // Check if aleady active 291 if (override == active_override) { 292 key_override_printf("Not activating override: Alerady actived\n"); 293 continue; 294 } 295 296 // Check if enabled 297 if (override->enabled != NULL && !((*(override->enabled) & 1))) { 298 key_override_printf("Not activating override: Not enabled\n"); 299 continue; 300 } 301 302 // Check mods precisely 303 if (!key_override_matches_active_modifiers(override, active_mods)) { 304 key_override_printf("Not activating override: Modifiers don't match\n"); 305 continue; 306 } 307 308 // Check if trigger key is down. 309 const bool trigger_down = is_trigger && key_down; 310 311 // 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 312 // If no trigger key is required, yes. 313 // If the trigger was just pressed, yes. 314 // If the last non-mod key that was pressed down is the trigger key, yes. 315 bool should_activate = no_trigger || trigger_down || last_key_down == override->trigger; 316 317 if (!should_activate) { 318 key_override_printf("Not activating override. Trigger not down\n"); 319 continue; 320 } 321 322 key_override_printf("Activating override\n"); 323 324 clear_active_override(false); 325 326 #ifdef DUMMY_MOD_NEUTRALIZER_KEYCODE 327 // Send a dummy keycode before unregistering the modifier(s) 328 // so that suppressing the modifier(s) doesn't falsely get interpreted 329 // by the host OS as a tap of a modifier key. 330 // For example, unintended activations of the start menu on Windows when 331 // using a GUI+<kc> key override with suppressed mods. 332 neutralize_flashing_modifiers(active_mods); 333 #endif 334 335 active_override = override; 336 active_override_trigger_is_down = true; 337 338 set_suppressed_override_mods(override->suppressed_mods); 339 340 if (!trigger_down && !no_trigger) { 341 // 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. 342 if (IS_BASIC_KEYCODE(override->trigger)) { 343 del_key(override->trigger); 344 } else { 345 unregister_code(override->trigger); 346 } 347 } 348 349 const uint16_t mod_free_replacement = clear_mods_from(override->replacement); 350 351 bool register_replacement = mod_free_replacement != KC_NO && // KC_NO is never registered 352 mod_free_replacement < SAFE_RANGE; // Custom keycodes are never registered 353 354 // Try firing the custom handler 355 if (override->custom_action != NULL) { 356 register_replacement &= override->custom_action(true, override->context); 357 } 358 359 if (register_replacement) { 360 const uint8_t override_mods = extract_mod_bits(override->replacement); 361 set_weak_override_mods(override_mods); 362 363 // If this is a modifier event that activates the key override we _always_ defer the actual full activation of the override 364 if (is_mod) { 365 key_override_printf("Deferring register replacement key\n"); 366 schedule_deferred_register(mod_free_replacement); 367 send_keyboard_report(); 368 } else { 369 if (IS_BASIC_KEYCODE(mod_free_replacement)) { 370 add_key(mod_free_replacement); 371 } else { 372 key_override_printf("NOT KEY 2\n"); 373 send_keyboard_report(); 374 // 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. 375 wait_ms(10); 376 register_code(mod_free_replacement); 377 } 378 } 379 } else { 380 // If not registering the replacement key send keyboard report to update the unregistered keys. 381 send_keyboard_report(); 382 } 383 384 *activated = true; 385 386 // If the trigger is down, suppress the event so that it does not get added to the keyboard report. 387 return !trigger_down; 388 } 389 390 *activated = false; 391 392 return true; 393 } 394 395 void key_override_task(void) { 396 if (deferred_register == 0) { 397 return; 398 } 399 400 if (timer_elapsed32(defer_reference_time) >= defer_delay) { 401 key_override_printf("Registering deferred key\n"); 402 register_code16(deferred_register); 403 deferred_register = 0; 404 defer_reference_time = 0; 405 defer_delay = 0; 406 } 407 } 408 409 bool process_key_override(const uint16_t keycode, const keyrecord_t *const record) { 410 #ifdef BENCH_KEY_OVERRIDE 411 uint16_t start = timer_read(); 412 #endif 413 414 const bool key_down = record->event.pressed; 415 const bool is_mod = IS_MODIFIER_KEYCODE(keycode); 416 417 if (key_down) { 418 switch (keycode) { 419 case QK_KEY_OVERRIDE_TOGGLE: 420 key_override_toggle(); 421 return false; 422 423 case QK_KEY_OVERRIDE_ON: 424 key_override_on(); 425 return false; 426 427 case QK_KEY_OVERRIDE_OFF: 428 key_override_off(); 429 return false; 430 431 default: 432 break; 433 } 434 } 435 436 if (!enabled) { 437 return true; 438 } 439 440 uint8_t effective_mods = get_mods(); 441 442 #ifdef KEY_OVERRIDE_INCLUDE_WEAK_MODS 443 effective_mods |= get_weak_mods(); 444 #endif 445 446 #ifndef NO_ACTION_ONESHOT 447 // 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. 448 effective_mods |= get_oneshot_locked_mods() | get_oneshot_mods(); 449 #endif 450 451 if (is_mod) { 452 // 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. 453 if (key_down) { 454 effective_mods |= MOD_BIT(keycode); 455 } else { 456 effective_mods &= ~MOD_BIT(keycode); 457 } 458 } else { 459 if (key_down) { 460 last_key_down = keycode; 461 last_key_down_time = timer_read32(); 462 deferred_register = 0; 463 } 464 465 // The last key that was pressed was just released. No more keys are therefore sending input 466 if (!key_down && keycode == last_key_down) { 467 last_key_down = 0; 468 last_key_down_time = 0; 469 // 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. 470 deferred_register = 0; 471 } 472 } 473 474 key_override_printf("key down: %u keycode: %u is mod: %u effective mods: %u\n", key_down, keycode, is_mod, effective_mods); 475 476 bool send_key_action = true; 477 bool activated = false; 478 479 // Non-mod key up events never activate a key override 480 if (is_mod || key_down) { 481 // Get the exact layer that was hit. It will be cached at this point 482 const uint8_t layer = read_source_layers_cache(record->event.key); 483 484 // Use blocked to ensure the same override is not activated again immediately after it is deactivated 485 send_key_action = try_activating_override(keycode, layer, key_down, is_mod, effective_mods, &activated); 486 487 if (!send_key_action) { 488 send_keyboard_report(); 489 } 490 } 491 492 if (!activated && active_override != NULL) { 493 if (is_mod) { 494 // Check if necessary modifier of current override goes up or a negative mod goes down 495 if (!key_override_matches_active_modifiers(active_override, effective_mods)) { 496 key_override_printf("Deactivating override because necessary modifier lifted or negative mod pressed\n"); 497 clear_active_override(true); 498 } 499 } else { 500 // Check if trigger of current override goes up or if override does not allow additional keys to be down and another key goes down 501 const bool is_trigger = keycode == active_override->trigger; 502 bool should_deactivate = false; 503 504 // Check if trigger key lifted 505 if (is_trigger && !key_down) { 506 should_deactivate = true; 507 active_override_trigger_is_down = false; 508 key_override_printf("Deactivating override because trigger key up\n"); 509 } 510 511 // Check if another key was pressed 512 if (key_down && (active_override->options & ko_option_no_unregister_on_other_key_down) == 0) { 513 should_deactivate = true; 514 key_override_printf("Deactivating override because another key was pressed\n"); 515 } 516 517 if (should_deactivate) { 518 clear_active_override(false); 519 } 520 } 521 } 522 523 #ifdef BENCH_KEY_OVERRIDE 524 uint16_t elapsed = timer_elapsed(start); 525 526 dprintf("Processing key overrides took: %u ms\n", elapsed); 527 #endif 528 529 return send_key_action; 530 }