qmk

QMK Firmware
git clone git://git.z3bra.org/qmk.git
Log | Files | Refs | Submodules | LICENSE

quantum.c (56413B)


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