You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

518 lines
20 KiB

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