]> git.donarmstrong.com Git - qmk_firmware.git/blob - quantum/quantum.c
Simple extended space cadet (#5277)
[qmk_firmware.git] / quantum / quantum.c
1 /* Copyright 2016-2017 Jack Humbert
2  *
3  * This program is free software: you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation, either version 2 of the License, or
6  * (at your option) any later version.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  */
16
17 #include "quantum.h"
18
19 #if !defined(RGBLIGHT_ENABLE) && !defined(RGB_MATRIX_ENABLE)
20         #include "rgb.h"
21 #endif
22
23 #ifdef PROTOCOL_LUFA
24 #include "outputselect.h"
25 #endif
26
27 #ifndef BREATHING_PERIOD
28 #define BREATHING_PERIOD 6
29 #endif
30
31 #include "backlight.h"
32 extern backlight_config_t backlight_config;
33
34 #ifdef FAUXCLICKY_ENABLE
35 #include "fauxclicky.h"
36 #endif
37
38 #ifdef API_ENABLE
39 #include "api.h"
40 #endif
41
42 #ifdef MIDI_ENABLE
43 #include "process_midi.h"
44 #endif
45
46 #ifdef VELOCIKEY_ENABLE
47 #include "velocikey.h"
48 #endif
49
50 #ifdef HAPTIC_ENABLE
51     #include "haptic.h"
52 #endif
53
54 #ifdef ENCODER_ENABLE
55 #include "encoder.h"
56 #endif
57
58 #ifdef AUDIO_ENABLE
59   #ifndef GOODBYE_SONG
60     #define GOODBYE_SONG SONG(GOODBYE_SOUND)
61   #endif
62   #ifndef AG_NORM_SONG
63     #define AG_NORM_SONG SONG(AG_NORM_SOUND)
64   #endif
65   #ifndef AG_SWAP_SONG
66     #define AG_SWAP_SONG SONG(AG_SWAP_SOUND)
67   #endif
68   float goodbye_song[][2] = GOODBYE_SONG;
69   float ag_norm_song[][2] = AG_NORM_SONG;
70   float ag_swap_song[][2] = AG_SWAP_SONG;
71   #ifdef DEFAULT_LAYER_SONGS
72     float default_layer_songs[][16][2] = DEFAULT_LAYER_SONGS;
73   #endif
74 #endif
75
76 static void do_code16 (uint16_t code, void (*f) (uint8_t)) {
77   switch (code) {
78   case QK_MODS ... QK_MODS_MAX:
79     break;
80   default:
81     return;
82   }
83
84   if (code & QK_LCTL)
85     f(KC_LCTL);
86   if (code & QK_LSFT)
87     f(KC_LSFT);
88   if (code & QK_LALT)
89     f(KC_LALT);
90   if (code & QK_LGUI)
91     f(KC_LGUI);
92
93   if (code < QK_RMODS_MIN) return;
94
95   if (code & QK_RCTL)
96     f(KC_RCTL);
97   if (code & QK_RSFT)
98     f(KC_RSFT);
99   if (code & QK_RALT)
100     f(KC_RALT);
101   if (code & QK_RGUI)
102     f(KC_RGUI);
103 }
104
105 static inline void qk_register_weak_mods(uint8_t kc) {
106     add_weak_mods(MOD_BIT(kc));
107     send_keyboard_report();
108 }
109
110 static inline void qk_unregister_weak_mods(uint8_t kc) {
111     del_weak_mods(MOD_BIT(kc));
112     send_keyboard_report();
113 }
114
115 static inline void qk_register_mods(uint8_t kc) {
116     add_weak_mods(MOD_BIT(kc));
117     send_keyboard_report();
118 }
119
120 static inline void qk_unregister_mods(uint8_t kc) {
121     del_weak_mods(MOD_BIT(kc));
122     send_keyboard_report();
123 }
124
125 void register_code16 (uint16_t code) {
126   if (IS_MOD(code) || code == KC_NO) {
127       do_code16 (code, qk_register_mods);
128   } else {
129       do_code16 (code, qk_register_weak_mods);
130   }
131   register_code (code);
132 }
133
134 void unregister_code16 (uint16_t code) {
135   unregister_code (code);
136   if (IS_MOD(code) || code == KC_NO) {
137       do_code16 (code, qk_unregister_mods);
138   } else {
139       do_code16 (code, qk_unregister_weak_mods);
140   }
141 }
142
143 void tap_code16(uint16_t code) {
144   register_code16(code);
145   #if TAP_CODE_DELAY > 0
146     wait_ms(TAP_CODE_DELAY);
147   #endif
148   unregister_code16(code);
149 }
150
151 __attribute__ ((weak))
152 bool process_action_kb(keyrecord_t *record) {
153   return true;
154 }
155
156 __attribute__ ((weak))
157 bool process_record_kb(uint16_t keycode, keyrecord_t *record) {
158   return process_record_user(keycode, record);
159 }
160
161 __attribute__ ((weak))
162 bool process_record_user(uint16_t keycode, keyrecord_t *record) {
163   return true;
164 }
165
166 void reset_keyboard(void) {
167   clear_keyboard();
168 #if defined(MIDI_ENABLE) && defined(MIDI_BASIC)
169   process_midi_all_notes_off();
170 #endif
171 #ifdef AUDIO_ENABLE
172   #ifndef NO_MUSIC_MODE
173     music_all_notes_off();
174   #endif
175   uint16_t timer_start = timer_read();
176   PLAY_SONG(goodbye_song);
177   shutdown_user();
178   while(timer_elapsed(timer_start) < 250)
179     wait_ms(1);
180   stop_all_notes();
181 #else
182   shutdown_user();
183   wait_ms(250);
184 #endif
185 #ifdef HAPTIC_ENABLE
186   haptic_shutdown();
187 #endif
188 // this is also done later in bootloader.c - not sure if it's neccesary here
189 #ifdef BOOTLOADER_CATERINA
190   *(uint16_t *)0x0800 = 0x7777; // these two are a-star-specific
191 #endif
192   bootloader_jump();
193 }
194
195 /* true if the last press of GRAVE_ESC was shifted (i.e. GUI or SHIFT were pressed), false otherwise.
196  * Used to ensure that the correct keycode is released if the key is released.
197  */
198 static bool grave_esc_was_shifted = false;
199
200 /* Convert record into usable keycode via the contained event. */
201 uint16_t get_record_keycode(keyrecord_t *record) {
202   return get_event_keycode(record->event);
203 }
204
205
206 /* Convert event into usable keycode. Checks the layer cache to ensure that it
207  * retains the correct keycode after a layer change, if the key is still pressed.
208  */
209 uint16_t get_event_keycode(keyevent_t event) {
210
211   #if !defined(NO_ACTION_LAYER) && !defined(STRICT_LAYER_RELEASE)
212     /* TODO: Use store_or_get_action() or a similar function. */
213     if (!disable_action_cache) {
214       uint8_t layer;
215
216       if (event.pressed) {
217         layer = layer_switch_get_layer(event.key);
218         update_source_layers_cache(event.key, layer);
219       } else {
220         layer = read_source_layers_cache(event.key);
221       }
222       return keymap_key_to_keycode(layer, event.key);
223     } else
224   #endif
225     return keymap_key_to_keycode(layer_switch_get_layer(event.key), event.key);
226 }
227
228 /* Main keycode processing function. Hands off handling to other functions,
229  * then processes internal Quantum keycodes, then processes ACTIONs.
230  */
231 bool process_record_quantum(keyrecord_t *record) {
232     uint16_t keycode = get_record_keycode(record);
233
234     // This is how you use actions here
235     // if (keycode == KC_LEAD) {
236     //   action_t action;
237     //   action.code = ACTION_DEFAULT_LAYER_SET(0);
238     //   process_action(record, action);
239     //   return false;
240     // }
241
242   #ifdef VELOCIKEY_ENABLE
243     if (velocikey_enabled() && record->event.pressed) { velocikey_accelerate(); }
244   #endif
245
246   #ifdef TAP_DANCE_ENABLE
247     preprocess_tap_dance(keycode, record);
248   #endif
249
250   #if defined(OLED_DRIVER_ENABLE) && !defined(OLED_DISABLE_TIMEOUT)
251     // Wake up oled if user is using those fabulous keys!
252     if (record->event.pressed)
253       oled_on();
254   #endif
255
256   if (!(
257   #if defined(KEY_LOCK_ENABLE)
258     // Must run first to be able to mask key_up events.
259     process_key_lock(&keycode, record) &&
260   #endif
261   #if defined(AUDIO_ENABLE) && defined(AUDIO_CLICKY)
262     process_clicky(keycode, record) &&
263   #endif //AUDIO_CLICKY
264   #ifdef HAPTIC_ENABLE
265     process_haptic(keycode, record) &&
266   #endif //HAPTIC_ENABLE
267   #if defined(RGB_MATRIX_ENABLE) && defined(RGB_MATRIX_KEYREACTIVE_ENABLED)
268     process_rgb_matrix(keycode, record) &&
269   #endif
270     process_record_kb(keycode, record) &&
271   #if defined(MIDI_ENABLE) && defined(MIDI_ADVANCED)
272     process_midi(keycode, record) &&
273   #endif
274   #ifdef AUDIO_ENABLE
275     process_audio(keycode, record) &&
276   #endif
277   #ifdef STENO_ENABLE
278     process_steno(keycode, record) &&
279   #endif
280   #if (defined(AUDIO_ENABLE) || (defined(MIDI_ENABLE) && defined(MIDI_BASIC))) && !defined(NO_MUSIC_MODE)
281     process_music(keycode, record) &&
282   #endif
283   #ifdef TAP_DANCE_ENABLE
284     process_tap_dance(keycode, record) &&
285   #endif
286   #if defined(UNICODE_ENABLE) || defined(UNICODEMAP_ENABLE) || defined(UCIS_ENABLE)
287     process_unicode_common(keycode, record) &&
288   #endif
289   #ifdef LEADER_ENABLE
290     process_leader(keycode, record) &&
291   #endif
292   #ifdef COMBO_ENABLE
293     process_combo(keycode, record) &&
294   #endif
295   #ifdef PRINTING_ENABLE
296     process_printer(keycode, record) &&
297   #endif
298   #ifdef AUTO_SHIFT_ENABLE
299     process_auto_shift(keycode, record) &&
300   #endif
301   #ifdef TERMINAL_ENABLE
302     process_terminal(keycode, record) &&
303   #endif
304   #ifdef SPACE_CADET_ENABLE
305     process_space_cadet(keycode, record) &&
306   #endif
307       true)) {
308     return false;
309   }
310
311   // Shift / paren setup
312
313   switch(keycode) {
314     case RESET:
315       if (record->event.pressed) {
316         reset_keyboard();
317       }
318     return false;
319     case DEBUG:
320       if (record->event.pressed) {
321           debug_enable = true;
322           print("DEBUG: enabled.\n");
323       }
324     return false;
325     case EEPROM_RESET:
326       if (record->event.pressed) {
327           eeconfig_init();
328       }
329     return false;
330   #ifdef FAUXCLICKY_ENABLE
331   case FC_TOG:
332     if (record->event.pressed) {
333       FAUXCLICKY_TOGGLE;
334     }
335     return false;
336   case FC_ON:
337     if (record->event.pressed) {
338       FAUXCLICKY_ON;
339     }
340     return false;
341   case FC_OFF:
342     if (record->event.pressed) {
343       FAUXCLICKY_OFF;
344     }
345     return false;
346   #endif
347   #if defined(RGBLIGHT_ENABLE) || defined(RGB_MATRIX_ENABLE)
348   case RGB_TOG:
349     // Split keyboards need to trigger on key-up for edge-case issue
350     #ifndef SPLIT_KEYBOARD
351     if (record->event.pressed) {
352     #else
353     if (!record->event.pressed) {
354     #endif
355       rgblight_toggle();
356     }
357     return false;
358   case RGB_MODE_FORWARD:
359     if (record->event.pressed) {
360       uint8_t shifted = get_mods() & (MOD_BIT(KC_LSHIFT)|MOD_BIT(KC_RSHIFT));
361       if(shifted) {
362         rgblight_step_reverse();
363       }
364       else {
365         rgblight_step();
366       }
367     }
368     return false;
369   case RGB_MODE_REVERSE:
370     if (record->event.pressed) {
371       uint8_t shifted = get_mods() & (MOD_BIT(KC_LSHIFT)|MOD_BIT(KC_RSHIFT));
372       if(shifted) {
373         rgblight_step();
374       }
375       else {
376         rgblight_step_reverse();
377       }
378     }
379     return false;
380   case RGB_HUI:
381     // Split keyboards need to trigger on key-up for edge-case issue
382     #ifndef SPLIT_KEYBOARD
383     if (record->event.pressed) {
384     #else
385     if (!record->event.pressed) {
386     #endif
387       rgblight_increase_hue();
388     }
389     return false;
390   case RGB_HUD:
391     // Split keyboards need to trigger on key-up for edge-case issue
392     #ifndef SPLIT_KEYBOARD
393     if (record->event.pressed) {
394     #else
395     if (!record->event.pressed) {
396     #endif
397       rgblight_decrease_hue();
398     }
399     return false;
400   case RGB_SAI:
401     // Split keyboards need to trigger on key-up for edge-case issue
402     #ifndef SPLIT_KEYBOARD
403     if (record->event.pressed) {
404     #else
405     if (!record->event.pressed) {
406     #endif
407       rgblight_increase_sat();
408     }
409     return false;
410   case RGB_SAD:
411     // Split keyboards need to trigger on key-up for edge-case issue
412     #ifndef SPLIT_KEYBOARD
413     if (record->event.pressed) {
414     #else
415     if (!record->event.pressed) {
416     #endif
417       rgblight_decrease_sat();
418     }
419     return false;
420   case RGB_VAI:
421     // Split keyboards need to trigger on key-up for edge-case issue
422     #ifndef SPLIT_KEYBOARD
423     if (record->event.pressed) {
424     #else
425     if (!record->event.pressed) {
426     #endif
427       rgblight_increase_val();
428     }
429     return false;
430   case RGB_VAD:
431     // Split keyboards need to trigger on key-up for edge-case issue
432     #ifndef SPLIT_KEYBOARD
433     if (record->event.pressed) {
434     #else
435     if (!record->event.pressed) {
436     #endif
437       rgblight_decrease_val();
438     }
439     return false;
440   case RGB_SPI:
441     if (record->event.pressed) {
442       rgblight_increase_speed();
443     }
444     return false;
445   case RGB_SPD:
446     if (record->event.pressed) {
447       rgblight_decrease_speed();
448     }
449     return false;
450   case RGB_MODE_PLAIN:
451     if (record->event.pressed) {
452       rgblight_mode(RGBLIGHT_MODE_STATIC_LIGHT);
453     }
454     return false;
455   case RGB_MODE_BREATHE:
456   #ifdef RGBLIGHT_EFFECT_BREATHING
457     if (record->event.pressed) {
458       if ((RGBLIGHT_MODE_BREATHING <= rgblight_get_mode()) &&
459           (rgblight_get_mode() < RGBLIGHT_MODE_BREATHING_end)) {
460         rgblight_step();
461       } else {
462         rgblight_mode(RGBLIGHT_MODE_BREATHING);
463       }
464     }
465   #endif
466     return false;
467   case RGB_MODE_RAINBOW:
468   #ifdef RGBLIGHT_EFFECT_RAINBOW_MOOD
469     if (record->event.pressed) {
470       if ((RGBLIGHT_MODE_RAINBOW_MOOD <= rgblight_get_mode()) &&
471           (rgblight_get_mode() < RGBLIGHT_MODE_RAINBOW_MOOD_end)) {
472         rgblight_step();
473       } else {
474         rgblight_mode(RGBLIGHT_MODE_RAINBOW_MOOD);
475       }
476     }
477   #endif
478     return false;
479   case RGB_MODE_SWIRL:
480   #ifdef RGBLIGHT_EFFECT_RAINBOW_SWIRL
481     if (record->event.pressed) {
482       if ((RGBLIGHT_MODE_RAINBOW_SWIRL <= rgblight_get_mode()) &&
483           (rgblight_get_mode() < RGBLIGHT_MODE_RAINBOW_SWIRL_end)) {
484         rgblight_step();
485       } else {
486         rgblight_mode(RGBLIGHT_MODE_RAINBOW_SWIRL);
487       }
488     }
489   #endif
490     return false;
491   case RGB_MODE_SNAKE:
492   #ifdef RGBLIGHT_EFFECT_SNAKE
493     if (record->event.pressed) {
494       if ((RGBLIGHT_MODE_SNAKE <= rgblight_get_mode()) &&
495           (rgblight_get_mode() < RGBLIGHT_MODE_SNAKE_end)) {
496         rgblight_step();
497       } else {
498         rgblight_mode(RGBLIGHT_MODE_SNAKE);
499       }
500     }
501   #endif
502     return false;
503   case RGB_MODE_KNIGHT:
504   #ifdef RGBLIGHT_EFFECT_KNIGHT
505     if (record->event.pressed) {
506       if ((RGBLIGHT_MODE_KNIGHT <= rgblight_get_mode()) &&
507           (rgblight_get_mode() < RGBLIGHT_MODE_KNIGHT_end)) {
508         rgblight_step();
509       } else {
510         rgblight_mode(RGBLIGHT_MODE_KNIGHT);
511       }
512     }
513   #endif
514     return false;
515   case RGB_MODE_XMAS:
516   #ifdef RGBLIGHT_EFFECT_CHRISTMAS
517     if (record->event.pressed) {
518       rgblight_mode(RGBLIGHT_MODE_CHRISTMAS);
519     }
520   #endif
521     return false;
522   case RGB_MODE_GRADIENT:
523   #ifdef RGBLIGHT_EFFECT_STATIC_GRADIENT
524     if (record->event.pressed) {
525       if ((RGBLIGHT_MODE_STATIC_GRADIENT <= rgblight_get_mode()) &&
526           (rgblight_get_mode() < RGBLIGHT_MODE_STATIC_GRADIENT_end)) {
527         rgblight_step();
528       } else {
529         rgblight_mode(RGBLIGHT_MODE_STATIC_GRADIENT);
530       }
531     }
532   #endif
533     return false;
534   case RGB_MODE_RGBTEST:
535   #ifdef RGBLIGHT_EFFECT_RGB_TEST
536     if (record->event.pressed) {
537       rgblight_mode(RGBLIGHT_MODE_RGB_TEST);
538     }
539   #endif
540     return false;
541   #endif // defined(RGBLIGHT_ENABLE) || defined(RGB_MATRIX_ENABLE)
542   #ifdef VELOCIKEY_ENABLE
543     case VLK_TOG:
544       if (record->event.pressed) {
545         velocikey_toggle();
546       }
547       return false;
548   #endif
549   #ifdef PROTOCOL_LUFA
550     case OUT_AUTO:
551       if (record->event.pressed) {
552         set_output(OUTPUT_AUTO);
553       }
554       return false;
555     case OUT_USB:
556       if (record->event.pressed) {
557         set_output(OUTPUT_USB);
558       }
559       return false;
560     #ifdef BLUETOOTH_ENABLE
561     case OUT_BT:
562       if (record->event.pressed) {
563         set_output(OUTPUT_BLUETOOTH);
564       }
565       return false;
566     #endif
567     #endif
568     case MAGIC_SWAP_CONTROL_CAPSLOCK ... MAGIC_TOGGLE_NKRO:
569       if (record->event.pressed) {
570         // MAGIC actions (BOOTMAGIC without the boot)
571         if (!eeconfig_is_enabled()) {
572             eeconfig_init();
573         }
574         /* keymap config */
575         keymap_config.raw = eeconfig_read_keymap();
576         switch (keycode)
577         {
578           case MAGIC_SWAP_CONTROL_CAPSLOCK:
579             keymap_config.swap_control_capslock = true;
580             break;
581           case MAGIC_CAPSLOCK_TO_CONTROL:
582             keymap_config.capslock_to_control = true;
583             break;
584           case MAGIC_SWAP_LALT_LGUI:
585             keymap_config.swap_lalt_lgui = true;
586             break;
587           case MAGIC_SWAP_RALT_RGUI:
588             keymap_config.swap_ralt_rgui = true;
589             break;
590           case MAGIC_NO_GUI:
591             keymap_config.no_gui = true;
592             break;
593           case MAGIC_SWAP_GRAVE_ESC:
594             keymap_config.swap_grave_esc = true;
595             break;
596           case MAGIC_SWAP_BACKSLASH_BACKSPACE:
597             keymap_config.swap_backslash_backspace = true;
598             break;
599           case MAGIC_HOST_NKRO:
600             keymap_config.nkro = true;
601             break;
602           case MAGIC_SWAP_ALT_GUI:
603             keymap_config.swap_lalt_lgui = true;
604             keymap_config.swap_ralt_rgui = true;
605             #ifdef AUDIO_ENABLE
606               PLAY_SONG(ag_swap_song);
607             #endif
608             break;
609           case MAGIC_UNSWAP_CONTROL_CAPSLOCK:
610             keymap_config.swap_control_capslock = false;
611             break;
612           case MAGIC_UNCAPSLOCK_TO_CONTROL:
613             keymap_config.capslock_to_control = false;
614             break;
615           case MAGIC_UNSWAP_LALT_LGUI:
616             keymap_config.swap_lalt_lgui = false;
617             break;
618           case MAGIC_UNSWAP_RALT_RGUI:
619             keymap_config.swap_ralt_rgui = false;
620             break;
621           case MAGIC_UNNO_GUI:
622             keymap_config.no_gui = false;
623             break;
624           case MAGIC_UNSWAP_GRAVE_ESC:
625             keymap_config.swap_grave_esc = false;
626             break;
627           case MAGIC_UNSWAP_BACKSLASH_BACKSPACE:
628             keymap_config.swap_backslash_backspace = false;
629             break;
630           case MAGIC_UNHOST_NKRO:
631             keymap_config.nkro = false;
632             break;
633           case MAGIC_UNSWAP_ALT_GUI:
634             keymap_config.swap_lalt_lgui = false;
635             keymap_config.swap_ralt_rgui = false;
636             #ifdef AUDIO_ENABLE
637               PLAY_SONG(ag_norm_song);
638             #endif
639             break;
640           case MAGIC_TOGGLE_ALT_GUI:
641             keymap_config.swap_lalt_lgui = !keymap_config.swap_lalt_lgui;
642             keymap_config.swap_ralt_rgui = !keymap_config.swap_ralt_rgui;
643             #ifdef AUDIO_ENABLE
644               if (keymap_config.swap_ralt_rgui) {
645                 PLAY_SONG(ag_swap_song);
646               } else {
647                 PLAY_SONG(ag_norm_song);
648               }
649             #endif
650             break;
651           case MAGIC_TOGGLE_NKRO:
652             keymap_config.nkro = !keymap_config.nkro;
653             break;
654           default:
655             break;
656         }
657         eeconfig_update_keymap(keymap_config.raw);
658         clear_keyboard(); // clear to prevent stuck keys
659
660         return false;
661       }
662       break;
663
664     case GRAVE_ESC: {
665       uint8_t shifted = get_mods() & ((MOD_BIT(KC_LSHIFT)|MOD_BIT(KC_RSHIFT)
666                                       |MOD_BIT(KC_LGUI)|MOD_BIT(KC_RGUI)));
667
668 #ifdef GRAVE_ESC_ALT_OVERRIDE
669       // if ALT is pressed, ESC is always sent
670       // this is handy for the cmd+opt+esc shortcut on macOS, among other things.
671       if (get_mods() & (MOD_BIT(KC_LALT) | MOD_BIT(KC_RALT))) {
672         shifted = 0;
673       }
674 #endif
675
676 #ifdef GRAVE_ESC_CTRL_OVERRIDE
677       // if CTRL is pressed, ESC is always sent
678       // this is handy for the ctrl+shift+esc shortcut on windows, among other things.
679       if (get_mods() & (MOD_BIT(KC_LCTL) | MOD_BIT(KC_RCTL))) {
680         shifted = 0;
681       }
682 #endif
683
684 #ifdef GRAVE_ESC_GUI_OVERRIDE
685       // if GUI is pressed, ESC is always sent
686       if (get_mods() & (MOD_BIT(KC_LGUI) | MOD_BIT(KC_RGUI))) {
687         shifted = 0;
688       }
689 #endif
690
691 #ifdef GRAVE_ESC_SHIFT_OVERRIDE
692       // if SHIFT is pressed, ESC is always sent
693       if (get_mods() & (MOD_BIT(KC_LSHIFT) | MOD_BIT(KC_RSHIFT))) {
694         shifted = 0;
695       }
696 #endif
697
698       if (record->event.pressed) {
699         grave_esc_was_shifted = shifted;
700         add_key(shifted ? KC_GRAVE : KC_ESCAPE);
701       }
702       else {
703         del_key(grave_esc_was_shifted ? KC_GRAVE : KC_ESCAPE);
704       }
705
706       send_keyboard_report();
707       return false;
708     }
709
710 #if defined(BACKLIGHT_ENABLE) && defined(BACKLIGHT_BREATHING)
711     case BL_BRTG: {
712       if (record->event.pressed)
713         breathing_toggle();
714       return false;
715     }
716 #endif
717   }
718
719   return process_action_kb(record);
720 }
721
722 __attribute__ ((weak))
723 const bool ascii_to_shift_lut[0x80] PROGMEM = {
724     0, 0, 0, 0, 0, 0, 0, 0,
725     0, 0, 0, 0, 0, 0, 0, 0,
726     0, 0, 0, 0, 0, 0, 0, 0,
727     0, 0, 0, 0, 0, 0, 0, 0,
728     0, 1, 1, 1, 1, 1, 1, 0,
729     1, 1, 1, 1, 0, 0, 0, 0,
730     0, 0, 0, 0, 0, 0, 0, 0,
731     0, 0, 1, 0, 1, 0, 1, 1,
732     1, 1, 1, 1, 1, 1, 1, 1,
733     1, 1, 1, 1, 1, 1, 1, 1,
734     1, 1, 1, 1, 1, 1, 1, 1,
735     1, 1, 1, 0, 0, 0, 1, 1,
736     0, 0, 0, 0, 0, 0, 0, 0,
737     0, 0, 0, 0, 0, 0, 0, 0,
738     0, 0, 0, 0, 0, 0, 0, 0,
739     0, 0, 0, 1, 1, 1, 1, 0
740 };
741
742 __attribute__ ((weak))
743 const bool ascii_to_altgr_lut[0x80] PROGMEM = {
744     0, 0, 0, 0, 0, 0, 0, 0,
745     0, 0, 0, 0, 0, 0, 0, 0,
746     0, 0, 0, 0, 0, 0, 0, 0,
747     0, 0, 0, 0, 0, 0, 0, 0,
748     0, 0, 0, 0, 0, 0, 0, 0,
749     0, 0, 0, 0, 0, 0, 0, 0,
750     0, 0, 0, 0, 0, 0, 0, 0,
751     0, 0, 0, 0, 0, 0, 0, 0,
752     0, 0, 0, 0, 0, 0, 0, 0,
753     0, 0, 0, 0, 0, 0, 0, 0,
754     0, 0, 0, 0, 0, 0, 0, 0,
755     0, 0, 0, 0, 0, 0, 0, 0,
756     0, 0, 0, 0, 0, 0, 0, 0,
757     0, 0, 0, 0, 0, 0, 0, 0,
758     0, 0, 0, 0, 0, 0, 0, 0,
759     0, 0, 0, 0, 0, 0, 0, 0
760 };
761
762 __attribute__ ((weak))
763 const uint8_t ascii_to_keycode_lut[0x80] PROGMEM = {
764     0, 0, 0, 0, 0, 0, 0, 0,
765     KC_BSPC, KC_TAB, KC_ENT, 0, 0, 0, 0, 0,
766     0, 0, 0, 0, 0, 0, 0, 0,
767     0, 0, 0, KC_ESC, 0, 0, 0, 0,
768     KC_SPC, KC_1, KC_QUOT, KC_3, KC_4, KC_5, KC_7, KC_QUOT,
769     KC_9, KC_0, KC_8, KC_EQL, KC_COMM, KC_MINS, KC_DOT, KC_SLSH,
770     KC_0, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7,
771     KC_8, KC_9, KC_SCLN, KC_SCLN, KC_COMM, KC_EQL, KC_DOT, KC_SLSH,
772     KC_2, KC_A, KC_B, KC_C, KC_D, KC_E, KC_F, KC_G,
773     KC_H, KC_I, KC_J, KC_K, KC_L, KC_M, KC_N, KC_O,
774     KC_P, KC_Q, KC_R, KC_S, KC_T, KC_U, KC_V, KC_W,
775     KC_X, KC_Y, KC_Z, KC_LBRC, KC_BSLS, KC_RBRC, KC_6, KC_MINS,
776     KC_GRV, KC_A, KC_B, KC_C, KC_D, KC_E, KC_F, KC_G,
777     KC_H, KC_I, KC_J, KC_K, KC_L, KC_M, KC_N, KC_O,
778     KC_P, KC_Q, KC_R, KC_S, KC_T, KC_U, KC_V, KC_W,
779     KC_X, KC_Y, KC_Z, KC_LBRC, KC_BSLS, KC_RBRC, KC_GRV, KC_DEL
780 };
781
782 void send_string(const char *str) {
783   send_string_with_delay(str, 0);
784 }
785
786 void send_string_P(const char *str) {
787   send_string_with_delay_P(str, 0);
788 }
789
790 void send_string_with_delay(const char *str, uint8_t interval) {
791     while (1) {
792         char ascii_code = *str;
793         if (!ascii_code) break;
794         if (ascii_code == SS_TAP_CODE) {
795           // tap
796           uint8_t keycode = *(++str);
797           register_code(keycode);
798           unregister_code(keycode);
799         } else if (ascii_code == SS_DOWN_CODE) {
800           // down
801           uint8_t keycode = *(++str);
802           register_code(keycode);
803         } else if (ascii_code == SS_UP_CODE) {
804           // up
805           uint8_t keycode = *(++str);
806           unregister_code(keycode);
807         } else {
808           send_char(ascii_code);
809         }
810         ++str;
811         // interval
812         { uint8_t ms = interval; while (ms--) wait_ms(1); }
813     }
814 }
815
816 void send_string_with_delay_P(const char *str, uint8_t interval) {
817     while (1) {
818         char ascii_code = pgm_read_byte(str);
819         if (!ascii_code) break;
820         if (ascii_code == SS_TAP_CODE) {
821           // tap
822           uint8_t keycode = pgm_read_byte(++str);
823           register_code(keycode);
824           unregister_code(keycode);
825         } else if (ascii_code == SS_DOWN_CODE) {
826           // down
827           uint8_t keycode = pgm_read_byte(++str);
828           register_code(keycode);
829         } else if (ascii_code == SS_UP_CODE) {
830           // up
831           uint8_t keycode = pgm_read_byte(++str);
832           unregister_code(keycode);
833         } else {
834           send_char(ascii_code);
835         }
836         ++str;
837         // interval
838         { uint8_t ms = interval; while (ms--) wait_ms(1); }
839     }
840 }
841
842 void send_char(char ascii_code) {
843   uint8_t keycode = pgm_read_byte(&ascii_to_keycode_lut[(uint8_t)ascii_code]);
844   bool is_shifted = pgm_read_byte(&ascii_to_shift_lut[(uint8_t)ascii_code]);
845   bool is_altgred = pgm_read_byte(&ascii_to_altgr_lut[(uint8_t)ascii_code]);
846
847   if (is_shifted) {
848     register_code(KC_LSFT);
849   }
850   if (is_altgred) {
851     register_code(KC_RALT);
852   }
853   tap_code(keycode);
854   if (is_altgred) {
855     unregister_code(KC_RALT);
856   }
857   if (is_shifted) {
858     unregister_code(KC_LSFT);
859   }
860 }
861
862 void set_single_persistent_default_layer(uint8_t default_layer) {
863   #if defined(AUDIO_ENABLE) && defined(DEFAULT_LAYER_SONGS)
864     PLAY_SONG(default_layer_songs[default_layer]);
865   #endif
866   eeconfig_update_default_layer(1U<<default_layer);
867   default_layer_set(1U<<default_layer);
868 }
869
870 uint32_t update_tri_layer_state(uint32_t state, uint8_t layer1, uint8_t layer2, uint8_t layer3) {
871   uint32_t mask12 = (1UL << layer1) | (1UL << layer2);
872   uint32_t mask3 = 1UL << layer3;
873   return (state & mask12) == mask12 ? (state | mask3) : (state & ~mask3);
874 }
875
876 void update_tri_layer(uint8_t layer1, uint8_t layer2, uint8_t layer3) {
877   layer_state_set(update_tri_layer_state(layer_state, layer1, layer2, layer3));
878 }
879
880 void tap_random_base64(void) {
881   #if defined(__AVR_ATmega32U4__)
882     uint8_t key = (TCNT0 + TCNT1 + TCNT3 + TCNT4) % 64;
883   #else
884     uint8_t key = rand() % 64;
885   #endif
886   switch (key) {
887     case 0 ... 25:
888       register_code(KC_LSFT);
889       register_code(key + KC_A);
890       unregister_code(key + KC_A);
891       unregister_code(KC_LSFT);
892       break;
893     case 26 ... 51:
894       register_code(key - 26 + KC_A);
895       unregister_code(key - 26 + KC_A);
896       break;
897     case 52:
898       register_code(KC_0);
899       unregister_code(KC_0);
900       break;
901     case 53 ... 61:
902       register_code(key - 53 + KC_1);
903       unregister_code(key - 53 + KC_1);
904       break;
905     case 62:
906       register_code(KC_LSFT);
907       register_code(KC_EQL);
908       unregister_code(KC_EQL);
909       unregister_code(KC_LSFT);
910       break;
911     case 63:
912       register_code(KC_SLSH);
913       unregister_code(KC_SLSH);
914       break;
915   }
916 }
917
918 __attribute__((weak))
919 void bootmagic_lite(void) {
920   // The lite version of TMK's bootmagic based on Wilba.
921   // 100% less potential for accidentally making the
922   // keyboard do stupid things.
923
924   // We need multiple scans because debouncing can't be turned off.
925   matrix_scan();
926   #if defined(DEBOUNCING_DELAY) && DEBOUNCING_DELAY > 0
927     wait_ms(DEBOUNCING_DELAY * 2);
928   #elif defined(DEBOUNCE) && DEBOUNCE > 0
929     wait_ms(DEBOUNCE * 2);
930   #else
931     wait_ms(30);
932   #endif
933   matrix_scan();
934
935   // If the Esc and space bar are held down on power up,
936   // reset the EEPROM valid state and jump to bootloader.
937   // Assumes Esc is at [0,0].
938   // This isn't very generalized, but we need something that doesn't
939   // rely on user's keymaps in firmware or EEPROM.
940   if (matrix_get_row(BOOTMAGIC_LITE_ROW) & (1 << BOOTMAGIC_LITE_COLUMN)) {
941     eeconfig_disable();
942     // Jump to bootloader.
943     bootloader_jump();
944   }
945 }
946
947 void matrix_init_quantum() {
948   #ifdef BOOTMAGIC_LITE
949     bootmagic_lite();
950   #endif
951   if (!eeconfig_is_enabled()) {
952     eeconfig_init();
953   }
954   #ifdef BACKLIGHT_ENABLE
955     #ifdef LED_MATRIX_ENABLE
956         led_matrix_init();
957     #else
958         backlight_init_ports();
959     #endif
960   #endif
961   #ifdef AUDIO_ENABLE
962     audio_init();
963   #endif
964   #ifdef RGB_MATRIX_ENABLE
965     rgb_matrix_init();
966   #endif
967   #ifdef ENCODER_ENABLE
968     encoder_init();
969   #endif
970   #if defined(UNICODE_ENABLE) || defined(UNICODEMAP_ENABLE) || defined(UCIS_ENABLE)
971     unicode_input_mode_init();
972   #endif
973   #ifdef HAPTIC_ENABLE
974     haptic_init();
975   #endif
976   #ifdef OUTPUT_AUTO_ENABLE
977     set_output(OUTPUT_AUTO);
978   #endif
979   #ifdef OLED_DRIVER_ENABLE
980     oled_init(OLED_ROTATION_0);
981   #endif
982   matrix_init_kb();
983 }
984
985 void matrix_scan_quantum() {
986   #if defined(AUDIO_ENABLE) && !defined(NO_MUSIC_MODE)
987     matrix_scan_music();
988   #endif
989
990   #ifdef TAP_DANCE_ENABLE
991     matrix_scan_tap_dance();
992   #endif
993
994   #ifdef COMBO_ENABLE
995     matrix_scan_combo();
996   #endif
997
998   #if defined(BACKLIGHT_ENABLE)
999     #if defined(LED_MATRIX_ENABLE)
1000         led_matrix_task();
1001     #elif defined(BACKLIGHT_PIN)
1002         backlight_task();
1003     #endif
1004   #endif
1005
1006   #ifdef RGB_MATRIX_ENABLE
1007     rgb_matrix_task();
1008   #endif
1009
1010   #ifdef ENCODER_ENABLE
1011     encoder_read();
1012   #endif
1013
1014   #ifdef HAPTIC_ENABLE
1015     haptic_task();
1016   #endif
1017
1018   #ifdef OLED_DRIVER_ENABLE
1019     oled_task();
1020   #endif
1021
1022   matrix_scan_kb();
1023 }
1024 #if defined(BACKLIGHT_ENABLE) && (defined(BACKLIGHT_PIN) || defined(BACKLIGHT_PINS))
1025
1026 // The logic is a bit complex, we support 3 setups:
1027 // 1. hardware PWM when backlight is wired to a PWM pin
1028 // depending on this pin, we use a different output compare unit
1029 // 2. software PWM with hardware timers, but the used timer depends
1030 // on the audio setup (audio wins other backlight)
1031 // 3. full software PWM
1032
1033 #if BACKLIGHT_PIN == B7
1034 #  define HARDWARE_PWM
1035 #  define TCCRxA TCCR1A
1036 #  define TCCRxB TCCR1B
1037 #  define COMxx1 COM1C1
1038 #  define OCRxx  OCR1C
1039 #  define ICRx   ICR1
1040 #elif BACKLIGHT_PIN == B6
1041 #  define HARDWARE_PWM
1042 #  define TCCRxA TCCR1A
1043 #  define TCCRxB TCCR1B
1044 #  define COMxx1 COM1B1
1045 #  define OCRxx  OCR1B
1046 #  define ICRx   ICR1
1047 #elif BACKLIGHT_PIN == B5
1048 #  define HARDWARE_PWM
1049 #  define TCCRxA TCCR1A
1050 #  define TCCRxB TCCR1B
1051 #  define COMxx1 COM1A1
1052 #  define OCRxx  OCR1A
1053 #  define ICRx   ICR1
1054 #elif BACKLIGHT_PIN == C6
1055 #  define HARDWARE_PWM
1056 #  define TCCRxA TCCR3A
1057 #  define TCCRxB TCCR3B
1058 #  define COMxx1 COM1A1
1059 #  define OCRxx  OCR3A
1060 #  define ICRx   ICR3
1061 #elif defined(__AVR_ATmega32A__) && BACKLIGHT_PIN == D4
1062 #  define TCCRxA TCCR1A
1063 #  define TCCRxB TCCR1B
1064 #  define COMxx1 COM1B1
1065 #  define OCRxx  OCR1B
1066 #  define ICRx   ICR1
1067 #  define TIMSK1 TIMSK
1068 #else
1069 #  if !defined(BACKLIGHT_CUSTOM_DRIVER)
1070 #    if !defined(B5_AUDIO) && !defined(B6_AUDIO) && !defined(B7_AUDIO)
1071      // timer 1 is not used by audio , backlight can use it
1072 #pragma message "Using hardware timer 1 with software PWM"
1073 #      define HARDWARE_PWM
1074 #      define BACKLIGHT_PWM_TIMER
1075 #      define TCCRxA TCCR1A
1076 #      define TCCRxB TCCR1B
1077 #      define OCRxx  OCR1A
1078 #      define OCRxAH OCR1AH
1079 #      define OCRxAL OCR1AL
1080 #      define TIMERx_COMPA_vect TIMER1_COMPA_vect
1081 #      define TIMERx_OVF_vect TIMER1_OVF_vect
1082 #      define OCIExA OCIE1A
1083 #      define TOIEx  TOIE1
1084 #      define ICRx   ICR1
1085 #      ifndef TIMSK
1086 #        define TIMSK TIMSK1
1087 #      endif
1088 #    elif !defined(C6_AUDIO) && !defined(C5_AUDIO) && !defined(C4_AUDIO)
1089 #pragma message "Using hardware timer 3 with software PWM"
1090 // timer 3 is not used by audio, backlight can use it
1091 #      define HARDWARE_PWM
1092 #      define BACKLIGHT_PWM_TIMER
1093 #      define TCCRxA TCCR3A
1094 #      define TCCRxB TCCR3B
1095 #      define OCRxx OCR3A
1096 #      define OCRxAH OCR3AH
1097 #      define OCRxAL OCR3AL
1098 #      define TIMERx_COMPA_vect TIMER3_COMPA_vect
1099 #      define TIMERx_OVF_vect TIMER3_OVF_vect
1100 #      define OCIExA OCIE3A
1101 #      define TOIEx  TOIE3
1102 #      define ICRx   ICR1
1103 #      ifndef TIMSK
1104 #        define TIMSK TIMSK3
1105 #      endif
1106 #    else
1107 #pragma message "Audio in use - using pure software PWM"
1108 #define NO_HARDWARE_PWM
1109 #    endif
1110 #  else
1111 #pragma message "Custom driver defined - using pure software PWM"
1112 #define NO_HARDWARE_PWM
1113 #  endif
1114 #endif
1115
1116 #ifndef BACKLIGHT_ON_STATE
1117 #define BACKLIGHT_ON_STATE 0
1118 #endif
1119
1120 void backlight_on(uint8_t backlight_pin) {
1121 #if BACKLIGHT_ON_STATE == 0
1122   writePinLow(backlight_pin);
1123 #else
1124   writePinHigh(backlight_pin);
1125 #endif
1126 }
1127
1128 void backlight_off(uint8_t backlight_pin) {
1129 #if BACKLIGHT_ON_STATE == 0
1130   writePinHigh(backlight_pin);
1131 #else
1132   writePinLow(backlight_pin);
1133 #endif
1134 }
1135
1136
1137 #if defined(NO_HARDWARE_PWM) || defined(BACKLIGHT_PWM_TIMER)  // pwm through software
1138
1139 // we support multiple backlight pins
1140 #ifndef BACKLIGHT_LED_COUNT
1141 #define BACKLIGHT_LED_COUNT 1
1142 #endif
1143
1144 #if BACKLIGHT_LED_COUNT == 1
1145 #define BACKLIGHT_PIN_INIT { BACKLIGHT_PIN }
1146 #else
1147 #define BACKLIGHT_PIN_INIT BACKLIGHT_PINS
1148 #endif
1149
1150 #define FOR_EACH_LED(x)                             \
1151   for (uint8_t i = 0; i < BACKLIGHT_LED_COUNT; i++) \
1152   {                                                 \
1153     uint8_t backlight_pin = backlight_pins[i];      \
1154     { \
1155       x                         \
1156     }                                             \
1157   }
1158
1159 static const uint8_t backlight_pins[BACKLIGHT_LED_COUNT] = BACKLIGHT_PIN_INIT;
1160
1161 #else // full hardware PWM
1162
1163 // we support only one backlight pin
1164 static const uint8_t backlight_pin = BACKLIGHT_PIN;
1165 #define FOR_EACH_LED(x) x
1166
1167 #endif
1168
1169 #ifdef NO_HARDWARE_PWM
1170 __attribute__((weak))
1171 void backlight_init_ports(void)
1172 {
1173   // Setup backlight pin as output and output to on state.
1174   FOR_EACH_LED(
1175     setPinOutput(backlight_pin);
1176     backlight_on(backlight_pin);
1177   )
1178 }
1179
1180 __attribute__ ((weak))
1181 void backlight_set(uint8_t level) {}
1182
1183 uint8_t backlight_tick = 0;
1184
1185 #ifndef BACKLIGHT_CUSTOM_DRIVER
1186 void backlight_task(void) {
1187   if ((0xFFFF >> ((BACKLIGHT_LEVELS - get_backlight_level()) * ((BACKLIGHT_LEVELS + 1) / 2))) & (1 << backlight_tick)) {
1188     FOR_EACH_LED(
1189       backlight_on(backlight_pin);
1190     )
1191   }
1192   else {
1193     FOR_EACH_LED(
1194       backlight_off(backlight_pin);
1195     )
1196   }
1197   backlight_tick = (backlight_tick + 1) % 16;
1198 }
1199 #endif
1200
1201 #ifdef BACKLIGHT_BREATHING
1202   #ifndef BACKLIGHT_CUSTOM_DRIVER
1203   #error "Backlight breathing only available with hardware PWM. Please disable."
1204   #endif
1205 #endif
1206
1207 #else // hardware pwm through timer
1208
1209 #ifdef BACKLIGHT_PWM_TIMER
1210
1211 // The idea of software PWM assisted by hardware timers is the following
1212 // we use the hardware timer in fast PWM mode like for hardware PWM, but
1213 // instead of letting the Output Match Comparator control the led pin
1214 // (which is not possible since the backlight is not wired to PWM pins on the
1215 // CPU), we do the LED on/off by oursleves.
1216 // The timer is setup to count up to 0xFFFF, and we set the Output Compare
1217 // register to the current 16bits backlight level (after CIE correction). 
1218 // This means the CPU will trigger a compare match interrupt when the counter 
1219 // reaches the backlight level, where we turn off the LEDs, 
1220 // but also an overflow interrupt when the counter rolls back to 0, 
1221 // in which we're going to turn on the LEDs.
1222 // The LED will then be on for OCRxx/0xFFFF time, adjusted every 244Hz.
1223
1224 // Triggered when the counter reaches the OCRx value
1225 ISR(TIMERx_COMPA_vect) {
1226   FOR_EACH_LED(
1227     backlight_off(backlight_pin);
1228   )
1229 }
1230
1231 // Triggered when the counter reaches the TOP value
1232 // this one triggers at F_CPU/65536 =~ 244 Hz 
1233 ISR(TIMERx_OVF_vect) {
1234 #ifdef BACKLIGHT_BREATHING
1235   breathing_task();
1236 #endif
1237   // for very small values of OCRxx (or backlight level)
1238   // we can't guarantee this whole code won't execute
1239   // at the same time as the compare match interrupt
1240   // which means that we might turn on the leds while
1241   // trying to turn them off, leading to flickering
1242   // artifacts (especially while breathing, because breathing_task
1243   // takes many computation cycles).
1244   // so better not turn them on while the counter TOP is very low.
1245   if (OCRxx > 256) {
1246     FOR_EACH_LED(
1247       backlight_on(backlight_pin);
1248     )
1249   }
1250 }
1251
1252 #endif
1253
1254 #define TIMER_TOP 0xFFFFU
1255
1256 // See http://jared.geek.nz/2013/feb/linear-led-pwm
1257 static uint16_t cie_lightness(uint16_t v) {
1258   if (v <= 5243) // if below 8% of max
1259     return v / 9; // same as dividing by 900%
1260   else {
1261     uint32_t y = (((uint32_t) v + 10486) << 8) / (10486 + 0xFFFFUL); // add 16% of max and compare
1262     // to get a useful result with integer division, we shift left in the expression above
1263     // and revert what we've done again after squaring.
1264     y = y * y * y >> 8;
1265     if (y > 0xFFFFUL) // prevent overflow
1266       return 0xFFFFU;
1267     else
1268       return (uint16_t) y;
1269   }
1270 }
1271
1272 // range for val is [0..TIMER_TOP]. PWM pin is high while the timer count is below val.
1273 static inline void set_pwm(uint16_t val) {
1274         OCRxx = val;
1275 }
1276
1277 #ifndef BACKLIGHT_CUSTOM_DRIVER
1278 __attribute__ ((weak))
1279 void backlight_set(uint8_t level) {
1280   if (level > BACKLIGHT_LEVELS)
1281     level = BACKLIGHT_LEVELS;
1282
1283   if (level == 0) {
1284     #ifdef BACKLIGHT_PWM_TIMER
1285       if (OCRxx) {
1286         TIMSK &= ~(_BV(OCIExA));
1287         TIMSK &= ~(_BV(TOIEx));
1288         FOR_EACH_LED(
1289           backlight_off(backlight_pin);
1290         )
1291       }
1292     #else
1293     // Turn off PWM control on backlight pin
1294     TCCRxA &= ~(_BV(COMxx1));
1295     #endif
1296   } else {
1297     #ifdef BACKLIGHT_PWM_TIMER
1298       if (!OCRxx) {
1299         TIMSK |= _BV(OCIExA);
1300         TIMSK |= _BV(TOIEx);
1301       }
1302     #else
1303     // Turn on PWM control of backlight pin
1304     TCCRxA |= _BV(COMxx1);
1305     #endif
1306   }
1307   // Set the brightness
1308   set_pwm(cie_lightness(TIMER_TOP * (uint32_t)level / BACKLIGHT_LEVELS));
1309 }
1310
1311 void backlight_task(void) {}
1312 #endif  // BACKLIGHT_CUSTOM_DRIVER
1313
1314 #ifdef BACKLIGHT_BREATHING
1315
1316 #define BREATHING_NO_HALT  0
1317 #define BREATHING_HALT_OFF 1
1318 #define BREATHING_HALT_ON  2
1319 #define BREATHING_STEPS 128
1320
1321 static uint8_t breathing_period = BREATHING_PERIOD;
1322 static uint8_t breathing_halt = BREATHING_NO_HALT;
1323 static uint16_t breathing_counter = 0;
1324
1325 #ifdef BACKLIGHT_PWM_TIMER
1326 static bool breathing = false;
1327
1328 bool is_breathing(void) {
1329   return breathing;
1330 }
1331
1332 #define breathing_interrupt_enable() do { breathing = true; } while (0)
1333 #define breathing_interrupt_disable() do { breathing = false; } while (0)
1334 #else
1335
1336 bool is_breathing(void) {
1337     return !!(TIMSK1 & _BV(TOIE1));
1338 }
1339
1340 #define breathing_interrupt_enable() do {TIMSK1 |= _BV(TOIE1);} while (0)
1341 #define breathing_interrupt_disable() do {TIMSK1 &= ~_BV(TOIE1);} while (0)
1342 #endif
1343
1344 #define breathing_min() do {breathing_counter = 0;} while (0)
1345 #define breathing_max() do {breathing_counter = breathing_period * 244 / 2;} while (0)
1346
1347 void breathing_enable(void)
1348 {
1349   breathing_counter = 0;
1350   breathing_halt = BREATHING_NO_HALT;
1351   breathing_interrupt_enable();
1352 }
1353
1354 void breathing_pulse(void)
1355 {
1356     if (get_backlight_level() == 0)
1357       breathing_min();
1358     else
1359       breathing_max();
1360     breathing_halt = BREATHING_HALT_ON;
1361     breathing_interrupt_enable();
1362 }
1363
1364 void breathing_disable(void)
1365 {
1366     breathing_interrupt_disable();
1367     // Restore backlight level
1368     backlight_set(get_backlight_level());
1369 }
1370
1371 void breathing_self_disable(void)
1372 {
1373   if (get_backlight_level() == 0)
1374     breathing_halt = BREATHING_HALT_OFF;
1375   else
1376     breathing_halt = BREATHING_HALT_ON;
1377 }
1378
1379 void breathing_toggle(void) {
1380   if (is_breathing())
1381     breathing_disable();
1382   else
1383     breathing_enable();
1384 }
1385
1386 void breathing_period_set(uint8_t value)
1387 {
1388   if (!value)
1389     value = 1;
1390   breathing_period = value;
1391 }
1392
1393 void breathing_period_default(void) {
1394   breathing_period_set(BREATHING_PERIOD);
1395 }
1396
1397 void breathing_period_inc(void)
1398 {
1399   breathing_period_set(breathing_period+1);
1400 }
1401
1402 void breathing_period_dec(void)
1403 {
1404   breathing_period_set(breathing_period-1);
1405 }
1406
1407 /* To generate breathing curve in python:
1408  * from math import sin, pi; [int(sin(x/128.0*pi)**4*255) for x in range(128)]
1409  */
1410 static const uint8_t breathing_table[BREATHING_STEPS] PROGMEM = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 17, 20, 24, 28, 32, 36, 41, 46, 51, 57, 63, 70, 76, 83, 91, 98, 106, 113, 121, 129, 138, 146, 154, 162, 170, 178, 185, 193, 200, 207, 213, 220, 225, 231, 235, 240, 244, 247, 250, 252, 253, 254, 255, 254, 253, 252, 250, 247, 244, 240, 235, 231, 225, 220, 213, 207, 200, 193, 185, 178, 170, 162, 154, 146, 138, 129, 121, 113, 106, 98, 91, 83, 76, 70, 63, 57, 51, 46, 41, 36, 32, 28, 24, 20, 17, 15, 12, 10, 8, 6, 5, 4, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1411
1412 // Use this before the cie_lightness function.
1413 static inline uint16_t scale_backlight(uint16_t v) {
1414   return v / BACKLIGHT_LEVELS * get_backlight_level();
1415 }
1416
1417 #ifdef BACKLIGHT_PWM_TIMER
1418 void breathing_task(void)
1419 #else
1420 /* Assuming a 16MHz CPU clock and a timer that resets at 64k (ICR1), the following interrupt handler will run
1421  * about 244 times per second.
1422  */
1423 ISR(TIMER1_OVF_vect)
1424 #endif
1425 {
1426   uint16_t interval = (uint16_t) breathing_period * 244 / BREATHING_STEPS;
1427   // resetting after one period to prevent ugly reset at overflow.
1428   breathing_counter = (breathing_counter + 1) % (breathing_period * 244);
1429   uint8_t index = breathing_counter / interval % BREATHING_STEPS;
1430
1431   if (((breathing_halt == BREATHING_HALT_ON) && (index == BREATHING_STEPS / 2)) ||
1432       ((breathing_halt == BREATHING_HALT_OFF) && (index == BREATHING_STEPS - 1)))
1433   {
1434       breathing_interrupt_disable();
1435   }
1436
1437   set_pwm(cie_lightness(scale_backlight((uint16_t) pgm_read_byte(&breathing_table[index]) * 0x0101U)));
1438 }
1439
1440 #endif // BACKLIGHT_BREATHING
1441
1442 __attribute__ ((weak))
1443 void backlight_init_ports(void)
1444 {
1445   // Setup backlight pin as output and output to on state.
1446   FOR_EACH_LED(
1447     setPinOutput(backlight_pin);
1448     backlight_on(backlight_pin);
1449   )
1450
1451   // I could write a wall of text here to explain... but TL;DW
1452   // Go read the ATmega32u4 datasheet.
1453   // And this: http://blog.saikoled.com/post/43165849837/secret-konami-cheat-code-to-high-resolution-pwm-on
1454
1455 #ifdef BACKLIGHT_PWM_TIMER
1456   // TimerX setup, Fast PWM mode count to TOP set in ICRx
1457   TCCRxA = _BV(WGM11); // = 0b00000010;
1458   // clock select clk/1
1459   TCCRxB = _BV(WGM13) | _BV(WGM12) | _BV(CS10); // = 0b00011001;
1460 #else // hardware PWM
1461   // Pin PB7 = OCR1C (Timer 1, Channel C)
1462   // Compare Output Mode = Clear on compare match, Channel C = COM1C1=1 COM1C0=0
1463   // (i.e. start high, go low when counter matches.)
1464   // WGM Mode 14 (Fast PWM) = WGM13=1 WGM12=1 WGM11=1 WGM10=0
1465   // Clock Select = clk/1 (no prescaling) = CS12=0 CS11=0 CS10=1
1466
1467   /*
1468   14.8.3:
1469   "In fast PWM mode, the compare units allow generation of PWM waveforms on the OCnx pins. Setting the COMnx1:0 bits to two will produce a non-inverted PWM [..]."
1470   "In fast PWM mode the counter is incremented until the counter value matches either one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGMn3:0 = 5, 6, or 7), the value in ICRn (WGMn3:0 = 14), or the value in OCRnA (WGMn3:0 = 15)."
1471   */
1472   TCCRxA = _BV(COMxx1) | _BV(WGM11);            // = 0b00001010;
1473   TCCRxB = _BV(WGM13) | _BV(WGM12) | _BV(CS10); // = 0b00011001;
1474 #endif
1475   // Use full 16-bit resolution. Counter counts to ICR1 before reset to 0.
1476   ICRx = TIMER_TOP;
1477
1478   backlight_init();
1479   #ifdef BACKLIGHT_BREATHING
1480     breathing_enable();
1481   #endif
1482 }
1483
1484 #endif // hardware backlight
1485
1486 #else // no backlight
1487
1488 __attribute__ ((weak))
1489 void backlight_init_ports(void) {}
1490
1491 __attribute__ ((weak))
1492 void backlight_set(uint8_t level) {}
1493
1494 #endif // backlight
1495
1496 #ifdef HD44780_ENABLED
1497 #include "hd44780.h"
1498 #endif
1499
1500
1501 // Functions for spitting out values
1502 //
1503
1504 void send_dword(uint32_t number) { // this might not actually work
1505     uint16_t word = (number >> 16);
1506     send_word(word);
1507     send_word(number & 0xFFFFUL);
1508 }
1509
1510 void send_word(uint16_t number) {
1511     uint8_t byte = number >> 8;
1512     send_byte(byte);
1513     send_byte(number & 0xFF);
1514 }
1515
1516 void send_byte(uint8_t number) {
1517     uint8_t nibble = number >> 4;
1518     send_nibble(nibble);
1519     send_nibble(number & 0xF);
1520 }
1521
1522 void send_nibble(uint8_t number) {
1523     switch (number) {
1524         case 0:
1525             register_code(KC_0);
1526             unregister_code(KC_0);
1527             break;
1528         case 1 ... 9:
1529             register_code(KC_1 + (number - 1));
1530             unregister_code(KC_1 + (number - 1));
1531             break;
1532         case 0xA ... 0xF:
1533             register_code(KC_A + (number - 0xA));
1534             unregister_code(KC_A + (number - 0xA));
1535             break;
1536     }
1537 }
1538
1539
1540 __attribute__((weak))
1541 uint16_t hex_to_keycode(uint8_t hex)
1542 {
1543   hex = hex & 0xF;
1544   if (hex == 0x0) {
1545     return KC_0;
1546   } else if (hex < 0xA) {
1547     return KC_1 + (hex - 0x1);
1548   } else {
1549     return KC_A + (hex - 0xA);
1550   }
1551 }
1552
1553 void api_send_unicode(uint32_t unicode) {
1554 #ifdef API_ENABLE
1555     uint8_t chunk[4];
1556     dword_to_bytes(unicode, chunk);
1557     MT_SEND_DATA(DT_UNICODE, chunk, 5);
1558 #endif
1559 }
1560
1561 __attribute__ ((weak))
1562 void led_set_user(uint8_t usb_led) {
1563
1564 }
1565
1566 __attribute__ ((weak))
1567 void led_set_kb(uint8_t usb_led) {
1568     led_set_user(usb_led);
1569 }
1570
1571 __attribute__ ((weak))
1572 void led_init_ports(void)
1573 {
1574
1575 }
1576
1577 __attribute__ ((weak))
1578 void led_set(uint8_t usb_led)
1579 {
1580
1581   // Example LED Code
1582   //
1583     // // Using PE6 Caps Lock LED
1584     // if (usb_led & (1<<USB_LED_CAPS_LOCK))
1585     // {
1586     //     // Output high.
1587     //     DDRE |= (1<<6);
1588     //     PORTE |= (1<<6);
1589     // }
1590     // else
1591     // {
1592     //     // Output low.
1593     //     DDRE &= ~(1<<6);
1594     //     PORTE &= ~(1<<6);
1595     // }
1596
1597 #if defined(BACKLIGHT_CAPS_LOCK) && defined(BACKLIGHT_ENABLE)
1598   // Use backlight as Caps Lock indicator
1599   uint8_t bl_toggle_lvl = 0;
1600
1601   if (IS_LED_ON(usb_led, USB_LED_CAPS_LOCK) && !backlight_config.enable) {
1602     // Turning Caps Lock ON and backlight is disabled in config
1603     // Toggling backlight to the brightest level
1604     bl_toggle_lvl = BACKLIGHT_LEVELS;
1605   } else if (IS_LED_OFF(usb_led, USB_LED_CAPS_LOCK) && backlight_config.enable) {
1606     // Turning Caps Lock OFF and backlight is enabled in config
1607     // Toggling backlight and restoring config level
1608     bl_toggle_lvl = backlight_config.level;
1609   }
1610
1611   // Set level without modify backlight_config to keep ability to restore state
1612   backlight_set(bl_toggle_lvl);
1613 #endif
1614
1615   led_set_kb(usb_led);
1616 }
1617
1618
1619 //------------------------------------------------------------------------------
1620 // Override these functions in your keymap file to play different tunes on
1621 // different events such as startup and bootloader jump
1622
1623 __attribute__ ((weak))
1624 void startup_user() {}
1625
1626 __attribute__ ((weak))
1627 void shutdown_user() {}
1628
1629 //------------------------------------------------------------------------------