Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

macro.c 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. /* Copyright (C) 2014 by Jacob Alexander
  2. *
  3. * This file is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This file is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this file. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. // ----- Includes -----
  17. // Compiler Includes
  18. #include <Lib/MacroLib.h>
  19. // Project Includes
  20. #include <cli.h>
  21. #include <led.h>
  22. #include <print.h>
  23. #include <scan_loop.h>
  24. // Keymaps
  25. #include "usb_hid.h"
  26. #include <defaultMap.h>
  27. #include "generatedKeymap.h" // TODO Use actual generated version
  28. // Local Includes
  29. #include "macro.h"
  30. // ----- Function Declarations -----
  31. void cliFunc_capList ( char* args );
  32. void cliFunc_capSelect ( char* args );
  33. void cliFunc_keyPress ( char* args );
  34. void cliFunc_keyRelease( char* args );
  35. void cliFunc_layerList ( char* args );
  36. void cliFunc_layerState( char* args );
  37. void cliFunc_macroDebug( char* args );
  38. void cliFunc_macroList ( char* args );
  39. void cliFunc_macroProc ( char* args );
  40. void cliFunc_macroShow ( char* args );
  41. void cliFunc_macroStep ( char* args );
  42. // ----- Enums -----
  43. // Bit positions are important, passes (correct key) always trump incorrect key votes
  44. typedef enum TriggerMacroVote {
  45. TriggerMacroVote_Release = 0x8, // Correct key
  46. TriggerMacroVote_PassRelease = 0xC, // Correct key (both pass and release)
  47. TriggerMacroVote_Pass = 0x4, // Correct key
  48. TriggerMacroVote_DoNothing = 0x2, // Incorrect key
  49. TriggerMacroVote_Fail = 0x1, // Incorrect key
  50. TriggerMacroVote_Invalid = 0x0, // Invalid state
  51. } TriggerMacroVote;
  52. typedef enum TriggerMacroEval {
  53. TriggerMacroEval_DoNothing,
  54. TriggerMacroEval_DoResult,
  55. TriggerMacroEval_DoResultAndRemove,
  56. TriggerMacroEval_Remove,
  57. } TriggerMacroEval;
  58. typedef enum ResultMacroEval {
  59. ResultMacroEval_DoNothing,
  60. ResultMacroEval_Remove,
  61. } ResultMacroEval;
  62. // ----- Variables -----
  63. // Macro Module command dictionary
  64. char* macroCLIDictName = "Macro Module Commands";
  65. CLIDictItem macroCLIDict[] = {
  66. { "capList", "Prints an indexed list of all non USB keycode capabilities.", cliFunc_capList },
  67. { "capSelect", "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B", cliFunc_capSelect },
  68. { "keyPress", "Send key-presses to the macro module. Held until released. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyPress },
  69. { "keyRelease", "Release a key-press from the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyRelease },
  70. { "layerList", "List available layers.", cliFunc_layerList },
  71. { "layerState", "Modify specified indexed layer state <layer> <state byte>." NL "\t\t\033[35mL2\033[0m Indexed Layer 0x02" NL "\t\t0 Off, 1 Shift, 2 Latch, 4 Lock States", cliFunc_layerState },
  72. { "macroDebug", "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes.", cliFunc_macroDebug },
  73. { "macroList", "List the defined trigger and result macros.", cliFunc_macroList },
  74. { "macroProc", "Pause/Resume macro processing.", cliFunc_macroProc },
  75. { "macroShow", "Show the macro corresponding to the given index." NL "\t\t\033[35mT16\033[0m Indexed Trigger Macro 0x10, \033[35mR12\033[0m Indexed Result Macro 0x0C", cliFunc_macroShow },
  76. { "macroStep", "Do N macro processing steps. Defaults to 1.", cliFunc_macroStep },
  77. { 0, 0, 0 } // Null entry for dictionary end
  78. };
  79. // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
  80. uint8_t macroDebugMode = 0;
  81. // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
  82. uint8_t macroPauseMode = 0;
  83. // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
  84. unsigned int macroStepCounter = 0;
  85. // Key Trigger List Buffer
  86. TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
  87. uint8_t macroTriggerListBufferSize = 0;
  88. // Pending Trigger Macro Index List
  89. // * Any trigger macros that need processing from a previous macro processing loop
  90. // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
  91. // Possibly could be calculated by the KLL compiler
  92. // XXX It may be possible to calculate the worst case using the KLL compiler
  93. unsigned int macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
  94. unsigned int macroTriggerMacroPendingListSize = 0;
  95. // Layer Index Stack
  96. // * When modifying layer state and the state is non-0x0, the stack must be adjusted
  97. unsigned int macroLayerIndexStack[ LayerNum ] = { 0 };
  98. unsigned int macroLayerIndexStackSize = 0;
  99. // Pending Result Macro Index List
  100. // * Any result macro that needs processing from a previous macro processing loop
  101. unsigned int macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
  102. unsigned int macroResultMacroPendingListSize = 0;
  103. // ----- Capabilities -----
  104. // Modifies the specified Layer control byte
  105. // Argument #1: Layer Index -> unsigned int
  106. // Argument #2: Toggle byte -> uint8_t
  107. void Macro_layerStateToggle_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  108. {
  109. // Display capability name
  110. if ( stateType == 0xFF && state == 0xFF )
  111. {
  112. print("Macro_layerState(layerIndex,toggleByte)");
  113. return;
  114. }
  115. // Get layer index from arguments
  116. unsigned int layer = (unsigned int)(&args[0]);
  117. // Get layer toggle byte
  118. uint8_t toggleByte = args[ sizeof(unsigned int) ];
  119. // Is layer in the LayerIndexStack?
  120. uint8_t inLayerIndexStack = 0;
  121. unsigned int stackItem = 0;
  122. while ( stackItem < macroLayerIndexStackSize )
  123. {
  124. // Flag if layer is already in the LayerIndexStack
  125. if ( macroLayerIndexStack[ stackItem ] == layer )
  126. {
  127. inLayerIndexStack = 1;
  128. break;
  129. }
  130. // Increment to next item
  131. stackItem++;
  132. }
  133. // Toggle Layer State Byte
  134. if ( LayerIndex[ layer ].state & toggleByte )
  135. {
  136. // Unset
  137. LayerIndex[ layer ].state &= ~toggleByte;
  138. }
  139. else
  140. {
  141. // Set
  142. LayerIndex[ layer ].state |= toggleByte;
  143. }
  144. // If the layer was not in the LayerIndexStack add it
  145. if ( !inLayerIndexStack )
  146. {
  147. macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
  148. }
  149. // If the layer is in the LayerIndexStack and the state is 0x00, remove
  150. if ( LayerIndex[ layer ].state == 0x00 && inLayerIndexStack )
  151. {
  152. // Remove the layer from the LayerIndexStack
  153. // Using the already positioned stackItem variable from the loop above
  154. while ( stackItem < macroLayerIndexStackSize )
  155. {
  156. macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
  157. stackItem++;
  158. }
  159. // Reduce LayerIndexStack size
  160. macroLayerIndexStackSize--;
  161. }
  162. }
  163. // ----- Functions -----
  164. // Looks up the trigger list for the given scan code (from the active layer)
  165. // NOTE: Calling function must handle the NULL pointer case
  166. unsigned int *Macro_layerLookup( uint8_t scanCode )
  167. {
  168. // If no trigger macro is defined at the given layer, fallthrough to the next layer
  169. for ( unsigned int layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
  170. {
  171. // Lookup Layer
  172. Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
  173. // Check if latch has been pressed for this layer
  174. // XXX Regardless of whether a key is found, the latch is removed on first lookup
  175. uint8_t latch = layer->state & 0x02;
  176. if ( latch )
  177. {
  178. layer->state &= ~0x02;
  179. }
  180. // Only use layer, if state is valid
  181. // XOR each of the state bits
  182. // If only two are enabled, do not use this state
  183. if ( (layer->state & 0x01) ^ (latch>>1) ^ ((layer->state & 0x04)>>2) )
  184. {
  185. // Lookup layer
  186. unsigned int **map = layer->triggerMap;
  187. // Determine if layer has key defined
  188. if ( map != 0 && *map[ scanCode ] != 0 )
  189. return map[ scanCode ];
  190. }
  191. }
  192. // Do lookup on default layer
  193. unsigned int **map = LayerIndex[0].triggerMap;
  194. // Determine if layer has key defined
  195. if ( map == 0 && *map[ scanCode ] == 0 )
  196. {
  197. erro_msg("Scan Code has no defined Trigger Macro: ");
  198. printHex( scanCode );
  199. return 0;
  200. }
  201. // Return lookup result
  202. return map[ scanCode ];
  203. }
  204. // Update the scancode key state
  205. // States:
  206. // * 0x00 - Off
  207. // * 0x01 - Pressed
  208. // * 0x02 - Held
  209. // * 0x03 - Released
  210. // * 0x04 - Unpressed (this is currently ignored)
  211. inline void Macro_keyState( uint8_t scanCode, uint8_t state )
  212. {
  213. // Only add to macro trigger list if one of three states
  214. switch ( state )
  215. {
  216. case 0x01: // Pressed
  217. case 0x02: // Held
  218. case 0x03: // Released
  219. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  220. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  221. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
  222. macroTriggerListBufferSize++;
  223. break;
  224. }
  225. }
  226. // Update the scancode analog state
  227. // States:
  228. // * 0x00 - Off
  229. // * 0x01 - Released
  230. // * 0x02-0xFF - Analog value (low to high)
  231. inline void Macro_analogState( uint8_t scanCode, uint8_t state )
  232. {
  233. // Only add to macro trigger list if non-off
  234. if ( state != 0x00 )
  235. {
  236. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  237. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  238. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
  239. macroTriggerListBufferSize++;
  240. }
  241. }
  242. // Update led state
  243. // States:
  244. // * 0x00 - Off
  245. // * 0x01 - On
  246. inline void Macro_ledState( uint8_t ledCode, uint8_t state )
  247. {
  248. // Only add to macro trigger list if non-off
  249. if ( state != 0x00 )
  250. {
  251. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
  252. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  253. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
  254. macroTriggerListBufferSize++;
  255. }
  256. }
  257. // Append result macro to pending list, checking for duplicates
  258. // Do nothing if duplicate
  259. inline void Macro_appendResultMacroToPendingList( unsigned int resultMacroIndex )
  260. {
  261. // Iterate through result macro pending list, making sure this macro hasn't been added yet
  262. for ( unsigned int macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  263. {
  264. // If duplicate found, do nothing
  265. if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
  266. return;
  267. }
  268. // No duplicates found, add to pending list
  269. macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
  270. }
  271. // Determine if long ResultMacro (more than 1 seqence element)
  272. inline uint8_t Macro_isLongResultMacro( ResultMacro *macro )
  273. {
  274. // Check the second sequence combo length
  275. // If non-zero return 1 (long sequence)
  276. // 0 otherwise (short sequence)
  277. return macro->guide[ macro->guide[0] * ResultGuideSize( (ResultGuide*)macro->guide ) ] > 0 ? 1 : 0;
  278. }
  279. // Votes on the given key vs. guide
  280. inline TriggerMacroVote Macro_evalTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
  281. {
  282. // Depending on key type
  283. switch ( guide->type )
  284. {
  285. // Normal State Type
  286. case 0x00:
  287. // Depending on the state of the buffered key, make voting decision
  288. // Incorrect key
  289. if ( guide->scanCode != key->scanCode )
  290. {
  291. switch ( key->state )
  292. {
  293. // Wrong key, pressed, fail
  294. case 0x01:
  295. return TriggerMacroVote_Fail;
  296. // Wrong key, held or released, do not pass (no effect)
  297. case 0x02:
  298. case 0x03:
  299. return TriggerMacroVote_DoNothing;
  300. }
  301. }
  302. // Correct key
  303. else
  304. {
  305. switch ( key->state )
  306. {
  307. // Correct key, pressed, possible passing
  308. case 0x01:
  309. return TriggerMacroVote_Pass;
  310. // Correct key, held, possible passing or release
  311. case 0x02:
  312. return TriggerMacroVote_PassRelease;
  313. // Correct key, released, possible release
  314. case 0x03:
  315. return TriggerMacroVote_Release;
  316. }
  317. }
  318. break;
  319. // LED State Type
  320. case 0x01:
  321. erro_print("LED State Type - Not implemented...");
  322. break;
  323. // Analog State Type
  324. case 0x02:
  325. erro_print("Analog State Type - Not implemented...");
  326. break;
  327. // Invalid State Type
  328. default:
  329. erro_print("Invalid State Type. This is a bug.");
  330. break;
  331. }
  332. // XXX Shouldn't reach here
  333. return TriggerMacroVote_Invalid;
  334. }
  335. // Evaluate/Update TriggerMacro
  336. inline TriggerMacroEval Macro_evalTriggerMacro( unsigned int triggerMacroIndex )
  337. {
  338. // Lookup TriggerMacro
  339. TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
  340. // Check if macro has finished and should be incremented sequence elements
  341. if ( macro->state == TriggerMacro_Release )
  342. {
  343. macro->state = TriggerMacro_Waiting;
  344. macro->pos = macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize;
  345. }
  346. // Current Macro position
  347. unsigned int pos = macro->pos;
  348. // Length of the combo being processed
  349. uint8_t comboLength = macro->guide[ pos ];
  350. // If no combo items are left, remove the TriggerMacro from the pending list
  351. if ( comboLength == 0 )
  352. {
  353. return TriggerMacroEval_Remove;
  354. }
  355. // Iterate through the key buffer, comparing to each key in the combo
  356. // If any of the pressed keys do not match, fail the macro
  357. //
  358. // The macro is waiting for input when in the TriggerMacro_Waiting state
  359. // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
  360. // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
  361. // On scan after position increment, change to TriggerMacro_Waiting state
  362. // TODO Add support for system LED states (NumLock, CapsLock, etc.)
  363. // TODO Add support for analog key states
  364. // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
  365. // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
  366. TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
  367. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  368. {
  369. // Lookup key information
  370. TriggerGuide *keyInfo = &macroTriggerListBuffer[ key ];
  371. // Iterate through the items in the combo, voting the on the key state
  372. TriggerMacroVote vote = TriggerMacroVote_Invalid;
  373. for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
  374. {
  375. // Assign TriggerGuide element (key type, state and scancode)
  376. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ comboItem ]);
  377. // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
  378. // Also mask all of the non-passing votes
  379. vote |= Macro_evalTriggerMacroVote( keyInfo, guide );
  380. if ( vote >= TriggerMacroVote_Pass )
  381. {
  382. vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
  383. break;
  384. }
  385. }
  386. // After voting, append to overall vote
  387. overallVote |= vote;
  388. }
  389. // Decide new state of macro after voting
  390. // Fail macro, remove from pending list
  391. if ( overallVote & TriggerMacroVote_Fail )
  392. {
  393. return TriggerMacroEval_Remove;
  394. }
  395. // Do nothing, incorrect key is being held or released
  396. else if ( overallVote & TriggerMacroVote_DoNothing )
  397. {
  398. // Just doing nothing :)
  399. }
  400. // If passing and in Waiting state, set macro state to Press
  401. else if ( overallVote & TriggerMacroVote_Pass && macro->state == TriggerMacro_Waiting )
  402. {
  403. macro->state = TriggerMacro_Press;
  404. // If in press state, and this is the final combo, send request for ResultMacro
  405. // Check to see if the result macro only has a single element
  406. // If this result macro has more than 1 key, only send once
  407. // TODO Add option to have macro repeat rate
  408. if ( macro->guide[ pos + comboLength ] == 0 )
  409. {
  410. // Long Macro, only send once (more than 1 sequence item)
  411. // Short Macro (only 1 sequence item)
  412. return Macro_isLongResultMacro( &ResultMacroList[ macro->result ] )
  413. ? TriggerMacroEval_DoResult
  414. : TriggerMacroEval_DoResultAndRemove;
  415. }
  416. }
  417. // If ready for transition and in Press state, set to Waiting and increment combo position
  418. // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
  419. else if ( overallVote & TriggerMacroVote_Release && macro->state == TriggerMacro_Press )
  420. {
  421. macro->state = TriggerMacro_Release;
  422. }
  423. return TriggerMacroEval_DoNothing;
  424. }
  425. // Evaluate/Update ResultMacro
  426. inline ResultMacroEval Macro_evalResultMacro( unsigned int resultMacroIndex )
  427. {
  428. // Lookup ResultMacro
  429. ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
  430. // Current Macro position
  431. unsigned int pos = macro->pos;
  432. // Length of combo being processed
  433. uint8_t comboLength = macro->guide[ pos ];
  434. // If no combo items are left, remove the ResultMacro from the pending list
  435. if ( comboLength == 0 )
  436. {
  437. return ResultMacroEval_Remove;
  438. }
  439. // Function Counter, used to keep track of the combo items processed
  440. unsigned int funcCount = 0;
  441. // Combo Item Position within the guide
  442. unsigned int comboItem = pos + 1;
  443. // Iterate through the Result Combo
  444. while ( funcCount < comboLength )
  445. {
  446. // Assign TriggerGuide element (key type, state and scancode)
  447. ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
  448. // Do lookup on capability function
  449. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  450. // Call capability
  451. capability( macro->state, macro->stateType, &guide->args );
  452. // Increment counters
  453. funcCount++;
  454. comboItem += ResultGuideSize( (ResultGuide*)(&macro->guide[ comboItem ]) );
  455. }
  456. // Move to next item in the sequence
  457. macro->pos = comboItem;
  458. // If the ResultMacro is finished, it will be removed on the next iteration
  459. return ResultMacroEval_DoNothing;
  460. }
  461. // Update pending trigger list
  462. void Macro_updateTriggerMacroPendingList()
  463. {
  464. // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
  465. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  466. {
  467. // Lookup Trigger List
  468. unsigned int *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode );
  469. // Number of Triggers in list
  470. unsigned int triggerListSize = triggerList[0];
  471. // Iterate over triggerList to see if any TriggerMacros need to be added
  472. // First item is the number of items in the TriggerList
  473. for ( unsigned int macro = 1; macro < triggerListSize + 1; macro++ )
  474. {
  475. // Lookup trigger macro index
  476. unsigned int triggerMacroIndex = triggerList[ macro ];
  477. // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
  478. // triggerList needs to be added
  479. unsigned int pending = 0;
  480. for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
  481. {
  482. // Stop scanning if the trigger macro index is found in the pending list
  483. if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
  484. break;
  485. }
  486. // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
  487. // Add it to the list
  488. if ( pending == macroTriggerMacroPendingListSize )
  489. {
  490. macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
  491. }
  492. }
  493. }
  494. }
  495. // Macro Procesing Loop
  496. // Called once per USB buffer send
  497. inline void Macro_process()
  498. {
  499. // Only do one round of macro processing between Output Module timer sends
  500. if ( USBKeys_Sent != 0 )
  501. return;
  502. // If the pause flag is set, only process if the step counter is non-zero
  503. if ( macroPauseMode )
  504. {
  505. if ( macroStepCounter == 0 )
  506. return;
  507. // Proceed, decrementing the step counter
  508. macroStepCounter--;
  509. }
  510. // Update pending trigger list, before processing TriggerMacros
  511. Macro_updateTriggerMacroPendingList();
  512. // Tail pointer for macroTriggerMacroPendingList
  513. // Macros must be explicitly re-added
  514. unsigned int macroTriggerMacroPendingListTail = 0;
  515. // Iterate through the pending TriggerMacros, processing each of them
  516. for ( unsigned int macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  517. {
  518. switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
  519. {
  520. // Trigger Result Macro (purposely falling through)
  521. case TriggerMacroEval_DoResult:
  522. // Append ResultMacro to PendingList
  523. Macro_appendResultMacroToPendingList( TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ].result );
  524. // Otherwise, just re-add
  525. default:
  526. macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
  527. break;
  528. // Trigger Result Macro and Remove (purposely falling through)
  529. case TriggerMacroEval_DoResultAndRemove:
  530. // Append ResultMacro to PendingList
  531. Macro_appendResultMacroToPendingList( TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ].result );
  532. // Remove Macro from Pending List, nothing to do, removing by default
  533. case TriggerMacroEval_Remove:
  534. break;
  535. }
  536. }
  537. // Update the macroTriggerMacroPendingListSize with the tail pointer
  538. macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
  539. // Tail pointer for macroResultMacroPendingList
  540. // Macros must be explicitly re-added
  541. unsigned int macroResultMacroPendingListTail = 0;
  542. // Iterate through the pending ResultMacros, processing each of them
  543. for ( unsigned int macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  544. {
  545. switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
  546. {
  547. // Re-add macros to pending list
  548. case ResultMacroEval_DoNothing:
  549. default:
  550. macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
  551. break;
  552. // Remove Macro from Pending List, nothing to do, removing by default
  553. case ResultMacroEval_Remove:
  554. break;
  555. }
  556. }
  557. // Update the macroResultMacroPendingListSize with the tail pointer
  558. macroResultMacroPendingListSize = macroResultMacroPendingListTail;
  559. // Signal buffer that we've used it
  560. Scan_finishedWithMacro( macroTriggerListBufferSize );
  561. // Reset TriggerList buffer
  562. macroTriggerListBufferSize = 0;
  563. // If Macro debug mode is set, clear the USB Buffer
  564. if ( macroDebugMode )
  565. {
  566. USBKeys_Modifiers = 0;
  567. USBKeys_Sent = 0;
  568. }
  569. }
  570. inline void Macro_setup()
  571. {
  572. // Register Macro CLI dictionary
  573. CLI_registerDictionary( macroCLIDict, macroCLIDictName );
  574. // Disable Macro debug mode
  575. macroDebugMode = 0;
  576. // Disable Macro pause flag
  577. macroPauseMode = 0;
  578. // Set Macro step counter to zero
  579. macroStepCounter = 0;
  580. // Make sure macro trigger buffer is empty
  581. macroTriggerListBufferSize = 0;
  582. // Initialize TriggerMacro states
  583. for ( unsigned int macro = 0; macro < TriggerMacroNum; macro++ )
  584. {
  585. TriggerMacroList[ macro ].result = 0;
  586. TriggerMacroList[ macro ].pos = 0;
  587. TriggerMacroList[ macro ].state = TriggerMacro_Waiting;
  588. }
  589. // Initialize ResultMacro states
  590. for ( unsigned int macro = 0; macro < ResultMacroNum; macro++ )
  591. {
  592. ResultMacroList[ macro ].pos = 0;
  593. ResultMacroList[ macro ].state = 0;
  594. ResultMacroList[ macro ].stateType = 0;
  595. }
  596. }
  597. // ----- CLI Command Functions -----
  598. void cliFunc_capList( char* args )
  599. {
  600. print( NL );
  601. info_msg("Capabilities List");
  602. // Iterate through all of the capabilities and display them
  603. for ( unsigned int cap = 0; cap < CapabilitiesNum; cap++ )
  604. {
  605. print( NL "\t" );
  606. printHex( cap );
  607. print(" - ");
  608. // Display/Lookup Capability Name (utilize debug mode of capability)
  609. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  610. capability( 0xFF, 0xFF, 0 );
  611. }
  612. }
  613. void cliFunc_capSelect( char* args )
  614. {
  615. // Parse code from argument
  616. char* curArgs;
  617. char* arg1Ptr;
  618. char* arg2Ptr = args;
  619. // Total number of args to scan (must do a lookup if a keyboard capability is selected)
  620. unsigned int totalArgs = 2; // Always at least two args
  621. unsigned int cap = 0;
  622. // Arguments used for keyboard capability function
  623. unsigned int argSetCount = 0;
  624. uint8_t *argSet = (uint8_t*)args;
  625. // Process all args
  626. for ( unsigned int c = 0; argSetCount < totalArgs; c++ )
  627. {
  628. curArgs = arg2Ptr;
  629. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  630. // Stop processing args if no more are found
  631. // Extra arguments are ignored
  632. if ( *arg1Ptr == '\0' )
  633. break;
  634. // For the first argument, choose the capability
  635. if ( c == 0 ) switch ( arg1Ptr[0] )
  636. {
  637. // Keyboard Capability
  638. case 'K':
  639. // Determine capability index
  640. cap = decToInt( &arg1Ptr[1] );
  641. // Lookup the number of args
  642. totalArgs += CapabilitiesList[ cap ].argCount;
  643. continue;
  644. }
  645. // Because allocating memory isn't doable, and the argument count is arbitrary
  646. // The argument pointer is repurposed as the argument list (much smaller anyways)
  647. argSet[ argSetCount++ ] = (uint8_t)decToInt( arg1Ptr );
  648. // Once all the arguments are prepared, call the keyboard capability function
  649. if ( argSetCount == totalArgs )
  650. {
  651. // Indicate that the capability was called
  652. print( NL );
  653. info_msg("K");
  654. printInt8( cap );
  655. print(" - ");
  656. printHex( argSet[0] );
  657. print(" - ");
  658. printHex( argSet[1] );
  659. print(" - ");
  660. printHex( argSet[2] );
  661. print( "..." NL );
  662. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  663. capability( argSet[0], argSet[1], &argSet[2] );
  664. }
  665. }
  666. }
  667. void cliFunc_keyPress( char* args )
  668. {
  669. // Parse codes from arguments
  670. char* curArgs;
  671. char* arg1Ptr;
  672. char* arg2Ptr = args;
  673. // Process all args
  674. for ( ;; )
  675. {
  676. curArgs = arg2Ptr;
  677. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  678. // Stop processing args if no more are found
  679. if ( *arg1Ptr == '\0' )
  680. break;
  681. // Ignore non-Scancode numbers
  682. switch ( arg1Ptr[0] )
  683. {
  684. // Scancode
  685. case 'S':
  686. Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
  687. break;
  688. }
  689. }
  690. }
  691. void cliFunc_keyRelease( char* args )
  692. {
  693. // Parse codes from arguments
  694. char* curArgs;
  695. char* arg1Ptr;
  696. char* arg2Ptr = args;
  697. // Process all args
  698. for ( ;; )
  699. {
  700. curArgs = arg2Ptr;
  701. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  702. // Stop processing args if no more are found
  703. if ( *arg1Ptr == '\0' )
  704. break;
  705. // Ignore non-Scancode numbers
  706. switch ( arg1Ptr[0] )
  707. {
  708. // Scancode
  709. case 'S':
  710. Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
  711. break;
  712. }
  713. }
  714. }
  715. void cliFunc_layerList( char* args )
  716. {
  717. print( NL );
  718. info_msg("Layer List");
  719. // Iterate through all of the layers and display them
  720. for ( unsigned int layer = 0; layer < LayerNum; layer++ )
  721. {
  722. print( NL "\t" );
  723. printHex( layer );
  724. print(" - ");
  725. // Display layer name
  726. dPrint( LayerIndex[ layer ].name );
  727. // Default map
  728. if ( layer == 0 )
  729. print(" \033[1m(default)\033[0m");
  730. // Layer State
  731. print( NL "\t\t Layer State: " );
  732. printHex( LayerIndex[ layer ].state );
  733. // Max Index
  734. print(" Max Index: ");
  735. printHex( LayerIndex[ layer ].max );
  736. }
  737. }
  738. void cliFunc_layerState( char* args )
  739. {
  740. // Parse codes from arguments
  741. char* curArgs;
  742. char* arg1Ptr;
  743. char* arg2Ptr = args;
  744. uint8_t arg1 = 0;
  745. uint8_t arg2 = 0;
  746. // Process first two args
  747. for ( uint8_t c = 0; c < 2; c++ )
  748. {
  749. curArgs = arg2Ptr;
  750. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  751. // Stop processing args if no more are found
  752. if ( *arg1Ptr == '\0' )
  753. break;
  754. switch ( c )
  755. {
  756. // First argument (e.g. L1)
  757. case 0:
  758. if ( arg1Ptr[0] != 'L' )
  759. return;
  760. arg1 = (uint8_t)decToInt( &arg1Ptr[1] );
  761. break;
  762. // Second argument (e.g. 4)
  763. case 1:
  764. arg2 = (uint8_t)decToInt( arg1Ptr );
  765. // Display operation (to indicate that it worked)
  766. print( NL );
  767. info_msg("Setting Layer L");
  768. printInt8( arg1 );
  769. print(" to - ");
  770. printHex( arg2 );
  771. // Set the layer state
  772. LayerIndex[ arg1 ].state = arg2;
  773. break;
  774. }
  775. }
  776. }
  777. void cliFunc_macroDebug( char* args )
  778. {
  779. // Toggle macro debug mode
  780. macroDebugMode = macroDebugMode ? 0 : 1;
  781. print( NL );
  782. info_msg("Macro Debug Mode: ");
  783. printInt8( macroDebugMode );
  784. }
  785. void cliFunc_macroList( char* args )
  786. {
  787. // Show available trigger macro indices
  788. print( NL );
  789. info_msg("Trigger Macros Range: T0 -> T");
  790. printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  791. // Show available result macro indices
  792. print( NL );
  793. info_msg("Result Macros Range: R0 -> R");
  794. printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  795. // Show Trigger to Result Macro Links
  796. print( NL );
  797. info_msg("Trigger : Result Macro Pairs");
  798. for ( unsigned int macro = 0; macro < TriggerMacroNum; macro++ )
  799. {
  800. print( NL );
  801. print("\tT");
  802. printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
  803. print(" : R");
  804. printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
  805. }
  806. }
  807. void cliFunc_macroProc( char* args )
  808. {
  809. // Toggle macro pause mode
  810. macroPauseMode = macroPauseMode ? 0 : 1;
  811. print( NL );
  812. info_msg("Macro Processing Mode: ");
  813. printInt8( macroPauseMode );
  814. }
  815. void macroDebugShowTrigger( unsigned int index )
  816. {
  817. // Only proceed if the macro exists
  818. if ( index >= TriggerMacroNum )
  819. return;
  820. // Trigger Macro Show
  821. TriggerMacro *macro = &TriggerMacroList[ index ];
  822. print( NL );
  823. info_msg("Trigger Macro Index: ");
  824. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  825. print( NL );
  826. // Read the comboLength for combo in the sequence (sequence of combos)
  827. unsigned int pos = 0;
  828. uint8_t comboLength = macro->guide[ pos ];
  829. // Iterate through and interpret the guide
  830. while ( comboLength != 0 )
  831. {
  832. // Initial position of the combo
  833. unsigned int comboPos = ++pos;
  834. // Iterate through the combo
  835. while ( pos < comboLength * TriggerGuideSize + comboPos )
  836. {
  837. // Assign TriggerGuide element (key type, state and scancode)
  838. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
  839. // Display guide information about trigger key
  840. printHex( guide->scanCode );
  841. print("|");
  842. printHex( guide->type );
  843. print("|");
  844. printHex( guide->state );
  845. // Increment position
  846. pos += TriggerGuideSize;
  847. // Only show combo separator if there are combos left in the sequence element
  848. if ( pos < comboLength * TriggerGuideSize + comboPos )
  849. print("+");
  850. }
  851. // Read the next comboLength
  852. comboLength = macro->guide[ pos ];
  853. // Only show sequence separator if there is another combo to process
  854. if ( comboLength != 0 )
  855. print(";");
  856. }
  857. // Display current position
  858. print( NL "Position: " );
  859. printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
  860. // Display result macro index
  861. print( NL "Result Macro Index: " );
  862. printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
  863. }
  864. void macroDebugShowResult( unsigned int index )
  865. {
  866. // Only proceed if the macro exists
  867. if ( index >= ResultMacroNum )
  868. return;
  869. // Trigger Macro Show
  870. ResultMacro *macro = &ResultMacroList[ index ];
  871. print( NL );
  872. info_msg("Result Macro Index: ");
  873. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  874. print( NL );
  875. // Read the comboLength for combo in the sequence (sequence of combos)
  876. unsigned int pos = 0;
  877. uint8_t comboLength = macro->guide[ pos++ ];
  878. // Iterate through and interpret the guide
  879. while ( comboLength != 0 )
  880. {
  881. // Function Counter, used to keep track of the combos processed
  882. unsigned int funcCount = 0;
  883. // Iterate through the combo
  884. while ( funcCount < comboLength )
  885. {
  886. // Assign TriggerGuide element (key type, state and scancode)
  887. ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
  888. // Display Function Index
  889. printHex( guide->index );
  890. print("|");
  891. // Display Function Ptr Address
  892. printHex( (unsigned int)CapabilitiesList[ guide->index ].func );
  893. print("|");
  894. // Display/Lookup Capability Name (utilize debug mode of capability)
  895. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  896. capability( 0xFF, 0xFF, 0 );
  897. // Display Argument(s)
  898. print("(");
  899. for ( unsigned int arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
  900. {
  901. // Arguments are only 8 bit values
  902. printHex( (&guide->args)[ arg ] );
  903. // Only show arg separator if there are args left
  904. if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
  905. print(",");
  906. }
  907. print(")");
  908. // Increment position
  909. pos += ResultGuideSize( guide );
  910. // Increment function count
  911. funcCount++;
  912. // Only show combo separator if there are combos left in the sequence element
  913. if ( funcCount < comboLength )
  914. print("+");
  915. }
  916. // Read the next comboLength
  917. comboLength = macro->guide[ pos++ ];
  918. // Only show sequence separator if there is another combo to process
  919. if ( comboLength != 0 )
  920. print(";");
  921. }
  922. // Display current position
  923. print( NL "Position: " );
  924. printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
  925. // Display final trigger state/type
  926. print( NL "Final Trigger State (State/Type): " );
  927. printHex( macro->state );
  928. print("/");
  929. printHex( macro->stateType );
  930. }
  931. void cliFunc_macroShow( char* args )
  932. {
  933. // Parse codes from arguments
  934. char* curArgs;
  935. char* arg1Ptr;
  936. char* arg2Ptr = args;
  937. // Process all args
  938. for ( ;; )
  939. {
  940. curArgs = arg2Ptr;
  941. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  942. // Stop processing args if no more are found
  943. if ( *arg1Ptr == '\0' )
  944. break;
  945. // Ignore invalid codes
  946. switch ( arg1Ptr[0] )
  947. {
  948. // Indexed Trigger Macro
  949. case 'T':
  950. macroDebugShowTrigger( decToInt( &arg1Ptr[1] ) );
  951. break;
  952. // Indexed Result Macro
  953. case 'R':
  954. macroDebugShowResult( decToInt( &arg1Ptr[1] ) );
  955. break;
  956. }
  957. }
  958. }
  959. void cliFunc_macroStep( char* args )
  960. {
  961. // Parse number from argument
  962. // NOTE: Only first argument is used
  963. char* arg1Ptr;
  964. char* arg2Ptr;
  965. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  966. // Set the macro step counter, negative int's are cast to uint
  967. macroStepCounter = (unsigned int)decToInt( arg1Ptr );
  968. }