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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829
  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. return map[ scanCode - layer->first ];
  343. }
  344. // If no trigger macro is defined at the given layer, fallthrough to the next layer
  345. for ( uint16_t layerIndex = macroLayerIndexStackSize; layerIndex != 0xFFFF; layerIndex-- )
  346. {
  347. // Lookup Layer
  348. const Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
  349. // Check if latch has been pressed for this layer
  350. // XXX Regardless of whether a key is found, the latch is removed on first lookup
  351. uint8_t latch = LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x02;
  352. if ( latch && latch_expire )
  353. {
  354. Macro_layerState( 0, 0, macroLayerIndexStack[ layerIndex ], 0x02 );
  355. }
  356. // Only use layer, if state is valid
  357. // XOR each of the state bits
  358. // If only two are enabled, do not use this state
  359. if ( (LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x01) ^ (latch>>1) ^ ((LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x04)>>2) )
  360. {
  361. // Lookup layer
  362. nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
  363. // Determine if layer has key defined
  364. // Make sure scanCode is between layer first and last scancodes
  365. if ( map != 0
  366. && scanCode <= layer->last
  367. && scanCode >= layer->first
  368. && *map[ scanCode - layer->first ] != 0 )
  369. {
  370. // Set the layer cache
  371. macroTriggerListLayerCache[ scanCode ] = macroLayerIndexStack[ layerIndex ];
  372. return map[ scanCode - layer->first ];
  373. }
  374. }
  375. }
  376. // Do lookup on default layer
  377. nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
  378. // Lookup default layer
  379. const Layer *layer = &LayerIndex[0];
  380. // Make sure scanCode is between layer first and last scancodes
  381. if ( map != 0
  382. && scanCode <= layer->last
  383. && scanCode >= layer->first
  384. && *map[ scanCode - layer->first ] != 0 )
  385. {
  386. // Set the layer cache to default map
  387. macroTriggerListLayerCache[ scanCode ] = 0;
  388. return map[ scanCode - layer->first ];
  389. }
  390. // Otherwise no defined Trigger Macro
  391. erro_msg("Scan Code has no defined Trigger Macro: ");
  392. printHex( scanCode );
  393. print( NL );
  394. return 0;
  395. }
  396. // Add an interconnect ScanCode
  397. // These are handled differently (less information is sent, hold/off states must be assumed)
  398. #if defined(ConnectEnabled_define)
  399. inline void Macro_interconnectAdd( void *trigger_ptr )
  400. {
  401. TriggerGuide *trigger = (TriggerGuide*)trigger_ptr;
  402. // Error checking
  403. uint8_t error = 0;
  404. switch ( trigger->type )
  405. {
  406. case 0x00: // Normal key
  407. switch ( trigger->state )
  408. {
  409. case 0x00:
  410. case 0x01:
  411. case 0x02:
  412. case 0x03:
  413. break;
  414. default:
  415. erro_msg("Invalid key state - ");
  416. error = 1;
  417. break;
  418. }
  419. break;
  420. // Invalid TriggerGuide type
  421. default:
  422. erro_msg("Invalid type - ");
  423. error = 1;
  424. break;
  425. }
  426. // Check if ScanCode is out of range
  427. if ( trigger->scanCode > MaxScanCode )
  428. {
  429. warn_msg("ScanCode is out of range/not defined - ");
  430. error = 1;
  431. }
  432. // Display TriggerGuide
  433. if ( error )
  434. {
  435. printHex( trigger->type );
  436. print(" ");
  437. printHex( trigger->state );
  438. print(" ");
  439. printHex( trigger->scanCode );
  440. print( NL );
  441. return;
  442. }
  443. // Add trigger to the Interconnect Cache
  444. // During each processing loop, a scancode may be re-added depending on it's state
  445. for ( uint8_t c = 0; c < macroInterconnectCacheSize; c++ )
  446. {
  447. // Check if the same ScanCode
  448. if ( macroInterconnectCache[ c ].scanCode == trigger->scanCode )
  449. {
  450. // Update the state
  451. macroInterconnectCache[ c ].state = trigger->state;
  452. return;
  453. }
  454. }
  455. // If not in the list, add it
  456. macroInterconnectCache[ macroInterconnectCacheSize++ ] = *trigger;
  457. }
  458. #endif
  459. // Update the scancode key state
  460. // States:
  461. // * 0x00 - Off
  462. // * 0x01 - Pressed
  463. // * 0x02 - Held
  464. // * 0x03 - Released
  465. // * 0x04 - Unpressed (this is currently ignored)
  466. inline void Macro_keyState( uint8_t scanCode, uint8_t state )
  467. {
  468. #if defined(ConnectEnabled_define)
  469. // Only compile in if a Connect node module is available
  470. if ( !Connect_master )
  471. {
  472. // ScanCodes are only added if there was a state change (on/off)
  473. switch ( state )
  474. {
  475. case 0x00: // Off
  476. case 0x02: // Held
  477. return;
  478. }
  479. }
  480. #endif
  481. // Only add to macro trigger list if one of three states
  482. switch ( state )
  483. {
  484. case 0x01: // Pressed
  485. case 0x02: // Held
  486. case 0x03: // Released
  487. // Check if ScanCode is out of range
  488. if ( scanCode > MaxScanCode )
  489. {
  490. warn_msg("ScanCode is out of range/not defined: ");
  491. printHex( scanCode );
  492. print( NL );
  493. return;
  494. }
  495. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  496. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  497. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
  498. macroTriggerListBufferSize++;
  499. break;
  500. }
  501. }
  502. // Update the scancode analog state
  503. // States:
  504. // * 0x00 - Off
  505. // * 0x01 - Released
  506. // * 0x02-0xFF - Analog value (low to high)
  507. inline void Macro_analogState( uint8_t scanCode, uint8_t state )
  508. {
  509. // Only add to macro trigger list if non-off
  510. // TODO Handle change for interconnect
  511. if ( state != 0x00 )
  512. {
  513. // Check if ScanCode is out of range
  514. if ( scanCode > MaxScanCode )
  515. {
  516. warn_msg("ScanCode is out of range/not defined: ");
  517. printHex( scanCode );
  518. print( NL );
  519. return;
  520. }
  521. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
  522. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  523. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
  524. macroTriggerListBufferSize++;
  525. }
  526. }
  527. // Update led state
  528. // States:
  529. // * 0x00 - Off
  530. // * 0x01 - On
  531. inline void Macro_ledState( uint8_t ledCode, uint8_t state )
  532. {
  533. // Only add to macro trigger list if non-off
  534. // TODO Handle change for interconnect
  535. if ( state != 0x00 )
  536. {
  537. // Check if LedCode is out of range
  538. // TODO
  539. macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
  540. macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
  541. macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
  542. macroTriggerListBufferSize++;
  543. }
  544. }
  545. // Append result macro to pending list, checking for duplicates
  546. // Do nothing if duplicate
  547. inline void Macro_appendResultMacroToPendingList( const TriggerMacro *triggerMacro )
  548. {
  549. // Lookup result macro index
  550. var_uint_t resultMacroIndex = triggerMacro->result;
  551. // Iterate through result macro pending list, making sure this macro hasn't been added yet
  552. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  553. {
  554. // If duplicate found, do nothing
  555. if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
  556. return;
  557. }
  558. // No duplicates found, add to pending list
  559. macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
  560. // Lookup scanCode of the last key in the last combo
  561. var_uint_t pos = 0;
  562. for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
  563. {
  564. pos += TriggerGuideSize * comboLength + 1;
  565. comboLength = triggerMacro->guide[ pos ];
  566. }
  567. uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
  568. // Lookup scanCode in buffer list for the current state and stateType
  569. for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
  570. {
  571. if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
  572. {
  573. ResultMacroRecordList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
  574. ResultMacroRecordList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
  575. }
  576. }
  577. // Reset the macro position
  578. ResultMacroRecordList[ resultMacroIndex ].pos = 0;
  579. }
  580. // Determine if long ResultMacro (more than 1 seqence element)
  581. inline uint8_t Macro_isLongResultMacro( const ResultMacro *macro )
  582. {
  583. // Check the second sequence combo length
  584. // If non-zero return non-zero (long sequence)
  585. // 0 otherwise (short sequence)
  586. var_uint_t position = 1;
  587. for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
  588. position += ResultGuideSize( (ResultGuide*)&macro->guide[ position ] );
  589. return macro->guide[ position ];
  590. }
  591. // Determine if long TriggerMacro (more than 1 sequence element)
  592. inline uint8_t Macro_isLongTriggerMacro( const TriggerMacro *macro )
  593. {
  594. // Check the second sequence combo length
  595. // If non-zero return non-zero (long sequence)
  596. // 0 otherwise (short sequence)
  597. return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
  598. }
  599. // Votes on the given key vs. guide, short macros
  600. inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
  601. {
  602. // Depending on key type
  603. switch ( guide->type )
  604. {
  605. // Normal State Type
  606. case 0x00:
  607. // For short TriggerMacros completely ignore incorrect keys
  608. if ( guide->scanCode == key->scanCode )
  609. {
  610. switch ( key->state )
  611. {
  612. // Correct key, pressed, possible passing
  613. case 0x01:
  614. return TriggerMacroVote_Pass;
  615. // Correct key, held, possible passing or release
  616. case 0x02:
  617. return TriggerMacroVote_PassRelease;
  618. // Correct key, released, possible release
  619. case 0x03:
  620. return TriggerMacroVote_Release;
  621. }
  622. }
  623. return TriggerMacroVote_DoNothing;
  624. // LED State Type
  625. case 0x01:
  626. erro_print("LED State Type - Not implemented...");
  627. break;
  628. // Analog State Type
  629. case 0x02:
  630. erro_print("Analog State Type - Not implemented...");
  631. break;
  632. // Invalid State Type
  633. default:
  634. erro_print("Invalid State Type. This is a bug.");
  635. break;
  636. }
  637. // XXX Shouldn't reach here
  638. return TriggerMacroVote_Invalid;
  639. }
  640. // Votes on the given key vs. guide, long macros
  641. // A long macro is defined as a guide with more than 1 combo
  642. inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
  643. {
  644. // Depending on key type
  645. switch ( guide->type )
  646. {
  647. // Normal State Type
  648. case 0x00:
  649. // Depending on the state of the buffered key, make voting decision
  650. // Incorrect key
  651. if ( guide->scanCode != key->scanCode )
  652. {
  653. switch ( key->state )
  654. {
  655. // Wrong key, pressed, fail
  656. case 0x01:
  657. return TriggerMacroVote_Fail;
  658. // Wrong key, held, do not pass (no effect)
  659. case 0x02:
  660. return TriggerMacroVote_DoNothing;
  661. // Wrong key released, fail out if pos == 0
  662. case 0x03:
  663. return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
  664. }
  665. }
  666. // Correct key
  667. else
  668. {
  669. switch ( key->state )
  670. {
  671. // Correct key, pressed, possible passing
  672. case 0x01:
  673. return TriggerMacroVote_Pass;
  674. // Correct key, held, possible passing or release
  675. case 0x02:
  676. return TriggerMacroVote_PassRelease;
  677. // Correct key, released, possible release
  678. case 0x03:
  679. return TriggerMacroVote_Release;
  680. }
  681. }
  682. break;
  683. // LED State Type
  684. case 0x01:
  685. erro_print("LED State Type - Not implemented...");
  686. break;
  687. // Analog State Type
  688. case 0x02:
  689. erro_print("Analog State Type - Not implemented...");
  690. break;
  691. // Invalid State Type
  692. default:
  693. erro_print("Invalid State Type. This is a bug.");
  694. break;
  695. }
  696. // XXX Shouldn't reach here
  697. return TriggerMacroVote_Invalid;
  698. }
  699. // Evaluate/Update TriggerMacro
  700. TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
  701. {
  702. // Lookup TriggerMacro
  703. const TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
  704. TriggerMacroRecord *record = &TriggerMacroRecordList[ triggerMacroIndex ];
  705. // Check if macro has finished and should be incremented sequence elements
  706. if ( record->state == TriggerMacro_Release )
  707. {
  708. record->state = TriggerMacro_Waiting;
  709. record->pos = record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1;
  710. }
  711. // Current Macro position
  712. var_uint_t pos = record->pos;
  713. // Length of the combo being processed
  714. uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
  715. // If no combo items are left, remove the TriggerMacro from the pending list
  716. if ( comboLength == 0 )
  717. {
  718. return TriggerMacroEval_Remove;
  719. }
  720. // Check if this is a long Trigger Macro
  721. uint8_t longMacro = Macro_isLongTriggerMacro( macro );
  722. // Iterate through the items in the combo, voting the on the key state
  723. // If any of the pressed keys do not match, fail the macro
  724. //
  725. // The macro is waiting for input when in the TriggerMacro_Waiting state
  726. // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
  727. // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
  728. // On scan after position increment, change to TriggerMacro_Waiting state
  729. // TODO Add support for system LED states (NumLock, CapsLock, etc.)
  730. // TODO Add support for analog key states
  731. // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
  732. // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
  733. TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
  734. for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
  735. {
  736. // Assign TriggerGuide element (key type, state and scancode)
  737. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ comboItem ]);
  738. TriggerMacroVote vote = TriggerMacroVote_Invalid;
  739. // Iterate through the key buffer, comparing to each key in the combo
  740. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  741. {
  742. // Lookup key information
  743. TriggerGuide *keyInfo = &macroTriggerListBuffer[ key ];
  744. // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
  745. // Also mask all of the non-passing votes
  746. vote |= longMacro
  747. ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
  748. : Macro_evalShortTriggerMacroVote( keyInfo, guide );
  749. if ( vote >= TriggerMacroVote_Pass )
  750. {
  751. vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
  752. break;
  753. }
  754. }
  755. // If no pass vote was found after scanning all of the keys
  756. // Fail the combo, if this is a short macro (long macros already will have a fail vote)
  757. if ( !longMacro && vote < TriggerMacroVote_Pass )
  758. vote |= TriggerMacroVote_Fail;
  759. // After voting, append to overall vote
  760. overallVote |= vote;
  761. }
  762. // If no pass vote was found after scanning the entire combo
  763. // And this is the first position in the combo, just remove it (nothing important happened)
  764. if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
  765. overallVote |= TriggerMacroVote_Fail;
  766. // Decide new state of macro after voting
  767. // Fail macro, remove from pending list
  768. if ( overallVote & TriggerMacroVote_Fail )
  769. {
  770. return TriggerMacroEval_Remove;
  771. }
  772. // Do nothing, incorrect key is being held or released
  773. else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
  774. {
  775. // Just doing nothing :)
  776. }
  777. // If ready for transition and in Press state, set to Waiting and increment combo position
  778. // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
  779. else if ( overallVote & TriggerMacroVote_Release && record->state == TriggerMacro_Press )
  780. {
  781. record->state = TriggerMacro_Release;
  782. // If this is the last combo in the sequence, remove from the pending list
  783. if ( macro->guide[ record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1 ] == 0 )
  784. return TriggerMacroEval_DoResultAndRemove;
  785. }
  786. // If passing and in Waiting state, set macro state to Press
  787. else if ( overallVote & TriggerMacroVote_Pass
  788. && ( record->state == TriggerMacro_Waiting || record->state == TriggerMacro_Press ) )
  789. {
  790. record->state = TriggerMacro_Press;
  791. // If in press state, and this is the final combo, send request for ResultMacro
  792. // Check to see if the result macro only has a single element
  793. // If this result macro has more than 1 key, only send once
  794. // TODO Add option to have long macro repeat rate
  795. if ( macro->guide[ pos + comboLength + 1 ] == 0 )
  796. {
  797. // Long result macro (more than 1 combo)
  798. if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
  799. {
  800. // Only ever trigger result once, on press
  801. if ( overallVote == TriggerMacroVote_Pass )
  802. {
  803. return TriggerMacroEval_DoResultAndRemove;
  804. }
  805. }
  806. // Short result macro
  807. else
  808. {
  809. // Only trigger result once, on press, if long trigger (more than 1 combo)
  810. if ( Macro_isLongTriggerMacro( macro ) )
  811. {
  812. return TriggerMacroEval_DoResultAndRemove;
  813. }
  814. // Otherwise, trigger result continuously
  815. else
  816. {
  817. return TriggerMacroEval_DoResult;
  818. }
  819. }
  820. }
  821. }
  822. // Otherwise, just remove the macro on key release
  823. // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
  824. else if ( overallVote & TriggerMacroVote_Release )
  825. {
  826. return TriggerMacroEval_DoResultAndRemove;
  827. }
  828. // If this is a short macro, just remove it
  829. // The state can be rebuilt on the next iteration
  830. if ( !longMacro )
  831. return TriggerMacroEval_Remove;
  832. return TriggerMacroEval_DoNothing;
  833. }
  834. // Evaluate/Update ResultMacro
  835. inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
  836. {
  837. // Lookup ResultMacro
  838. const ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
  839. ResultMacroRecord *record = &ResultMacroRecordList[ resultMacroIndex ];
  840. // Current Macro position
  841. var_uint_t pos = record->pos;
  842. // Length of combo being processed
  843. uint8_t comboLength = macro->guide[ pos ];
  844. // Function Counter, used to keep track of the combo items processed
  845. var_uint_t funcCount = 0;
  846. // Combo Item Position within the guide
  847. var_uint_t comboItem = pos + 1;
  848. // Iterate through the Result Combo
  849. while ( funcCount < comboLength )
  850. {
  851. // Assign TriggerGuide element (key type, state and scancode)
  852. ResultGuide *guide = (ResultGuide*)(&macro->guide[ comboItem ]);
  853. // Do lookup on capability function
  854. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  855. // Call capability
  856. capability( record->state, record->stateType, &guide->args );
  857. // Increment counters
  858. funcCount++;
  859. comboItem += ResultGuideSize( (ResultGuide*)(&macro->guide[ comboItem ]) );
  860. }
  861. // Move to next item in the sequence
  862. record->pos = comboItem;
  863. // If the ResultMacro is finished, remove
  864. if ( macro->guide[ comboItem ] == 0 )
  865. {
  866. record->pos = 0;
  867. return ResultMacroEval_Remove;
  868. }
  869. // Otherwise leave the macro in the list
  870. return ResultMacroEval_DoNothing;
  871. }
  872. // Update pending trigger list
  873. inline void Macro_updateTriggerMacroPendingList()
  874. {
  875. // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
  876. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  877. {
  878. // TODO LED States
  879. // TODO Analog Switches
  880. // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
  881. if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
  882. continue;
  883. // TODO Analog
  884. // If this is a release case, indicate to layer lookup for possible latch expiry
  885. uint8_t latch_expire = macroTriggerListBuffer[ key ].state == 0x03;
  886. // Lookup Trigger List
  887. nat_ptr_t *triggerList = Macro_layerLookup( &macroTriggerListBuffer[ key ], latch_expire );
  888. // If there was an error during lookup, skip
  889. if ( triggerList == 0 )
  890. continue;
  891. // Number of Triggers in list
  892. nat_ptr_t triggerListSize = triggerList[0];
  893. // Iterate over triggerList to see if any TriggerMacros need to be added
  894. // First item is the number of items in the TriggerList
  895. for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
  896. {
  897. // Lookup trigger macro index
  898. var_uint_t triggerMacroIndex = triggerList[ macro ];
  899. // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
  900. // triggerList needs to be added
  901. var_uint_t pending = 0;
  902. for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
  903. {
  904. // Stop scanning if the trigger macro index is found in the pending list
  905. if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
  906. break;
  907. }
  908. // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
  909. // Add it to the list
  910. if ( pending == macroTriggerMacroPendingListSize )
  911. {
  912. macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
  913. // Reset macro position
  914. TriggerMacroRecordList[ triggerMacroIndex ].pos = 0;
  915. TriggerMacroRecordList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
  916. }
  917. }
  918. }
  919. }
  920. // Macro Procesing Loop
  921. // Called once per USB buffer send
  922. inline void Macro_process()
  923. {
  924. #if defined(ConnectEnabled_define)
  925. // Only compile in if a Connect node module is available
  926. // If this is a interconnect slave node, send all scancodes to master node
  927. if ( !Connect_master )
  928. {
  929. if ( macroTriggerListBufferSize > 0 )
  930. {
  931. Connect_send_ScanCode( Connect_id, macroTriggerListBuffer, macroTriggerListBufferSize );
  932. macroTriggerListBufferSize = 0;
  933. }
  934. return;
  935. }
  936. #endif
  937. // Only do one round of macro processing between Output Module timer sends
  938. if ( USBKeys_Sent != 0 )
  939. return;
  940. #if defined(ConnectEnabled_define)
  941. // Check if there are any ScanCodes in the interconnect cache to process
  942. if ( Connect_master && macroInterconnectCacheSize > 0 )
  943. {
  944. // Iterate over all the cache ScanCodes
  945. uint8_t currentInterconnectCacheSize = macroInterconnectCacheSize;
  946. macroInterconnectCacheSize = 0;
  947. for ( uint8_t c = 0; c < currentInterconnectCacheSize; c++ )
  948. {
  949. // Add to the trigger list
  950. macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = macroInterconnectCache[ c ];
  951. // TODO Handle other TriggerGuide types (e.g. analog)
  952. switch ( macroInterconnectCache[ c ].type )
  953. {
  954. // Normal (Press/Hold/Release)
  955. case 0x00:
  956. // Decide what to do based on the current state
  957. switch ( macroInterconnectCache[ c ].state )
  958. {
  959. // Re-add to interconnect cache in hold state
  960. case 0x01: // Press
  961. //case 0x02: // Hold // XXX Why does this not work? -HaaTa
  962. macroInterconnectCache[ c ].state = 0x02;
  963. macroInterconnectCache[ macroInterconnectCacheSize++ ] = macroInterconnectCache[ c ];
  964. break;
  965. case 0x03: // Remove
  966. break;
  967. // Otherwise, do not re-add
  968. }
  969. }
  970. }
  971. }
  972. #endif
  973. // If the pause flag is set, only process if the step counter is non-zero
  974. if ( macroPauseMode )
  975. {
  976. if ( macroStepCounter == 0 )
  977. return;
  978. // Proceed, decrementing the step counter
  979. macroStepCounter--;
  980. dbug_print("Macro Step");
  981. }
  982. // Update pending trigger list, before processing TriggerMacros
  983. Macro_updateTriggerMacroPendingList();
  984. // Tail pointer for macroTriggerMacroPendingList
  985. // Macros must be explicitly re-added
  986. var_uint_t macroTriggerMacroPendingListTail = 0;
  987. // Iterate through the pending TriggerMacros, processing each of them
  988. for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  989. {
  990. switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
  991. {
  992. // Trigger Result Macro (purposely falling through)
  993. case TriggerMacroEval_DoResult:
  994. // Append ResultMacro to PendingList
  995. Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
  996. default:
  997. macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
  998. break;
  999. // Trigger Result Macro and Remove (purposely falling through)
  1000. case TriggerMacroEval_DoResultAndRemove:
  1001. // Append ResultMacro to PendingList
  1002. Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
  1003. // Remove Macro from Pending List, nothing to do, removing by default
  1004. case TriggerMacroEval_Remove:
  1005. break;
  1006. }
  1007. }
  1008. // Update the macroTriggerMacroPendingListSize with the tail pointer
  1009. macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
  1010. // Tail pointer for macroResultMacroPendingList
  1011. // Macros must be explicitly re-added
  1012. var_uint_t macroResultMacroPendingListTail = 0;
  1013. // Iterate through the pending ResultMacros, processing each of them
  1014. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  1015. {
  1016. switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
  1017. {
  1018. // Re-add macros to pending list
  1019. case ResultMacroEval_DoNothing:
  1020. default:
  1021. macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
  1022. break;
  1023. // Remove Macro from Pending List, nothing to do, removing by default
  1024. case ResultMacroEval_Remove:
  1025. break;
  1026. }
  1027. }
  1028. // Update the macroResultMacroPendingListSize with the tail pointer
  1029. macroResultMacroPendingListSize = macroResultMacroPendingListTail;
  1030. // Signal buffer that we've used it
  1031. Scan_finishedWithMacro( macroTriggerListBufferSize );
  1032. // Reset TriggerList buffer
  1033. macroTriggerListBufferSize = 0;
  1034. // If Macro debug mode is set, clear the USB Buffer
  1035. if ( macroDebugMode )
  1036. {
  1037. USBKeys_Modifiers = 0;
  1038. USBKeys_Sent = 0;
  1039. }
  1040. }
  1041. inline void Macro_setup()
  1042. {
  1043. // Register Macro CLI dictionary
  1044. CLI_registerDictionary( macroCLIDict, macroCLIDictName );
  1045. // Disable Macro debug mode
  1046. macroDebugMode = 0;
  1047. // Disable Macro pause flag
  1048. macroPauseMode = 0;
  1049. // Set Macro step counter to zero
  1050. macroStepCounter = 0;
  1051. // Make sure macro trigger buffer is empty
  1052. macroTriggerListBufferSize = 0;
  1053. // Set the current rotated layer to 0
  1054. Macro_rotationLayer = 0;
  1055. // Initialize TriggerMacro states
  1056. for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
  1057. {
  1058. TriggerMacroRecordList[ macro ].pos = 0;
  1059. TriggerMacroRecordList[ macro ].state = TriggerMacro_Waiting;
  1060. }
  1061. // Initialize ResultMacro states
  1062. for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
  1063. {
  1064. ResultMacroRecordList[ macro ].pos = 0;
  1065. ResultMacroRecordList[ macro ].state = 0;
  1066. ResultMacroRecordList[ macro ].stateType = 0;
  1067. }
  1068. }
  1069. // ----- CLI Command Functions -----
  1070. void cliFunc_capList( char* args )
  1071. {
  1072. print( NL );
  1073. info_msg("Capabilities List ");
  1074. printHex( CapabilitiesNum );
  1075. // Iterate through all of the capabilities and display them
  1076. for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
  1077. {
  1078. print( NL "\t" );
  1079. printHex( cap );
  1080. print(" - ");
  1081. // Display/Lookup Capability Name (utilize debug mode of capability)
  1082. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  1083. capability( 0xFF, 0xFF, 0 );
  1084. }
  1085. }
  1086. void cliFunc_capSelect( char* args )
  1087. {
  1088. // Parse code from argument
  1089. char* curArgs;
  1090. char* arg1Ptr;
  1091. char* arg2Ptr = args;
  1092. // Total number of args to scan (must do a lookup if a keyboard capability is selected)
  1093. var_uint_t totalArgs = 2; // Always at least two args
  1094. var_uint_t cap = 0;
  1095. // Arguments used for keyboard capability function
  1096. var_uint_t argSetCount = 0;
  1097. uint8_t *argSet = (uint8_t*)args;
  1098. // Process all args
  1099. for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
  1100. {
  1101. curArgs = arg2Ptr;
  1102. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1103. // Stop processing args if no more are found
  1104. // Extra arguments are ignored
  1105. if ( *arg1Ptr == '\0' )
  1106. break;
  1107. // For the first argument, choose the capability
  1108. if ( c == 0 ) switch ( arg1Ptr[0] )
  1109. {
  1110. // Keyboard Capability
  1111. case 'K':
  1112. // Determine capability index
  1113. cap = numToInt( &arg1Ptr[1] );
  1114. // Lookup the number of args
  1115. totalArgs += CapabilitiesList[ cap ].argCount;
  1116. continue;
  1117. }
  1118. // Because allocating memory isn't doable, and the argument count is arbitrary
  1119. // The argument pointer is repurposed as the argument list (much smaller anyways)
  1120. argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
  1121. // Once all the arguments are prepared, call the keyboard capability function
  1122. if ( argSetCount == totalArgs )
  1123. {
  1124. // Indicate that the capability was called
  1125. print( NL );
  1126. info_msg("K");
  1127. printInt8( cap );
  1128. print(" - ");
  1129. printHex( argSet[0] );
  1130. print(" - ");
  1131. printHex( argSet[1] );
  1132. print(" - ");
  1133. printHex( argSet[2] );
  1134. print( "..." NL );
  1135. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  1136. capability( argSet[0], argSet[1], &argSet[2] );
  1137. }
  1138. }
  1139. }
  1140. void cliFunc_keyHold( char* args )
  1141. {
  1142. // Parse codes from arguments
  1143. char* curArgs;
  1144. char* arg1Ptr;
  1145. char* arg2Ptr = args;
  1146. // Process all args
  1147. for ( ;; )
  1148. {
  1149. curArgs = arg2Ptr;
  1150. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1151. // Stop processing args if no more are found
  1152. if ( *arg1Ptr == '\0' )
  1153. break;
  1154. // Ignore non-Scancode numbers
  1155. switch ( arg1Ptr[0] )
  1156. {
  1157. // Scancode
  1158. case 'S':
  1159. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
  1160. break;
  1161. }
  1162. }
  1163. }
  1164. void cliFunc_keyPress( char* args )
  1165. {
  1166. // Parse codes from arguments
  1167. char* curArgs;
  1168. char* arg1Ptr;
  1169. char* arg2Ptr = args;
  1170. // Process all args
  1171. for ( ;; )
  1172. {
  1173. curArgs = arg2Ptr;
  1174. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1175. // Stop processing args if no more are found
  1176. if ( *arg1Ptr == '\0' )
  1177. break;
  1178. // Ignore non-Scancode numbers
  1179. switch ( arg1Ptr[0] )
  1180. {
  1181. // Scancode
  1182. case 'S':
  1183. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
  1184. break;
  1185. }
  1186. }
  1187. }
  1188. void cliFunc_keyRelease( char* args )
  1189. {
  1190. // Parse codes from arguments
  1191. char* curArgs;
  1192. char* arg1Ptr;
  1193. char* arg2Ptr = args;
  1194. // Process all args
  1195. for ( ;; )
  1196. {
  1197. curArgs = arg2Ptr;
  1198. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1199. // Stop processing args if no more are found
  1200. if ( *arg1Ptr == '\0' )
  1201. break;
  1202. // Ignore non-Scancode numbers
  1203. switch ( arg1Ptr[0] )
  1204. {
  1205. // Scancode
  1206. case 'S':
  1207. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
  1208. break;
  1209. }
  1210. }
  1211. }
  1212. void cliFunc_layerDebug( char *args )
  1213. {
  1214. // Toggle layer debug mode
  1215. layerDebugMode = layerDebugMode ? 0 : 1;
  1216. print( NL );
  1217. info_msg("Layer Debug Mode: ");
  1218. printInt8( layerDebugMode );
  1219. }
  1220. void cliFunc_layerList( char* args )
  1221. {
  1222. print( NL );
  1223. info_msg("Layer List");
  1224. // Iterate through all of the layers and display them
  1225. for ( uint16_t layer = 0; layer < LayerNum; layer++ )
  1226. {
  1227. print( NL "\t" );
  1228. printHex( layer );
  1229. print(" - ");
  1230. // Display layer name
  1231. dPrint( (char*)LayerIndex[ layer ].name );
  1232. // Default map
  1233. if ( layer == 0 )
  1234. print(" \033[1m(default)\033[0m");
  1235. // Layer State
  1236. print( NL "\t\t Layer State: " );
  1237. printHex( LayerState[ layer ] );
  1238. // First -> Last Indices
  1239. print(" First -> Last Indices: ");
  1240. printHex( LayerIndex[ layer ].first );
  1241. print(" -> ");
  1242. printHex( LayerIndex[ layer ].last );
  1243. }
  1244. }
  1245. void cliFunc_layerState( char* args )
  1246. {
  1247. // Parse codes from arguments
  1248. char* curArgs;
  1249. char* arg1Ptr;
  1250. char* arg2Ptr = args;
  1251. uint8_t arg1 = 0;
  1252. uint8_t arg2 = 0;
  1253. // Process first two args
  1254. for ( uint8_t c = 0; c < 2; c++ )
  1255. {
  1256. curArgs = arg2Ptr;
  1257. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1258. // Stop processing args if no more are found
  1259. if ( *arg1Ptr == '\0' )
  1260. break;
  1261. switch ( c )
  1262. {
  1263. // First argument (e.g. L1)
  1264. case 0:
  1265. if ( arg1Ptr[0] != 'L' )
  1266. return;
  1267. arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
  1268. break;
  1269. // Second argument (e.g. 4)
  1270. case 1:
  1271. arg2 = (uint8_t)numToInt( arg1Ptr );
  1272. // Display operation (to indicate that it worked)
  1273. print( NL );
  1274. info_msg("Setting Layer L");
  1275. printInt8( arg1 );
  1276. print(" to - ");
  1277. printHex( arg2 );
  1278. // Set the layer state
  1279. LayerState[ arg1 ] = arg2;
  1280. break;
  1281. }
  1282. }
  1283. }
  1284. void cliFunc_macroDebug( char* args )
  1285. {
  1286. // Toggle macro debug mode
  1287. macroDebugMode = macroDebugMode ? 0 : 1;
  1288. print( NL );
  1289. info_msg("Macro Debug Mode: ");
  1290. printInt8( macroDebugMode );
  1291. }
  1292. void cliFunc_macroList( char* args )
  1293. {
  1294. // Show pending key events
  1295. print( NL );
  1296. info_msg("Pending Key Events: ");
  1297. printInt16( (uint16_t)macroTriggerListBufferSize );
  1298. print(" : ");
  1299. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  1300. {
  1301. printHex( macroTriggerListBuffer[ key ].scanCode );
  1302. print(" ");
  1303. }
  1304. // Show pending trigger macros
  1305. print( NL );
  1306. info_msg("Pending Trigger Macros: ");
  1307. printInt16( (uint16_t)macroTriggerMacroPendingListSize );
  1308. print(" : ");
  1309. for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  1310. {
  1311. printHex( macroTriggerMacroPendingList[ macro ] );
  1312. print(" ");
  1313. }
  1314. // Show pending result macros
  1315. print( NL );
  1316. info_msg("Pending Result Macros: ");
  1317. printInt16( (uint16_t)macroResultMacroPendingListSize );
  1318. print(" : ");
  1319. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  1320. {
  1321. printHex( macroResultMacroPendingList[ macro ] );
  1322. print(" ");
  1323. }
  1324. // Show available trigger macro indices
  1325. print( NL );
  1326. info_msg("Trigger Macros Range: T0 -> T");
  1327. printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  1328. // Show available result macro indices
  1329. print( NL );
  1330. info_msg("Result Macros Range: R0 -> R");
  1331. printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  1332. // Show Trigger to Result Macro Links
  1333. print( NL );
  1334. info_msg("Trigger : Result Macro Pairs");
  1335. for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
  1336. {
  1337. print( NL );
  1338. print("\tT");
  1339. printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
  1340. print(" : R");
  1341. printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
  1342. }
  1343. }
  1344. void cliFunc_macroProc( char* args )
  1345. {
  1346. // Toggle macro pause mode
  1347. macroPauseMode = macroPauseMode ? 0 : 1;
  1348. print( NL );
  1349. info_msg("Macro Processing Mode: ");
  1350. printInt8( macroPauseMode );
  1351. }
  1352. void macroDebugShowTrigger( var_uint_t index )
  1353. {
  1354. // Only proceed if the macro exists
  1355. if ( index >= TriggerMacroNum )
  1356. return;
  1357. // Trigger Macro Show
  1358. const TriggerMacro *macro = &TriggerMacroList[ index ];
  1359. TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
  1360. print( NL );
  1361. info_msg("Trigger Macro Index: ");
  1362. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  1363. print( NL );
  1364. // Read the comboLength for combo in the sequence (sequence of combos)
  1365. var_uint_t pos = 0;
  1366. uint8_t comboLength = macro->guide[ pos ];
  1367. // Iterate through and interpret the guide
  1368. while ( comboLength != 0 )
  1369. {
  1370. // Initial position of the combo
  1371. var_uint_t comboPos = ++pos;
  1372. // Iterate through the combo
  1373. while ( pos < comboLength * TriggerGuideSize + comboPos )
  1374. {
  1375. // Assign TriggerGuide element (key type, state and scancode)
  1376. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
  1377. // Display guide information about trigger key
  1378. printHex( guide->scanCode );
  1379. print("|");
  1380. printHex( guide->type );
  1381. print("|");
  1382. printHex( guide->state );
  1383. // Increment position
  1384. pos += TriggerGuideSize;
  1385. // Only show combo separator if there are combos left in the sequence element
  1386. if ( pos < comboLength * TriggerGuideSize + comboPos )
  1387. print("+");
  1388. }
  1389. // Read the next comboLength
  1390. comboLength = macro->guide[ pos ];
  1391. // Only show sequence separator if there is another combo to process
  1392. if ( comboLength != 0 )
  1393. print(";");
  1394. }
  1395. // Display current position
  1396. print( NL "Position: " );
  1397. printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
  1398. // Display result macro index
  1399. print( NL "Result Macro Index: " );
  1400. printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
  1401. // Display trigger macro state
  1402. print( NL "Trigger Macro State: " );
  1403. switch ( record->state )
  1404. {
  1405. case TriggerMacro_Press: print("Press"); break;
  1406. case TriggerMacro_Release: print("Release"); break;
  1407. case TriggerMacro_Waiting: print("Waiting"); break;
  1408. }
  1409. }
  1410. void macroDebugShowResult( var_uint_t index )
  1411. {
  1412. // Only proceed if the macro exists
  1413. if ( index >= ResultMacroNum )
  1414. return;
  1415. // Trigger Macro Show
  1416. const ResultMacro *macro = &ResultMacroList[ index ];
  1417. ResultMacroRecord *record = &ResultMacroRecordList[ index ];
  1418. print( NL );
  1419. info_msg("Result Macro Index: ");
  1420. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  1421. print( NL );
  1422. // Read the comboLength for combo in the sequence (sequence of combos)
  1423. var_uint_t pos = 0;
  1424. uint8_t comboLength = macro->guide[ pos++ ];
  1425. // Iterate through and interpret the guide
  1426. while ( comboLength != 0 )
  1427. {
  1428. // Function Counter, used to keep track of the combos processed
  1429. var_uint_t funcCount = 0;
  1430. // Iterate through the combo
  1431. while ( funcCount < comboLength )
  1432. {
  1433. // Assign TriggerGuide element (key type, state and scancode)
  1434. ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
  1435. // Display Function Index
  1436. printHex( guide->index );
  1437. print("|");
  1438. // Display Function Ptr Address
  1439. printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
  1440. print("|");
  1441. // Display/Lookup Capability Name (utilize debug mode of capability)
  1442. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  1443. capability( 0xFF, 0xFF, 0 );
  1444. // Display Argument(s)
  1445. print("(");
  1446. for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
  1447. {
  1448. // Arguments are only 8 bit values
  1449. printHex( (&guide->args)[ arg ] );
  1450. // Only show arg separator if there are args left
  1451. if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
  1452. print(",");
  1453. }
  1454. print(")");
  1455. // Increment position
  1456. pos += ResultGuideSize( guide );
  1457. // Increment function count
  1458. funcCount++;
  1459. // Only show combo separator if there are combos left in the sequence element
  1460. if ( funcCount < comboLength )
  1461. print("+");
  1462. }
  1463. // Read the next comboLength
  1464. comboLength = macro->guide[ pos++ ];
  1465. // Only show sequence separator if there is another combo to process
  1466. if ( comboLength != 0 )
  1467. print(";");
  1468. }
  1469. // Display current position
  1470. print( NL "Position: " );
  1471. printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
  1472. // Display final trigger state/type
  1473. print( NL "Final Trigger State (State/Type): " );
  1474. printHex( record->state );
  1475. print("/");
  1476. printHex( record->stateType );
  1477. }
  1478. void cliFunc_macroShow( char* args )
  1479. {
  1480. // Parse codes from arguments
  1481. char* curArgs;
  1482. char* arg1Ptr;
  1483. char* arg2Ptr = args;
  1484. // Process all args
  1485. for ( ;; )
  1486. {
  1487. curArgs = arg2Ptr;
  1488. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1489. // Stop processing args if no more are found
  1490. if ( *arg1Ptr == '\0' )
  1491. break;
  1492. // Ignore invalid codes
  1493. switch ( arg1Ptr[0] )
  1494. {
  1495. // Indexed Trigger Macro
  1496. case 'T':
  1497. macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
  1498. break;
  1499. // Indexed Result Macro
  1500. case 'R':
  1501. macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
  1502. break;
  1503. }
  1504. }
  1505. }
  1506. void cliFunc_macroStep( char* args )
  1507. {
  1508. // Parse number from argument
  1509. // NOTE: Only first argument is used
  1510. char* arg1Ptr;
  1511. char* arg2Ptr;
  1512. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  1513. // Default to 1, if no argument given
  1514. var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
  1515. if ( count == 0 )
  1516. count = 1;
  1517. // Set the macro step counter, negative int's are cast to uint
  1518. macroStepCounter = count;
  1519. }