summaryrefslogtreecommitdiff
path: root/common/layer_switch.c
blob: 22bfb34f656bc49c866499b35d01de4d099d08c2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <stdint.h>
#include "keyboard.h"
#include "action.h"
#include "debug.h"
#include "util.h"
#include "layer_switch.h"


uint8_t default_layer = 0;

uint16_t layer_switch_stat = 0;


uint16_t layer_switch_get_stat(void)
{
    return layer_switch_stat;
}

/* return highest layer whose state is on */
uint8_t layer_switch_get_layer(void)
{
    return biton16(layer_switch_stat);
}

static inline void stat_set(uint16_t stat)
{
    debug("layer_switch: ");
    layer_switch_debug(); debug(" to ");

    layer_switch_stat = stat;

    layer_switch_debug(); debug("\n");

    clear_keyboard_but_mods(); // To avoid stuck keys
}

void layer_switch_clear(void)
{
    stat_set(0);
}


void layer_switch_set(uint16_t stat)
{
    stat_set(stat);
}

void layer_switch_move(uint8_t layer)
{
    if (layer)
        stat_set(1<<layer);
    else
        stat_set(0);    // fall back to default layer
}

void layer_switch_on(uint8_t layer)
{
    stat_set(layer_switch_stat | (1<<layer));
}

void layer_switch_off(uint8_t layer)
{
    stat_set(layer_switch_stat & ~(1<<layer));
}

void layer_switch_invert(uint8_t layer)
{
    stat_set(layer_switch_stat ^ (1<<layer));
}

void layer_switch_or(uint16_t stat)
{
    stat_set(layer_switch_stat | stat);
}
void layer_switch_and(uint16_t stat)
{
    stat_set(layer_switch_stat & stat);
}
void layer_switch_xor(uint16_t stat)
{
    stat_set(layer_switch_stat ^ stat);
}

void layer_switch_debug(void)
{
    debug_hex16(layer_switch_stat); debug("("); debug_dec(layer_switch_get_layer()); debug(")");
}

action_t layer_switch_get_action(key_t key)
{
    action_t action;
    action.code = ACTION_TRANSPARENT;

    /* higher layer first */
    for (int8_t i = 15; i >= 0; i--) {
        if (layer_switch_stat & (1<<i)) {
            action = action_for_key(i, key);
            if (action.code != ACTION_TRANSPARENT) {
                return action;
            }
        }
    }
    return action;
}