diff --git a/examples/AppSwitcher/AppSwitcher.ino b/examples/AppSwitcher/AppSwitcher.ino index e8b231d5..7303cc33 100644 --- a/examples/AppSwitcher/AppSwitcher.ino +++ b/examples/AppSwitcher/AppSwitcher.ino @@ -24,7 +24,7 @@ #include "Macros.h" /* *INDENT-OFF* */ -const Key keymaps[][ROWS][COLS] PROGMEM = { +KEYMAPS( [0] = KEYMAP_STACKED ( Key_NoKey, Key_1, Key_2, Key_3, Key_4, Key_5, Key_NoKey, @@ -43,7 +43,7 @@ const Key keymaps[][ROWS][COLS] PROGMEM = { Key_RightShift, Key_RightAlt, Key_Spacebar, Key_RightControl, M(M_APPCANCEL) ), -}; +) /* *INDENT-ON* */ diff --git a/examples/Kaleidoscope/Kaleidoscope.ino b/examples/Kaleidoscope/Kaleidoscope.ino index 64c42bb7..e3a90086 100644 --- a/examples/Kaleidoscope/Kaleidoscope.ino +++ b/examples/Kaleidoscope/Kaleidoscope.ino @@ -57,14 +57,13 @@ Key_KeymapNext_Momentary, Key_KeymapNext_Momentary \ ) -const Key keymaps[][ROWS][COLS] PROGMEM = { +KEYMAPS( QWERTY, GENERIC_FN2, NUMPAD +) -}; - static kaleidoscope::LEDSolidColor solidRed(60, 0, 0); static kaleidoscope::LEDSolidColor solidOrange(60, 20, 0); static kaleidoscope::LEDSolidColor solidYellow(40, 35, 0); diff --git a/src/layers.cpp b/src/layers.cpp index 702672a8..b647510a 100644 --- a/src/layers.cpp +++ b/src/layers.cpp @@ -8,6 +8,11 @@ Key Layer_::liveCompositeKeymap[ROWS][COLS]; uint8_t Layer_::activeLayers[ROWS][COLS]; Key(*Layer_::getKey)(uint8_t layer, byte row, byte col) = Layer.getKeyFromPROGMEM; +// The total number of defined layers in the firmware sketch keymaps[] +// array. If the keymap wasn't defined using CREATE_KEYMAP() in the +// sketch file, layer_count gets the default value of zero. +uint8_t layer_count __attribute__((weak)) = 0; + static void handleKeymapKeyswitchEvent(Key keymapEntry, uint8_t keyState) { if (keymapEntry.keyCode >= LAYER_SHIFT_OFFSET) { uint8_t target = keymapEntry.keyCode - LAYER_SHIFT_OFFSET; @@ -125,6 +130,11 @@ void Layer_::move(uint8_t layer) { } void Layer_::on(uint8_t layer) { + // If we're trying to turn on a layer that doesn't exist, abort (but + // if the keymap wasn't defined using CREATE_KEYMAP(), proceed anyway + if (layer_count != 0 && layer >= layer_count) + return; + bool wasOn = isOn(layer); bitSet(LayerState, layer); diff --git a/src/layers.h b/src/layers.h index c9b2cd8b..3d4ae465 100644 --- a/src/layers.h +++ b/src/layers.h @@ -4,6 +4,14 @@ #include "key_defs.h" #include KALEIDOSCOPE_HARDWARE_H +// Macro for defining the keymap. This should be used in the sketch +// file (*.ino) to define the keymap[] array that holds the user's +// layers. It also computes the number of layers in that keymap. +#define KEYMAPS(layers...) \ + const Key keymaps[][ROWS][COLS] PROGMEM = { layers }; \ + uint8_t layer_count = sizeof(keymaps) / sizeof(*keymaps); + + class Layer_ { public: Layer_(void);