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 52KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857
  1. /* Copyright (C) 2014-2015 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 <generatedKeymap.h> // Generated using kll at compile time, in build directory
  27. // Connect Includes
  28. #if defined(ConnectEnabled_define)
  29. #include <connect_scan.h>
  30. #endif
  31. // Local Includes
  32. #include "macro.h"
  33. // ----- Function Declarations -----
  34. void cliFunc_capList ( char* args );
  35. void cliFunc_capSelect ( char* args );
  36. void cliFunc_keyHold ( char* args );
  37. void cliFunc_keyPress ( char* args );
  38. void cliFunc_keyRelease( char* args );
  39. void cliFunc_layerDebug( char* args );
  40. void cliFunc_layerList ( char* args );
  41. void cliFunc_layerState( char* args );
  42. void cliFunc_macroDebug( char* args );
  43. void cliFunc_macroList ( char* args );
  44. void cliFunc_macroProc ( char* args );
  45. void cliFunc_macroShow ( char* args );
  46. void cliFunc_macroStep ( char* args );
  47. // ----- Enums -----
  48. // Bit positions are important, passes (correct key) always trump incorrect key votes
  49. typedef enum TriggerMacroVote {
  50. TriggerMacroVote_Release = 0x10, // Correct key
  51. TriggerMacroVote_PassRelease = 0x18, // Correct key (both pass and release)
  52. TriggerMacroVote_Pass = 0x8, // Correct key
  53. TriggerMacroVote_DoNothingRelease = 0x4, // Incorrect key
  54. TriggerMacroVote_DoNothing = 0x2, // Incorrect key
  55. TriggerMacroVote_Fail = 0x1, // Incorrect key
  56. TriggerMacroVote_Invalid = 0x0, // Invalid state
  57. } TriggerMacroVote;
  58. typedef enum TriggerMacroEval {
  59. TriggerMacroEval_DoNothing,
  60. TriggerMacroEval_DoResult,
  61. TriggerMacroEval_DoResultAndRemove,
  62. TriggerMacroEval_Remove,
  63. } TriggerMacroEval;
  64. typedef enum ResultMacroEval {
  65. ResultMacroEval_DoNothing,
  66. ResultMacroEval_Remove,
  67. } ResultMacroEval;
  68. // ----- Variables -----
  69. // Macro Module command dictionary
  70. CLIDict_Entry( capList, "Prints an indexed list of all non USB keycode capabilities." );
  71. CLIDict_Entry( capSelect, "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B" );
  72. CLIDict_Entry( keyHold, "Send key-hold events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
  73. CLIDict_Entry( keyPress, "Send key-press events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
  74. CLIDict_Entry( keyRelease, "Send key-release event to macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
  75. CLIDict_Entry( layerDebug, "Layer debug mode. Shows layer stack and any changes." );
  76. CLIDict_Entry( layerList, "List available layers." );
  77. CLIDict_Entry( 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" );
  78. CLIDict_Entry( macroDebug, "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes." );
  79. CLIDict_Entry( macroList, "List the defined trigger and result macros." );
  80. CLIDict_Entry( macroProc, "Pause/Resume macro processing." );
  81. CLIDict_Entry( 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" );
  82. CLIDict_Entry( macroStep, "Do N macro processing steps. Defaults to 1." );
  83. CLIDict_Def( macroCLIDict, "Macro Module Commands" ) = {
  84. CLIDict_Item( capList ),
  85. CLIDict_Item( capSelect ),
  86. CLIDict_Item( keyHold ),
  87. CLIDict_Item( keyPress ),
  88. CLIDict_Item( keyRelease ),
  89. CLIDict_Item( layerDebug ),
  90. CLIDict_Item( layerList ),
  91. CLIDict_Item( layerState ),
  92. CLIDict_Item( macroDebug ),
  93. CLIDict_Item( macroList ),
  94. CLIDict_Item( macroProc ),
  95. CLIDict_Item( macroShow ),
  96. CLIDict_Item( macroStep ),
  97. { 0, 0, 0 } // Null entry for dictionary end
  98. };
  99. // Layer debug flag - If set, displays any changes to layers and the full layer stack on change
  100. uint8_t layerDebugMode = 0;
  101. // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
  102. uint8_t macroDebugMode = 0;
  103. // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
  104. uint8_t macroPauseMode = 0;
  105. // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
  106. uint16_t macroStepCounter = 0;
  107. // Key Trigger List Buffer and Layer Cache
  108. // The layer cache is set on press only, hold and release events refer to the value set on press
  109. TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
  110. uint8_t macroTriggerListBufferSize = 0;
  111. var_uint_t macroTriggerListLayerCache[ MaxScanCode ];
  112. // Pending Trigger Macro Index List
  113. // * Any trigger macros that need processing from a previous macro processing loop
  114. // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
  115. // Possibly could be calculated by the KLL compiler
  116. // XXX It may be possible to calculate the worst case using the KLL compiler
  117. uint16_t macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
  118. uint16_t macroTriggerMacroPendingListSize = 0;
  119. // Layer Index Stack
  120. // * When modifying layer state and the state is non-0x0, the stack must be adjusted
  121. uint16_t macroLayerIndexStack[ LayerNum + 1 ] = { 0 };
  122. uint16_t macroLayerIndexStackSize = 0;
  123. // Pending Result Macro Index List
  124. // * Any result macro that needs processing from a previous macro processing loop
  125. uint16_t macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
  126. uint16_t macroResultMacroPendingListSize = 0;
  127. // Interconnect ScanCode Cache
  128. #if defined(ConnectEnabled_define)
  129. // TODO This can be shrunk by the size of the max node 0 ScanCode
  130. TriggerGuide macroInterconnectCache[ MaxScanCode ];
  131. uint8_t macroInterconnectCacheSize = 0;
  132. #endif
  133. // ----- Capabilities -----
  134. // Sets the given layer with the specified layerState
  135. void Macro_layerState( uint8_t state, uint8_t stateType, uint16_t layer, uint8_t layerState )
  136. {
  137. // Ignore if layer does not exist or trying to manipulate layer 0/Default layer
  138. if ( layer >= LayerNum || layer == 0 )
  139. return;
  140. // Is layer in the LayerIndexStack?
  141. uint8_t inLayerIndexStack = 0;
  142. uint16_t stackItem = 0;
  143. while ( stackItem < macroLayerIndexStackSize )
  144. {
  145. // Flag if layer is already in the LayerIndexStack
  146. if ( macroLayerIndexStack[ stackItem ] == layer )
  147. {
  148. inLayerIndexStack = 1;
  149. break;
  150. }
  151. // Increment to next item
  152. stackItem++;
  153. }
  154. // Toggle Layer State Byte
  155. if ( LayerState[ layer ] & layerState )
  156. {
  157. // Unset
  158. LayerState[ layer ] &= ~layerState;
  159. }
  160. else
  161. {
  162. // Set
  163. LayerState[ layer ] |= layerState;
  164. }
  165. // If the layer was not in the LayerIndexStack add it
  166. if ( !inLayerIndexStack )
  167. {
  168. macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
  169. }
  170. // If the layer is in the LayerIndexStack and the state is 0x00, remove
  171. if ( LayerState[ layer ] == 0x00 && inLayerIndexStack )
  172. {
  173. // Remove the layer from the LayerIndexStack
  174. // Using the already positioned stackItem variable from the loop above
  175. while ( stackItem < macroLayerIndexStackSize )
  176. {
  177. macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
  178. stackItem++;
  179. }
  180. // Reduce LayerIndexStack size
  181. macroLayerIndexStackSize--;
  182. }
  183. // Layer Debug Mode
  184. if ( layerDebugMode )
  185. {
  186. dbug_msg("Layer ");
  187. // Iterate over each of the layers displaying the state as a hex value
  188. for ( uint16_t index = 0; index < LayerNum; index++ )
  189. {
  190. printHex_op( LayerState[ index ], 0 );
  191. }
  192. // Always show the default layer (it's always 0)
  193. print(" 0");
  194. // Iterate over the layer stack starting from the bottom of the stack
  195. for ( uint16_t index = macroLayerIndexStackSize; index > 0; index-- )
  196. {
  197. print(":");
  198. printHex_op( macroLayerIndexStack[ index - 1 ], 0 );
  199. }
  200. print( NL );
  201. }
  202. }
  203. // Modifies the specified Layer control byte
  204. // Argument #1: Layer Index -> uint16_t
  205. // Argument #2: Layer State -> uint8_t
  206. void Macro_layerState_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  207. {
  208. // Display capability name
  209. if ( stateType == 0xFF && state == 0xFF )
  210. {
  211. print("Macro_layerState(layerIndex,layerState)");
  212. return;
  213. }
  214. // Only use capability on press or release
  215. // TODO Analog
  216. // XXX This may cause issues, might be better to implement state table here to decide -HaaTa
  217. if ( stateType == 0x00 && state == 0x02 ) // Hold condition
  218. return;
  219. // Get layer index from arguments
  220. // Cast pointer to uint8_t to uint16_t then access that memory location
  221. uint16_t layer = *(uint16_t*)(&args[0]);
  222. // Get layer toggle byte
  223. uint8_t layerState = args[ sizeof(uint16_t) ];
  224. Macro_layerState( state, stateType, layer, layerState );
  225. }
  226. // Latches given layer
  227. // Argument #1: Layer Index -> uint16_t
  228. void Macro_layerLatch_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  229. {
  230. // Display capability name
  231. if ( stateType == 0xFF && state == 0xFF )
  232. {
  233. print("Macro_layerLatch(layerIndex)");
  234. return;
  235. }
  236. // Only use capability on press
  237. // TODO Analog
  238. if ( stateType == 0x00 && state != 0x03 ) // Only on release
  239. return;
  240. // Get layer index from arguments
  241. // Cast pointer to uint8_t to uint16_t then access that memory location
  242. uint16_t layer = *(uint16_t*)(&args[0]);
  243. Macro_layerState( state, stateType, layer, 0x02 );
  244. }
  245. // Locks given layer
  246. // Argument #1: Layer Index -> uint16_t
  247. void Macro_layerLock_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  248. {
  249. // Display capability name
  250. if ( stateType == 0xFF && state == 0xFF )
  251. {
  252. print("Macro_layerLock(layerIndex)");
  253. return;
  254. }
  255. // Only use capability on press
  256. // TODO Analog
  257. // XXX Could also be on release, but that's sorta dumb -HaaTa
  258. if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
  259. return;
  260. // Get layer index from arguments
  261. // Cast pointer to uint8_t to uint16_t then access that memory location
  262. uint16_t layer = *(uint16_t*)(&args[0]);
  263. Macro_layerState( state, stateType, layer, 0x04 );
  264. }
  265. // Shifts given layer
  266. // Argument #1: Layer Index -> uint16_t
  267. void Macro_layerShift_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  268. {
  269. // Display capability name
  270. if ( stateType == 0xFF && state == 0xFF )
  271. {
  272. print("Macro_layerShift(layerIndex)");
  273. return;
  274. }
  275. // Only use capability on press or release
  276. // TODO Analog
  277. if ( stateType == 0x00 && ( state == 0x00 || state == 0x02 ) ) // Only pass press or release conditions
  278. return;
  279. // Get layer index from arguments
  280. // Cast pointer to uint8_t to uint16_t then access that memory location
  281. uint16_t layer = *(uint16_t*)(&args[0]);
  282. Macro_layerState( state, stateType, layer, 0x01 );
  283. }
  284. // Rotate layer to next/previous
  285. // Uses state variable to keep track of the current layer position
  286. // Layers are still evaluated using the layer stack
  287. uint16_t Macro_rotationLayer;
  288. void Macro_layerRotate_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  289. {
  290. // Display capability name
  291. if ( stateType == 0xFF && state == 0xFF )
  292. {
  293. print("Macro_layerRotate(previous)");
  294. return;
  295. }
  296. // Only use capability on press
  297. // TODO Analog
  298. // XXX Could also be on release, but that's sorta dumb -HaaTa
  299. if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
  300. return;
  301. // Unset previous rotation layer if not 0
  302. if ( Macro_rotationLayer != 0 )
  303. {
  304. Macro_layerState( state, stateType, Macro_rotationLayer, 0x04 );
  305. }
  306. // Get direction of rotation, 0, next, non-zero previous
  307. uint8_t direction = *args;
  308. // Next
  309. if ( !direction )
  310. {
  311. Macro_rotationLayer++;
  312. // Invalid layer
  313. if ( Macro_rotationLayer >= LayerNum )
  314. Macro_rotationLayer = 0;
  315. }
  316. // Previous
  317. else
  318. {
  319. Macro_rotationLayer--;
  320. // Layer wrap
  321. if ( Macro_rotationLayer >= LayerNum )
  322. Macro_rotationLayer = LayerNum - 1;
  323. }
  324. // Toggle the computed layer rotation
  325. Macro_layerState( state, stateType, Macro_rotationLayer, 0x04 );
  326. }
  327. // ----- Functions -----
  328. // Looks up the trigger list for the given scan code (from the active layer)
  329. // NOTE: Calling function must handle the NULL pointer case
  330. nat_ptr_t *Macro_layerLookup( TriggerGuide *guide, uint8_t latch_expire )
  331. {
  332. uint8_t scanCode = guide->scanCode;
  333. // TODO Analog
  334. // If a normal key, and not pressed, do a layer cache lookup
  335. if ( guide->type == 0x00 && guide->state != 0x01 )
  336. {
  337. // Cached layer
  338. var_uint_t cachedLayer = macroTriggerListLayerCache[ scanCode ];
  339. // Lookup map, then layer
  340. nat_ptr_t **map = (nat_ptr_t**)LayerIndex[ cachedLayer ].triggerMap;
  341. const Layer *layer = &LayerIndex[ cachedLayer ];
  342. // Cache trigger list before attempting to expire latch
  343. nat_ptr_t *trigger_list = map[ scanCode - layer->first ];
  344. // Check if latch has been pressed for this layer
  345. uint8_t latch = LayerState[ cachedLayer ] & 0x02;
  346. if ( latch && latch_expire )
  347. {
  348. Macro_layerState( 0, 0, cachedLayer, 0x02 );
  349. #if defined(ConnectEnabled_define) && defined(LCDEnabled_define)
  350. // Evaluate the layerStack capability if available (LCD + Interconnect)
  351. extern void LCD_layerStack_capability( uint8_t state, uint8_t stateType, uint8_t *args );
  352. LCD_layerStack_capability( 0, 0, 0 );
  353. #endif
  354. }
  355. return trigger_list;
  356. }
  357. // If no trigger macro is defined at the given layer, fallthrough to the next layer
  358. for ( uint16_t layerIndex = macroLayerIndexStackSize; layerIndex != 0xFFFF; layerIndex-- )
  359. {
  360. // Lookup Layer
  361. const Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
  362. // Check if latch has been pressed for this layer
  363. // XXX Regardless of whether a key is found, the latch is removed on first lookup
  364. uint8_t latch = LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x02;
  365. if ( latch && latch_expire )
  366. {
  367. Macro_layerState( 0, 0, macroLayerIndexStack[ layerIndex ], 0x02 );
  368. }
  369. // Only use layer, if state is valid
  370. // XOR each of the state bits
  371. // If only two are enabled, do not use this state
  372. if ( (LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x01) ^ (latch>>1) ^ ((LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x04)>>2) )
  373. {
  374. // Lookup layer
  375. nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
  376. // Determine if layer has key defined
  377. // Make sure scanCode is between layer first and last scancodes
  378. if ( map != 0
  379. && scanCode <= layer->last
  380. && scanCode >= layer->first
  381. && *map[ scanCode - layer->first ] != 0 )
  382. {
  383. // Set the layer cache
  384. macroTriggerListLayerCache[ scanCode ] = macroLayerIndexStack[ layerIndex ];
  385. return map[ scanCode - layer->first ];
  386. }
  387. }
  388. }
  389. // Do lookup on default layer
  390. nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
  391. // Lookup default layer
  392. const Layer *layer = &LayerIndex[0];
  393. // Make sure scanCode is between layer first and last scancodes
  394. if ( map != 0
  395. && scanCode <= layer->last
  396. && scanCode >= layer->first
  397. && *map[ scanCode - layer->first ] != 0 )
  398. {
  399. // Set the layer cache to default map
  400. macroTriggerListLayerCache[ scanCode ] = 0;
  401. return map[ scanCode - layer->first ];
  402. }
  403. // Otherwise no defined Trigger Macro
  404. erro_msg("Scan Code has no defined Trigger Macro: ");
  405. printHex( scanCode );
  406. print( NL );
  407. return 0;
  408. }
  409. // Add an interconnect ScanCode
  410. // These are handled differently (less information is sent, hold/off states must be assumed)
  411. #if defined(ConnectEnabled_define)
  412. inline void Macro_interconnectAdd( void *trigger_ptr )
  413. {
  414. TriggerGuide *trigger = (TriggerGuide*)trigger_ptr;
  415. // Error checking
  416. uint8_t error = 0;
  417. switch ( trigger->type )
  418. {
  419. case 0x00: // Normal key
  420. switch ( trigger->state )
  421. {
  422. case 0x00:
  423. case 0x01:
  424. case 0x02:
  425. case 0x03:
  426. break;
  427. default:
  428. erro_msg("Invalid key state - ");
  429. error = 1;
  430. break;
  431. }
  432. break;
  433. // Invalid TriggerGuide type
  434. default:
  435. erro_msg("Invalid type - ");
  436. error = 1;
  437. break;
  438. }
  439. // Check if ScanCode is out of range
  440. if ( trigger->scanCode > MaxScanCode )
  441. {
  442. warn_msg("ScanCode is out of range/not defined - ");
  443. error = 1;
  444. }
  445. // Display TriggerGuide
  446. if ( error )
  447. {
  448. printHex( trigger->type );
  449. print(" ");
  450. printHex( trigger->state );
  451. print(" ");
  452. printHex( trigger->scanCode );
  453. print( NL );
  454. return;
  455. }
  456. // Add trigger to the Interconnect Cache
  457. // During each processing loop, a scancode may be re-added depending on it's state
  458. for ( uint8_t c = 0; c < macroInterconnectCacheSize; c++ )
  459. {
  460. // Check if the same ScanCode
  461. if ( macroInterconnectCache[ c ].scanCode == trigger->scanCode )
  462. {
  463. // Update the state
  464. macroInterconnectCache[ c ].state = trigger->state;
  465. return;
  466. }
  467. }
  468. // If not in the list, add it
  469. macroInterconnectCache[ macroInterconnectCacheSize++ ] = *trigger;
  470. }
  471. #endif
  472. // Update the scancode key state
  473. // States:
  474. // * 0x00 - Off
  475. // * 0x01 - Pressed
  476. // * 0x02 - Held
  477. // * 0x03 - Released
  478. // * 0x04 - Unpressed (this is currently ignored)
  479. inline void Macro_keyState( uint8_t scanCode, uint8_t state )
  480. {
  481. #if defined(ConnectEnabled_define)
  482. // Only compile in if a Connect node module is available
  483. if ( !Connect_master )
  484. {
  485. // ScanCodes are only added if there was a state change (on/off)
  486. switch ( state )
  487. {
  488. case 0x00: // Off
  489. case 0x02: // Held
  490. return;
  491. }
  492. }
  493. #endif
  494. // Only add to macro trigger list if one of three states
  495. switch ( state )
  496. {
  497. case 0x01: // Pressed
  498. case 0x02: // Held
  499. case 0x03: // Released
  500. // Check if ScanCode is out of range
  501. if ( scanCode > MaxScanCode )
  502. {
  503. warn_msg("ScanCode is out of range/not defined: ");
  504. printHex( scanCode );
  505. print( NL );
  506. return;
  507. }
  508. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  509. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  510. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
  511. macroTriggerListBufferSize++;
  512. break;
  513. }
  514. }
  515. // Update the scancode analog state
  516. // States:
  517. // * 0x00 - Off
  518. // * 0x01 - Released
  519. // * 0x02-0xFF - Analog value (low to high)
  520. inline void Macro_analogState( uint8_t scanCode, uint8_t state )
  521. {
  522. // Only add to macro trigger list if non-off
  523. // TODO Handle change for interconnect
  524. if ( state != 0x00 )
  525. {
  526. // Check if ScanCode is out of range
  527. if ( scanCode > MaxScanCode )
  528. {
  529. warn_msg("ScanCode is out of range/not defined: ");
  530. printHex( scanCode );
  531. print( NL );
  532. return;
  533. }
  534. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  535. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  536. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
  537. macroTriggerListBufferSize++;
  538. }
  539. }
  540. // Update led state
  541. // States:
  542. // * 0x00 - Off
  543. // * 0x01 - On
  544. inline void Macro_ledState( uint8_t ledCode, uint8_t state )
  545. {
  546. // Only add to macro trigger list if non-off
  547. // TODO Handle change for interconnect
  548. if ( state != 0x00 )
  549. {
  550. // Check if LedCode is out of range
  551. // TODO
  552. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
  553. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  554. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
  555. macroTriggerListBufferSize++;
  556. }
  557. }
  558. // Append result macro to pending list, checking for duplicates
  559. // Do nothing if duplicate
  560. inline void Macro_appendResultMacroToPendingList( const TriggerMacro *triggerMacro )
  561. {
  562. // Lookup result macro index
  563. var_uint_t resultMacroIndex = triggerMacro->result;
  564. // Iterate through result macro pending list, making sure this macro hasn't been added yet
  565. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  566. {
  567. // If duplicate found, do nothing
  568. if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
  569. return;
  570. }
  571. // No duplicates found, add to pending list
  572. macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
  573. // Lookup scanCode of the last key in the last combo
  574. var_uint_t pos = 0;
  575. for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
  576. {
  577. pos += TriggerGuideSize * comboLength + 1;
  578. comboLength = triggerMacro->guide[ pos ];
  579. }
  580. uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
  581. // Lookup scanCode in buffer list for the current state and stateType
  582. for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
  583. {
  584. if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
  585. {
  586. ResultMacroRecordList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
  587. ResultMacroRecordList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
  588. }
  589. }
  590. // Reset the macro position
  591. ResultMacroRecordList[ resultMacroIndex ].pos = 0;
  592. }
  593. // Determine if long ResultMacro (more than 1 seqence element)
  594. inline uint8_t Macro_isLongResultMacro( const ResultMacro *macro )
  595. {
  596. // Check the second sequence combo length
  597. // If non-zero return non-zero (long sequence)
  598. // 0 otherwise (short sequence)
  599. var_uint_t position = 1;
  600. for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
  601. position += ResultGuideSize( (ResultGuide*)&macro->guide[ position ] );
  602. return macro->guide[ position ];
  603. }
  604. // Determine if long TriggerMacro (more than 1 sequence element)
  605. inline uint8_t Macro_isLongTriggerMacro( const TriggerMacro *macro )
  606. {
  607. // Check the second sequence combo length
  608. // If non-zero return non-zero (long sequence)
  609. // 0 otherwise (short sequence)
  610. return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
  611. }
  612. // Votes on the given key vs. guide, short macros
  613. inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
  614. {
  615. // Depending on key type
  616. switch ( guide->type )
  617. {
  618. // Normal State Type
  619. case 0x00:
  620. // For short TriggerMacros completely ignore incorrect keys
  621. if ( guide->scanCode == key->scanCode )
  622. {
  623. switch ( key->state )
  624. {
  625. // Correct key, pressed, possible passing
  626. case 0x01:
  627. return TriggerMacroVote_Pass;
  628. // Correct key, held, possible passing or release
  629. case 0x02:
  630. return TriggerMacroVote_PassRelease;
  631. // Correct key, released, possible release
  632. case 0x03:
  633. return TriggerMacroVote_Release;
  634. }
  635. }
  636. return TriggerMacroVote_DoNothing;
  637. // LED State Type
  638. case 0x01:
  639. erro_print("LED State Type - Not implemented...");
  640. break;
  641. // Analog State Type
  642. case 0x02:
  643. erro_print("Analog State Type - Not implemented...");
  644. break;
  645. // Invalid State Type
  646. default:
  647. erro_print("Invalid State Type. This is a bug.");
  648. break;
  649. }
  650. // XXX Shouldn't reach here
  651. return TriggerMacroVote_Invalid;
  652. }
  653. // Votes on the given key vs. guide, long macros
  654. // A long macro is defined as a guide with more than 1 combo
  655. inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
  656. {
  657. // Depending on key type
  658. switch ( guide->type )
  659. {
  660. // Normal State Type
  661. case 0x00:
  662. // Depending on the state of the buffered key, make voting decision
  663. // Incorrect key
  664. if ( guide->scanCode != key->scanCode )
  665. {
  666. switch ( key->state )
  667. {
  668. // Wrong key, pressed, fail
  669. case 0x01:
  670. return TriggerMacroVote_Fail;
  671. // Wrong key, held, do not pass (no effect)
  672. case 0x02:
  673. return TriggerMacroVote_DoNothing;
  674. // Wrong key released, fail out if pos == 0
  675. case 0x03:
  676. return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
  677. }
  678. }
  679. // Correct key
  680. else
  681. {
  682. switch ( key->state )
  683. {
  684. // Correct key, pressed, possible passing
  685. case 0x01:
  686. return TriggerMacroVote_Pass;
  687. // Correct key, held, possible passing or release
  688. case 0x02:
  689. return TriggerMacroVote_PassRelease;
  690. // Correct key, released, possible release
  691. case 0x03:
  692. return TriggerMacroVote_Release;
  693. }
  694. }
  695. break;
  696. // LED State Type
  697. case 0x01:
  698. erro_print("LED State Type - Not implemented...");
  699. break;
  700. // Analog State Type
  701. case 0x02:
  702. erro_print("Analog State Type - Not implemented...");
  703. break;
  704. // Invalid State Type
  705. default:
  706. erro_print("Invalid State Type. This is a bug.");
  707. break;
  708. }
  709. // XXX Shouldn't reach here
  710. return TriggerMacroVote_Invalid;
  711. }
  712. // Evaluate/Update TriggerMacro
  713. TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
  714. {
  715. // Lookup TriggerMacro
  716. const TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
  717. TriggerMacroRecord *record = &TriggerMacroRecordList[ triggerMacroIndex ];
  718. // Check if macro has finished and should be incremented sequence elements
  719. if ( record->state == TriggerMacro_Release )
  720. {
  721. record->state = TriggerMacro_Waiting;
  722. record->pos = record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1;
  723. }
  724. // Current Macro position
  725. var_uint_t pos = record->pos;
  726. // Length of the combo being processed
  727. uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
  728. // If no combo items are left, remove the TriggerMacro from the pending list
  729. if ( comboLength == 0 )
  730. {
  731. return TriggerMacroEval_Remove;
  732. }
  733. // Check if this is a long Trigger Macro
  734. uint8_t longMacro = Macro_isLongTriggerMacro( macro );
  735. // Iterate through the items in the combo, voting the on the key state
  736. // If any of the pressed keys do not match, fail the macro
  737. //
  738. // The macro is waiting for input when in the TriggerMacro_Waiting state
  739. // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
  740. // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
  741. // On scan after position increment, change to TriggerMacro_Waiting state
  742. // TODO Add support for system LED states (NumLock, CapsLock, etc.)
  743. // TODO Add support for analog key states
  744. // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
  745. // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
  746. TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
  747. for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
  748. {
  749. // Assign TriggerGuide element (key type, state and scancode)
  750. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ comboItem ]);
  751. TriggerMacroVote vote = TriggerMacroVote_Invalid;
  752. // Iterate through the key buffer, comparing to each key in the combo
  753. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  754. {
  755. // Lookup key information
  756. TriggerGuide *keyInfo = &macroTriggerListBuffer[ key ];
  757. // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
  758. // Also mask all of the non-passing votes
  759. vote |= longMacro
  760. ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
  761. : Macro_evalShortTriggerMacroVote( keyInfo, guide );
  762. if ( vote >= TriggerMacroVote_Pass )
  763. {
  764. vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
  765. break;
  766. }
  767. }
  768. // If no pass vote was found after scanning all of the keys
  769. // Fail the combo, if this is a short macro (long macros already will have a fail vote)
  770. if ( !longMacro && vote < TriggerMacroVote_Pass )
  771. vote |= TriggerMacroVote_Fail;
  772. // After voting, append to overall vote
  773. overallVote |= vote;
  774. }
  775. // If no pass vote was found after scanning the entire combo
  776. // And this is the first position in the combo, just remove it (nothing important happened)
  777. if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
  778. overallVote |= TriggerMacroVote_Fail;
  779. // Decide new state of macro after voting
  780. // Fail macro, remove from pending list
  781. if ( overallVote & TriggerMacroVote_Fail )
  782. {
  783. return TriggerMacroEval_Remove;
  784. }
  785. // Do nothing, incorrect key is being held or released
  786. else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
  787. {
  788. // Just doing nothing :)
  789. }
  790. // If ready for transition and in Press state, set to Waiting and increment combo position
  791. // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
  792. else if ( overallVote & TriggerMacroVote_Release && record->state == TriggerMacro_Press )
  793. {
  794. record->state = TriggerMacro_Release;
  795. // If this is the last combo in the sequence, remove from the pending list
  796. if ( macro->guide[ record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1 ] == 0 )
  797. return TriggerMacroEval_DoResultAndRemove;
  798. }
  799. // If passing and in Waiting state, set macro state to Press
  800. else if ( overallVote & TriggerMacroVote_Pass
  801. && ( record->state == TriggerMacro_Waiting || record->state == TriggerMacro_Press ) )
  802. {
  803. record->state = TriggerMacro_Press;
  804. // If in press state, and this is the final combo, send request for ResultMacro
  805. // Check to see if the result macro only has a single element
  806. // If this result macro has more than 1 key, only send once
  807. // TODO Add option to have long macro repeat rate
  808. if ( macro->guide[ pos + comboLength + 1 ] == 0 )
  809. {
  810. // Long result macro (more than 1 combo)
  811. if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
  812. {
  813. // Only ever trigger result once, on press
  814. if ( overallVote == TriggerMacroVote_Pass )
  815. {
  816. return TriggerMacroEval_DoResultAndRemove;
  817. }
  818. }
  819. // Short result macro
  820. else
  821. {
  822. // Only trigger result once, on press, if long trigger (more than 1 combo)
  823. if ( Macro_isLongTriggerMacro( macro ) )
  824. {
  825. return TriggerMacroEval_DoResultAndRemove;
  826. }
  827. // Otherwise, trigger result continuously
  828. else
  829. {
  830. return TriggerMacroEval_DoResult;
  831. }
  832. }
  833. }
  834. }
  835. // Otherwise, just remove the macro on key release
  836. // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
  837. else if ( overallVote & TriggerMacroVote_Release )
  838. {
  839. return TriggerMacroEval_DoResultAndRemove;
  840. }
  841. // If this is a short macro, just remove it
  842. // The state can be rebuilt on the next iteration
  843. if ( !longMacro )
  844. return TriggerMacroEval_Remove;
  845. return TriggerMacroEval_DoNothing;
  846. }
  847. // Evaluate/Update ResultMacro
  848. inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
  849. {
  850. // Lookup ResultMacro
  851. const ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
  852. ResultMacroRecord *record = &ResultMacroRecordList[ resultMacroIndex ];
  853. // Current Macro position
  854. var_uint_t pos = record->pos;
  855. // Length of combo being processed
  856. uint8_t comboLength = macro->guide[ pos ];
  857. // Function Counter, used to keep track of the combo items processed
  858. var_uint_t funcCount = 0;
  859. // Combo Item Position within the guide
  860. var_uint_t comboItem = pos + 1;
  861. // Iterate through the Result Combo
  862. while ( funcCount < comboLength )
  863. {
  864. // Assign TriggerGuide element (key type, state and scancode)
  865. ResultGuide *guide = (ResultGuide*)(&macro->guide[ comboItem ]);
  866. // Do lookup on capability function
  867. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  868. // Call capability
  869. capability( record->state, record->stateType, &guide->args );
  870. // Increment counters
  871. funcCount++;
  872. comboItem += ResultGuideSize( (ResultGuide*)(&macro->guide[ comboItem ]) );
  873. }
  874. // Move to next item in the sequence
  875. record->pos = comboItem;
  876. // If the ResultMacro is finished, remove
  877. if ( macro->guide[ comboItem ] == 0 )
  878. {
  879. record->pos = 0;
  880. return ResultMacroEval_Remove;
  881. }
  882. // Otherwise leave the macro in the list
  883. return ResultMacroEval_DoNothing;
  884. }
  885. // Update pending trigger list
  886. inline void Macro_updateTriggerMacroPendingList()
  887. {
  888. // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
  889. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  890. {
  891. // TODO LED States
  892. // TODO Analog Switches
  893. // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
  894. if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
  895. continue;
  896. // TODO Analog
  897. // If this is a release case, indicate to layer lookup for possible latch expiry
  898. uint8_t latch_expire = macroTriggerListBuffer[ key ].state == 0x03;
  899. // Lookup Trigger List
  900. nat_ptr_t *triggerList = Macro_layerLookup( &macroTriggerListBuffer[ key ], latch_expire );
  901. // If there was an error during lookup, skip
  902. if ( triggerList == 0 )
  903. continue;
  904. // Number of Triggers in list
  905. nat_ptr_t triggerListSize = triggerList[0];
  906. // Iterate over triggerList to see if any TriggerMacros need to be added
  907. // First item is the number of items in the TriggerList
  908. for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
  909. {
  910. // Lookup trigger macro index
  911. var_uint_t triggerMacroIndex = triggerList[ macro ];
  912. // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
  913. // triggerList needs to be added
  914. var_uint_t pending = 0;
  915. for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
  916. {
  917. // Stop scanning if the trigger macro index is found in the pending list
  918. if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
  919. break;
  920. }
  921. // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
  922. // Add it to the list
  923. if ( pending == macroTriggerMacroPendingListSize )
  924. {
  925. macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
  926. // Reset macro position
  927. TriggerMacroRecordList[ triggerMacroIndex ].pos = 0;
  928. TriggerMacroRecordList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
  929. }
  930. }
  931. }
  932. }
  933. // Macro Procesing Loop
  934. // Called once per USB buffer send
  935. inline void Macro_process()
  936. {
  937. #if defined(ConnectEnabled_define)
  938. // Only compile in if a Connect node module is available
  939. // If this is a interconnect slave node, send all scancodes to master node
  940. if ( !Connect_master )
  941. {
  942. if ( macroTriggerListBufferSize > 0 )
  943. {
  944. Connect_send_ScanCode( Connect_id, macroTriggerListBuffer, macroTriggerListBufferSize );
  945. macroTriggerListBufferSize = 0;
  946. }
  947. return;
  948. }
  949. #endif
  950. // Only do one round of macro processing between Output Module timer sends
  951. if ( USBKeys_Sent != 0 )
  952. return;
  953. #if defined(ConnectEnabled_define)
  954. // Check if there are any ScanCodes in the interconnect cache to process
  955. if ( Connect_master && macroInterconnectCacheSize > 0 )
  956. {
  957. // Iterate over all the cache ScanCodes
  958. uint8_t currentInterconnectCacheSize = macroInterconnectCacheSize;
  959. macroInterconnectCacheSize = 0;
  960. for ( uint8_t c = 0; c < currentInterconnectCacheSize; c++ )
  961. {
  962. // Add to the trigger list
  963. macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = macroInterconnectCache[ c ];
  964. // TODO Handle other TriggerGuide types (e.g. analog)
  965. switch ( macroInterconnectCache[ c ].type )
  966. {
  967. // Normal (Press/Hold/Release)
  968. case 0x00:
  969. // Decide what to do based on the current state
  970. switch ( macroInterconnectCache[ c ].state )
  971. {
  972. // Re-add to interconnect cache in hold state
  973. case 0x01: // Press
  974. //case 0x02: // Hold // XXX Why does this not work? -HaaTa
  975. macroInterconnectCache[ c ].state = 0x02;
  976. macroInterconnectCache[ macroInterconnectCacheSize++ ] = macroInterconnectCache[ c ];
  977. break;
  978. case 0x03: // Remove
  979. break;
  980. // Otherwise, do not re-add
  981. }
  982. }
  983. }
  984. }
  985. #endif
  986. // If the pause flag is set, only process if the step counter is non-zero
  987. if ( macroPauseMode )
  988. {
  989. if ( macroStepCounter == 0 )
  990. return;
  991. // Proceed, decrementing the step counter
  992. macroStepCounter--;
  993. dbug_print("Macro Step");
  994. }
  995. // Update pending trigger list, before processing TriggerMacros
  996. Macro_updateTriggerMacroPendingList();
  997. // Tail pointer for macroTriggerMacroPendingList
  998. // Macros must be explicitly re-added
  999. var_uint_t macroTriggerMacroPendingListTail = 0;
  1000. // Iterate through the pending TriggerMacros, processing each of them
  1001. for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  1002. {
  1003. switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
  1004. {
  1005. // Trigger Result Macro (purposely falling through)
  1006. case TriggerMacroEval_DoResult:
  1007. // Append ResultMacro to PendingList
  1008. Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
  1009. default:
  1010. macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
  1011. break;
  1012. // Trigger Result Macro and Remove (purposely falling through)
  1013. case TriggerMacroEval_DoResultAndRemove:
  1014. // Append ResultMacro to PendingList
  1015. Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
  1016. // Remove Macro from Pending List, nothing to do, removing by default
  1017. case TriggerMacroEval_Remove:
  1018. break;
  1019. }
  1020. }
  1021. // Update the macroTriggerMacroPendingListSize with the tail pointer
  1022. macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
  1023. // Tail pointer for macroResultMacroPendingList
  1024. // Macros must be explicitly re-added
  1025. var_uint_t macroResultMacroPendingListTail = 0;
  1026. // Iterate through the pending ResultMacros, processing each of them
  1027. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  1028. {
  1029. switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
  1030. {
  1031. // Re-add macros to pending list
  1032. case ResultMacroEval_DoNothing:
  1033. default:
  1034. macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
  1035. break;
  1036. // Remove Macro from Pending List, nothing to do, removing by default
  1037. case ResultMacroEval_Remove:
  1038. break;
  1039. }
  1040. }
  1041. // Update the macroResultMacroPendingListSize with the tail pointer
  1042. macroResultMacroPendingListSize = macroResultMacroPendingListTail;
  1043. // Signal buffer that we've used it
  1044. Scan_finishedWithMacro( macroTriggerListBufferSize );
  1045. // Reset TriggerList buffer
  1046. macroTriggerListBufferSize = 0;
  1047. // If Macro debug mode is set, clear the USB Buffer
  1048. if ( macroDebugMode )
  1049. {
  1050. USBKeys_Modifiers = 0;
  1051. USBKeys_Sent = 0;
  1052. }
  1053. }
  1054. inline void Macro_setup()
  1055. {
  1056. // Register Macro CLI dictionary
  1057. CLI_registerDictionary( macroCLIDict, macroCLIDictName );
  1058. // Disable Macro debug mode
  1059. macroDebugMode = 0;
  1060. // Disable Macro pause flag
  1061. macroPauseMode = 0;
  1062. // Set Macro step counter to zero
  1063. macroStepCounter = 0;
  1064. // Make sure macro trigger buffer is empty
  1065. macroTriggerListBufferSize = 0;
  1066. // Set the current rotated layer to 0
  1067. Macro_rotationLayer = 0;
  1068. // Initialize TriggerMacro states
  1069. for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
  1070. {
  1071. TriggerMacroRecordList[ macro ].pos = 0;
  1072. TriggerMacroRecordList[ macro ].state = TriggerMacro_Waiting;
  1073. }
  1074. // Initialize ResultMacro states
  1075. for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
  1076. {
  1077. ResultMacroRecordList[ macro ].pos = 0;
  1078. ResultMacroRecordList[ macro ].state = 0;
  1079. ResultMacroRecordList[ macro ].stateType = 0;
  1080. }
  1081. }
  1082. // ----- CLI Command Functions -----
  1083. void cliFunc_capList( char* args )
  1084. {
  1085. print( NL );
  1086. info_msg("Capabilities List ");
  1087. printHex( CapabilitiesNum );
  1088. // Iterate through all of the capabilities and display them
  1089. for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
  1090. {
  1091. print( NL "\t" );
  1092. printHex( cap );
  1093. print(" - ");
  1094. // Display/Lookup Capability Name (utilize debug mode of capability)
  1095. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  1096. capability( 0xFF, 0xFF, 0 );
  1097. }
  1098. }
  1099. void cliFunc_capSelect( char* args )
  1100. {
  1101. // Parse code from argument
  1102. char* curArgs;
  1103. char* arg1Ptr;
  1104. char* arg2Ptr = args;
  1105. // Total number of args to scan (must do a lookup if a keyboard capability is selected)
  1106. var_uint_t totalArgs = 2; // Always at least two args
  1107. var_uint_t cap = 0;
  1108. // Arguments used for keyboard capability function
  1109. var_uint_t argSetCount = 0;
  1110. uint8_t *argSet = (uint8_t*)args;
  1111. // Process all args
  1112. for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
  1113. {
  1114. curArgs = arg2Ptr;
  1115. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1116. // Stop processing args if no more are found
  1117. // Extra arguments are ignored
  1118. if ( *arg1Ptr == '\0' )
  1119. break;
  1120. // For the first argument, choose the capability
  1121. if ( c == 0 ) switch ( arg1Ptr[0] )
  1122. {
  1123. // Keyboard Capability
  1124. case 'K':
  1125. // Determine capability index
  1126. cap = numToInt( &arg1Ptr[1] );
  1127. // Lookup the number of args
  1128. totalArgs += CapabilitiesList[ cap ].argCount;
  1129. continue;
  1130. }
  1131. // Because allocating memory isn't doable, and the argument count is arbitrary
  1132. // The argument pointer is repurposed as the argument list (much smaller anyways)
  1133. argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
  1134. // Once all the arguments are prepared, call the keyboard capability function
  1135. if ( argSetCount == totalArgs )
  1136. {
  1137. // Indicate that the capability was called
  1138. print( NL );
  1139. info_msg("K");
  1140. printInt8( cap );
  1141. print(" - ");
  1142. printHex( argSet[0] );
  1143. print(" - ");
  1144. printHex( argSet[1] );
  1145. print(" - ");
  1146. printHex( argSet[2] );
  1147. print( "..." NL );
  1148. // Make sure this isn't the reload capability
  1149. // If it is, and the remote reflash define is not set, ignore
  1150. if ( flashModeEnabled_define == 0 ) for ( uint32_t cap = 0; cap < CapabilitiesNum; cap++ )
  1151. {
  1152. if ( CapabilitiesList[ cap ].func == (const void*)Output_flashMode_capability )
  1153. {
  1154. print( NL );
  1155. warn_print("flashModeEnabled not set, cancelling firmware reload...");
  1156. info_msg("Set flashModeEnabled to 1 in your kll configuration.");
  1157. return;
  1158. }
  1159. }
  1160. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  1161. capability( argSet[0], argSet[1], &argSet[2] );
  1162. }
  1163. }
  1164. }
  1165. void cliFunc_keyHold( char* args )
  1166. {
  1167. // Parse codes from arguments
  1168. char* curArgs;
  1169. char* arg1Ptr;
  1170. char* arg2Ptr = args;
  1171. // Process all args
  1172. for ( ;; )
  1173. {
  1174. curArgs = arg2Ptr;
  1175. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1176. // Stop processing args if no more are found
  1177. if ( *arg1Ptr == '\0' )
  1178. break;
  1179. // Ignore non-Scancode numbers
  1180. switch ( arg1Ptr[0] )
  1181. {
  1182. // Scancode
  1183. case 'S':
  1184. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. void cliFunc_keyPress( char* args )
  1190. {
  1191. // Parse codes from arguments
  1192. char* curArgs;
  1193. char* arg1Ptr;
  1194. char* arg2Ptr = args;
  1195. // Process all args
  1196. for ( ;; )
  1197. {
  1198. curArgs = arg2Ptr;
  1199. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1200. // Stop processing args if no more are found
  1201. if ( *arg1Ptr == '\0' )
  1202. break;
  1203. // Ignore non-Scancode numbers
  1204. switch ( arg1Ptr[0] )
  1205. {
  1206. // Scancode
  1207. case 'S':
  1208. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
  1209. break;
  1210. }
  1211. }
  1212. }
  1213. void cliFunc_keyRelease( char* args )
  1214. {
  1215. // Parse codes from arguments
  1216. char* curArgs;
  1217. char* arg1Ptr;
  1218. char* arg2Ptr = args;
  1219. // Process all args
  1220. for ( ;; )
  1221. {
  1222. curArgs = arg2Ptr;
  1223. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1224. // Stop processing args if no more are found
  1225. if ( *arg1Ptr == '\0' )
  1226. break;
  1227. // Ignore non-Scancode numbers
  1228. switch ( arg1Ptr[0] )
  1229. {
  1230. // Scancode
  1231. case 'S':
  1232. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
  1233. break;
  1234. }
  1235. }
  1236. }
  1237. void cliFunc_layerDebug( char *args )
  1238. {
  1239. // Toggle layer debug mode
  1240. layerDebugMode = layerDebugMode ? 0 : 1;
  1241. print( NL );
  1242. info_msg("Layer Debug Mode: ");
  1243. printInt8( layerDebugMode );
  1244. }
  1245. void cliFunc_layerList( char* args )
  1246. {
  1247. print( NL );
  1248. info_msg("Layer List");
  1249. // Iterate through all of the layers and display them
  1250. for ( uint16_t layer = 0; layer < LayerNum; layer++ )
  1251. {
  1252. print( NL "\t" );
  1253. printHex( layer );
  1254. print(" - ");
  1255. // Display layer name
  1256. dPrint( (char*)LayerIndex[ layer ].name );
  1257. // Default map
  1258. if ( layer == 0 )
  1259. print(" \033[1m(default)\033[0m");
  1260. // Layer State
  1261. print( NL "\t\t Layer State: " );
  1262. printHex( LayerState[ layer ] );
  1263. // First -> Last Indices
  1264. print(" First -> Last Indices: ");
  1265. printHex( LayerIndex[ layer ].first );
  1266. print(" -> ");
  1267. printHex( LayerIndex[ layer ].last );
  1268. }
  1269. }
  1270. void cliFunc_layerState( char* args )
  1271. {
  1272. // Parse codes from arguments
  1273. char* curArgs;
  1274. char* arg1Ptr;
  1275. char* arg2Ptr = args;
  1276. uint8_t arg1 = 0;
  1277. uint8_t arg2 = 0;
  1278. // Process first two args
  1279. for ( uint8_t c = 0; c < 2; c++ )
  1280. {
  1281. curArgs = arg2Ptr;
  1282. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1283. // Stop processing args if no more are found
  1284. if ( *arg1Ptr == '\0' )
  1285. break;
  1286. switch ( c )
  1287. {
  1288. // First argument (e.g. L1)
  1289. case 0:
  1290. if ( arg1Ptr[0] != 'L' )
  1291. return;
  1292. arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
  1293. break;
  1294. // Second argument (e.g. 4)
  1295. case 1:
  1296. arg2 = (uint8_t)numToInt( arg1Ptr );
  1297. // Display operation (to indicate that it worked)
  1298. print( NL );
  1299. info_msg("Setting Layer L");
  1300. printInt8( arg1 );
  1301. print(" to - ");
  1302. printHex( arg2 );
  1303. // Set the layer state
  1304. LayerState[ arg1 ] = arg2;
  1305. break;
  1306. }
  1307. }
  1308. }
  1309. void cliFunc_macroDebug( char* args )
  1310. {
  1311. // Toggle macro debug mode
  1312. macroDebugMode = macroDebugMode ? 0 : 1;
  1313. print( NL );
  1314. info_msg("Macro Debug Mode: ");
  1315. printInt8( macroDebugMode );
  1316. }
  1317. void cliFunc_macroList( char* args )
  1318. {
  1319. // Show pending key events
  1320. print( NL );
  1321. info_msg("Pending Key Events: ");
  1322. printInt16( (uint16_t)macroTriggerListBufferSize );
  1323. print(" : ");
  1324. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  1325. {
  1326. printHex( macroTriggerListBuffer[ key ].scanCode );
  1327. print(" ");
  1328. }
  1329. // Show pending trigger macros
  1330. print( NL );
  1331. info_msg("Pending Trigger Macros: ");
  1332. printInt16( (uint16_t)macroTriggerMacroPendingListSize );
  1333. print(" : ");
  1334. for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  1335. {
  1336. printHex( macroTriggerMacroPendingList[ macro ] );
  1337. print(" ");
  1338. }
  1339. // Show pending result macros
  1340. print( NL );
  1341. info_msg("Pending Result Macros: ");
  1342. printInt16( (uint16_t)macroResultMacroPendingListSize );
  1343. print(" : ");
  1344. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  1345. {
  1346. printHex( macroResultMacroPendingList[ macro ] );
  1347. print(" ");
  1348. }
  1349. // Show available trigger macro indices
  1350. print( NL );
  1351. info_msg("Trigger Macros Range: T0 -> T");
  1352. printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  1353. // Show available result macro indices
  1354. print( NL );
  1355. info_msg("Result Macros Range: R0 -> R");
  1356. printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  1357. // Show Trigger to Result Macro Links
  1358. print( NL );
  1359. info_msg("Trigger : Result Macro Pairs");
  1360. for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
  1361. {
  1362. print( NL );
  1363. print("\tT");
  1364. printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
  1365. print(" : R");
  1366. printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
  1367. }
  1368. }
  1369. void cliFunc_macroProc( char* args )
  1370. {
  1371. // Toggle macro pause mode
  1372. macroPauseMode = macroPauseMode ? 0 : 1;
  1373. print( NL );
  1374. info_msg("Macro Processing Mode: ");
  1375. printInt8( macroPauseMode );
  1376. }
  1377. void macroDebugShowTrigger( var_uint_t index )
  1378. {
  1379. // Only proceed if the macro exists
  1380. if ( index >= TriggerMacroNum )
  1381. return;
  1382. // Trigger Macro Show
  1383. const TriggerMacro *macro = &TriggerMacroList[ index ];
  1384. TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
  1385. print( NL );
  1386. info_msg("Trigger Macro Index: ");
  1387. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  1388. print( NL );
  1389. // Read the comboLength for combo in the sequence (sequence of combos)
  1390. var_uint_t pos = 0;
  1391. uint8_t comboLength = macro->guide[ pos ];
  1392. // Iterate through and interpret the guide
  1393. while ( comboLength != 0 )
  1394. {
  1395. // Initial position of the combo
  1396. var_uint_t comboPos = ++pos;
  1397. // Iterate through the combo
  1398. while ( pos < comboLength * TriggerGuideSize + comboPos )
  1399. {
  1400. // Assign TriggerGuide element (key type, state and scancode)
  1401. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
  1402. // Display guide information about trigger key
  1403. printHex( guide->scanCode );
  1404. print("|");
  1405. printHex( guide->type );
  1406. print("|");
  1407. printHex( guide->state );
  1408. // Increment position
  1409. pos += TriggerGuideSize;
  1410. // Only show combo separator if there are combos left in the sequence element
  1411. if ( pos < comboLength * TriggerGuideSize + comboPos )
  1412. print("+");
  1413. }
  1414. // Read the next comboLength
  1415. comboLength = macro->guide[ pos ];
  1416. // Only show sequence separator if there is another combo to process
  1417. if ( comboLength != 0 )
  1418. print(";");
  1419. }
  1420. // Display current position
  1421. print( NL "Position: " );
  1422. printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
  1423. // Display result macro index
  1424. print( NL "Result Macro Index: " );
  1425. printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
  1426. // Display trigger macro state
  1427. print( NL "Trigger Macro State: " );
  1428. switch ( record->state )
  1429. {
  1430. case TriggerMacro_Press: print("Press"); break;
  1431. case TriggerMacro_Release: print("Release"); break;
  1432. case TriggerMacro_Waiting: print("Waiting"); break;
  1433. }
  1434. }
  1435. void macroDebugShowResult( var_uint_t index )
  1436. {
  1437. // Only proceed if the macro exists
  1438. if ( index >= ResultMacroNum )
  1439. return;
  1440. // Trigger Macro Show
  1441. const ResultMacro *macro = &ResultMacroList[ index ];
  1442. ResultMacroRecord *record = &ResultMacroRecordList[ index ];
  1443. print( NL );
  1444. info_msg("Result Macro Index: ");
  1445. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  1446. print( NL );
  1447. // Read the comboLength for combo in the sequence (sequence of combos)
  1448. var_uint_t pos = 0;
  1449. uint8_t comboLength = macro->guide[ pos++ ];
  1450. // Iterate through and interpret the guide
  1451. while ( comboLength != 0 )
  1452. {
  1453. // Function Counter, used to keep track of the combos processed
  1454. var_uint_t funcCount = 0;
  1455. // Iterate through the combo
  1456. while ( funcCount < comboLength )
  1457. {
  1458. // Assign TriggerGuide element (key type, state and scancode)
  1459. ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
  1460. // Display Function Index
  1461. printHex( guide->index );
  1462. print("|");
  1463. // Display Function Ptr Address
  1464. printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
  1465. print("|");
  1466. // Display/Lookup Capability Name (utilize debug mode of capability)
  1467. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  1468. capability( 0xFF, 0xFF, 0 );
  1469. // Display Argument(s)
  1470. print("(");
  1471. for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
  1472. {
  1473. // Arguments are only 8 bit values
  1474. printHex( (&guide->args)[ arg ] );
  1475. // Only show arg separator if there are args left
  1476. if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
  1477. print(",");
  1478. }
  1479. print(")");
  1480. // Increment position
  1481. pos += ResultGuideSize( guide );
  1482. // Increment function count
  1483. funcCount++;
  1484. // Only show combo separator if there are combos left in the sequence element
  1485. if ( funcCount < comboLength )
  1486. print("+");
  1487. }
  1488. // Read the next comboLength
  1489. comboLength = macro->guide[ pos++ ];
  1490. // Only show sequence separator if there is another combo to process
  1491. if ( comboLength != 0 )
  1492. print(";");
  1493. }
  1494. // Display current position
  1495. print( NL "Position: " );
  1496. printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
  1497. // Display final trigger state/type
  1498. print( NL "Final Trigger State (State/Type): " );
  1499. printHex( record->state );
  1500. print("/");
  1501. printHex( record->stateType );
  1502. }
  1503. void cliFunc_macroShow( char* args )
  1504. {
  1505. // Parse codes from arguments
  1506. char* curArgs;
  1507. char* arg1Ptr;
  1508. char* arg2Ptr = args;
  1509. // Process all args
  1510. for ( ;; )
  1511. {
  1512. curArgs = arg2Ptr;
  1513. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1514. // Stop processing args if no more are found
  1515. if ( *arg1Ptr == '\0' )
  1516. break;
  1517. // Ignore invalid codes
  1518. switch ( arg1Ptr[0] )
  1519. {
  1520. // Indexed Trigger Macro
  1521. case 'T':
  1522. macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
  1523. break;
  1524. // Indexed Result Macro
  1525. case 'R':
  1526. macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
  1527. break;
  1528. }
  1529. }
  1530. }
  1531. void cliFunc_macroStep( char* args )
  1532. {
  1533. // Parse number from argument
  1534. // NOTE: Only first argument is used
  1535. char* arg1Ptr;
  1536. char* arg2Ptr;
  1537. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  1538. // Default to 1, if no argument given
  1539. var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
  1540. if ( count == 0 )
  1541. count = 1;
  1542. // Set the macro step counter, negative int's are cast to uint
  1543. macroStepCounter = count;
  1544. }