aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorzwnk <david@impstyle.com>2018-08-14 00:23:11 -0300
committerDrashna Jaelre <drashna@live.com>2018-08-13 20:23:11 -0700
commit61b61161478ebe1a65fc4b9a9efc0f887a342767 (patch)
treed1237aa86ac269e76de2becac3776f9093c81ef3
parente12151f15e49191b48d88eb428e010dc020fbc14 (diff)
downloadfirmware-61b61161478ebe1a65fc4b9a9efc0f887a342767.tar.gz
firmware-61b61161478ebe1a65fc4b9a9efc0f887a342767.tar.bz2
firmware-61b61161478ebe1a65fc4b9a9efc0f887a342767.zip
Keyboard: Dactyl manuform 5x6 added and working (#3627)
* mouse layer keys shifted * mouse layer keys shifted * manuform 5x6 added * mouse layer keys shifted * manuform 5x6 added * dactyl_manuform 5x6 keymap added * reorg. dactyl manuform folder * removed LAYOUTS = ortho_4x12 for 4x5 * Rows and Cols in config.h fixed * MASTER_LEFT * 5x6 matrix fixed * keymap updated * removed the i2c, serial, split_util and matrix files and inserted SPLIT_KEYBOARD
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/config.h (renamed from keyboards/handwired/dactyl_manuform/config.h)0
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/dactyl_manuform.c (renamed from keyboards/handwired/dactyl_manuform/dactyl_manuform.c)0
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/dactyl_manuform.h (renamed from keyboards/handwired/dactyl_manuform/dactyl_manuform.h)6
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/keymaps/default/config.h (renamed from keyboards/handwired/dactyl_manuform/keymaps/default/config.h)0
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/keymaps/default/keymap.c (renamed from keyboards/handwired/dactyl_manuform/keymaps/default/keymap.c)0
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/keymaps/default/rules.mk (renamed from keyboards/handwired/dactyl_manuform/keymaps/default/rules.mk)0
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/config.h (renamed from keyboards/handwired/dactyl_manuform/keymaps/dvorak/config.h)0
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/keymap.c (renamed from keyboards/handwired/dactyl_manuform/keymaps/dvorak/keymap.c)0
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/rules.mk (renamed from keyboards/handwired/dactyl_manuform/keymaps/dvorak/rules.mk)0
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/readme.md (renamed from keyboards/handwired/dactyl_manuform/readme.md)10
-rw-r--r--keyboards/handwired/dactyl_manuform/4x5/rules.mk (renamed from keyboards/handwired/dactyl_manuform/rules.mk)9
-rw-r--r--keyboards/handwired/dactyl_manuform/5x6/config.h97
-rw-r--r--keyboards/handwired/dactyl_manuform/5x6/dactyl_manuform.c23
-rw-r--r--keyboards/handwired/dactyl_manuform/5x6/dactyl_manuform.h47
-rw-r--r--keyboards/handwired/dactyl_manuform/5x6/keymaps/impstyle/config.h28
-rw-r--r--keyboards/handwired/dactyl_manuform/5x6/keymaps/impstyle/keymap.c75
-rw-r--r--keyboards/handwired/dactyl_manuform/5x6/readme.md142
-rw-r--r--keyboards/handwired/dactyl_manuform/5x6/rules.mk67
-rw-r--r--keyboards/handwired/dactyl_manuform/eeprom-lefthand.eep2
-rw-r--r--keyboards/handwired/dactyl_manuform/eeprom-righthand.eep2
-rw-r--r--keyboards/handwired/dactyl_manuform/i2c.c162
-rw-r--r--keyboards/handwired/dactyl_manuform/i2c.h49
-rw-r--r--keyboards/handwired/dactyl_manuform/matrix.c465
-rw-r--r--keyboards/handwired/dactyl_manuform/serial.c228
-rw-r--r--keyboards/handwired/dactyl_manuform/serial.h26
-rw-r--r--keyboards/handwired/dactyl_manuform/split_util.c86
-rw-r--r--keyboards/handwired/dactyl_manuform/split_util.h20
-rw-r--r--keyboards/iris/keymaps/impstyle/keymap.c8
28 files changed, 493 insertions, 1059 deletions
diff --git a/keyboards/handwired/dactyl_manuform/config.h b/keyboards/handwired/dactyl_manuform/4x5/config.h
index 8917630e4..8917630e4 100644
--- a/keyboards/handwired/dactyl_manuform/config.h
+++ b/keyboards/handwired/dactyl_manuform/4x5/config.h
diff --git a/keyboards/handwired/dactyl_manuform/dactyl_manuform.c b/keyboards/handwired/dactyl_manuform/4x5/dactyl_manuform.c
index 17caecb4f..17caecb4f 100644
--- a/keyboards/handwired/dactyl_manuform/dactyl_manuform.c
+++ b/keyboards/handwired/dactyl_manuform/4x5/dactyl_manuform.c
diff --git a/keyboards/handwired/dactyl_manuform/dactyl_manuform.h b/keyboards/handwired/dactyl_manuform/4x5/dactyl_manuform.h
index 3dc8405ff..7e126d301 100644
--- a/keyboards/handwired/dactyl_manuform/dactyl_manuform.h
+++ b/keyboards/handwired/dactyl_manuform/4x5/dactyl_manuform.h
@@ -41,6 +41,9 @@
{ KC_NO, R43, R42, R41, R40 } \
}
#else
+
+
+
#define LAYOUT( \
L00, L01, L02, L03, L04, R00, R01, R02, R03, R04, \
L10, L11, L12, L13, L14, R10, R11, R12, R13, R14, \
@@ -61,9 +64,8 @@
{ L10, L11, L12, L13, L14 }, \
{ L20, L21, L22, L23, L24 }, \
{ KC_NO, L31, L32, L33, L34 }, \
- { KC_NO, L41, L42, L43, L44 } \
+ { KC_NO, L41, L42, L43, L44 } \
\
}
#endif
-
#endif
diff --git a/keyboards/handwired/dactyl_manuform/keymaps/default/config.h b/keyboards/handwired/dactyl_manuform/4x5/keymaps/default/config.h
index 216917ed7..216917ed7 100644
--- a/keyboards/handwired/dactyl_manuform/keymaps/default/config.h
+++ b/keyboards/handwired/dactyl_manuform/4x5/keymaps/default/config.h
diff --git a/keyboards/handwired/dactyl_manuform/keymaps/default/keymap.c b/keyboards/handwired/dactyl_manuform/4x5/keymaps/default/keymap.c
index 24c02215e..24c02215e 100644
--- a/keyboards/handwired/dactyl_manuform/keymaps/default/keymap.c
+++ b/keyboards/handwired/dactyl_manuform/4x5/keymaps/default/keymap.c
diff --git a/keyboards/handwired/dactyl_manuform/keymaps/default/rules.mk b/keyboards/handwired/dactyl_manuform/4x5/keymaps/default/rules.mk
index 457a3d01d..457a3d01d 100644
--- a/keyboards/handwired/dactyl_manuform/keymaps/default/rules.mk
+++ b/keyboards/handwired/dactyl_manuform/4x5/keymaps/default/rules.mk
diff --git a/keyboards/handwired/dactyl_manuform/keymaps/dvorak/config.h b/keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/config.h
index 216917ed7..216917ed7 100644
--- a/keyboards/handwired/dactyl_manuform/keymaps/dvorak/config.h
+++ b/keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/config.h
diff --git a/keyboards/handwired/dactyl_manuform/keymaps/dvorak/keymap.c b/keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/keymap.c
index 0a1c90b6b..0a1c90b6b 100644
--- a/keyboards/handwired/dactyl_manuform/keymaps/dvorak/keymap.c
+++ b/keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/keymap.c
diff --git a/keyboards/handwired/dactyl_manuform/keymaps/dvorak/rules.mk b/keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/rules.mk
index 457a3d01d..457a3d01d 100644
--- a/keyboards/handwired/dactyl_manuform/keymaps/dvorak/rules.mk
+++ b/keyboards/handwired/dactyl_manuform/4x5/keymaps/dvorak/rules.mk
diff --git a/keyboards/handwired/dactyl_manuform/readme.md b/keyboards/handwired/dactyl_manuform/4x5/readme.md
index 8b2875712..aab792f22 100644
--- a/keyboards/handwired/dactyl_manuform/readme.md
+++ b/keyboards/handwired/dactyl_manuform/4x5/readme.md
@@ -1,4 +1,4 @@
-Dactyl Manuform
+Dactyl Manuform 4x5
======
the [Dactyl-Manuform](https://github.com/tshort/dactyl-keyboard) is a split curved keyboard based on the design of [adereth dactyl](https://github.com/adereth/dactyl-keyboard) and thumb cluster design of the [manuform](https://geekhack.org/index.php?topic=46015.0) keyboard, the hardware is similar to the let's split keyboard. all information needed for making one is in the first link.
![Imgur](https://i.imgur.com/7y0Vbyd.jpg)
@@ -9,25 +9,25 @@ the [Dactyl-Manuform](https://github.com/tshort/dactyl-keyboard) is a split curv
Download or clone the `qmk_firmware` repo and navigate to its top level directory. Once your build environment is setup, you'll be able to generate the default .hex using:
```
-$ make dactyl_manuform:dvorak
+$ make handwired/dactyl_manuform/4x5:dvorak
```
You will see a lot of output and if everything worked correctly you will see the built hex file:
```
-dactyl_manuform_dvorak.hex
+dactyl_manuform_4x5_dvorak.hex
```
If you would like to use one of the alternative keymaps, or create your own, copy one of the existing [keymaps](keymaps/) and run make like so:
```
-$ make dactyl_manuform:YOUR_KEYMAP_NAME
+$ make handwired/dactyl_manuform/4x5:YOUR_KEYMAP_NAME
```
If everything worked correctly you will see a file:
```
-dactyl_manuform_YOUR_KEYMAP_NAME.hex
+dactyl_manuform_4x5_YOUR_KEYMAP_NAME.hex
```
For more information on customizing keymaps, take a look at the primary documentation for [Customizing Your Keymap](/docs/faq_keymap.md) in the main readme.md.
diff --git a/keyboards/handwired/dactyl_manuform/rules.mk b/keyboards/handwired/dactyl_manuform/4x5/rules.mk
index 6c0949b54..99ac2880d 100644
--- a/keyboards/handwired/dactyl_manuform/rules.mk
+++ b/keyboards/handwired/dactyl_manuform/4x5/rules.mk
@@ -1,9 +1,3 @@
-SRC += matrix.c \
- i2c.c \
- split_util.c \
- serial.c \
- ssd1306.c
-
# MCU name
#MCU = at90usb1287
MCU = atmega32u4
@@ -70,6 +64,5 @@ USE_I2C = yes
# Do not enable SLEEP_LED_ENABLE. it uses the same timer as BACKLIGHT_ENABLE
SLEEP_LED_ENABLE = no # Breathing sleep LED during USB suspend
-CUSTOM_MATRIX = yes
+SPLIT_KEYBOARD = yes
-LAYOUTS = ortho_4x12
diff --git a/keyboards/handwired/dactyl_manuform/5x6/config.h b/keyboards/handwired/dactyl_manuform/5x6/config.h
new file mode 100644
index 000000000..97495e935
--- /dev/null
+++ b/keyboards/handwired/dactyl_manuform/5x6/config.h
@@ -0,0 +1,97 @@
+/*
+Copyright 2012 Jun Wako <wakojun@gmail.com>
+Copyright 2015 Jack Humbert
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef CONFIG_H
+#define CONFIG_H
+
+#include "config_common.h"
+
+/* USB Device descriptor parameter */
+#define VENDOR_ID 0xFEED
+#define PRODUCT_ID 0x3060
+#define DEVICE_VER 0x0001
+#define MANUFACTURER tshort
+#define PRODUCT Dactyl-Manuform
+#define DESCRIPTION A split keyboard for the cheap makers
+
+/* key matrix size */
+// Rows are doubled-up
+#define MATRIX_ROWS 12
+#define MATRIX_COLS 6
+
+// wiring of each half
+#define MATRIX_COL_PINS { D4, C6, D7, E6, B4, B5 }
+#define MATRIX_ROW_PINS { F6, F7, B1, B3, B2, B6 }
+
+
+/* define if matrix has ghost */
+//#define MATRIX_HAS_GHOST
+
+/* number of backlight levels */
+// #define BACKLIGHT_LEVELS 3
+
+/* mouse config */
+#define MOUSEKEY_INTERVAL 20
+#define MOUSEKEY_DELAY 0
+#define MOUSEKEY_TIME_TO_MAX 60
+#define MOUSEKEY_MAX_SPEED 7
+#define MOUSEKEY_WHEEL_DELAY 0
+
+/* Set 0 if debouncing isn't needed */
+#define DEBOUNCING_DELAY 5
+
+/* Mechanical locking support. Use KC_LCAP, KC_LNUM or KC_LSCR instead in keymap */
+#define LOCKING_SUPPORT_ENABLE
+/* Locking resynchronize hack */
+#define LOCKING_RESYNC_ENABLE
+
+/* key combination for command */
+#define IS_COMMAND() ( \
+ keyboard_report->mods == (MOD_BIT(KC_LSHIFT) | MOD_BIT(KC_RSHIFT)) \
+)
+
+/* Enables This makes it easier for fast typists to use dual-function keys */
+#define PERMISSIVE_HOLD
+
+/* ws2812 RGB LED */
+#define RGB_DI_PIN D3
+#define RGBLIGHT_TIMER
+#define RGBLED_NUM 12 // Number of LEDs
+#define ws2812_PORTREG PORTD
+#define ws2812_DDRREG DDRD
+
+/*
+ * Feature disable options
+ * These options are also useful to firmware size reduction.
+ */
+
+/* disable debug print */
+// #define NO_DEBUG
+
+/* disable print */
+// #define NO_PRINT
+
+/* disable action features */
+//#define NO_ACTION_LAYER
+//#define NO_ACTION_TAPPING
+//#define NO_ACTION_ONESHOT
+//#define NO_ACTION_MACRO
+//#define NO_ACTION_FUNCTION
+
+
+#endif
diff --git a/keyboards/handwired/dactyl_manuform/5x6/dactyl_manuform.c b/keyboards/handwired/dactyl_manuform/5x6/dactyl_manuform.c
new file mode 100644
index 000000000..17caecb4f
--- /dev/null
+++ b/keyboards/handwired/dactyl_manuform/5x6/dactyl_manuform.c
@@ -0,0 +1,23 @@
+#include "dactyl_manuform.h"
+
+
+#ifdef SSD1306OLED
+void led_set_kb(uint8_t usb_led) {
+ // put your keyboard LED indicator (ex: Caps Lock LED) toggling code here
+ led_set_user(usb_led);
+}
+#endif
+
+void matrix_init_kb(void) {
+
+ // // green led on
+ // DDRD |= (1<<5);
+ // PORTD &= ~(1<<5);
+
+ // // orange led on
+ // DDRB |= (1<<0);
+ // PORTB &= ~(1<<0);
+
+ matrix_init_user();
+};
+
diff --git a/keyboards/handwired/dactyl_manuform/5x6/dactyl_manuform.h b/keyboards/handwired/dactyl_manuform/5x6/dactyl_manuform.h
new file mode 100644
index 000000000..5c1a4339b
--- /dev/null
+++ b/keyboards/handwired/dactyl_manuform/5x6/dactyl_manuform.h
@@ -0,0 +1,47 @@
+#ifndef REV2_H
+#define REV2_H
+
+#include "dactyl_manuform.h"
+
+//void promicro_bootloader_jmp(bool program);
+#include "quantum.h"
+
+
+#ifdef USE_I2C
+#include <stddef.h>
+#ifdef __AVR__
+ #include <avr/io.h>
+ #include <avr/interrupt.h>
+#endif
+#endif
+
+//void promicro_bootloader_jmp(bool program);
+
+
+#define LAYOUT_5x6(\
+ L00, L01, L02, L03, L04, L05, R00, R01, R02, R03, R04, R05, \
+ L10, L11, L12, L13, L14, L15, R10, R11, R12, R13, R14, R15, \
+ L20, L21, L22, L23, L24, L25, R20, R21, R22, R23, R24, R25, \
+ L30, L31, L32, L33, L34, L35, R30, R31, R32, R33, R34, R35, \
+ L42, L43, R42, R43, \
+ L44, L45, R40, R41, \
+ L54, L55, R50, R51, \
+ L52, L53, R52, R53 \
+ ) \
+ { \
+ { L00, L01, L02, L03, L04, L05 }, \
+ { L10, L11, L12, L13, L14, L15 }, \
+ { L20, L21, L22, L23, L24, L25 }, \
+ { L30, L31, L32, L33, L34, L35 }, \
+ { KC_NO, KC_NO, L42, L43, L44, L45 }, \
+ { KC_NO, KC_NO, L52, L53, L54, L55 }, \
+\
+ { R00, R01, R02, R03, R04, R05 }, \
+ { R10, R11, R12, R13, R14, R15 }, \
+ { R20, R21, R22, R23, R24, R25 }, \
+ { R30, R31, R32, R33, R34, R35 }, \
+ { R40, R41, R42, R43, KC_NO, KC_NO },\
+ { R50, R51, R52, R53, KC_NO, KC_NO }, \
+ }
+
+#endif
diff --git a/keyboards/handwired/dactyl_manuform/5x6/keymaps/impstyle/config.h b/keyboards/handwired/dactyl_manuform/5x6/keymaps/impstyle/config.h
new file mode 100644
index 000000000..1a7d1e065
--- /dev/null
+++ b/keyboards/handwired/dactyl_manuform/5x6/keymaps/impstyle/config.h
@@ -0,0 +1,28 @@
+/*
+Copyright 2012 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+
+#define USE_SERIAL
+
+#define MASTER_LEFT
+// #define MASTER_RIGHT
+//#define EE_HANDS
+// Rows are doubled-up
+#define MATRIX_ROWS 12
+#define MATRIX_COLS 6
+
+#include "../../config.h"
diff --git a/keyboards/handwired/dactyl_manuform/5x6/keymaps/impstyle/keymap.c b/keyboards/handwired/dactyl_manuform/5x6/keymaps/impstyle/keymap.c
new file mode 100644
index 000000000..7dd9f7c86
--- /dev/null
+++ b/keyboards/handwired/dactyl_manuform/5x6/keymaps/impstyle/keymap.c
@@ -0,0 +1,75 @@
+#include "dactyl_manuform.h"
+#include "action_layer.h"
+#include "eeconfig.h"
+
+extern keymap_config_t keymap_config;
+
+// Each layer gets a name for readability, which is then used in the keymap matrix below.
+// The underscores don't mean anything - you can have a layer called STUFF or any other name.
+// Layer names don't all need to be of the same length, obviously, and you can also skip them
+// entirely and just use numbers.
+#define _QWERTY 0
+#define _LOWER 1
+#define _RAISE 2
+
+#define SFT_ESC SFT_T(KC_ESC)
+#define CTL_BSPC CTL_T(KC_BSPC)
+#define ALT_SPC ALT_T(KC_SPC)
+#define SFT_ENT SFT_T(KC_ENT)
+
+#define KC_ML KC_MS_LEFT
+#define KC_MR KC_MS_RIGHT
+#define KC_MU KC_MS_UP
+#define KC_MD KC_MS_DOWN
+#define KC_MB1 KC_MS_BTN1
+#define KC_MB2 KC_MS_BTN1
+#define RAISE MO(_RAISE)
+#define LOWER MO(_LOWER)
+
+#define _______ KC_TRNS
+
+
+
+const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
+
+
+ [_QWERTY] = LAYOUT_5x6(
+ KC_ESC , KC_1 , KC_2 , KC_3 , KC_4 , KC_5 , KC_6 , KC_7 , KC_8 , KC_9 , KC_0 ,KC_BSPC,
+ KC_TAB , KC_Q , KC_W , KC_E , KC_R , KC_T , KC_Y , KC_U , KC_I , KC_O , KC_P ,KC_MINS,
+ KC_LSFT, KC_A , KC_S , KC_D , KC_F , KC_G , KC_H , KC_J , KC_K , KC_L ,KC_SCLN,KC_QUOT,
+ KC_LCTL, KC_Z , KC_X , KC_C , KC_V , KC_B , KC_N , KC_M ,KC_COMM,KC_DOT ,KC_SLSH,KC_BSLASH,
+ KC_LBRC,KC_RBRC, KC_PLUS, KC_EQL,
+ RAISE,KC_SPC, KC_ENT, LOWER,
+ KC_TAB,KC_HOME, KC_END, KC_DEL,
+ KC_BSPC, KC_GRV, KC_LGUI, KC_LALT
+ ),
+
+ [_LOWER] = LAYOUT_5x6(
+ KC_TILD,KC_EXLM, KC_AT ,KC_HASH,KC_DLR ,KC_PERC, KC_CIRC,KC_AMPR,KC_ASTR,KC_LPRN,KC_RPRN,KC_DEL,
+ _______,_______,_______,_______,_______,KC_LBRC, KC_RBRC, KC_P7 , KC_P8 , KC_P9 ,_______,KC_PLUS,
+ _______,KC_HOME,KC_PGUP,KC_PGDN,KC_END ,KC_LPRN, KC_RPRN, KC_P4 , KC_P5 , KC_P6 ,KC_MINS,KC_PIPE,
+ _______,_______,_______,_______,_______,_______, _______, KC_P1 , KC_P2 , KC_P3 ,KC_EQL ,KC_UNDS,
+ _______,KC_PSCR, _______, KC_P0,
+ _______,_______, _______,_______,
+ _______,_______, _______,_______,
+ _______,_______, _______,_______
+),
+
+ [_RAISE] = LAYOUT_5x6(
+ KC_F12 , KC_F1 , KC_F2 , KC_F3 , KC_F4 , KC_F5 , KC_F6 , KC_F7 , KC_F8 , KC_F9 ,KC_F10 ,KC_F11 ,
+ _______,_______,_______,_______,_______,KC_LBRC, KC_RBRC,_______,KC_NLCK,KC_INS ,KC_SLCK,KC_MUTE,
+ _______,KC_LEFT,KC_UP ,KC_DOWN,KC_RGHT,KC_LPRN, KC_RPRN,KC_MPRV,KC_MPLY,KC_MNXT,_______,KC_VOLU,
+ _______,_______,_______,_______,_______,_______, _______,_______,_______,_______,_______,KC_VOLD,
+ _______,_______, KC_EQL ,_______,
+ _______,_______, _______,_______,
+ _______,_______, _______,_______,
+ _______,_______, _______,_______
+ ),
+
+ };
+
+
+void persistant_default_layer_set(uint16_t default_layer) {
+ eeconfig_update_default_layer(default_layer);
+ default_layer_set(default_layer);
+}
diff --git a/keyboards/handwired/dactyl_manuform/5x6/readme.md b/keyboards/handwired/dactyl_manuform/5x6/readme.md
new file mode 100644
index 000000000..eb76a7150
--- /dev/null
+++ b/keyboards/handwired/dactyl_manuform/5x6/readme.md
@@ -0,0 +1,142 @@
+Dactyl Manuform 5x6
+======
+the [Dactyl-Manuform](https://github.com/tshort/dactyl-keyboard) is a split curved keyboard based on the design of [adereth dactyl](https://github.com/adereth/dactyl-keyboard) and thumb cluster design of the [manuform](https://geekhack.org/index.php?topic=46015.0) keyboard, the hardware is similar to the let's split keyboard. all information needed for making one is in the first link.
+![Imgur](https://i.imgur.com/7y0Vbyd.jpg)
+
+
+## First Time Setup
+
+Download or clone the `qmk_firmware` repo and navigate to its top level directory. Once your build environment is setup, you'll be able to generate the default .hex using:
+
+```
+$ make handwired/dactyl_manuform/5x6:YOUR_KEYMAP_NAME
+```
+
+If everything worked correctly you will see a file:
+
+```
+dactyl_manuform_5x6_YOUR_KEYMAP_NAME.hex
+```
+
+For more information on customizing keymaps, take a look at the primary documentation for [Customizing Your Keymap](/docs/faq_keymap.md) in the main readme.md.
+
+## Keymaps
+Currently there are only two keymaps: Qwerty and Dvorak, feel free to make changes and contribute your keymap.
+### Impstyle
+
+
+
+Required Hardware
+-----------------
+
+Apart from diodes and key switches for the keyboard matrix in each half, you
+will need:
+
+* 2 Arduino Pro Micros. You can find these on AliExpress for ≈3.50USD each.
+* 2 TRRS sockets and 1 TRRS cable, or 2 TRS sockets and 1 TRS cable
+
+Alternatively, you can use any sort of cable and socket that has at least 3
+wires. If you want to use I2C to communicate between halves, you will need a
+cable with at least 4 wires and 2x 4.7kΩ pull-up resistors
+
+Optional Hardware
+-----------------
+A speaker can be hooked-up to either side to the `5` (`C6`) pin and `GND`, and turned on via `AUDIO_ENABLE`.
+
+Wiring
+------
+
+The 3 wires of the TRS/TRRS cable need to connect GND, VCC, and digital pin 3 (i.e.
+PD0 on the ATmega32u4) between the two Pro Micros.
+
+Next, wire your key matrix to any of the remaining 17 IO pins of the pro micro
+and modify the `matrix.c` accordingly.
+
+The wiring for serial:
+
+![serial wiring](https://i.imgur.com/C3D1GAQ.png)
+
+The wiring for i2c:
+
+![i2c wiring](https://i.imgur.com/Hbzhc6E.png)
+
+The pull-up resistors may be placed on either half. It is also possible
+to use 4 resistors and have the pull-ups in both halves, but this is
+unnecessary in simple use cases.
+
+You can change your configuration between serial and i2c by modifying your `config.h` file.
+
+Notes on Software Configuration
+-------------------------------
+
+the keymaps in here are for the 4x5 layout of the keyboard only.
+
+Flashing
+-------
+From the top level `qmk_firmware` directory run `make KEYBOARD:KEYMAP:avrdude` for automatic serial port resolution and flashing.
+Example: `make lets_split/rev2:default:avrdude`
+
+
+Choosing which board to plug the USB cable into (choosing Master)
+--------
+Because the two boards are identical, the firmware has logic to differentiate the left and right board.
+
+It uses two strategies to figure things out: looking at the EEPROM (memory on the chip) or looking if the current board has the usb cable.
+
+The EEPROM approach requires additional setup (flashing the eeprom) but allows you to swap the usb cable to either side.
+
+The USB cable approach is easier to setup and if you just want the usb cable on the left board, you do not need to do anything extra.
+
+### Setting the left hand as master
+If you always plug the usb cable into the left board, nothing extra is needed as this is the default. Comment out `EE_HANDS` and comment out `I2C_MASTER_RIGHT` or `MASTER_RIGHT` if for some reason it was set.
+
+### Setting the right hand as master
+If you always plug the usb cable into the right board, add an extra flag to your `config.h`
+```
+ #define MASTER_RIGHT
+```
+
+### Setting EE_hands to use either hands as master
+If you define `EE_HANDS` in your `config.h`, you will need to set the
+EEPROM for the left and right halves.
+
+The EEPROM is used to store whether the
+half is left handed or right handed. This makes it so that the same firmware
+file will run on both hands instead of having to flash left and right handed
+versions of the firmware to each half. To flash the EEPROM file for the left
+half run:
+```
+avrdude -p atmega32u4 -P $(COM_PORT) -c avr109 -U eeprom:w:eeprom-lefthand.eep
+// or the equivalent in dfu-programmer
+
+```
+and similarly for right half
+```
+avrdude -p atmega32u4 -P $(COM_PORT) -c avr109 -U eeprom:w:eeprom-righhand.eep
+// or the equivalent in dfu-programmer
+```
+
+NOTE: replace `$(COM_PORT)` with the port of your device (e.g. `/dev/ttyACM0`)
+
+After you have flashed the EEPROM, you then need to set `EE_HANDS` in your config.h, rebuild the hex files and reflash.
+
+Note that you need to program both halves, but you have the option of using
+different keymaps for each half. You could program the left half with a QWERTY
+layout and the right half with a Colemak layout using bootmagic's default layout option.
+Then if you connect the left half to a computer by USB the keyboard will use QWERTY and Colemak when the
+right half is connected.
+
+
+Notes on Using Pro Micro 3.3V
+-----------------------------
+
+Do update the `F_CPU` parameter in `rules.mk` to `8000000` which reflects
+the frequency on the 3.3V board.
+
+Also, if the slave board is producing weird characters in certain columns,
+update the following line in `matrix.c` to the following:
+
+```
+// _delay_us(30); // without this wait read unstable value.
+_delay_us(300); // without this wait read unstable value.
+```
diff --git a/keyboards/handwired/dactyl_manuform/5x6/rules.mk b/keyboards/handwired/dactyl_manuform/5x6/rules.mk
new file mode 100644
index 000000000..6b1201781
--- /dev/null
+++ b/keyboards/handwired/dactyl_manuform/5x6/rules.mk
@@ -0,0 +1,67 @@
+# MCU name
+#MCU = at90usb1287
+MCU = atmega32u4
+
+# Processor frequency.
+# This will define a symbol, F_CPU, in all source code files equal to the
+# processor frequency in Hz. You can then use this symbol in your source code to
+# calculate timings. Do NOT tack on a 'UL' at the end, this will be done
+# automatically to create a 32-bit value in your source code.
+#
+# This will be an integer division of F_USB below, as it is sourced by
+# F_USB after it has run through any CPU prescalers. Note that this value
+# does not *change* the processor frequency - it should merely be updated to
+# reflect the processor speed set externally so that the code can use accurate
+# software delays.
+F_CPU = 16000000
+
+#
+# LUFA specific
+#
+# Target architecture (see library "Board Types" documentation).
+ARCH = AVR8
+
+# Input clock frequency.
+# This will define a symbol, F_USB, in all source code files equal to the
+# input clock frequency (before any prescaling is performed) in Hz. This value may
+# differ from F_CPU if prescaling is used on the latter, and is required as the
+# raw input clock is fed directly to the PLL sections of the AVR for high speed
+# clock generation for the USB and other AVR subsections. Do NOT tack on a 'UL'
+# at the end, this will be done automatically to create a 32-bit value in your
+# source code.
+#
+# If no clock division is performed on the input clock inside the AVR (via the
+# CPU clock adjust registers or the clock division fuses), this will be equal to F_CPU.
+F_USB = $(F_CPU)
+
+# Bootloader
+# This definition is optional, and if your keyboard supports multiple bootloaders of
+# different sizes, comment this out, and the correct address will be loaded
+# automatically (+60). See bootloader.mk for all options.
+BOOTLOADER = caterina
+
+# Interrupt driven control endpoint task(+60)
+OPT_DEFS += -DINTERRUPT_CONTROL_ENDPOINT
+
+# Build Options
+# change to "no" to disable the options, or define them in the Makefile in
+# the appropriate keymap folder that will get included automatically
+#
+BOOTMAGIC_ENABLE = no # Virtual DIP switch configuration(+1000)
+MOUSEKEY_ENABLE = yes # Mouse keys(+4700)
+EXTRAKEY_ENABLE = yes # Audio control and System control(+450)
+CONSOLE_ENABLE = no # Console for debug(+400)
+COMMAND_ENABLE = yes # Commands for debug and configuration
+NKRO_ENABLE = no # Nkey Rollover - if this doesn't work, see here: https://github.com/tmk/tmk_keyboard/wiki/FAQ#nkro-doesnt-work
+BACKLIGHT_ENABLE = no # Enable keyboard backlight functionality
+MIDI_ENABLE = no # MIDI controls
+AUDIO_ENABLE = no # Audio output on port C6
+UNICODE_ENABLE = no # Unicode
+BLUETOOTH_ENABLE = no # Enable Bluetooth with the Adafruit EZ-Key HID
+RGBLIGHT_ENABLE = no # Enable WS2812 RGB underlight. Do not enable this with audio at the same time.
+SUBPROJECT_rev1 = yes
+USE_I2C = yes
+# Do not enable SLEEP_LED_ENABLE. it uses the same timer as BACKLIGHT_ENABLE
+SLEEP_LED_ENABLE = no # Breathing sleep LED during USB suspend
+
+SPLIT_KEYBOARD = yes \ No newline at end of file
diff --git a/keyboards/handwired/dactyl_manuform/eeprom-lefthand.eep b/keyboards/handwired/dactyl_manuform/eeprom-lefthand.eep
deleted file mode 100644
index bda23cdb6..000000000
--- a/keyboards/handwired/dactyl_manuform/eeprom-lefthand.eep
+++ /dev/null
@@ -1,2 +0,0 @@
-:0F000000000000000000000000000000000001F0
-:00000001FF
diff --git a/keyboards/handwired/dactyl_manuform/eeprom-righthand.eep b/keyboards/handwired/dactyl_manuform/eeprom-righthand.eep
deleted file mode 100644
index 549cd1ef0..000000000
--- a/keyboards/handwired/dactyl_manuform/eeprom-righthand.eep
+++ /dev/null
@@ -1,2 +0,0 @@
-:0F000000000000000000000000000000000000F1
-:00000001FF
diff --git a/keyboards/handwired/dactyl_manuform/i2c.c b/keyboards/handwired/dactyl_manuform/i2c.c
deleted file mode 100644
index 084c890c4..000000000
--- a/keyboards/handwired/dactyl_manuform/i2c.c
+++ /dev/null
@@ -1,162 +0,0 @@
-#include <util/twi.h>
-#include <avr/io.h>
-#include <stdlib.h>
-#include <avr/interrupt.h>
-#include <util/twi.h>
-#include <stdbool.h>
-#include "i2c.h"
-
-#ifdef USE_I2C
-
-// Limits the amount of we wait for any one i2c transaction.
-// Since were running SCL line 100kHz (=> 10μs/bit), and each transactions is
-// 9 bits, a single transaction will take around 90μs to complete.
-//
-// (F_CPU/SCL_CLOCK) => # of μC cycles to transfer a bit
-// poll loop takes at least 8 clock cycles to execute
-#define I2C_LOOP_TIMEOUT (9+1)*(F_CPU/SCL_CLOCK)/8
-
-#define BUFFER_POS_INC() (slave_buffer_pos = (slave_buffer_pos+1)%SLAVE_BUFFER_SIZE)
-
-volatile uint8_t i2c_slave_buffer[SLAVE_BUFFER_SIZE];
-
-static volatile uint8_t slave_buffer_pos;
-static volatile bool slave_has_register_set = false;
-
-// Wait for an i2c operation to finish
-inline static
-void i2c_delay(void) {
- uint16_t lim = 0;
- while(!(TWCR & (1<<TWINT)) && lim < I2C_LOOP_TIMEOUT)
- lim++;
-
- // easier way, but will wait slightly longer
- // _delay_us(100);
-}
-
-// Setup twi to run at 100kHz
-void i2c_master_init(void) {
- // no prescaler
- TWSR = 0;
- // Set TWI clock frequency to SCL_CLOCK. Need TWBR>10.
- // Check datasheets for more info.
- TWBR = ((F_CPU/SCL_CLOCK)-16)/2;
-}
-
-// Start a transaction with the given i2c slave address. The direction of the
-// transfer is set with I2C_READ and I2C_WRITE.
-// returns: 0 => success
-// 1 => error
-uint8_t i2c_master_start(uint8_t address) {
- TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTA);
-
- i2c_delay();
-
- // check that we started successfully
- if ( (TW_STATUS != TW_START) && (TW_STATUS != TW_REP_START))
- return 1;
-
- TWDR = address;
- TWCR = (1<<TWINT) | (1<<TWEN);
-
- i2c_delay();
-
- if ( (TW_STATUS != TW_MT_SLA_ACK) && (TW_STATUS != TW_MR_SLA_ACK) )
- return 1; // slave did not acknowledge
- else
- return 0; // success
-}
-
-
-// Finish the i2c transaction.
-void i2c_master_stop(void) {
- TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
-
- uint16_t lim = 0;
- while(!(TWCR & (1<<TWSTO)) && lim < I2C_LOOP_TIMEOUT)
- lim++;
-}
-
-// Write one byte to the i2c slave.
-// returns 0 => slave ACK
-// 1 => slave NACK
-uint8_t i2c_master_write(uint8_t data) {
- TWDR = data;
- TWCR = (1<<TWINT) | (1<<TWEN);
-
- i2c_delay();
-
- // check if the slave acknowledged us
- return (TW_STATUS == TW_MT_DATA_ACK) ? 0 : 1;
-}
-
-// Read one byte from the i2c slave. If ack=1 the slave is acknowledged,
-// if ack=0 the acknowledge bit is not set.
-// returns: byte read from i2c device
-uint8_t i2c_master_read(int ack) {
- TWCR = (1<<TWINT) | (1<<TWEN) | (ack<<TWEA);
-
- i2c_delay();
- return TWDR;
-}
-
-void i2c_reset_state(void) {
- TWCR = 0;
-}
-
-void i2c_slave_init(uint8_t address) {
- TWAR = address << 0; // slave i2c address
- // TWEN - twi enable
- // TWEA - enable address acknowledgement
- // TWINT - twi interrupt flag
- // TWIE - enable the twi interrupt
- TWCR = (1<<TWIE) | (1<<TWEA) | (1<<TWINT) | (1<<TWEN);
-}
-
-ISR(TWI_vect);
-
-ISR(TWI_vect) {
- uint8_t ack = 1;
- switch(TW_STATUS) {
- case TW_SR_SLA_ACK:
- // this device has been addressed as a slave receiver
- slave_has_register_set = false;
- break;
-
- case TW_SR_DATA_ACK:
- // this device has received data as a slave receiver
- // The first byte that we receive in this transaction sets the location
- // of the read/write location of the slaves memory that it exposes over
- // i2c. After that, bytes will be written at slave_buffer_pos, incrementing
- // slave_buffer_pos after each write.
- if(!slave_has_register_set) {
- slave_buffer_pos = TWDR;
- // don't acknowledge the master if this memory loctaion is out of bounds
- if ( slave_buffer_pos >= SLAVE_BUFFER_SIZE ) {
- ack = 0;
- slave_buffer_pos = 0;
- }
- slave_has_register_set = true;
- } else {
- i2c_slave_buffer[slave_buffer_pos] = TWDR;
- BUFFER_POS_INC();
- }
- break;
-
- case TW_ST_SLA_ACK:
- case TW_ST_DATA_ACK:
- // master has addressed this device as a slave transmitter and is
- // requesting data.
- TWDR = i2c_slave_buffer[slave_buffer_pos];
- BUFFER_POS_INC();
- break;
-
- case TW_BUS_ERROR: // something went wrong, reset twi state
- TWCR = 0;
- default:
- break;
- }
- // Reset everything, so we are ready for the next TWI interrupt
- TWCR |= (1<<TWIE) | (1<<TWINT) | (ack<<TWEA) | (1<<TWEN);
-}
-#endif
diff --git a/keyboards/handwired/dactyl_manuform/i2c.h b/keyboards/handwired/dactyl_manuform/i2c.h
deleted file mode 100644
index c15b6bc50..000000000
--- a/keyboards/handwired/dactyl_manuform/i2c.h
+++ /dev/null
@@ -1,49 +0,0 @@
-#ifndef I2C_H
-#define I2C_H
-
-#include <stdint.h>
-
-#ifndef F_CPU
-#define F_CPU 16000000UL
-#endif
-
-#define I2C_READ 1
-#define I2C_WRITE 0
-
-#define I2C_ACK 1
-#define I2C_NACK 0
-
-#define SLAVE_BUFFER_SIZE 0x10
-
-// i2c SCL clock frequency
-#define SCL_CLOCK 400000L
-
-extern volatile uint8_t i2c_slave_buffer[SLAVE_BUFFER_SIZE];
-
-void i2c_master_init(void);
-uint8_t i2c_master_start(uint8_t address);
-void i2c_master_stop(void);
-uint8_t i2c_master_write(uint8_t data);
-uint8_t i2c_master_read(int);
-void i2c_reset_state(void);
-void i2c_slave_init(uint8_t address);
-
-
-static inline unsigned char i2c_start_read(unsigned char addr) {
- return i2c_master_start((addr << 1) | I2C_READ);
-}
-
-static inline unsigned char i2c_start_write(unsigned char addr) {
- return i2c_master_start((addr << 1) | I2C_WRITE);
-}
-
-// from SSD1306 scrips
-extern unsigned char i2c_rep_start(unsigned char addr);
-extern void i2c_start_wait(unsigned char addr);
-extern unsigned char i2c_readAck(void);
-extern unsigned char i2c_readNak(void);
-extern unsigned char i2c_read(unsigned char ack);
-
-#define i2c_read(ack) (ack) ? i2c_readAck() : i2c_readNak();
-
-#endif
diff --git a/keyboards/handwired/dactyl_manuform/matrix.c b/keyboards/handwired/dactyl_manuform/matrix.c
deleted file mode 100644
index 904850d4d..000000000
--- a/keyboards/handwired/dactyl_manuform/matrix.c
+++ /dev/null
@@ -1,465 +0,0 @@
-/*
-Copyright 2012 Jun Wako <wakojun@gmail.com>
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 2 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
-*/
-
-/*
- * scan matrix
- */
-#include <stdint.h>
-#include <stdbool.h>
-#include <avr/io.h>
-#include "wait.h"
-#include "print.h"
-#include "debug.h"
-#include "util.h"
-#include "matrix.h"
-#include "split_util.h"
-#include "pro_micro.h"
-#include "config.h"
-#include "timer.h"
-
-#ifdef USE_I2C
-# include "i2c.h"
-#else // USE_SERIAL
-# include "serial.h"
-#endif
-
-#ifndef DEBOUNCING_DELAY
-# define DEBOUNCING_DELAY 5
-#endif
-
-#if (DEBOUNCING_DELAY > 0)
- static uint16_t debouncing_time;
- static bool debouncing = false;
-#endif
-
-#if (MATRIX_COLS <= 8)
-# define print_matrix_header() print("\nr/c 01234567\n")
-# define print_matrix_row(row) print_bin_reverse8(matrix_get_row(row))
-# define matrix_bitpop(i) bitpop(matrix[i])
-# define ROW_SHIFTER ((uint8_t)1)
-#else
-# error "Currently only supports 8 COLS"
-#endif
-static matrix_row_t matrix_debouncing[MATRIX_ROWS];
-
-#define ERROR_DISCONNECT_COUNT 5
-
-#define ROWS_PER_HAND (MATRIX_ROWS/2)
-
-static uint8_t error_count = 0;
-
-static const uint8_t row_pins[MATRIX_ROWS] = MATRIX_ROW_PINS;
-static const uint8_t col_pins[MATRIX_COLS] = MATRIX_COL_PINS;
-
-/* matrix state(1:on, 0:off) */
-static matrix_row_t matrix[MATRIX_ROWS];
-static matrix_row_t matrix_debouncing[MATRIX_ROWS];
-
-#if (DIODE_DIRECTION == COL2ROW)
- static void init_cols(void);
- static bool read_cols_on_row(matrix_row_t current_matrix[], uint8_t current_row);
- static void unselect_rows(void);
- static void select_row(uint8_t row);
- static void unselect_row(uint8_t row);
-#elif (DIODE_DIRECTION == ROW2COL)
- static void init_rows(void);
- static bool read_rows_on_col(matrix_row_t current_matrix[], uint8_t current_col);
- static void unselect_cols(void);
- static void unselect_col(uint8_t col);
- static void select_col(uint8_t col);
-#endif
-
-__attribute__ ((weak))
-void matrix_init_kb(void) {
- matrix_init_user();
-}
-
-__attribute__ ((weak))
-void matrix_scan_kb(void) {
- matrix_scan_user();
-}
-
-__attribute__ ((weak))
-void matrix_init_user(void) {
-}
-
-__attribute__ ((weak))
-void matrix_scan_user(void) {
-}
-
-inline
-uint8_t matrix_rows(void)
-{
- return MATRIX_ROWS;
-}
-
-inline
-uint8_t matrix_cols(void)
-{
- return MATRIX_COLS;
-}
-
-void matrix_init(void)
-{
-#ifdef DISABLE_JTAG
- // JTAG disable for PORT F. write JTD bit twice within four cycles.
- MCUCR |= (1<<JTD);
- MCUCR |= (1<<JTD);
-#endif
-
- debug_enable = true;
- debug_matrix = true;
- debug_mouse = true;
- // initialize row and col
-#if (DIODE_DIRECTION == COL2ROW)
- unselect_rows();
- init_cols();
-#elif (DIODE_DIRECTION == ROW2COL)
- unselect_cols();
- init_rows();
-#endif
-
- TX_RX_LED_INIT;
-
- // initialize matrix state: all keys off
- for (uint8_t i=0; i < MATRIX_ROWS; i++) {
- matrix[i] = 0;
- matrix_debouncing[i] = 0;
- }
-
- matrix_init_quantum();
-
-}
-
-uint8_t _matrix_scan(void)
-{
- int offset = isLeftHand ? 0 : (ROWS_PER_HAND);
-#if (DIODE_DIRECTION == COL2ROW)
- // Set row, read cols
- for (uint8_t current_row = 0; current_row < ROWS_PER_HAND; current_row++) {
-# if (DEBOUNCING_DELAY > 0)
- bool matrix_changed = read_cols_on_row(matrix_debouncing+offset, current_row);
-
- if (matrix_changed) {
- debouncing = true;
- debouncing_time = timer_read();
- }
-
-# else
- read_cols_on_row(matrix+offset, current_row);
-# endif
-
- }
-
-#elif (DIODE_DIRECTION == ROW2COL)
- // Set col, read rows
- for (uint8_t current_col = 0; current_col < MATRIX_COLS; current_col++) {
-# if (DEBOUNCING_DELAY > 0)
- bool matrix_changed = read_rows_on_col(matrix_debouncing+offset, current_col);
- if (matrix_changed) {
- debouncing = true;
- debouncing_time = timer_read();
- }
-# else
- read_rows_on_col(matrix+offset, current_col);
-# endif
-
- }
-#endif
-
-# if (DEBOUNCING_DELAY > 0)
- if (debouncing && (timer_elapsed(debouncing_time) > DEBOUNCING_DELAY)) {
- for (uint8_t i = 0; i < ROWS_PER_HAND; i++) {
- matrix[i+offset] = matrix_debouncing[i+offset];
- }
- debouncing = false;
- }
-# endif
-
- return 1;
-}
-
-#ifdef USE_I2C
-
-// Get rows from other half over i2c
-int i2c_transaction(void) {
- int slaveOffset = (isLeftHand) ? (ROWS_PER_HAND) : 0;
-
- int err = i2c_master_start(SLAVE_I2C_ADDRESS + I2C_WRITE);
- if (err) goto i2c_error;
-
- // start of matrix stored at 0x00
- err = i2c_master_write(0x00);
- if (err) goto i2c_error;
-
- // Start read
- err = i2c_master_start(SLAVE_I2C_ADDRESS + I2C_READ);
- if (err) goto i2c_error;
-
- if (!err) {
- int i;
- for (i = 0; i < ROWS_PER_HAND-1; ++i) {
- matrix[slaveOffset+i] = i2c_master_read(I2C_ACK);
- }
- matrix[slaveOffset+i] = i2c_master_read(I2C_NACK);
- i2c_master_stop();
- } else {
-i2c_error: // the cable is disconnceted, or something else went wrong
- i2c_reset_state();
- return err;
- }
-
- return 0;
-}
-
-#else // USE_SERIAL
-
-int serial_transaction(void) {
- int slaveOffset = (isLeftHand) ? (ROWS_PER_HAND) : 0;
-
- if (serial_update_buffers()) {
- return 1;
- }
-
- for (int i = 0; i < ROWS_PER_HAND; ++i) {
- matrix[slaveOffset+i] = serial_slave_buffer[i];
- }
- return 0;
-}
-#endif
-
-uint8_t matrix_scan(void)
-{
- uint8_t ret = _matrix_scan();
-
-#ifdef USE_I2C
- if( i2c_transaction() ) {
-#else // USE_SERIAL
- if( serial_transaction() ) {
-#endif
- // turn on the indicator led when halves are disconnected
- TXLED1;
-
- error_count++;
-
- if (error_count > ERROR_DISCONNECT_COUNT) {
- // reset other half if disconnected
- int slaveOffset = (isLeftHand) ? (ROWS_PER_HAND) : 0;
- for (int i = 0; i < ROWS_PER_HAND; ++i) {
- matrix[slaveOffset+i] = 0;
- }
- }
- } else {
- // turn off the indicator led on no error
- TXLED0;
- error_count = 0;
- }
- matrix_scan_quantum();
- return ret;
-}
-
-void matrix_slave_scan(void) {
- _matrix_scan();
-
- int offset = (isLeftHand) ? 0 : ROWS_PER_HAND;
-
-#ifdef USE_I2C
- for (int i = 0; i < ROWS_PER_HAND; ++i) {
- i2c_slave_buffer[i] = matrix[offset+i];
- }
-#else // USE_SERIAL
- for (int i = 0; i < ROWS_PER_HAND; ++i) {
- serial_slave_buffer[i] = matrix[offset+i];
- }
-#endif
-}
-
-bool matrix_is_modified(void)
-{
- if (debouncing) return false;
- return true;
-}
-
-inline
-bool matrix_is_on(uint8_t row, uint8_t col)
-{
- return (matrix[row] & ((matrix_row_t)1<<col));
-}
-
-inline
-matrix_row_t matrix_get_row(uint8_t row)
-{
- return matrix[row];
-}
-
-void matrix_print(void)
-{
- print("\nr/c 0123456789ABCDEF\n");
- for (uint8_t row = 0; row < MATRIX_ROWS; row++) {
- phex(row); print(": ");
- pbin_reverse16(matrix_get_row(row));
- print("\n");
- }
-}
-
-uint8_t matrix_key_count(void)
-{
- uint8_t count = 0;
- for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
- count += bitpop16(matrix[i]);
- }
- return count;
-}
-
-#if (DIODE_DIRECTION == COL2ROW)
-
-static void init_cols(void)
-{
- for(uint8_t x = 0; x < MATRIX_COLS; x++) {
- uint8_t pin = col_pins[x];
- _SFR_IO8((pin >> 4) + 1) &= ~_BV(pin & 0xF); // IN
- _SFR_IO8((pin >> 4) + 2) |= _BV(pin & 0xF); // HI
- }
-}
-
-static bool read_cols_on_row(matrix_row_t current_matrix[], uint8_t current_row)
-{
- // Store last value of row prior to reading
- matrix_row_t last_row_value = current_matrix[current_row];
-
- // Clear data in matrix row
- current_matrix[current_row] = 0;
-
- // Select row and wait for row selecton to stabilize
- select_row(current_row);
- wait_us(30);
-
- // For each col...
- for(uint8_t col_index = 0; col_index < MATRIX_COLS; col_index++) {
-
- // Select the col pin to read (active low)
- uint8_t pin = col_pins[col_index];
- uint8_t pin_state = (_SFR_IO8(pin >> 4) & _BV(pin & 0xF));
-
- // Populate the matrix row with the state of the col pin
- current_matrix[current_row] |= pin_state ? 0 : (ROW_SHIFTER << col_index);
- }
-
- // Unselect row
- unselect_row(current_row);
-
- return (last_row_value != current_matrix[current_row]);
-}
-
-static void select_row(uint8_t row)
-{
- uint8_t pin = row_pins[row];
- _SFR_IO8((pin >> 4) + 1) |= _BV(pin & 0xF); // OUT
- _SFR_IO8((pin >> 4) + 2) &= ~_BV(pin & 0xF); // LOW
-}
-
-static void unselect_row(uint8_t row)
-{
- uint8_t pin = row_pins[row];
- _SFR_IO8((pin >> 4) + 1) &= ~_BV(pin & 0xF); // IN
- _SFR_IO8((pin >> 4) + 2) |= _BV(pin & 0xF); // HI
-}
-
-static void unselect_rows(void)
-{
- for(uint8_t x = 0; x < ROWS_PER_HAND; x++) {
- uint8_t pin = row_pins[x];
- _SFR_IO8((pin >> 4) + 1) &= ~_BV(pin & 0xF); // IN
- _SFR_IO8((pin >> 4) + 2) |= _BV(pin & 0xF); // HI
- }
-}
-
-#elif (DIODE_DIRECTION == ROW2COL)
-
-static void init_rows(void)
-{
- for(uint8_t x = 0; x < ROWS_PER_HAND; x++) {
- uint8_t pin = row_pins[x];
- _SFR_IO8((pin >> 4) + 1) &= ~_BV(pin & 0xF); // IN
- _SFR_IO8((pin >> 4) + 2) |= _BV(pin & 0xF); // HI
- }
-}
-
-static bool read_rows_on_col(matrix_row_t current_matrix[], uint8_t current_col)
-{
- bool matrix_changed = false;
-
- // Select col and wait for col selecton to stabilize
- select_col(current_col);
- wait_us(30);
-
- // For each row...
- for(uint8_t row_index = 0; row_index < ROWS_PER_HAND; row_index++)
- {
-
- // Store last value of row prior to reading
- matrix_row_t last_row_value = current_matrix[row_index];
-
- // Check row pin state
- if ((_SFR_IO8(row_pins[row_index] >> 4) & _BV(row_pins[row_index] & 0xF)) == 0)
- {
- // Pin LO, set col bit
- current_matrix[row_index] |= (ROW_SHIFTER << current_col);
- }
- else
- {
- // Pin HI, clear col bit
- current_matrix[row_index] &= ~(ROW_SHIFTER << current_col);
- }
-
- // Determine if the matrix changed state
- if ((last_row_value != current_matrix[row_index]) && !(matrix_changed))
- {
- matrix_changed = true;
- }
- }
-
- // Unselect col
- unselect_col(current_col);
-
- return matrix_changed;
-}
-
-static void select_col(uint8_t col)
-{
- uint8_t pin = col_pins[col];
- _SFR_IO8((pin >> 4) + 1) |= _BV(pin & 0xF); // OUT
- _SFR_IO8((pin >> 4) + 2) &= ~_BV(pin & 0xF); // LOW
-}
-
-static void unselect_col(uint8_t col)
-{
- uint8_t pin = col_pins[col];
- _SFR_IO8((pin >> 4) + 1) &= ~_BV(pin & 0xF); // IN
- _SFR_IO8((pin >> 4) + 2) |= _BV(pin & 0xF); // HI
-}
-
-static void unselect_cols(void)
-{
- for(uint8_t x = 0; x < MATRIX_COLS; x++) {
- uint8_t pin = col_pins[x];
- _SFR_IO8((pin >> 4) + 1) &= ~_BV(pin & 0xF); // IN
- _SFR_IO8((pin >> 4) + 2) |= _BV(pin & 0xF); // HI
- }
-}
-
-#endif
diff --git a/keyboards/handwired/dactyl_manuform/serial.c b/keyboards/handwired/dactyl_manuform/serial.c
deleted file mode 100644
index 74bcbb6bf..000000000
--- a/keyboards/handwired/dactyl_manuform/serial.c
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * WARNING: be careful changing this code, it is very timing dependent
- */
-
-#ifndef F_CPU
-#define F_CPU 16000000
-#endif
-
-#include <avr/io.h>
-#include <avr/interrupt.h>
-#include <util/delay.h>
-#include <stdbool.h>
-#include "serial.h"
-
-#ifndef USE_I2C
-
-// Serial pulse period in microseconds. Its probably a bad idea to lower this
-// value.
-#define SERIAL_DELAY 24
-
-uint8_t volatile serial_slave_buffer[SERIAL_SLAVE_BUFFER_LENGTH] = {0};
-uint8_t volatile serial_master_buffer[SERIAL_MASTER_BUFFER_LENGTH] = {0};
-
-#define SLAVE_DATA_CORRUPT (1<<0)
-volatile uint8_t status = 0;
-
-inline static
-void serial_delay(void) {
- _delay_us(SERIAL_DELAY);
-}
-
-inline static
-void serial_output(void) {
- SERIAL_PIN_DDR |= SERIAL_PIN_MASK;
-}
-
-// make the serial pin an input with pull-up resistor
-inline static
-void serial_input(void) {
- SERIAL_PIN_DDR &= ~SERIAL_PIN_MASK;
- SERIAL_PIN_PORT |= SERIAL_PIN_MASK;
-}
-
-inline static
-uint8_t serial_read_pin(void) {
- return !!(SERIAL_PIN_INPUT & SERIAL_PIN_MASK);
-}
-
-inline static
-void serial_low(void) {
- SERIAL_PIN_PORT &= ~SERIAL_PIN_MASK;
-}
-
-inline static
-void serial_high(void) {
- SERIAL_PIN_PORT |= SERIAL_PIN_MASK;
-}
-
-void serial_master_init(void) {
- serial_output();
- serial_high();
-}
-
-void serial_slave_init(void) {
- serial_input();
-
- // Enable INT0
- EIMSK |= _BV(INT0);
- // Trigger on falling edge of INT0
- EICRA &= ~(_BV(ISC00) | _BV(ISC01));
-}
-
-// Used by the master to synchronize timing with the slave.
-static
-void sync_recv(void) {
- serial_input();
- // This shouldn't hang if the slave disconnects because the
- // serial line will float to high if the slave does disconnect.
- while (!serial_read_pin());
- serial_delay();
-}
-
-// Used by the slave to send a synchronization signal to the master.
-static
-void sync_send(void) {
- serial_output();
-
- serial_low();
- serial_delay();
-
- serial_high();
-}
-
-// Reads a byte from the serial line
-static
-uint8_t serial_read_byte(void) {
- uint8_t byte = 0;
- serial_input();
- for ( uint8_t i = 0; i < 8; ++i) {
- byte = (byte << 1) | serial_read_pin();
- serial_delay();
- _delay_us(1);
- }
-
- return byte;
-}
-
-// Sends a byte with MSB ordering
-static
-void serial_write_byte(uint8_t data) {
- uint8_t b = 8;
- serial_output();
- while( b-- ) {
- if(data & (1 << b)) {
- serial_high();
- } else {
- serial_low();
- }
- serial_delay();
- }
-}
-
-// interrupt handle to be used by the slave device
-ISR(SERIAL_PIN_INTERRUPT) {
- sync_send();
-
- uint8_t checksum = 0;
- for (int i = 0; i < SERIAL_SLAVE_BUFFER_LENGTH; ++i) {
- serial_write_byte(serial_slave_buffer[i]);
- sync_send();
- checksum += serial_slave_buffer[i];
- }
- serial_write_byte(checksum);
- sync_send();
-
- // wait for the sync to finish sending
- serial_delay();
-
- // read the middle of pulses
- _delay_us(SERIAL_DELAY/2);
-
- uint8_t checksum_computed = 0;
- for (int i = 0; i < SERIAL_MASTER_BUFFER_LENGTH; ++i) {
- serial_master_buffer[i] = serial_read_byte();
- sync_send();
- checksum_computed += serial_master_buffer[i];
- }
- uint8_t checksum_received = serial_read_byte();
- sync_send();
-
- serial_input(); // end transaction
-
- if ( checksum_computed != checksum_received ) {
- status |= SLAVE_DATA_CORRUPT;
- } else {
- status &= ~SLAVE_DATA_CORRUPT;
- }
-}
-
-inline
-bool serial_slave_DATA_CORRUPT(void) {
- return status & SLAVE_DATA_CORRUPT;
-}
-
-// Copies the serial_slave_buffer to the master and sends the
-// serial_master_buffer to the slave.
-//
-// Returns:
-// 0 => no error
-// 1 => slave did not respond
-int serial_update_buffers(void) {
- // this code is very time dependent, so we need to disable interrupts
- cli();
-
- // signal to the slave that we want to start a transaction
- serial_output();
- serial_low();
- _delay_us(1);
-
- // wait for the slaves response
- serial_input();
- serial_high();
- _delay_us(SERIAL_DELAY);
-
- // check if the slave is present
- if (serial_read_pin()) {
- // slave failed to pull the line low, assume not present
- sei();
- return 1;
- }
-
- // if the slave is present syncronize with it
- sync_recv();
-
- uint8_t checksum_computed = 0;
- // receive data from the slave
- for (int i = 0; i < SERIAL_SLAVE_BUFFER_LENGTH; ++i) {
- serial_slave_buffer[i] = serial_read_byte();
- sync_recv();
- checksum_computed += serial_slave_buffer[i];
- }
- uint8_t checksum_received = serial_read_byte();
- sync_recv();
-
- if (checksum_computed != checksum_received) {
- sei();
- return 1;
- }
-
- uint8_t checksum = 0;
- // send data to the slave
- for (int i = 0; i < SERIAL_MASTER_BUFFER_LENGTH; ++i) {
- serial_write_byte(serial_master_buffer[i]);
- sync_recv();
- checksum += serial_master_buffer[i];
- }
- serial_write_byte(checksum);
- sync_recv();
-
- // always, release the line when not in use
- serial_output();
- serial_high();
-
- sei();
- return 0;
-}
-
-#endif
diff --git a/keyboards/handwired/dactyl_manuform/serial.h b/keyboards/handwired/dactyl_manuform/serial.h
deleted file mode 100644
index 15fe4db7b..000000000
--- a/keyboards/handwired/dactyl_manuform/serial.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#ifndef MY_SERIAL_H
-#define MY_SERIAL_H
-
-#include "config.h"
-#include <stdbool.h>
-
-/* TODO: some defines for interrupt setup */
-#define SERIAL_PIN_DDR DDRD
-#define SERIAL_PIN_PORT PORTD
-#define SERIAL_PIN_INPUT PIND
-#define SERIAL_PIN_MASK _BV(PD0)
-#define SERIAL_PIN_INTERRUPT INT0_vect
-
-#define SERIAL_SLAVE_BUFFER_LENGTH MATRIX_ROWS/2
-#define SERIAL_MASTER_BUFFER_LENGTH 1
-
-// Buffers for master - slave communication
-extern volatile uint8_t serial_slave_buffer[SERIAL_SLAVE_BUFFER_LENGTH];
-extern volatile uint8_t serial_master_buffer[SERIAL_MASTER_BUFFER_LENGTH];
-
-void serial_master_init(void);
-void serial_slave_init(void);
-int serial_update_buffers(void);
-bool serial_slave_data_corrupt(void);
-
-#endif
diff --git a/keyboards/handwired/dactyl_manuform/split_util.c b/keyboards/handwired/dactyl_manuform/split_util.c
deleted file mode 100644
index 346cbc908..000000000
--- a/keyboards/handwired/dactyl_manuform/split_util.c
+++ /dev/null
@@ -1,86 +0,0 @@
-#include <avr/io.h>
-#include <avr/wdt.h>
-#include <avr/power.h>
-#include <avr/interrupt.h>
-#include <util/delay.h>
-#include <avr/eeprom.h>
-#include "split_util.h"
-#include "matrix.h"
-#include "keyboard.h"
-#include "config.h"
-#include "timer.h"
-
-#ifdef USE_I2C
-# include "i2c.h"
-#else
-# include "serial.h"
-#endif
-
-volatile bool isLeftHand = true;
-
-static void setup_handedness(void) {
- #ifdef EE_HANDS
- isLeftHand = eeprom_read_byte(EECONFIG_HANDEDNESS);
- #else
- // I2C_MASTER_RIGHT is deprecated, use MASTER_RIGHT instead, since this works for both serial and i2c
- #if defined(I2C_MASTER_RIGHT) || defined(MASTER_RIGHT)
- isLeftHand = !has_usb();
- #else
- isLeftHand = has_usb();
- #endif
- #endif
-}
-
-static void keyboard_master_setup(void) {
-#ifdef USE_I2C
- i2c_master_init();
-#ifdef SSD1306OLED
- matrix_master_OLED_init ();
-#endif
-#else
- serial_master_init();
-#endif
-}
-
-static void keyboard_slave_setup(void) {
- timer_init();
-#ifdef USE_I2C
- i2c_slave_init(SLAVE_I2C_ADDRESS);
-#else
- serial_slave_init();
-#endif
-}
-
-bool has_usb(void) {
- USBCON |= (1 << OTGPADE); //enables VBUS pad
- _delay_us(5);
- return (USBSTA & (1<<VBUS)); //checks state of VBUS
-}
-
-void split_keyboard_setup(void) {
- setup_handedness();
-
- if (has_usb()) {
- keyboard_master_setup();
- } else {
- keyboard_slave_setup();
- }
- sei();
-}
-
-void keyboard_slave_loop(void) {
- matrix_init();
-
- while (1) {
- matrix_slave_scan();
- }
-}
-
-// this code runs before the usb and keyboard is initialized
-void matrix_setup(void) {
- split_keyboard_setup();
-
- if (!has_usb()) {
- keyboard_slave_loop();
- }
-}
diff --git a/keyboards/handwired/dactyl_manuform/split_util.h b/keyboards/handwired/dactyl_manuform/split_util.h
deleted file mode 100644
index 595a0659e..000000000
--- a/keyboards/handwired/dactyl_manuform/split_util.h
+++ /dev/null
@@ -1,20 +0,0 @@
-#ifndef SPLIT_KEYBOARD_UTIL_H
-#define SPLIT_KEYBOARD_UTIL_H
-
-#include <stdbool.h>
-#include "eeconfig.h"
-
-#define SLAVE_I2C_ADDRESS 0x32
-
-extern volatile bool isLeftHand;
-
-// slave version of matix scan, defined in matrix.c
-void matrix_slave_scan(void);
-
-void split_keyboard_setup(void);
-bool has_usb(void);
-void keyboard_slave_loop(void);
-
-void matrix_master_OLED_init (void);
-
-#endif
diff --git a/keyboards/iris/keymaps/impstyle/keymap.c b/keyboards/iris/keymaps/impstyle/keymap.c
index ba49cf72c..30b4bf2d9 100644
--- a/keyboards/iris/keymaps/impstyle/keymap.c
+++ b/keyboards/iris/keymaps/impstyle/keymap.c
@@ -94,17 +94,17 @@ const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
//|----+----+----+----+----+----| |----+----+----+----+----+----|
// , , , , , , MS_WH_UP, , , , , ,
//|----+----+----+----+----+----| |----+----+----+----+----+----|
- // MS_LEFT,MS_UP,MS_DOWN,MS_RGHT,,, MS_WH_DN,MS_BT1,MS_BT2,MS_BT3, , ,
+ // ,,MS_LEFT,MS_UP,MS_DOWN,MS_RGHT,, MS_WH_DN,MS_BT1,MS_BT2,MS_BT3, , ,
//|----+----+----+----+----+----+----. ,----|----+----+----+----+----+----|
// , , , , , , , , , , ,MS_ACC0,MS_ACC1MS_ACC2
//`----+----+----+--+-+----+----+----/ \----+----+----+----+----+----+----'
// , , , , ,
// `----+----+----' `----+----+----'
[_MOUSE] = LAYOUT(
- _______,_______,_______,_______,_______,_______, _______,_______,_______,_______,_______,_______,
+ _______,_______,_______,_______,_______,_______, _______,_______,_______,_______,_______,_______,
_______,_______,_______,_______,_______,_______, KC_MS_WH_UP,_______,_______,_______,_______,_______,
- KC_MS_LEFT,KC_MS_UP,KC_MS_DOWN,KC_MS_RIGHT,_______,_______, KC_MS_WH_DOWN,KC_MS_BTN1,KC_MS_BTN2,KC_MS_BTN3,_______,_______,
- _______,_______,_______,_______,_______,_______,_______, _______,_______,_______,_______,KC_MS_ACCEL0,KC_MS_ACCEL1,KC_MS_ACCEL2,
+ _______,KC_MS_LEFT,KC_MS_UP,KC_MS_DOWN,KC_MS_RIGHT,_______, KC_MS_WH_DOWN,KC_MS_BTN1,KC_MS_BTN2,KC_MS_BTN3,_______,_______,
+ _______,_______,_______,_______,_______,_______,_______, _______,_______,_______,_______,KC_MS_ACCEL0,KC_MS_ACCEL1,KC_MS_ACCEL2,
_______,_______,_______, _______,_______,_______
),
'>3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271
# gMock Cookbook

<!-- GOOGLETEST_CM0012 DO NOT DELETE -->

You can find recipes for using gMock here. If you haven't yet, please read
[this](for_dummies.md) first to make sure you understand the basics.

**Note:** gMock lives in the `testing` name space. For readability, it is
recommended to write `using ::testing::Foo;` once in your file before using the
name `Foo` defined by gMock. We omit such `using` statements in this section for
brevity, but you should do it in your own code.

## Creating Mock Classes

Mock classes are defined as normal classes, using the `MOCK_METHOD` macro to
generate mocked methods. The macro gets 3 or 4 parameters:

```cpp
class MyMock {
 public:
  MOCK_METHOD(ReturnType, MethodName, (Args...));
  MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...));
};
```

The first 3 parameters are simply the method declaration, split into 3 parts.
The 4th parameter accepts a closed list of qualifiers, which affect the
generated method:

*   **`const`** - Makes the mocked method a `const` method. Required if
    overriding a `const` method.
*   **`override`** - Marks the method with `override`. Recommended if overriding
    a `virtual` method.
*   **`noexcept`** - Marks the method with `noexcept`. Required if overriding a
    `noexcept` method.
*   **`Calltype(...)`** - Sets the call type for the method (e.g. to
    `STDMETHODCALLTYPE`), useful in Windows.

### Dealing with unprotected commas

Unprotected commas, i.e. commas which are not surrounded by parentheses, prevent
`MOCK_METHOD` from parsing its arguments correctly:

```cpp {.bad}
class MockFoo {
 public:
  MOCK_METHOD(std::pair<bool, int>, GetPair, ());  // Won't compile!
  MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool));  // Won't compile!
};
```

Solution 1 - wrap with parentheses:

```cpp {.good}
class MockFoo {
 public:
  MOCK_METHOD((std::pair<bool, int>), GetPair, ());
  MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool));
};
```

Note that wrapping a return or argument type with parentheses is, in general,
invalid C++. `MOCK_METHOD` removes the parentheses.

Solution 2 - define an alias:

```cpp {.good}
class MockFoo {
 public:
  using BoolAndInt = std::pair<bool, int>;
  MOCK_METHOD(BoolAndInt, GetPair, ());
  using MapIntDouble = std::map<int, double>;
  MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool));
};
```

### Mocking Private or Protected Methods

You must always put a mock method definition (`MOCK_METHOD`) in a `public:`
section of the mock class, regardless of the method being mocked being `public`,
`protected`, or `private` in the base class. This allows `ON_CALL` and
`EXPECT_CALL` to reference the mock function from outside of the mock class.
(Yes, C++ allows a subclass to change the access level of a virtual function in
the base class.) Example:

```cpp
class Foo {
 public:
  ...
  virtual bool Transform(Gadget* g) = 0;

 protected:
  virtual void Resume();

 private:
  virtual int GetTimeOut();
};

class MockFoo : public Foo {
 public:
  ...
  MOCK_METHOD(bool, Transform, (Gadget* g), (override));

  // The following must be in the public section, even though the
  // methods are protected or private in the base class.
  MOCK_METHOD(void, Resume, (), (override));
  MOCK_METHOD(int, GetTimeOut, (), (override));
};
```

### Mocking Overloaded Methods

You can mock overloaded functions as usual. No special attention is required:

```cpp
class Foo {
  ...

  // Must be virtual as we'll inherit from Foo.
  virtual ~Foo();

  // Overloaded on the types and/or numbers of arguments.
  virtual int Add(Element x);
  virtual int Add(int times, Element x);

  // Overloaded on the const-ness of this object.
  virtual Bar& GetBar();
  virtual const Bar& GetBar() const;
};

class MockFoo : public Foo {
  ...
  MOCK_METHOD(int, Add, (Element x), (override));
  MOCK_METHOD(int, Add, (int times, Element x), (override));

  MOCK_METHOD(Bar&, GetBar, (), (override));
  MOCK_METHOD(const Bar&, GetBar, (), (const, override));
};
```

**Note:** if you don't mock all versions of the overloaded method, the compiler
will give you a warning about some methods in the base class being hidden. To
fix that, use `using` to bring them in scope:

```cpp
class MockFoo : public Foo {
  ...
  using Foo::Add;
  MOCK_METHOD(int, Add, (Element x), (override));
  // We don't want to mock int Add(int times, Element x);
  ...
};
```

### Mocking Class Templates

You can mock class templates just like any class.

```cpp
template <typename Elem>
class StackInterface {
  ...
  // Must be virtual as we'll inherit from StackInterface.
  virtual ~StackInterface();

  virtual int GetSize() const = 0;
  virtual void Push(const Elem& x) = 0;
};

template <typename Elem>
class MockStack : public StackInterface<Elem> {
  ...
  MOCK_METHOD(int, GetSize, (), (override));
  MOCK_METHOD(void, Push, (const Elem& x), (override));
};
```

### Mocking Non-virtual Methods {#MockingNonVirtualMethods}

gMock can mock non-virtual functions to be used in Hi-perf dependency
injection.<!-- GOOGLETEST_CM0017 DO NOT DELETE -->

In this case, instead of sharing a common base class with the real class, your
mock class will be *unrelated* to the real class, but contain methods with the
same signatures. The syntax for mocking non-virtual methods is the *same* as
mocking virtual methods (just don't add `override`):

```cpp
// A simple packet stream class.  None of its members is virtual.
class ConcretePacketStream {
 public:
  void AppendPacket(Packet* new_packet);
  const Packet* GetPacket(size_t packet_number) const;
  size_t NumberOfPackets() const;
  ...
};

// A mock packet stream class.  It inherits from no other, but defines
// GetPacket() and NumberOfPackets().
class MockPacketStream {
 public:
  MOCK_METHOD(const Packet*, GetPacket, (size_t packet_number), (const));
  MOCK_METHOD(size_t, NumberOfPackets, (), (const));
  ...
};
```

Note that the mock class doesn't define `AppendPacket()`, unlike the real class.
That's fine as long as the test doesn't need to call it.

Next, you need a way to say that you want to use `ConcretePacketStream` in
production code, and use `MockPacketStream` in tests. Since the functions are
not virtual and the two classes are unrelated, you must specify your choice at
*compile time* (as opposed to run time).

One way to do it is to templatize your code that needs to use a packet stream.
More specifically, you will give your code a template type argument for the type
of the packet stream. In production, you will instantiate your template with
`ConcretePacketStream` as the type argument. In tests, you will instantiate the
same template with `MockPacketStream`. For example, you may write:

```cpp
template <class PacketStream>
void CreateConnection(PacketStream* stream) { ... }

template <class PacketStream>
class PacketReader {
 public:
  void ReadPackets(PacketStream* stream, size_t packet_num);
};
```

Then you can use `CreateConnection<ConcretePacketStream>()` and
`PacketReader<ConcretePacketStream>` in production code, and use
`CreateConnection<MockPacketStream>()` and `PacketReader<MockPacketStream>` in
tests.

```cpp
  MockPacketStream mock_stream;
  EXPECT_CALL(mock_stream, ...)...;
  .. set more expectations on mock_stream ...
  PacketReader<MockPacketStream> reader(&mock_stream);
  ... exercise reader ...
```

### Mocking Free Functions

It's possible to use gMock to mock a free function (i.e. a C-style function or a
static method). You just need to rewrite your code to use an interface (abstract
class).

Instead of calling a free function (say, `OpenFile`) directly, introduce an
interface for it and have a concrete subclass that calls the free function:

```cpp
class FileInterface {
 public:
  ...
  virtual bool Open(const char* path, const char* mode) = 0;
};

class File : public FileInterface {
 public:
  ...
  virtual bool Open(const char* path, const char* mode) {
     return OpenFile(path, mode);
  }
};
```

Your code should talk to `FileInterface` to open a file. Now it's easy to mock
out the function.

This may seem like a lot of hassle, but in practice you often have multiple
related functions that you can put in the same interface, so the per-function
syntactic overhead will be much lower.

If you are concerned about the performance overhead incurred by virtual
functions, and profiling confirms your concern, you can combine this with the
recipe for [mocking non-virtual methods](#MockingNonVirtualMethods).

### Old-Style `MOCK_METHODn` Macros

Before the generic `MOCK_METHOD` macro was introduced, mocks where created using
a family of macros collectively called `MOCK_METHODn`. These macros are still
supported, though migration to the new `MOCK_METHOD` is recommended.

The macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`:

*   The general structure is `MOCK_METHODn(MethodName, ReturnType(Args))`,
    instead of `MOCK_METHOD(ReturnType, MethodName, (Args))`.
*   The number `n` must equal the number of arguments.
*   When mocking a const method, one must use `MOCK_CONST_METHODn`.
*   When mocking a class template, the macro name must be suffixed with `_T`.
*   In order to specify the call type, the macro name must be suffixed with
    `_WITH_CALLTYPE`, and the call type is the first macro argument.

Old macros and their new equivalents:

<a name="table99"></a>
<table border="1" cellspacing="0" cellpadding="1">
<tr> <th colspan=2> Simple </th></tr>
<tr> <td> Old </td> <td> `MOCK_METHOD1(Foo, bool(int))` </td> </tr>
<tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int))` </td> </tr>

<tr> <th colspan=2> Const Method </th></tr> <tr> <td> Old </td> <td>
`MOCK_CONST_METHOD1(Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td>
`MOCK_METHOD(bool, Foo, (int), (const))` </td> </tr>

<tr> <th colspan=2> Method in a Class Template </th></tr> <tr> <td> Old </td>
<td> `MOCK_METHOD1_T(Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td>
`MOCK_METHOD(bool, Foo, (int))` </td> </tr>

<tr> <th colspan=2> Const Method in a Class Template </th></tr> <tr> <td> Old
</td> <td> `MOCK_CONST_METHOD1_T(Foo, bool(int))` </td> </tr> <tr> <td> New
</td> <td> `MOCK_METHOD(bool, Foo, (int), (const))` </td> </tr>

<tr> <th colspan=2> Method with Call Type </th></tr> <tr> <td> Old </td> <td>
`MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))` </td> </tr> <tr>
<td> New </td> <td> `MOCK_METHOD(bool, Foo, (int),
(Calltype(STDMETHODCALLTYPE)))` </td> </tr>

<tr> <th colspan=2> Const Method with Call Type </th></tr> <tr> <td> Old</td>
<td> `MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))` </td>
</tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int), (const,
Calltype(STDMETHODCALLTYPE)))` </td> </tr>

<tr> <th colspan=2> Method with Call Type in a Class Template </th></tr> <tr>
<td> Old </td> <td> `MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo,
bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo, (int),
(Calltype(STDMETHODCALLTYPE)))` </td> </tr>

<tr> <th colspan=2> Const Method with Call Type in a Class Template </th></tr>
<tr> <td> Old </td> <td> `MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE,
Foo, bool(int))` </td> </tr> <tr> <td> New </td> <td> `MOCK_METHOD(bool, Foo,
(int), (const, Calltype(STDMETHODCALLTYPE)))` </td> </tr>

</table>

### The Nice, the Strict, and the Naggy {#NiceStrictNaggy}

If a mock method has no `EXPECT_CALL` spec but is called, we say that it's an
"uninteresting call", and the default action (which can be specified using
`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will
also by default cause gMock to print a warning. (In the future, we might remove
this warning by default.)

However, sometimes you may want to ignore these uninteresting calls, and
sometimes you may want to treat them as errors. gMock lets you make the decision
on a per-mock-object basis.

Suppose your test uses a mock class `MockFoo`:

```cpp
TEST(...) {
  MockFoo mock_foo;
  EXPECT_CALL(mock_foo, DoThis());
  ... code that uses mock_foo ...
}
```

If a method of `mock_foo` other than `DoThis()` is called, you will get a
warning. However, if you rewrite your test to use `NiceMock<MockFoo>` instead,
you can suppress the warning:

```cpp
using ::testing::NiceMock;

TEST(...) {
  NiceMock<MockFoo> mock_foo;
  EXPECT_CALL(mock_foo, DoThis());
  ... code that uses mock_foo ...
}
```

`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used wherever
`MockFoo` is accepted.

It also works if `MockFoo`'s constructor takes some arguments, as
`NiceMock<MockFoo>` "inherits" `MockFoo`'s constructors:

```cpp
using ::testing::NiceMock;

TEST(...) {
  NiceMock<MockFoo> mock_foo(5, "hi");  // Calls MockFoo(5, "hi").
  EXPECT_CALL(mock_foo, DoThis());
  ... code that uses mock_foo ...
}
```

The usage of `StrictMock` is similar, except that it makes all uninteresting
calls failures:

```cpp
using ::testing::StrictMock;

TEST(...) {
  StrictMock<MockFoo> mock_foo;
  EXPECT_CALL(mock_foo, DoThis());
  ... code that uses mock_foo ...

  // The test will fail if a method of mock_foo other than DoThis()
  // is called.
}
```

NOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of
*methods* with no expectations); they do not affect *unexpected* calls (calls of
methods with expectations, but they don't match). See
[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected).

There are some caveats though (I dislike them just as much as the next guy, but
sadly they are side effects of C++'s limitations):

1.  `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods
    defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class.
    If a mock method is defined in a **base class** of `MockFoo`, the "nice" or
    "strict" modifier may not affect it, depending on the compiler. In
    particular, nesting `NiceMock` and `StrictMock` (e.g.
    `NiceMock<StrictMock<MockFoo> >`) is **not** supported.
2.  `NiceMock<MockFoo>` and `StrictMock<MockFoo>` may not work correctly if the
    destructor of `MockFoo` is not virtual. We would like to fix this, but it
    requires cleaning up existing tests.
3.  During the constructor or destructor of `MockFoo`, the mock object is *not*
    nice or strict. This may cause surprises if the constructor or destructor
    calls a mock method on `this` object. (This behavior, however, is consistent
    with C++'s general rule: if a constructor or destructor calls a virtual
    method of `this` object, that method is treated as non-virtual. In other
    words, to the base class's constructor or destructor, `this` object behaves
    like an instance of the base class, not the derived class. This rule is
    required for safety. Otherwise a base constructor may use members of a
    derived class before they are initialized, or a base destructor may use
    members of a derived class after they have been destroyed.)

Finally, you should be **very cautious** about when to use naggy or strict
mocks, as they tend to make tests more brittle and harder to maintain. When you
refactor your code without changing its externally visible behavior, ideally you
shouldn't need to update any tests. If your code interacts with a naggy mock,
however, you may start to get spammed with warnings as the result of your
change. Worse, if your code interacts with a strict mock, your tests may start
to fail and you'll be forced to fix them. Our general recommendation is to use
nice mocks (not yet the default) most of the time, use naggy mocks (the current
default) when developing or debugging tests, and use strict mocks only as the
last resort.

### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces}

Sometimes a method has a long list of arguments that is mostly uninteresting.
For example:

```cpp
class LogSink {
 public:
  ...
  virtual void send(LogSeverity severity, const char* full_filename,
                    const char* base_filename, int line,
                    const struct tm* tm_time,
                    const char* message, size_t message_len) = 0;
};
```

This method's argument list is lengthy and hard to work with (the `message`
argument is not even 0-terminated). If we mock it as is, using the mock will be
awkward. If, however, we try to simplify this interface, we'll need to fix all
clients depending on it, which is often infeasible.

The trick is to redispatch the method in the mock class:

```cpp
class ScopedMockLog : public LogSink {
 public:
  ...
  virtual void send(LogSeverity severity, const char* full_filename,
                    const char* base_filename, int line, const tm* tm_time,
                    const char* message, size_t message_len) {
    // We are only interested in the log severity, full file name, and
    // log message.
    Log(severity, full_filename, std::string(message, message_len));
  }

  // Implements the mock method:
  //
  //   void Log(LogSeverity severity,
  //            const string& file_path,
  //            const string& message);
  MOCK_METHOD(void, Log,
              (LogSeverity severity, const string& file_path,
               const string& message));
};
```

By defining a new mock method with a trimmed argument list, we make the mock
class more user-friendly.

This technique may also be applied to make overloaded methods more amenable to
mocking. For example, when overloads have been used to implement default
arguments:

```cpp
class MockTurtleFactory : public TurtleFactory {
 public:
  Turtle* MakeTurtle(int length, int weight) override { ... }
  Turtle* MakeTurtle(int length, int weight, int speed) override { ... }

  // the above methods delegate to this one:
  MOCK_METHOD(Turtle*, DoMakeTurtle, ());
};
```

This allows tests that don't care which overload was invoked to avoid specifying
argument matchers:

```cpp
ON_CALL(factory, DoMakeTurtle)
    .WillByDefault(MakeMockTurtle());
```

### Alternative to Mocking Concrete Classes

Often you may find yourself using classes that don't implement interfaces. In
order to test your code that uses such a class (let's call it `Concrete`), you
may be tempted to make the methods of `Concrete` virtual and then mock it.

Try not to do that.

Making a non-virtual function virtual is a big decision. It creates an extension
point where subclasses can tweak your class' behavior. This weakens your control
on the class because now it's harder to maintain the class invariants. You
should make a function virtual only when there is a valid reason for a subclass
to override it.

Mocking concrete classes directly is problematic as it creates a tight coupling
between the class and the tests - any small change in the class may invalidate
your tests and make test maintenance a pain.

To avoid such problems, many programmers have been practicing "coding to
interfaces": instead of talking to the `Concrete` class, your code would define
an interface and talk to it. Then you implement that interface as an adaptor on
top of `Concrete`. In tests, you can easily mock that interface to observe how
your code is doing.

This technique incurs some overhead:

*   You pay the cost of virtual function calls (usually not a problem).
*   There is more abstraction for the programmers to learn.

However, it can also bring significant benefits in addition to better
testability:

*   `Concrete`'s API may not fit your problem domain very well, as you may not
    be the only client it tries to serve. By designing your own interface, you
    have a chance to tailor it to your need - you may add higher-level
    functionalities, rename stuff, etc instead of just trimming the class. This
    allows you to write your code (user of the interface) in a more natural way,
    which means it will be more readable, more maintainable, and you'll be more
    productive.
*   If `Concrete`'s implementation ever has to change, you don't have to rewrite
    everywhere it is used. Instead, you can absorb the change in your
    implementation of the interface, and your other code and tests will be
    insulated from this change.

Some people worry that if everyone is practicing this technique, they will end
up writing lots of redundant code. This concern is totally understandable.
However, there are two reasons why it may not be the case:

*   Different projects may need to use `Concrete` in different ways, so the best
    interfaces for them will be different. Therefore, each of them will have its
    own domain-specific interface on top of `Concrete`, and they will not be the
    same code.
*   If enough projects want to use the same interface, they can always share it,
    just like they have been sharing `Concrete`. You can check in the interface
    and the adaptor somewhere near `Concrete` (perhaps in a `contrib`
    sub-directory) and let many projects use it.

You need to weigh the pros and cons carefully for your particular problem, but
I'd like to assure you that the Java community has been practicing this for a
long time and it's a proven effective technique applicable in a wide variety of
situations. :-)

### Delegating Calls to a Fake {#DelegatingToFake}

Some times you have a non-trivial fake implementation of an interface. For
example:

```cpp
class Foo {
 public:
  virtual ~Foo() {}
  virtual char DoThis(int n) = 0;
  virtual void DoThat(const char* s, int* p) = 0;
};

class FakeFoo : public Foo {
 public:
  char DoThis(int n) override {
    return (n > 0) ? '+' :
           (n < 0) ? '-' : '0';
  }

  void DoThat(const char* s, int* p) override {
    *p = strlen(s);
  }
};
```

Now you want to mock this interface such that you can set expectations on it.
However, you also want to use `FakeFoo` for the default behavior, as duplicating
it in the mock object is, well, a lot of work.

When you define the mock class using gMock, you can have it delegate its default
action to a fake class you already have, using this pattern:

```cpp
class MockFoo : public Foo {
 public:
  // Normal mock method definitions using gMock.
  MOCK_METHOD(char, DoThis, (int n), (override));
  MOCK_METHOD(void, DoThat, (const char* s, int* p), (override));

  // Delegates the default actions of the methods to a FakeFoo object.
  // This must be called *before* the custom ON_CALL() statements.
  void DelegateToFake() {
    ON_CALL(*this, DoThis).WillByDefault([this](int n) {
      return fake_.DoThis(n);
    });
    ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) {
      fake_.DoThat(s, p);
    });
  }

 private:
  FakeFoo fake_;  // Keeps an instance of the fake in the mock.
};
```

With that, you can use `MockFoo` in your tests as usual. Just remember that if
you don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the
fake will be called upon to do it.:

```cpp
using ::testing::_;

TEST(AbcTest, Xyz) {
  MockFoo foo;

  foo.DelegateToFake();  // Enables the fake for delegation.

  // Put your ON_CALL(foo, ...)s here, if any.

  // No action specified, meaning to use the default action.
  EXPECT_CALL(foo, DoThis(5));
  EXPECT_CALL(foo, DoThat(_, _));

  int n = 0;
  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.
  foo.DoThat("Hi", &n);  // FakeFoo::DoThat() is invoked.
  EXPECT_EQ(2, n);
}
```

**Some tips:**

*   If you want, you can still override the default action by providing your own
    `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.
*   In `DelegateToFake()`, you only need to delegate the methods whose fake
    implementation you intend to use.

*   The general technique discussed here works for overloaded methods, but
    you'll need to tell the compiler which version you mean. To disambiguate a
    mock function (the one you specify inside the parentheses of `ON_CALL()`),
    use [this technique](#SelectOverload); to disambiguate a fake function (the
    one you place inside `Invoke()`), use a `static_cast` to specify the
    function's type. For instance, if class `Foo` has methods `char DoThis(int
    n)` and `bool DoThis(double x) const`, and you want to invoke the latter,
    you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double)
    const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)`
    (The strange-looking thing inside the angled brackets of `static_cast` is
    the type of a function pointer to the second `DoThis()` method.).

*   Having to mix a mock and a fake is often a sign of something gone wrong.
    Perhaps you haven't got used to the interaction-based way of testing yet. Or
    perhaps your interface is taking on too many roles and should be split up.
    Therefore, **don't abuse this**. We would only recommend to do it as an
    intermediate step when you are refactoring your code.

Regarding the tip on mixing a mock and a fake, here's an example on why it may
be a bad sign: Suppose you have a class `System` for low-level system
operations. In particular, it does file and I/O operations. And suppose you want
to test how your code uses `System` to do I/O, and you just want the file
operations to work normally. If you mock out the entire `System` class, you'll
have to provide a fake implementation for the file operation part, which
suggests that `System` is taking on too many roles.

Instead, you can define a `FileOps` interface and an `IOOps` interface and split
`System`'s functionalities into the two. Then you can mock `IOOps` without
mocking `FileOps`.

### Delegating Calls to a Real Object

When using testing doubles (mocks, fakes, stubs, and etc), sometimes their
behaviors will differ from those of the real objects. This difference could be
either intentional (as in simulating an error such that you can test the error
handling code) or unintentional. If your mocks have different behaviors than the
real objects by mistake, you could end up with code that passes the tests but
fails in production.

You can use the *delegating-to-real* technique to ensure that your mock has the
same behavior as the real object while retaining the ability to validate calls.
This technique is very similar to the [delegating-to-fake](#DelegatingToFake)
technique, the difference being that we use a real object instead of a fake.
Here's an example:

```cpp
using ::testing::AtLeast;

class MockFoo : public Foo {
 public:
  MockFoo() {
    // By default, all calls are delegated to the real object.
    ON_CALL(*this, DoThis).WillByDefault([this](int n) {
      return real_.DoThis(n);
    });
    ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) {
      real_.DoThat(s, p);
    });
    ...
  }
  MOCK_METHOD(char, DoThis, ...);
  MOCK_METHOD(void, DoThat, ...);
  ...
 private:
  Foo real_;
};

...
  MockFoo mock;
  EXPECT_CALL(mock, DoThis())
      .Times(3);
  EXPECT_CALL(mock, DoThat("Hi"))
      .Times(AtLeast(1));
  ... use mock in test ...
```

With this, gMock will verify that your code made the right calls (with the right
arguments, in the right order, called the right number of times, etc), and a
real object will answer the calls (so the behavior will be the same as in
production). This gives you the best of both worlds.

### Delegating Calls to a Parent Class

Ideally, you should code to interfaces, whose methods are all pure virtual. In
reality, sometimes you do need to mock a virtual method that is not pure (i.e,
it already has an implementation). For example:

```cpp
class Foo {
 public:
  virtual ~Foo();

  virtual void Pure(int n) = 0;
  virtual int Concrete(const char* str) { ... }
};

class MockFoo : public Foo {
 public:
  // Mocking a pure method.
  MOCK_METHOD(void, Pure, (int n), (override));
  // Mocking a concrete method.  Foo::Concrete() is shadowed.
  MOCK_METHOD(int, Concrete, (const char* str), (override));
};
```

Sometimes you may want to call `Foo::Concrete()` instead of
`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub action, or
perhaps your test doesn't need to mock `Concrete()` at all (but it would be
oh-so painful to have to define a new mock class whenever you don't need to mock
one of its methods).

The trick is to leave a back door in your mock class for accessing the real
methods in the base class:

```cpp
class MockFoo : public Foo {
 public:
  // Mocking a pure method.
  MOCK_METHOD(void, Pure, (int n), (override));
  // Mocking a concrete method.  Foo::Concrete() is shadowed.
  MOCK_METHOD(int, Concrete, (const char* str), (override));

  // Use this to call Concrete() defined in Foo.
  int FooConcrete(const char* str) { return Foo::Concrete(str); }
};
```

Now, you can call `Foo::Concrete()` inside an action by:

```cpp
...
  EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) {
    return foo.FooConcrete(str);
  });
```

or tell the mock object that you don't want to mock `Concrete()`:

```cpp
...
  ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) {
    return foo.FooConcrete(str);
  });
```

(Why don't we just write `{ return foo.Concrete(str); }`? If you do that,
`MockFoo::Concrete()` will be called (and cause an infinite recursion) since
`Foo::Concrete()` is virtual. That's just how C++ works.)

## Using Matchers

### Matching Argument Values Exactly

You can specify exactly which arguments a mock method is expecting:

```cpp
using ::testing::Return;
...
  EXPECT_CALL(foo, DoThis(5))
      .WillOnce(Return('a'));
  EXPECT_CALL(foo, DoThat("Hello", bar));
```

### Using Simple Matchers

You can use matchers to match arguments that have a certain property:

```cpp
using ::testing::NotNull;
using ::testing::Return;
...
  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.
      .WillOnce(Return('a'));
  EXPECT_CALL(foo, DoThat("Hello", NotNull()));
      // The second argument must not be NULL.
```

A frequently used matcher is `_`, which matches anything:

```cpp
  EXPECT_CALL(foo, DoThat(_, NotNull()));
```
<!-- GOOGLETEST_CM0022 DO NOT DELETE -->

### Combining Matchers {#CombiningMatchers}

You can build complex matchers from existing ones using `AllOf()`,
`AllOfArray()`, `AnyOf()`, `AnyOfArray()` and `Not()`:

```cpp
using ::testing::AllOf;
using ::testing::Gt;
using ::testing::HasSubstr;
using ::testing::Ne;
using ::testing::Not;
...
  // The argument must be > 5 and != 10.
  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
                                Ne(10))));

  // The first argument must not contain sub-string "blah".
  EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
                          NULL));
```

### Casting Matchers {#SafeMatcherCast}

gMock matchers are statically typed, meaning that the compiler can catch your
mistake if you use a matcher of the wrong type (for example, if you use `Eq(5)`
to match a `string` argument). Good for you!

Sometimes, however, you know what you're doing and want the compiler to give you
some slack. One example is that you have a matcher for `long` and the argument
you want to match is `int`. While the two types aren't exactly the same, there
is nothing really wrong with using a `Matcher<long>` to match an `int` - after
all, we can first convert the `int` argument to a `long` losslessly before
giving it to the matcher.

To support this need, gMock gives you the `SafeMatcherCast<T>(m)` function. It
casts a matcher `m` to type `Matcher<T>`. To ensure safety, gMock checks that
(let `U` be the type `m` accepts :

1.  Type `T` can be *implicitly* cast to type `U`;
2.  When both `T` and `U` are built-in arithmetic types (`bool`, integers, and
    floating-point numbers), the conversion from `T` to `U` is not lossy (in
    other words, any value representable by `T` can also be represented by `U`);
    and
3.  When `U` is a reference, `T` must also be a reference (as the underlying
    matcher may be interested in the address of the `U` value).

The code won't compile if any of these conditions isn't met.

Here's one example:

```cpp
using ::testing::SafeMatcherCast;

// A base class and a child class.
class Base { ... };
class Derived : public Base { ... };

class MockFoo : public Foo {
 public:
  MOCK_METHOD(void, DoThis, (Derived* derived), (override));
};

...
  MockFoo foo;
  // m is a Matcher<Base*> we got from somewhere.
  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
```

If you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar function
`MatcherCast<T>(m)`. The difference is that `MatcherCast` works as long as you
can `static_cast` type `T` to type `U`.

`MatcherCast` essentially lets you bypass C++'s type system (`static_cast` isn't
always safe as it could throw away information, for example), so be careful not
to misuse/abuse it.

### Selecting Between Overloaded Functions {#SelectOverload}

If you expect an overloaded function to be called, the compiler may need some
help on which overloaded version it is.

To disambiguate functions overloaded on the const-ness of this object, use the
`Const()` argument wrapper.

```cpp
using ::testing::ReturnRef;

class MockFoo : public Foo {
  ...
  MOCK_METHOD(Bar&, GetBar, (), (override));
  MOCK_METHOD(const Bar&, GetBar, (), (const, override));
};

...
  MockFoo foo;
  Bar bar1, bar2;
  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().
      .WillOnce(ReturnRef(bar1));
  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().
      .WillOnce(ReturnRef(bar2));
```

(`Const()` is defined by gMock and returns a `const` reference to its argument.)

To disambiguate overloaded functions with the same number of arguments but
different argument types, you may need to specify the exact type of a matcher,
either by wrapping your matcher in `Matcher<type>()`, or using a matcher whose
type is fixed (`TypedEq<type>`, `An<type>()`, etc):

```cpp
using ::testing::An;
using ::testing::Matcher;
using ::testing::TypedEq;

class MockPrinter : public Printer {
 public:
  MOCK_METHOD(void, Print, (int n), (override));
  MOCK_METHOD(void, Print, (char c), (override));
};

TEST(PrinterTest, Print) {
  MockPrinter printer;

  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);
  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);
  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);

  printer.Print(3);
  printer.Print(6);
  printer.Print('a');
}
```

### Performing Different Actions Based on the Arguments

When a mock method is called, the *last* matching expectation that's still
active will be selected (think "newer overrides older"). So, you can make a
method do different things depending on its argument values like this:

```cpp
using ::testing::_;
using ::testing::Lt;
using ::testing::Return;
...
  // The default case.
  EXPECT_CALL(foo, DoThis(_))
      .WillRepeatedly(Return('b'));
  // The more specific case.
  EXPECT_CALL(foo, DoThis(Lt(5)))
      .WillRepeatedly(Return('a'));
```

Now, if `foo.DoThis()` is called with a value less than 5, `'a'` will be
returned; otherwise `'b'` will be returned.

### Matching Multiple Arguments as a Whole

Sometimes it's not enough to match the arguments individually. For example, we
may want to say that the first argument must be less than the second argument.
The `With()` clause allows us to match all arguments of a mock function as a
whole. For example,

```cpp
using ::testing::_;
using ::testing::Ne;
using ::testing::Lt;
...
  EXPECT_CALL(foo, InRange(Ne(0), _))
      .With(Lt());
```

says that the first argument of `InRange()` must not be 0, and must be less than
the second argument.

The expression inside `With()` must be a matcher of type `Matcher<std::tuple<A1,
..., An>>`, where `A1`, ..., `An` are the types of the function arguments.

You can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms
are equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`.

You can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments (as a
tuple) against `m`. For example,

```cpp
using ::testing::_;
using ::testing::AllOf;
using ::testing::Args;
using ::testing::Lt;
...
  EXPECT_CALL(foo, Blah)
      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
```

says that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y <
z`. Note that in this example, it wasn't necessary specify the positional
matchers.

As a convenience and example, gMock provides some matchers for 2-tuples,
including the `Lt()` matcher above. See [here](#MultiArgMatchers) for the
complete list.

Note that if you want to pass the arguments to a predicate of your own (e.g.
`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to
take a `std::tuple` as its argument; gMock will pass the `n` selected arguments
as *one* single tuple to the predicate.

### Using Matchers as Predicates

Have you noticed that a matcher is just a fancy predicate that also knows how to
describe itself? Many existing algorithms take predicates as arguments (e.g.
those defined in STL's `<algorithm>` header), and it would be a shame if gMock
matchers were not allowed to participate.

Luckily, you can use a matcher where a unary predicate functor is expected by
wrapping it inside the `Matches()` function. For example,

```cpp
#include <algorithm>
#include <vector>

using ::testing::Matches;
using ::testing::Ge;

vector<int> v;
...
// How many elements in v are >= 10?
const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
```

Since you can build complex matchers from simpler ones easily using gMock, this
gives you a way to conveniently construct composite predicates (doing the same
using STL's `<functional>` header is just painful). For example, here's a
predicate that's satisfied by any number that is >= 0, <= 100, and != 50:

```cpp
using testing::AllOf;
using testing::Ge;
using testing::Le;
using testing::Matches;
using testing::Ne;
...
Matches(AllOf(Ge(0), Le(100), Ne(50)))
```

### Using Matchers in googletest Assertions

Since matchers are basically predicates that also know how to describe
themselves, there is a way to take advantage of them in googletest assertions.
It's called `ASSERT_THAT` and `EXPECT_THAT`:

```cpp
  ASSERT_THAT(value, matcher);  // Asserts that value matches matcher.
  EXPECT_THAT(value, matcher);  // The non-fatal version.
```

For example, in a googletest test you can write:

```cpp
#include "gmock/gmock.h"

using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
using ::testing::MatchesRegex;
using ::testing::StartsWith;

...
  EXPECT_THAT(Foo(), StartsWith("Hello"));
  EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
  ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
```

which (as you can probably guess) executes `Foo()`, `Bar()`, and `Baz()`, and
verifies that:

*   `Foo()` returns a string that starts with `"Hello"`.
*   `Bar()` returns a string that matches regular expression `"Line \\d+"`.
*   `Baz()` returns a number in the range [5, 10].

The nice thing about these macros is that *they read like English*. They
generate informative messages too. For example, if the first `EXPECT_THAT()`
above fails, the message will be something like:

```cpp
Value of: Foo()
  Actual: "Hi, world!"
Expected: starts with "Hello"
```

**Credit:** The idea of `(ASSERT|EXPECT)_THAT` was borrowed from Joe Walnes'
Hamcrest project, which adds `assertThat()` to JUnit.

### Using Predicates as Matchers

gMock provides a [built-in set](#MatcherList) of matchers. In case you find them
lacking, you can use an arbitrary unary predicate function or functor as a
matcher - as long as the predicate accepts a value of the type you want. You do
this by wrapping the predicate inside the `Truly()` function, for example:

```cpp
using ::testing::Truly;

int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
...
  // Bar() must be called with an even number.
  EXPECT_CALL(foo, Bar(Truly(IsEven)));
```

Note that the predicate function / functor doesn't have to return `bool`. It
works as long as the return value can be used as the condition in in statement
`if (condition) ...`.

<!-- GOOGLETEST_CM0023 DO NOT DELETE -->

### Matching Arguments that Are Not Copyable

When you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of
`bar`. When `Foo()` is called later, gMock compares the argument to `Foo()` with
the saved copy of `bar`. This way, you don't need to worry about `bar` being
modified or destroyed after the `EXPECT_CALL()` is executed. The same is true
when you use matchers like `Eq(bar)`, `Le(bar)`, and so on.

But what if `bar` cannot be copied (i.e. has no copy constructor)? You could
define your own matcher function or callback and use it with `Truly()`, as the
previous couple of recipes have shown. Or, you may be able to get away from it
if you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is
executed. Just tell gMock that it should save a reference to `bar`, instead of a
copy of it. Here's how:

```cpp
using ::testing::ByRef;
using ::testing::Eq;
using ::testing::Lt;
...
  // Expects that Foo()'s argument == bar.
  EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));

  // Expects that Foo()'s argument < bar.
  EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
```

Remember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the
result is undefined.

### Validating a Member of an Object

Often a mock function takes a reference to object as an argument. When matching
the argument, you may not want to compare the entire object against a fixed
object, as that may be over-specification. Instead, you may need to validate a
certain member variable or the result of a certain getter method of the object.
You can do this with `Field()` and `Property()`. More specifically,

```cpp
Field(&Foo::bar, m)
```

is a matcher that matches a `Foo` object whose `bar` member variable satisfies
matcher `m`.

```cpp
Property(&Foo::baz, m)
```

is a matcher that matches a `Foo` object whose `baz()` method returns a value
that satisfies matcher `m`.

For example:

<!-- mdformat off(github rendering does not support multiline tables) -->
| Expression                   | Description                              |
| :--------------------------- | :--------------------------------------- |
| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`.       |
| `Property(&Foo::name,  StartsWith("John "))` | Matches `x` where `x.name()` starts with  `"John "`. |
<!-- mdformat on -->

Note that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument
and be declared as `const`.

BTW, `Field()` and `Property()` can also match plain pointers to objects. For
instance,

```cpp
using ::testing::Field;
using ::testing::Ge;
...
Field(&Foo::number, Ge(3))
```

matches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, the match
will always fail regardless of the inner matcher.

What if you want to validate more than one members at the same time? Remember
that there are [`AllOf()` and `AllOfArray()`](#CombiningMatchers).

Finally `Field()` and `Property()` provide overloads that take the field or
property names as the first argument to include it in the error message. This
can be useful when creating combined matchers.

```cpp
using ::testing::AllOf;
using ::testing::Field;
using ::testing::Matcher;
using ::testing::SafeMatcherCast;

Matcher<Foo> IsFoo(const Foo& foo) {
  return AllOf(Field("some_field", &Foo::some_field, foo.some_field),
               Field("other_field", &Foo::other_field, foo.other_field),
               Field("last_field", &Foo::last_field, foo.last_field));
}
```

### Validating the Value Pointed to by a Pointer Argument

C++ functions often take pointers as arguments. You can use matchers like
`IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but
what if you want to make sure the value *pointed to* by the pointer, instead of
the pointer itself, has a certain property? Well, you can use the `Pointee(m)`
matcher.

`Pointee(m)` matches a pointer if and only if `m` matches the value the pointer
points to. For example:

```cpp
using ::testing::Ge;
using ::testing::Pointee;
...
  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
```

expects `foo.Bar()` to be called with a pointer that points to a value greater
than or equal to 3.

One nice thing about `Pointee()` is that it treats a `NULL` pointer as a match
failure, so you can write `Pointee(m)` instead of

```cpp
using ::testing::AllOf;
using ::testing::NotNull;
using ::testing::Pointee;
...
  AllOf(NotNull(), Pointee(m))
```

without worrying that a `NULL` pointer will crash your test.

Also, did we tell you that `Pointee()` works with both raw pointers **and**
smart pointers (`std::unique_ptr`, `std::shared_ptr`, etc)?

What if you have a pointer to pointer? You guessed it - you can use nested
`Pointee()` to probe deeper inside the value. For example,
`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points
to a number less than 3 (what a mouthful...).

### Testing a Certain Property of an Object

Sometimes you want to specify that an object argument has a certain property,
but there is no existing matcher that does this. If you want good error
messages, you should [define a matcher](#NewMatchers). If you want to do it
quick and dirty, you could get away with writing an ordinary function.

Let's say you have a mock function that takes an object of type `Foo`, which has
an `int bar()` method and an `int baz()` method, and you want to constrain that
the argument's `bar()` value plus its `baz()` value is a given number. Here's
how you can define a matcher to do it:

```cpp
using ::testing::Matcher;
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;

class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
 public:
  explicit BarPlusBazEqMatcher(int expected_sum)
      : expected_sum_(expected_sum) {}

  bool MatchAndExplain(const Foo& foo,
                       MatchResultListener* /* listener */) const override {
    return (foo.bar() + foo.baz()) == expected_sum_;
  }

  void DescribeTo(std::ostream* os) const override {
    *os << "bar() + baz() equals " << expected_sum_;
  }

  void DescribeNegationTo(std::ostream* os) const override {
    *os << "bar() + baz() does not equal " << expected_sum_;
  }
 private:
  const int expected_sum_;
};

Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
  return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
}

...
  EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
```

### Matching Containers

Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock
function and you may want to validate it. Since most STL containers support the
`==` operator, you can write `Eq(expected_container)` or simply
`expected_container` to match a container exactly.

Sometimes, though, you may want to be more flexible (for example, the first
element must be an exact match, but the second element can be any positive
number, and so on). Also, containers used in tests often have a small number of
elements, and having to define the expected container out-of-line is a bit of a
hassle.

You can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such
cases:

```cpp
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::Gt;
...
  MOCK_METHOD(void, Foo, (const vector<int>& numbers), (override));
...
  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
```

The above matcher says that the container must have 4 elements, which must be 1,
greater than 0, anything, and 5 respectively.

If you instead write:

```cpp
using ::testing::_;
using ::testing::Gt;
using ::testing::UnorderedElementsAre;
...
  MOCK_METHOD(void, Foo, (const vector<int>& numbers), (override));
...
  EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5)));
```

It means that the container must have 4 elements, which (under some permutation)
must be 1, greater than 0, anything, and 5 respectively.

As an alternative you can place the arguments in a C-style array and use
`ElementsAreArray()` or `UnorderedElementsAreArray()` instead:

```cpp
using ::testing::ElementsAreArray;
...
  // ElementsAreArray accepts an array of element values.
  const int expected_vector1[] = {1, 5, 2, 4, ...};
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));

  // Or, an array of element matchers.
  Matcher<int> expected_vector2[] = {1, Gt(2), _, 3, ...};
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
```

In case the array needs to be dynamically created (and therefore the array size
cannot be inferred by the compiler), you can give `ElementsAreArray()` an
additional argument to specify the array size:

```cpp
using ::testing::ElementsAreArray;
...
  int* const expected_vector3 = new int[count];
  ... fill expected_vector3 with values ...
  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
```

Use `Pair` when comparing maps or other associative containers.

```cpp
using testing::ElementsAre;
using testing::Pair;
...
  std::map<string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}};