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