]> git.donarmstrong.com Git - qmk_firmware.git/blob - quantum/quantum.c
Merge pull request #1571 from BalzGuenat/grave-esc-fix
[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 #ifdef PROTOCOL_LUFA
19 #include "outputselect.h"
20 #endif
21
22 #ifndef TAPPING_TERM
23 #define TAPPING_TERM 200
24 #endif
25
26 #include "backlight.h"
27 extern backlight_config_t backlight_config;
28
29 #ifdef FAUXCLICKY_ENABLE
30 #include "fauxclicky.h"
31 #endif
32
33 #ifdef AUDIO_ENABLE
34   #ifndef GOODBYE_SONG
35     #define GOODBYE_SONG SONG(GOODBYE_SOUND)
36   #endif
37   #ifndef AG_NORM_SONG
38     #define AG_NORM_SONG SONG(AG_NORM_SOUND)
39   #endif
40   #ifndef AG_SWAP_SONG
41     #define AG_SWAP_SONG SONG(AG_SWAP_SOUND)
42   #endif
43   float goodbye_song[][2] = GOODBYE_SONG;
44   float ag_norm_song[][2] = AG_NORM_SONG;
45   float ag_swap_song[][2] = AG_SWAP_SONG;
46   #ifdef DEFAULT_LAYER_SONGS
47     float default_layer_songs[][16][2] = DEFAULT_LAYER_SONGS;
48   #endif
49 #endif
50
51 static void do_code16 (uint16_t code, void (*f) (uint8_t)) {
52   switch (code) {
53   case QK_MODS ... QK_MODS_MAX:
54     break;
55   default:
56     return;
57   }
58
59   if (code & QK_LCTL)
60     f(KC_LCTL);
61   if (code & QK_LSFT)
62     f(KC_LSFT);
63   if (code & QK_LALT)
64     f(KC_LALT);
65   if (code & QK_LGUI)
66     f(KC_LGUI);
67
68   if (code < QK_RMODS_MIN) return;
69
70   if (code & QK_RCTL)
71     f(KC_RCTL);
72   if (code & QK_RSFT)
73     f(KC_RSFT);
74   if (code & QK_RALT)
75     f(KC_RALT);
76   if (code & QK_RGUI)
77     f(KC_RGUI);
78 }
79
80 static inline void qk_register_weak_mods(uint8_t kc) {
81     add_weak_mods(MOD_BIT(kc));
82     send_keyboard_report();
83 }
84
85 static inline void qk_unregister_weak_mods(uint8_t kc) {
86     del_weak_mods(MOD_BIT(kc));
87     send_keyboard_report();
88 }
89
90 static inline void qk_register_mods(uint8_t kc) {
91     add_weak_mods(MOD_BIT(kc));
92     send_keyboard_report();
93 }
94
95 static inline void qk_unregister_mods(uint8_t kc) {
96     del_weak_mods(MOD_BIT(kc));
97     send_keyboard_report();
98 }
99
100 void register_code16 (uint16_t code) {
101   if (IS_MOD(code) || code == KC_NO) {
102       do_code16 (code, qk_register_mods);
103   } else {
104       do_code16 (code, qk_register_weak_mods);
105   }
106   register_code (code);
107 }
108
109 void unregister_code16 (uint16_t code) {
110   unregister_code (code);
111   if (IS_MOD(code) || code == KC_NO) {
112       do_code16 (code, qk_unregister_mods);
113   } else {
114       do_code16 (code, qk_unregister_weak_mods);
115   }
116 }
117
118 __attribute__ ((weak))
119 bool process_action_kb(keyrecord_t *record) {
120   return true;
121 }
122
123 __attribute__ ((weak))
124 bool process_record_kb(uint16_t keycode, keyrecord_t *record) {
125   return process_record_user(keycode, record);
126 }
127
128 __attribute__ ((weak))
129 bool process_record_user(uint16_t keycode, keyrecord_t *record) {
130   return true;
131 }
132
133 void reset_keyboard(void) {
134   clear_keyboard();
135 #if defined(AUDIO_ENABLE) || (defined(MIDI_ENABLE) && defined(MIDI_ENABLE_BASIC))
136   music_all_notes_off();
137   uint16_t timer_start = timer_read();
138   PLAY_SONG(goodbye_song);
139   shutdown_user();
140   while(timer_elapsed(timer_start) < 250) 
141     wait_ms(1);
142   stop_all_notes();
143 #else
144   wait_ms(250);
145 #endif
146 #ifdef CATERINA_BOOTLOADER
147   *(uint16_t *)0x0800 = 0x7777; // these two are a-star-specific
148 #endif
149   bootloader_jump();
150 }
151
152 // Shift / paren setup
153
154 #ifndef LSPO_KEY
155   #define LSPO_KEY KC_9
156 #endif
157 #ifndef RSPC_KEY
158   #define RSPC_KEY KC_0
159 #endif
160
161 static bool shift_interrupted[2] = {0, 0};
162 static uint16_t scs_timer[2] = {0, 0};
163
164 /* true if the last press of GRAVE_ESC was shifted (i.e. GUI or SHIFT were pressed), false otherwise.
165  * Used to ensure that the correct keycode is released if the key is released.
166  */
167 static bool grave_esc_was_shifted = false;
168
169 bool process_record_quantum(keyrecord_t *record) {
170
171   /* This gets the keycode from the key pressed */
172   keypos_t key = record->event.key;
173   uint16_t keycode;
174
175   #if !defined(NO_ACTION_LAYER) && defined(PREVENT_STUCK_MODIFIERS)
176     /* TODO: Use store_or_get_action() or a similar function. */
177     if (!disable_action_cache) {
178       uint8_t layer;
179
180       if (record->event.pressed) {
181         layer = layer_switch_get_layer(key);
182         update_source_layers_cache(key, layer);
183       } else {
184         layer = read_source_layers_cache(key);
185       }
186       keycode = keymap_key_to_keycode(layer, key);
187     } else
188   #endif
189     keycode = keymap_key_to_keycode(layer_switch_get_layer(key), key);
190
191     // This is how you use actions here
192     // if (keycode == KC_LEAD) {
193     //   action_t action;
194     //   action.code = ACTION_DEFAULT_LAYER_SET(0);
195     //   process_action(record, action);
196     //   return false;
197     // }
198
199   if (!(
200   #if defined(KEY_LOCK_ENABLE)
201     // Must run first to be able to mask key_up events.
202     process_key_lock(&keycode, record) &&
203   #endif
204     process_record_kb(keycode, record) &&
205   #if defined(MIDI_ENABLE) && defined(MIDI_ADVANCED)
206     process_midi(keycode, record) &&
207   #endif
208   #ifdef AUDIO_ENABLE
209     process_audio(keycode, record) &&
210   #endif
211   #ifdef STENO_ENABLE
212     process_steno(keycode, record) &&
213   #endif
214   #if defined(AUDIO_ENABLE) || (defined(MIDI_ENABLE) && defined(MIDI_BASIC))
215     process_music(keycode, record) &&
216   #endif
217   #ifdef TAP_DANCE_ENABLE
218     process_tap_dance(keycode, record) &&
219   #endif
220   #ifndef DISABLE_LEADER
221     process_leader(keycode, record) &&
222   #endif
223   #ifndef DISABLE_CHORDING
224     process_chording(keycode, record) &&
225   #endif
226   #ifdef COMBO_ENABLE
227     process_combo(keycode, record) &&
228   #endif
229   #ifdef UNICODE_ENABLE
230     process_unicode(keycode, record) &&
231   #endif
232   #ifdef UCIS_ENABLE
233     process_ucis(keycode, record) &&
234   #endif
235   #ifdef PRINTING_ENABLE
236     process_printer(keycode, record) &&
237   #endif
238   #ifdef UNICODEMAP_ENABLE
239     process_unicode_map(keycode, record) &&
240   #endif
241       true)) {
242     return false;
243   }
244
245   // Shift / paren setup
246
247   switch(keycode) {
248     case RESET:
249       if (record->event.pressed) {
250         reset_keyboard();
251       }
252           return false;
253       break;
254     case DEBUG:
255       if (record->event.pressed) {
256           print("\nDEBUG: enabled.\n");
257           debug_enable = true;
258       }
259           return false;
260       break;
261   #ifdef FAUXCLICKY_ENABLE
262   case FC_TOG:
263     if (record->event.pressed) {
264       FAUXCLICKY_TOGGLE;
265     }
266     return false;
267     break;
268   case FC_ON:
269     if (record->event.pressed) {
270       FAUXCLICKY_ON;
271     }
272     return false;
273     break;
274   case FC_OFF:
275     if (record->event.pressed) {
276       FAUXCLICKY_OFF;
277     }
278     return false;
279     break;
280   #endif
281         #ifdef RGBLIGHT_ENABLE
282         case RGB_TOG:
283                 if (record->event.pressed) {
284                         rgblight_toggle();
285       }
286           return false;
287       break;
288         case RGB_MOD:
289                 if (record->event.pressed) {
290                         rgblight_step();
291       }
292           return false;
293       break;
294         case RGB_HUI:
295                 if (record->event.pressed) {
296                         rgblight_increase_hue();
297       }
298           return false;
299       break;
300         case RGB_HUD:
301                 if (record->event.pressed) {
302                         rgblight_decrease_hue();
303       }
304           return false;
305       break;
306         case RGB_SAI:
307                 if (record->event.pressed) {
308                         rgblight_increase_sat();
309       }
310           return false;
311       break;
312         case RGB_SAD:
313                 if (record->event.pressed) {
314                         rgblight_decrease_sat();
315       }
316           return false;
317       break;
318         case RGB_VAI:
319                 if (record->event.pressed) {
320                         rgblight_increase_val();
321       }
322           return false;
323       break;
324         case RGB_VAD:
325                 if (record->event.pressed) {
326                         rgblight_decrease_val();
327       }
328           return false;
329       break;
330         #endif
331     #ifdef PROTOCOL_LUFA
332     case OUT_AUTO:
333       if (record->event.pressed) {
334         set_output(OUTPUT_AUTO);
335       }
336       return false;
337       break;
338     case OUT_USB:
339       if (record->event.pressed) {
340         set_output(OUTPUT_USB);
341       }
342       return false;
343       break;
344     #ifdef BLUETOOTH_ENABLE
345     case OUT_BT:
346       if (record->event.pressed) {
347         set_output(OUTPUT_BLUETOOTH);
348       }
349       return false;
350       break;
351     #endif
352     #endif
353     case MAGIC_SWAP_CONTROL_CAPSLOCK ... MAGIC_TOGGLE_NKRO:
354       if (record->event.pressed) {
355         // MAGIC actions (BOOTMAGIC without the boot)
356         if (!eeconfig_is_enabled()) {
357             eeconfig_init();
358         }
359         /* keymap config */
360         keymap_config.raw = eeconfig_read_keymap();
361         switch (keycode)
362         {
363           case MAGIC_SWAP_CONTROL_CAPSLOCK:
364             keymap_config.swap_control_capslock = true;
365             break;
366           case MAGIC_CAPSLOCK_TO_CONTROL:
367             keymap_config.capslock_to_control = true;
368             break;
369           case MAGIC_SWAP_LALT_LGUI:
370             keymap_config.swap_lalt_lgui = true;
371             break;
372           case MAGIC_SWAP_RALT_RGUI:
373             keymap_config.swap_ralt_rgui = true;
374             break;
375           case MAGIC_NO_GUI:
376             keymap_config.no_gui = true;
377             break;
378           case MAGIC_SWAP_GRAVE_ESC:
379             keymap_config.swap_grave_esc = true;
380             break;
381           case MAGIC_SWAP_BACKSLASH_BACKSPACE:
382             keymap_config.swap_backslash_backspace = true;
383             break;
384           case MAGIC_HOST_NKRO:
385             keymap_config.nkro = true;
386             break;
387           case MAGIC_SWAP_ALT_GUI:
388             keymap_config.swap_lalt_lgui = true;
389             keymap_config.swap_ralt_rgui = true;
390             #ifdef AUDIO_ENABLE
391               PLAY_SONG(ag_swap_song);
392             #endif
393             break;
394           case MAGIC_UNSWAP_CONTROL_CAPSLOCK:
395             keymap_config.swap_control_capslock = false;
396             break;
397           case MAGIC_UNCAPSLOCK_TO_CONTROL:
398             keymap_config.capslock_to_control = false;
399             break;
400           case MAGIC_UNSWAP_LALT_LGUI:
401             keymap_config.swap_lalt_lgui = false;
402             break;
403           case MAGIC_UNSWAP_RALT_RGUI:
404             keymap_config.swap_ralt_rgui = false;
405             break;
406           case MAGIC_UNNO_GUI:
407             keymap_config.no_gui = false;
408             break;
409           case MAGIC_UNSWAP_GRAVE_ESC:
410             keymap_config.swap_grave_esc = false;
411             break;
412           case MAGIC_UNSWAP_BACKSLASH_BACKSPACE:
413             keymap_config.swap_backslash_backspace = false;
414             break;
415           case MAGIC_UNHOST_NKRO:
416             keymap_config.nkro = false;
417             break;
418           case MAGIC_UNSWAP_ALT_GUI:
419             keymap_config.swap_lalt_lgui = false;
420             keymap_config.swap_ralt_rgui = false;
421             #ifdef AUDIO_ENABLE
422               PLAY_SONG(ag_norm_song);
423             #endif
424             break;
425           case MAGIC_TOGGLE_NKRO:
426             keymap_config.nkro = !keymap_config.nkro;
427             break;
428           default:
429             break;
430         }
431         eeconfig_update_keymap(keymap_config.raw);
432         clear_keyboard(); // clear to prevent stuck keys
433
434         return false;
435       }
436       break;
437     case KC_LSPO: {
438       if (record->event.pressed) {
439         shift_interrupted[0] = false;
440         scs_timer[0] = timer_read ();
441         register_mods(MOD_BIT(KC_LSFT));
442       }
443       else {
444         #ifdef DISABLE_SPACE_CADET_ROLLOVER
445           if (get_mods() & MOD_BIT(KC_RSFT)) {
446             shift_interrupted[0] = true;
447             shift_interrupted[1] = true;
448           }
449         #endif
450         if (!shift_interrupted[0] && timer_elapsed(scs_timer[0]) < TAPPING_TERM) {
451           register_code(LSPO_KEY);
452           unregister_code(LSPO_KEY);
453         }
454         unregister_mods(MOD_BIT(KC_LSFT));
455       }
456       return false;
457       // break;
458     }
459
460     case KC_RSPC: {
461       if (record->event.pressed) {
462         shift_interrupted[1] = false;
463         scs_timer[1] = timer_read ();
464         register_mods(MOD_BIT(KC_RSFT));
465       }
466       else {
467         #ifdef DISABLE_SPACE_CADET_ROLLOVER
468           if (get_mods() & MOD_BIT(KC_LSFT)) {
469             shift_interrupted[0] = true;
470             shift_interrupted[1] = true;
471           }
472         #endif
473         if (!shift_interrupted[1] && timer_elapsed(scs_timer[1]) < TAPPING_TERM) {
474           register_code(RSPC_KEY);
475           unregister_code(RSPC_KEY);
476         }
477         unregister_mods(MOD_BIT(KC_RSFT));
478       }
479       return false;
480       // break;
481     }
482     case GRAVE_ESC: {
483       uint8_t shifted = get_mods() & ((MOD_BIT(KC_LSHIFT)|MOD_BIT(KC_RSHIFT)
484                                       |MOD_BIT(KC_LGUI)|MOD_BIT(KC_RGUI)));
485
486 #ifdef GRAVE_ESC_CTRL_OVERRIDE
487       // if CTRL is pressed, ESC is always read as ESC, even if SHIFT or GUI is pressed.
488       // this is handy for the ctrl+shift+esc shortcut on windows, among other things.
489       if (get_mods() & (MOD_BIT(KC_LCTL) | MOD_BIT(KC_RCTL)))
490         shifted = 0;
491 #endif
492
493       if (record->event.pressed) {
494         grave_esc_was_shifted = shifted;
495         add_key(shifted ? KC_GRAVE : KC_ESCAPE);
496       }
497       else {
498         del_key(grave_esc_was_shifted ? KC_GRAVE : KC_ESCAPE);
499       }
500
501       send_keyboard_report();
502     }
503     default: {
504       shift_interrupted[0] = true;
505       shift_interrupted[1] = true;
506       break;
507     }
508   }
509
510   return process_action_kb(record);
511 }
512
513 __attribute__ ((weak))
514 const bool ascii_to_shift_lut[0x80] PROGMEM = {
515     0, 0, 0, 0, 0, 0, 0, 0,
516     0, 0, 0, 0, 0, 0, 0, 0,
517     0, 0, 0, 0, 0, 0, 0, 0,
518     0, 0, 0, 0, 0, 0, 0, 0,
519     0, 1, 1, 1, 1, 1, 1, 0,
520     1, 1, 1, 1, 0, 0, 0, 0,
521     0, 0, 0, 0, 0, 0, 0, 0,
522     0, 0, 1, 0, 1, 0, 1, 1,
523     1, 1, 1, 1, 1, 1, 1, 1,
524     1, 1, 1, 1, 1, 1, 1, 1,
525     1, 1, 1, 1, 1, 1, 1, 1,
526     1, 1, 1, 0, 0, 0, 1, 1,
527     0, 0, 0, 0, 0, 0, 0, 0,
528     0, 0, 0, 0, 0, 0, 0, 0,
529     0, 0, 0, 0, 0, 0, 0, 0,
530     0, 0, 0, 1, 1, 1, 1, 0
531 };
532
533 __attribute__ ((weak))
534 const uint8_t ascii_to_keycode_lut[0x80] PROGMEM = {
535     0, 0, 0, 0, 0, 0, 0, 0,
536     KC_BSPC, KC_TAB, KC_ENT, 0, 0, 0, 0, 0,
537     0, 0, 0, 0, 0, 0, 0, 0,
538     0, 0, 0, KC_ESC, 0, 0, 0, 0,
539     KC_SPC, KC_1, KC_QUOT, KC_3, KC_4, KC_5, KC_7, KC_QUOT,
540     KC_9, KC_0, KC_8, KC_EQL, KC_COMM, KC_MINS, KC_DOT, KC_SLSH,
541     KC_0, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7,
542     KC_8, KC_9, KC_SCLN, KC_SCLN, KC_COMM, KC_EQL, KC_DOT, KC_SLSH,
543     KC_2, KC_A, KC_B, KC_C, KC_D, KC_E, KC_F, KC_G,
544     KC_H, KC_I, KC_J, KC_K, KC_L, KC_M, KC_N, KC_O,
545     KC_P, KC_Q, KC_R, KC_S, KC_T, KC_U, KC_V, KC_W,
546     KC_X, KC_Y, KC_Z, KC_LBRC, KC_BSLS, KC_RBRC, KC_6, KC_MINS,
547     KC_GRV, KC_A, KC_B, KC_C, KC_D, KC_E, KC_F, KC_G,
548     KC_H, KC_I, KC_J, KC_K, KC_L, KC_M, KC_N, KC_O,
549     KC_P, KC_Q, KC_R, KC_S, KC_T, KC_U, KC_V, KC_W,
550     KC_X, KC_Y, KC_Z, KC_LBRC, KC_BSLS, KC_RBRC, KC_GRV, KC_DEL
551 };
552
553 void send_string(const char *str) {
554   send_string_with_delay(str, 0);
555 }
556
557 void send_string_with_delay(const char *str, uint8_t interval) {
558     while (1) {
559         uint8_t keycode;
560         uint8_t ascii_code = pgm_read_byte(str);
561         if (!ascii_code) break;
562         keycode = pgm_read_byte(&ascii_to_keycode_lut[ascii_code]);
563         if (pgm_read_byte(&ascii_to_shift_lut[ascii_code])) {
564             register_code(KC_LSFT);
565             register_code(keycode);
566             unregister_code(keycode);
567             unregister_code(KC_LSFT);
568         }
569         else {
570             register_code(keycode);
571             unregister_code(keycode);
572         }
573         ++str;
574         // interval
575         { uint8_t ms = interval; while (ms--) wait_ms(1); }
576     }
577 }
578
579 void set_single_persistent_default_layer(uint8_t default_layer) {
580   #if defined(AUDIO_ENABLE) && defined(DEFAULT_LAYER_SONGS)
581     PLAY_SONG(default_layer_songs[default_layer]);
582   #endif
583   eeconfig_update_default_layer(1U<<default_layer);
584   default_layer_set(1U<<default_layer);
585 }
586
587 void update_tri_layer(uint8_t layer1, uint8_t layer2, uint8_t layer3) {
588   if (IS_LAYER_ON(layer1) && IS_LAYER_ON(layer2)) {
589     layer_on(layer3);
590   } else {
591     layer_off(layer3);
592   }
593 }
594
595 void tap_random_base64(void) {
596   #if defined(__AVR_ATmega32U4__)
597     uint8_t key = (TCNT0 + TCNT1 + TCNT3 + TCNT4) % 64;
598   #else
599     uint8_t key = rand() % 64;
600   #endif
601   switch (key) {
602     case 0 ... 25:
603       register_code(KC_LSFT);
604       register_code(key + KC_A);
605       unregister_code(key + KC_A);
606       unregister_code(KC_LSFT);
607       break;
608     case 26 ... 51:
609       register_code(key - 26 + KC_A);
610       unregister_code(key - 26 + KC_A);
611       break;
612     case 52:
613       register_code(KC_0);
614       unregister_code(KC_0);
615       break;
616     case 53 ... 61:
617       register_code(key - 53 + KC_1);
618       unregister_code(key - 53 + KC_1);
619       break;
620     case 62:
621       register_code(KC_LSFT);
622       register_code(KC_EQL);
623       unregister_code(KC_EQL);
624       unregister_code(KC_LSFT);
625       break;
626     case 63:
627       register_code(KC_SLSH);
628       unregister_code(KC_SLSH);
629       break;
630   }
631 }
632
633 void matrix_init_quantum() {
634   #ifdef BACKLIGHT_ENABLE
635     backlight_init_ports();
636   #endif
637   #ifdef AUDIO_ENABLE
638     audio_init();
639   #endif
640   matrix_init_kb();
641 }
642
643 void matrix_scan_quantum() {
644   #ifdef AUDIO_ENABLE
645     matrix_scan_music();
646   #endif
647
648   #ifdef TAP_DANCE_ENABLE
649     matrix_scan_tap_dance();
650   #endif
651
652   #ifdef COMBO_ENABLE
653     matrix_scan_combo();
654   #endif
655
656   #if defined(BACKLIGHT_ENABLE) && defined(BACKLIGHT_PIN)
657     backlight_task();
658   #endif
659
660   matrix_scan_kb();
661 }
662
663 #if defined(BACKLIGHT_ENABLE) && defined(BACKLIGHT_PIN)
664
665 static const uint8_t backlight_pin = BACKLIGHT_PIN;
666
667 #if BACKLIGHT_PIN == B7
668 #  define COM1x1 COM1C1
669 #  define OCR1x  OCR1C
670 #elif BACKLIGHT_PIN == B6
671 #  define COM1x1 COM1B1
672 #  define OCR1x  OCR1B
673 #elif BACKLIGHT_PIN == B5
674 #  define COM1x1 COM1A1
675 #  define OCR1x  OCR1A
676 #else
677 #  define NO_BACKLIGHT_CLOCK
678 #endif
679
680 #ifndef BACKLIGHT_ON_STATE
681 #define BACKLIGHT_ON_STATE 0
682 #endif
683
684 __attribute__ ((weak))
685 void backlight_init_ports(void)
686 {
687
688   // Setup backlight pin as output and output to on state.
689   // DDRx |= n
690   _SFR_IO8((backlight_pin >> 4) + 1) |= _BV(backlight_pin & 0xF);
691   #if BACKLIGHT_ON_STATE == 0
692     // PORTx &= ~n
693     _SFR_IO8((backlight_pin >> 4) + 2) &= ~_BV(backlight_pin & 0xF);
694   #else
695     // PORTx |= n
696     _SFR_IO8((backlight_pin >> 4) + 2) |= _BV(backlight_pin & 0xF);
697   #endif
698
699   #ifndef NO_BACKLIGHT_CLOCK
700     // Use full 16-bit resolution.
701     ICR1 = 0xFFFF;
702
703     // I could write a wall of text here to explain... but TL;DW
704     // Go read the ATmega32u4 datasheet.
705     // And this: http://blog.saikoled.com/post/43165849837/secret-konami-cheat-code-to-high-resolution-pwm-on
706
707     // Pin PB7 = OCR1C (Timer 1, Channel C)
708     // Compare Output Mode = Clear on compare match, Channel C = COM1C1=1 COM1C0=0
709     // (i.e. start high, go low when counter matches.)
710     // WGM Mode 14 (Fast PWM) = WGM13=1 WGM12=1 WGM11=1 WGM10=0
711     // Clock Select = clk/1 (no prescaling) = CS12=0 CS11=0 CS10=1
712
713     TCCR1A = _BV(COM1x1) | _BV(WGM11); // = 0b00001010;
714     TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10); // = 0b00011001;
715   #endif
716
717   backlight_init();
718   #ifdef BACKLIGHT_BREATHING
719     breathing_defaults();
720   #endif
721 }
722
723 __attribute__ ((weak))
724 void backlight_set(uint8_t level)
725 {
726   // Prevent backlight blink on lowest level
727   // #if BACKLIGHT_ON_STATE == 0
728   //   // PORTx &= ~n
729   //   _SFR_IO8((backlight_pin >> 4) + 2) &= ~_BV(backlight_pin & 0xF);
730   // #else
731   //   // PORTx |= n
732   //   _SFR_IO8((backlight_pin >> 4) + 2) |= _BV(backlight_pin & 0xF);
733   // #endif
734
735   if ( level == 0 ) {
736     #ifndef NO_BACKLIGHT_CLOCK
737       // Turn off PWM control on backlight pin, revert to output low.
738       TCCR1A &= ~(_BV(COM1x1));
739       OCR1x = 0x0;
740     #else
741       // #if BACKLIGHT_ON_STATE == 0
742       //   // PORTx |= n
743       //   _SFR_IO8((backlight_pin >> 4) + 2) |= _BV(backlight_pin & 0xF);
744       // #else
745       //   // PORTx &= ~n
746       //   _SFR_IO8((backlight_pin >> 4) + 2) &= ~_BV(backlight_pin & 0xF);
747       // #endif
748     #endif
749   }
750   #ifndef NO_BACKLIGHT_CLOCK
751     else if ( level == BACKLIGHT_LEVELS ) {
752       // Turn on PWM control of backlight pin
753       TCCR1A |= _BV(COM1x1);
754       // Set the brightness
755       OCR1x = 0xFFFF;
756     }
757     else {
758       // Turn on PWM control of backlight pin
759       TCCR1A |= _BV(COM1x1);
760       // Set the brightness
761       OCR1x = 0xFFFF >> ((BACKLIGHT_LEVELS - level) * ((BACKLIGHT_LEVELS + 1) / 2));
762     }
763   #endif
764
765   #ifdef BACKLIGHT_BREATHING
766     breathing_intensity_default();
767   #endif
768 }
769
770 uint8_t backlight_tick = 0;
771
772 void backlight_task(void) {
773   #ifdef NO_BACKLIGHT_CLOCK
774   if ((0xFFFF >> ((BACKLIGHT_LEVELS - backlight_config.level) * ((BACKLIGHT_LEVELS + 1) / 2))) & (1 << backlight_tick)) {
775     #if BACKLIGHT_ON_STATE == 0
776       // PORTx &= ~n
777       _SFR_IO8((backlight_pin >> 4) + 2) &= ~_BV(backlight_pin & 0xF);
778     #else
779       // PORTx |= n
780       _SFR_IO8((backlight_pin >> 4) + 2) |= _BV(backlight_pin & 0xF);
781     #endif
782   } else {
783     #if BACKLIGHT_ON_STATE == 0
784       // PORTx |= n
785       _SFR_IO8((backlight_pin >> 4) + 2) |= _BV(backlight_pin & 0xF);
786     #else
787       // PORTx &= ~n
788       _SFR_IO8((backlight_pin >> 4) + 2) &= ~_BV(backlight_pin & 0xF);
789     #endif
790   }
791   backlight_tick = (backlight_tick + 1) % 16;
792   #endif
793 }
794
795 #ifdef BACKLIGHT_BREATHING
796
797 #define BREATHING_NO_HALT  0
798 #define BREATHING_HALT_OFF 1
799 #define BREATHING_HALT_ON  2
800
801 static uint8_t breath_intensity;
802 static uint8_t breath_speed;
803 static uint16_t breathing_index;
804 static uint8_t breathing_halt;
805
806 void breathing_enable(void)
807 {
808     if (get_backlight_level() == 0)
809     {
810         breathing_index = 0;
811     }
812     else
813     {
814         // Set breathing_index to be at the midpoint (brightest point)
815         breathing_index = 0x20 << breath_speed;
816     }
817
818     breathing_halt = BREATHING_NO_HALT;
819
820     // Enable breathing interrupt
821     TIMSK1 |= _BV(OCIE1A);
822 }
823
824 void breathing_pulse(void)
825 {
826     if (get_backlight_level() == 0)
827     {
828         breathing_index = 0;
829     }
830     else
831     {
832         // Set breathing_index to be at the midpoint + 1 (brightest point)
833         breathing_index = 0x21 << breath_speed;
834     }
835
836     breathing_halt = BREATHING_HALT_ON;
837
838     // Enable breathing interrupt
839     TIMSK1 |= _BV(OCIE1A);
840 }
841
842 void breathing_disable(void)
843 {
844     // Disable breathing interrupt
845     TIMSK1 &= ~_BV(OCIE1A);
846     backlight_set(get_backlight_level());
847 }
848
849 void breathing_self_disable(void)
850 {
851     if (get_backlight_level() == 0)
852     {
853         breathing_halt = BREATHING_HALT_OFF;
854     }
855     else
856     {
857         breathing_halt = BREATHING_HALT_ON;
858     }
859
860     //backlight_set(get_backlight_level());
861 }
862
863 void breathing_toggle(void)
864 {
865     if (!is_breathing())
866     {
867         if (get_backlight_level() == 0)
868         {
869             breathing_index = 0;
870         }
871         else
872         {
873             // Set breathing_index to be at the midpoint + 1 (brightest point)
874             breathing_index = 0x21 << breath_speed;
875         }
876
877         breathing_halt = BREATHING_NO_HALT;
878     }
879
880     // Toggle breathing interrupt
881     TIMSK1 ^= _BV(OCIE1A);
882
883     // Restore backlight level
884     if (!is_breathing())
885     {
886         backlight_set(get_backlight_level());
887     }
888 }
889
890 bool is_breathing(void)
891 {
892     return (TIMSK1 && _BV(OCIE1A));
893 }
894
895 void breathing_intensity_default(void)
896 {
897     //breath_intensity = (uint8_t)((uint16_t)100 * (uint16_t)get_backlight_level() / (uint16_t)BACKLIGHT_LEVELS);
898     breath_intensity = ((BACKLIGHT_LEVELS - get_backlight_level()) * ((BACKLIGHT_LEVELS + 1) / 2));
899 }
900
901 void breathing_intensity_set(uint8_t value)
902 {
903     breath_intensity = value;
904 }
905
906 void breathing_speed_default(void)
907 {
908     breath_speed = 4;
909 }
910
911 void breathing_speed_set(uint8_t value)
912 {
913     bool is_breathing_now = is_breathing();
914     uint8_t old_breath_speed = breath_speed;
915
916     if (is_breathing_now)
917     {
918         // Disable breathing interrupt
919         TIMSK1 &= ~_BV(OCIE1A);
920     }
921
922     breath_speed = value;
923
924     if (is_breathing_now)
925     {
926         // Adjust index to account for new speed
927         breathing_index = (( (uint8_t)( (breathing_index) >> old_breath_speed ) ) & 0x3F) << breath_speed;
928
929         // Enable breathing interrupt
930         TIMSK1 |= _BV(OCIE1A);
931     }
932
933 }
934
935 void breathing_speed_inc(uint8_t value)
936 {
937     if ((uint16_t)(breath_speed - value) > 10 )
938     {
939         breathing_speed_set(0);
940     }
941     else
942     {
943         breathing_speed_set(breath_speed - value);
944     }
945 }
946
947 void breathing_speed_dec(uint8_t value)
948 {
949     if ((uint16_t)(breath_speed + value) > 10 )
950     {
951         breathing_speed_set(10);
952     }
953     else
954     {
955         breathing_speed_set(breath_speed + value);
956     }
957 }
958
959 void breathing_defaults(void)
960 {
961     breathing_intensity_default();
962     breathing_speed_default();
963     breathing_halt = BREATHING_NO_HALT;
964 }
965
966 /* Breathing Sleep LED brighness(PWM On period) table
967  * (64[steps] * 4[duration]) / 64[PWM periods/s] = 4 second breath cycle
968  *
969  * http://www.wolframalpha.com/input/?i=%28sin%28+x%2F64*pi%29**8+*+255%2C+x%3D0+to+63
970  * (0..63).each {|x| p ((sin(x/64.0*PI)**8)*255).to_i }
971  */
972 static const uint8_t breathing_table[64] PROGMEM = {
973   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   2,   4,   6,  10,
974  15,  23,  32,  44,  58,  74,  93, 113, 135, 157, 179, 199, 218, 233, 245, 252,
975 255, 252, 245, 233, 218, 199, 179, 157, 135, 113,  93,  74,  58,  44,  32,  23,
976  15,  10,   6,   4,   2,   1,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
977 };
978
979 ISR(TIMER1_COMPA_vect)
980 {
981     // OCR1x = (pgm_read_byte(&breathing_table[ ( (uint8_t)( (breathing_index++) >> breath_speed ) ) & 0x3F ] )) * breath_intensity;
982
983
984     uint8_t local_index = ( (uint8_t)( (breathing_index++) >> breath_speed ) ) & 0x3F;
985
986     if (((breathing_halt == BREATHING_HALT_ON) && (local_index == 0x20)) || ((breathing_halt == BREATHING_HALT_OFF) && (local_index == 0x3F)))
987     {
988         // Disable breathing interrupt
989         TIMSK1 &= ~_BV(OCIE1A);
990     }
991
992     OCR1x = (uint16_t)(((uint16_t)pgm_read_byte(&breathing_table[local_index]) * 257)) >> breath_intensity;
993
994 }
995
996
997
998 #endif // breathing
999
1000 #else // backlight
1001
1002 __attribute__ ((weak))
1003 void backlight_init_ports(void)
1004 {
1005
1006 }
1007
1008 __attribute__ ((weak))
1009 void backlight_set(uint8_t level)
1010 {
1011
1012 }
1013
1014 #endif // backlight
1015
1016
1017 // Functions for spitting out values
1018 //
1019
1020 void send_dword(uint32_t number) { // this might not actually work
1021     uint16_t word = (number >> 16);
1022     send_word(word);
1023     send_word(number & 0xFFFFUL);
1024 }
1025
1026 void send_word(uint16_t number) {
1027     uint8_t byte = number >> 8;
1028     send_byte(byte);
1029     send_byte(number & 0xFF);
1030 }
1031
1032 void send_byte(uint8_t number) {
1033     uint8_t nibble = number >> 4;
1034     send_nibble(nibble);
1035     send_nibble(number & 0xF);
1036 }
1037
1038 void send_nibble(uint8_t number) {
1039     switch (number) {
1040         case 0:
1041             register_code(KC_0);
1042             unregister_code(KC_0);
1043             break;
1044         case 1 ... 9:
1045             register_code(KC_1 + (number - 1));
1046             unregister_code(KC_1 + (number - 1));
1047             break;
1048         case 0xA ... 0xF:
1049             register_code(KC_A + (number - 0xA));
1050             unregister_code(KC_A + (number - 0xA));
1051             break;
1052     }
1053 }
1054
1055
1056 __attribute__((weak))
1057 uint16_t hex_to_keycode(uint8_t hex)
1058 {
1059   if (hex == 0x0) {
1060     return KC_0;
1061   } else if (hex < 0xA) {
1062     return KC_1 + (hex - 0x1);
1063   } else {
1064     return KC_A + (hex - 0xA);
1065   }
1066 }
1067
1068 void api_send_unicode(uint32_t unicode) {
1069 #ifdef API_ENABLE
1070     uint8_t chunk[4];
1071     dword_to_bytes(unicode, chunk);
1072     MT_SEND_DATA(DT_UNICODE, chunk, 5);
1073 #endif
1074 }
1075
1076 __attribute__ ((weak))
1077 void led_set_user(uint8_t usb_led) {
1078
1079 }
1080
1081 __attribute__ ((weak))
1082 void led_set_kb(uint8_t usb_led) {
1083     led_set_user(usb_led);
1084 }
1085
1086 __attribute__ ((weak))
1087 void led_init_ports(void)
1088 {
1089
1090 }
1091
1092 __attribute__ ((weak))
1093 void led_set(uint8_t usb_led)
1094 {
1095
1096   // Example LED Code
1097   //
1098     // // Using PE6 Caps Lock LED
1099     // if (usb_led & (1<<USB_LED_CAPS_LOCK))
1100     // {
1101     //     // Output high.
1102     //     DDRE |= (1<<6);
1103     //     PORTE |= (1<<6);
1104     // }
1105     // else
1106     // {
1107     //     // Output low.
1108     //     DDRE &= ~(1<<6);
1109     //     PORTE &= ~(1<<6);
1110     // }
1111
1112   led_set_kb(usb_led);
1113 }
1114
1115
1116 //------------------------------------------------------------------------------
1117 // Override these functions in your keymap file to play different tunes on
1118 // different events such as startup and bootloader jump
1119
1120 __attribute__ ((weak))
1121 void startup_user() {}
1122
1123 __attribute__ ((weak))
1124 void shutdown_user() {}
1125
1126 //------------------------------------------------------------------------------