Parent directory

caps_word.c

2309 bytes
 1// Copyright 2021-2022 Google LLC
 2//
 3// Licensed under the Apache License, Version 2.0 (the "License");
 4// you may not use this file except in compliance with the License.
 5// You may obtain a copy of the License at
 6//
 7//     https://www.apache.org/licenses/LICENSE-2.0
 8//
 9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <stdint.h>
16#include "caps_word.h"
17#include "timer.h"
18#include "action.h"
19#include "action_util.h"
20
21/** @brief True when Caps Word is active. */
22static bool caps_word_active = false;
23
24#if CAPS_WORD_IDLE_TIMEOUT > 0
25// Constrain timeout to a sensible range. With 16-bit timers, the longest
26// timeout possible is 32768 ms, rounded here to 30000 ms = half a minute.
27#    if CAPS_WORD_IDLE_TIMEOUT < 100 || CAPS_WORD_IDLE_TIMEOUT > 30000
28#        error "CAPS_WORD_IDLE_TIMEOUT must be between 100 and 30000 ms"
29#    endif
30
31/** @brief Deadline for idle timeout. */
32static uint16_t idle_timer = 0;
33
34void caps_word_task(void) {
35    if (caps_word_active && timer_expired(timer_read(), idle_timer)) {
36        caps_word_off();
37    }
38}
39
40void caps_word_reset_idle_timer(void) {
41    idle_timer = timer_read() + CAPS_WORD_IDLE_TIMEOUT;
42}
43#else
44void caps_word_task(void) {}
45#endif // CAPS_WORD_IDLE_TIMEOUT > 0
46
47void caps_word_on(void) {
48    if (caps_word_active) {
49        return;
50    }
51
52    clear_mods();
53#ifndef NO_ACTION_ONESHOT
54    clear_oneshot_mods();
55#endif // NO_ACTION_ONESHOT
56#if CAPS_WORD_IDLE_TIMEOUT > 0
57    caps_word_reset_idle_timer();
58#endif // CAPS_WORD_IDLE_TIMEOUT > 0
59
60    caps_word_active = true;
61    caps_word_set_user(true);
62}
63
64void caps_word_off(void) {
65    if (!caps_word_active) {
66        return;
67    }
68
69    unregister_weak_mods(MOD_MASK_SHIFT); // Make sure weak shift is off.
70    caps_word_active = false;
71    caps_word_set_user(false);
72}
73
74void caps_word_toggle(void) {
75    if (caps_word_active) {
76        caps_word_off();
77    } else {
78        caps_word_on();
79    }
80}
81
82bool is_caps_word_on(void) {
83    return caps_word_active;
84}
85
86__attribute__((weak)) void caps_word_set_user(bool active) {}