]> git.donarmstrong.com Git - qmk_firmware.git/blob - common/keyboard.c
b0e0ed7935278f5b97f617822bfb2b12944951b6
[qmk_firmware.git] / common / keyboard.c
1 /*
2 Copyright 2011 Jun Wako <wakojun@gmail.com>
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 "keyboard.h"
18 #include "matrix.h"
19 #include "keymap.h"
20 #include "host.h"
21 #include "led.h"
22 #include "keycode.h"
23 #include "timer.h"
24 #include "print.h"
25 #include "debug.h"
26 #include "command.h"
27 #include "util.h"
28 #ifdef MOUSEKEY_ENABLE
29 #include "mousekey.h"
30 #endif
31
32
33 #define Kdebug(s)       do { if (debug_keyboard) debug(s); } while(0)
34 #define Kdebug_P(s)     do { if (debug_keyboard) debug_P(s); } while(0)
35 #define Kdebug_hex(s)   do { if (debug_keyboard) debug_hex(s); } while(0)
36
37 #define LAYER_DELAY     250
38
39 typedef enum keykind {
40     NONE,
41     FN_DOWN, FN_UP,
42     FNK_DOWN, FNK_UP,
43     KEY_DOWN, KEY_UP,
44     MOD_DOWN, MOD_UP,
45 } keykind_t;
46
47 typedef enum { IDLE, DELAYING, WAITING, PRESSING } kbdstate_t;
48
49
50 #ifdef KEYMAP_DEFAULT_LAYER
51 uint8_t default_layer = KEYMAP_DEFAULT_LAYER;
52 uint8_t current_layer = KEYMAP_DEFAULT_LAYER;
53 #else
54 uint8_t default_layer = 0;
55 uint8_t current_layer = 0;
56 #endif
57
58 /* keyboard internal states */
59 static kbdstate_t kbdstate = IDLE;
60 static uint8_t fn_state_bits = 0;
61 static keyrecord_t delayed_fn;
62 static keyrecord_t waiting_key;
63
64
65 static const char *state_str(kbdstate_t state)
66 {
67     if (state == IDLE)      return PSTR("IDLE");
68     if (state == DELAYING)  return PSTR("DELAYING");
69     if (state == WAITING)   return PSTR("WAITING");
70     if (state == PRESSING)  return PSTR("PRESSING");
71     return PSTR("UNKNOWN");
72 }
73
74 static inline keykind_t get_keykind(uint8_t code, bool pressed)
75 {
76     if IS_KEY(code)         return (pressed ? KEY_DOWN : KEY_UP);
77     if IS_MOD(code)         return (pressed ? MOD_DOWN : MOD_UP);
78     if IS_FN(code) {
79         if (keymap_fn_keycode(FN_INDEX(code)))
80             return (pressed ? FNK_DOWN : FNK_UP);
81         else
82             return (pressed ? FN_DOWN : FN_UP);
83     }
84     if IS_MOUSEKEY(code)    return (pressed ? KEY_DOWN : KEY_UP);
85     if IS_SYSTEM(code)      return (pressed ? KEY_DOWN : KEY_UP);
86     if IS_CONSUMER(code)    return (pressed ? KEY_DOWN : KEY_UP);
87     return  NONE;
88 }
89
90 static void clear_keyboard(void)
91 {
92     host_clear_keys();
93     host_clear_mods();
94     host_send_keyboard_report();
95
96     host_system_send(0);
97     host_consumer_send(0);
98
99 #ifdef MOUSEKEY_ENABLE
100     mousekey_clear();
101     mousekey_send();
102 #endif
103 }
104
105 static void clear_keyboard_but_mods(void)
106 {
107     host_clear_keys();
108     host_send_keyboard_report();
109
110     host_system_send(0);
111     host_consumer_send(0);
112
113 #ifdef MOUSEKEY_ENABLE
114     mousekey_clear();
115     mousekey_send();
116 #endif
117 }
118
119 static bool anykey_sent_to_host(void)
120 {
121     return (host_has_anykey() || host_mouse_in_use() ||
122             host_last_sysytem_report() || host_last_consumer_report());
123 }
124
125 static void layer_switch_on(uint8_t code)
126 {
127     if (!IS_FN(code)) return;
128     fn_state_bits |= FN_BIT(code);
129     uint8_t new_layer = (fn_state_bits ? keymap_fn_layer(biton(fn_state_bits)) : default_layer);
130     if (current_layer != new_layer) {
131         Kdebug("Layer Switch(on): "); Kdebug_hex(current_layer);
132         Kdebug(" -> "); Kdebug_hex(new_layer); Kdebug("\n");
133
134         clear_keyboard_but_mods();
135         current_layer = new_layer;
136     }
137 }
138
139 static bool layer_switch_off(uint8_t code)
140 {
141     if (!IS_FN(code)) return false;
142     fn_state_bits &= ~FN_BIT(code);
143     uint8_t new_layer = (fn_state_bits ? keymap_fn_layer(biton(fn_state_bits)) : default_layer);
144     if (current_layer != new_layer) {
145         Kdebug("Layer Switch(off): "); Kdebug_hex(current_layer);
146         Kdebug(" -> "); Kdebug_hex(new_layer); Kdebug("\n");
147
148         clear_keyboard_but_mods();
149         current_layer = new_layer;
150         return true;
151     }
152     return false;
153 }
154
155 static void register_code(uint8_t code)
156 {
157     if IS_KEY(code) {
158         if (!command_proc(code)) {
159             host_add_key(code);
160             host_send_keyboard_report();
161         }
162     }
163     else if IS_MOD(code) {
164         host_add_mod_bit(MOD_BIT(code));
165         host_send_keyboard_report();
166     }
167     else if IS_FN(code) {
168         if (!command_proc(keymap_fn_keycode(FN_INDEX(code)))) {
169             host_add_key(keymap_fn_keycode(FN_INDEX(code)));
170             host_send_keyboard_report();
171         }
172     }
173     else if IS_MOUSEKEY(code) {
174 #ifdef MOUSEKEY_ENABLE
175         mousekey_on(code);
176         mousekey_send();
177 #endif
178     }
179     else if IS_CONSUMER(code) {
180         uint16_t usage = 0;
181         switch (code) {
182             case KC_AUDIO_MUTE:
183                 usage = AUDIO_MUTE;
184                 break;
185             case KC_AUDIO_VOL_UP:
186                 usage = AUDIO_VOL_UP;
187                 break;
188             case KC_AUDIO_VOL_DOWN:
189                 usage = AUDIO_VOL_DOWN;
190                 break;
191             case KC_MEDIA_NEXT_TRACK:
192                 usage = TRANSPORT_NEXT_TRACK;
193                 break;
194             case KC_MEDIA_PREV_TRACK:
195                 usage = TRANSPORT_PREV_TRACK;
196                 break;
197             case KC_MEDIA_STOP:
198                 usage = TRANSPORT_STOP;
199                 break;
200             case KC_MEDIA_PLAY_PAUSE:
201                 usage = TRANSPORT_PLAY_PAUSE;
202                 break;
203             case KC_MEDIA_SELECT:
204                 usage = AL_CC_CONFIG;
205                 break;
206             case KC_MAIL:
207                 usage = AL_EMAIL;
208                 break;
209             case KC_CALCULATOR:
210                 usage = AL_CALCULATOR;
211                 break;
212             case KC_MY_COMPUTER:
213                 usage = AL_LOCAL_BROWSER;
214                 break;
215             case KC_WWW_SEARCH:
216                 usage = AC_SEARCH;
217                 break;
218             case KC_WWW_HOME:
219                 usage = AC_HOME;
220                 break;
221             case KC_WWW_BACK:
222                 usage = AC_BACK;
223                 break;
224             case KC_WWW_FORWARD:
225                 usage = AC_FORWARD;
226                 break;
227             case KC_WWW_STOP:
228                 usage = AC_STOP;
229                 break;
230             case KC_WWW_REFRESH:
231                 usage = AC_REFRESH;
232                 break;
233             case KC_WWW_FAVORITES:
234                 usage = AC_BOOKMARKS;
235                 break;
236         }
237         host_consumer_send(usage);
238     }
239     else if IS_SYSTEM(code) {
240         uint16_t usage = 0;
241         switch (code) {
242             case KC_SYSTEM_POWER:
243                 usage = SYSTEM_POWER_DOWN;
244                 break;
245             case KC_SYSTEM_SLEEP:
246                 usage = SYSTEM_SLEEP;
247                 break;
248             case KC_SYSTEM_WAKE:
249                 usage = SYSTEM_WAKE_UP;
250                 break;
251         }
252         host_system_send(usage);
253     }
254
255 }
256
257 static void unregister_code(uint8_t code)
258 {
259     if IS_KEY(code) {
260         host_del_key(code);
261         host_send_keyboard_report();
262     }
263     else if IS_MOD(code) {
264         host_del_mod_bit(MOD_BIT(code));
265         host_send_keyboard_report();
266     }
267     else if IS_FN(code) {
268         host_del_key(keymap_fn_keycode(FN_INDEX(code)));
269         host_send_keyboard_report();
270     }
271     else if IS_MOUSEKEY(code) {
272 #ifdef MOUSEKEY_ENABLE
273         mousekey_off(code);
274         mousekey_send();
275 #endif
276     }
277     else if IS_CONSUMER(code) {
278         host_consumer_send(0x0000);
279     }
280     else if IS_SYSTEM(code) {
281         host_system_send(0x0000);
282     }
283 }
284
285 /*
286  *
287  * Event/State|IDLE          PRESSING      DELAYING[f]      WAITING[f,k]         
288  * -----------+------------------------------------------------------------------
289  * Fn  Down   |(L+)          -*1           WAITING(Sk)      IDLE(Rf,Ps)*7        
290  *     Up     |(L-)          IDLE(L-)*8    IDLE(L-)*8       IDLE(L-)*8           
291  * Fnk Down   |DELAYING(Sf)* (Rf)          WAITING(Sk)      IDLE(Rf,Ps,Rf)       
292  *     Up     |(L-)          IDLE(L-/Uf)*8 IDLE(Rf,Uf/L-)*3 IDLE(Rf,Ps,Uf/L-)*3  
293  * Key Down   |PRESSING(Rk)  (Rk)          WAITING(Sk)      IDLE(Rf,Ps,Rk)       
294  *     Up     |(Uk)          IDLE(Uk)*4    (Uk)             IDLE(L+,Ps,Pk)/(Uk)*a
295  *            |
296  * Delay      |-             -             IDLE(L+)         IDLE(L+,Ps)          
297  * Magic Key  |COMMAND*5
298  *
299  * *1: ignore Fn if other key is down.
300  * *2: register Fnk if any key is pressing
301  * *3: register/unregister delayed Fnk and move to IDLE if code == delayed Fnk, else *8
302  * *4: if no keys registered to host
303  * *5: unregister all keys
304  * *6: only if no keys down
305  * *7: ignore Fn because Fnk key and stored key are down.
306  * *8: move to IDLE if layer switch(off) occurs, else stay at current state
307  * *9: repeat key if pressing Fnk twice quickly(move to PRESSING)
308  * *a: layer switch and process waiting key and code if code == wainting key, else unregister key
309  *
310  * States:
311  *      IDLE: No key is down except modifiers
312  *      DELAYING: delay layer switch after pressing Fn with alt keycode
313  *      WAITING: key is pressed during DELAYING
314  *
315  * Events:
316  *      Fn: Fn key without alternative keycode
317  *      Fnk: Fn key with alternative keycode
318  *      -: ignore
319  *      Delay: layer switch delay term is elapsed
320  *
321  * Actions:
322  *      Rk: register key
323  *      Uk: unregister key
324  *      Rf: register Fn(alt keycode)
325  *      Uf: unregister Fn(alt keycode)
326  *      Rs: register stored key
327  *      Us: unregister stored key
328  *      Sk: Store key(waiting Key)
329  *      Sf: Store Fn(delayed Fn)
330  *      Ps: Process stored key
331  *      Ps: Process key
332  *      Is: Interpret stored keys in current layer
333  *      L+: Switch to new layer(*unregister* all keys but modifiers)
334  *      L-: Switch back to last layer(*unregister* all keys but modifiers)
335  *      Ld: Switch back to default layer(*unregister* all keys but modifiers)
336  */
337 #define NEXT(state)     do { \
338     Kdebug("NEXT: "); Kdebug_P(state_str(kbdstate)); \
339     kbdstate = state; \
340     Kdebug(" -> "); Kdebug_P(state_str(kbdstate)); Kdebug("\n"); \
341 } while (0)
342
343 static inline void process_key(keyevent_t event)
344 {
345     uint8_t code = keymap_get_keycode(current_layer, event.key.row, event.key.col);
346     keykind_t kind = get_keykind(code, event.pressed);
347
348     uint8_t tmp_mods;
349
350     Kdebug("state: "); Kdebug_P(state_str(kbdstate));
351     Kdebug(" kind: "); Kdebug_hex(kind);
352     Kdebug(" code: "); Kdebug_hex(code);
353     if (event.pressed) { Kdebug("d"); } else { Kdebug("u"); }
354     Kdebug("\n");
355
356     switch (kbdstate) {
357         case IDLE:
358             switch (kind) {
359                 case FN_DOWN:
360                     layer_switch_on(code);
361                     break;
362                 case FN_UP:
363                     layer_switch_off(code);
364                     break;
365                 case FNK_DOWN:
366                     // repeat Fn alt key when press Fn key down, up then down again quickly
367                     if (KEYEQ(delayed_fn.event.key, event.key) &&
368                             timer_elapsed(delayed_fn.time) < LAYER_DELAY) {
369                         register_code(code);
370                         NEXT(PRESSING);
371                     } else {
372                         delayed_fn = (keyrecord_t) {
373                             .event = event,
374                             .code = code,
375                             .mods = keyboard_report->mods,
376                             .time = timer_read()
377                         };
378                         NEXT(DELAYING);
379                     }
380                     break;
381                 case FNK_UP:
382                     layer_switch_off(code);
383                     break;
384                 case KEY_DOWN:
385                     register_code(code);
386                     NEXT(PRESSING);
387                     break;
388                 case MOD_DOWN:
389                     register_code(code);
390                     break;
391                 case KEY_UP:
392                 case MOD_UP:
393                     unregister_code(code);
394                     break;
395                 default:
396                     break;
397             }
398             break;
399         case PRESSING:
400             switch (kind) {
401                 case FN_DOWN:
402                     // ignored when any key is pressed
403                     break;
404                 case FN_UP:
405                     if (layer_switch_off(code))
406                         NEXT(IDLE);
407                     break;
408                 case FNK_DOWN:
409                     register_code(code);
410                     break;
411                 case FNK_UP:
412                     if (layer_switch_off(code)) {
413                         NEXT(IDLE);
414                     } else {
415                         unregister_code(code);
416                         if (!anykey_sent_to_host())
417                             NEXT(IDLE);
418                     }
419                     break;
420                 case KEY_DOWN:
421                 case MOD_DOWN:
422                     register_code(code);
423                     break;
424                 case KEY_UP:
425                 case MOD_UP:
426                     unregister_code(code);
427                     if (!anykey_sent_to_host())
428                         NEXT(IDLE);
429                     break;
430                 default:
431                     break;
432             }
433             break;
434         case DELAYING:
435             switch (kind) {
436                 case FN_DOWN:
437                 case FNK_DOWN:
438                 case KEY_DOWN:
439                     waiting_key = (keyrecord_t) {
440                         .event = event,
441                         .code = code,
442                         .mods = keyboard_report->mods,
443                         .time = timer_read()
444                     };
445                     NEXT(WAITING);
446                     break;
447                 case MOD_DOWN:
448                     register_code(code);
449                     break;
450                 case FN_UP:
451                     if (layer_switch_off(code))
452                         NEXT(IDLE);
453                     break;
454                 case FNK_UP:
455                     if (code == delayed_fn.code) {
456                         // type Fn with alt keycode
457                         // restore the mod status at the time of pressing Fn key
458                         tmp_mods = keyboard_report->mods;
459                         host_set_mods(delayed_fn.mods);
460                         register_code(delayed_fn.code);
461                         unregister_code(delayed_fn.code);
462                         host_set_mods(tmp_mods);
463                         NEXT(IDLE);
464                     } else {
465                         if (layer_switch_off(code))
466                             NEXT(IDLE);
467                     }
468                     break;
469                 case KEY_UP:
470                 case MOD_UP:
471                     unregister_code(code);
472                     break;
473                 default:
474                     break;
475             }
476             break;
477         case WAITING:
478             switch (kind) {
479                 case FN_DOWN:
480                 case FNK_DOWN:
481                 case KEY_DOWN:
482                     tmp_mods = keyboard_report->mods;
483                     host_set_mods(delayed_fn.mods);
484                     register_code(delayed_fn.code);
485                     host_set_mods(waiting_key.mods);
486                     register_code(waiting_key.code);
487                     host_set_mods(tmp_mods);
488                     if (kind == FN_DOWN) {
489                         // ignore Fn
490                     } else if (kind == FNK_DOWN) {
491                         register_code(code);
492                     } else if (kind == KEY_DOWN) {
493                         register_code(code);
494                     }
495                     NEXT(IDLE);
496                     break;
497                 case MOD_DOWN:
498                     register_code(code);
499                     break;
500                 case FN_UP:
501                     if (layer_switch_off(code))
502                         NEXT(IDLE);
503                     break;
504                 case FNK_UP:
505                     if (code == delayed_fn.code) {
506                         // alt down, key down, alt up
507                         tmp_mods = keyboard_report->mods;
508                         host_set_mods(delayed_fn.mods);
509                         register_code(delayed_fn.code);
510                         host_set_mods(waiting_key.mods);
511                         register_code(waiting_key.code);
512                         unregister_code(delayed_fn.code);
513                         host_set_mods(tmp_mods);
514                         NEXT(IDLE);
515                     } else {
516                         if (layer_switch_off(code))
517                             NEXT(IDLE);
518                     }
519                     break;
520                 case KEY_UP:
521                     if (code == waiting_key.code) {
522                         layer_switch_on(delayed_fn.code);
523                         NEXT(IDLE);
524                         // process waiting_key
525                         tmp_mods = keyboard_report->mods;
526                         host_set_mods(waiting_key.mods);
527                         process_key(waiting_key.event);
528                         host_set_mods(tmp_mods);
529                         process_key(event);
530                     } else {
531                         unregister_code(code);
532                     }
533                     break;
534                 case MOD_UP:
535                     unregister_code(code);
536                     break;
537                 default:
538                     break;
539             }
540             break;
541     }
542 }
543
544 void keyboard_init(void)
545 {
546     debug_keyboard = true;
547
548     timer_init();
549     matrix_init();
550 #ifdef PS2_MOUSE_ENABLE
551     ps2_mouse_init();
552 #endif
553 }
554
555 void keyboard_task(void)
556 {
557     static matrix_row_t matrix_prev[MATRIX_ROWS];
558     static uint8_t led_status = 0;
559     matrix_row_t matrix_row = 0;
560     matrix_row_t matrix_change = 0;
561
562     matrix_scan();
563     for (int r = 0; r < MATRIX_ROWS; r++) {
564         matrix_row = matrix_get_row(r);
565         matrix_change = matrix_row ^ matrix_prev[r];
566         if (matrix_change) {
567             if (debug_matrix) matrix_print();
568
569             for (int c = 0; c < MATRIX_COLS; c++) {
570                 if (matrix_change & (1<<c)) {
571                     process_key((keyevent_t){
572                         .key = (key_t){ .row = r, .col = c },
573                         .pressed = (matrix_row & (1<<c))
574                     });
575                     // record a processed key
576                     matrix_prev[r] ^= (1<<c);
577                     // process a key per task call
578                     goto MATRIX_LOOP_END;
579                 }
580             }
581         }
582     }
583     MATRIX_LOOP_END:
584
585     // layer switch when delay term elapses
586     if (kbdstate == DELAYING || kbdstate == WAITING) {
587         if (timer_elapsed(delayed_fn.time) > LAYER_DELAY) {
588             if (kbdstate == DELAYING) {
589                 layer_switch_on(delayed_fn.code);
590                 NEXT(IDLE);
591             }
592             if (kbdstate == WAITING) {
593                 layer_switch_on(delayed_fn.code);
594                 NEXT(IDLE);
595                 uint8_t tmp_mods = keyboard_report->mods;
596                 host_set_mods(waiting_key.mods);
597                 process_key(waiting_key.event);
598                 host_set_mods(tmp_mods);
599             }
600         }
601     }
602
603 #ifdef MOUSEKEY_ENABLE
604     // mousekey repeat & acceleration
605     mousekey_task();
606 #endif
607
608     // FAIL SAFE: clear all key if no key down
609     if (matrix_change) {
610         matrix_row_t is_matrix_on = 0;
611         for (int r = 0; r < MATRIX_ROWS; r++) {
612             is_matrix_on |= matrix_get_row(r);
613         }
614         if (!is_matrix_on) {
615             Kdebug("FAIL SAFE: clear all keys(default layer).\n");
616             clear_keyboard();
617             current_layer = default_layer;
618         }
619     }
620
621     // update LED
622     if (led_status != host_keyboard_leds()) {
623         led_status = host_keyboard_leds();
624         keyboard_set_leds(led_status);
625     }
626
627     return;
628 }
629
630 void keyboard_set_leds(uint8_t leds)
631 {
632     led_set(leds);
633 }