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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  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. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
  1149. capability( argSet[0], argSet[1], &argSet[2] );
  1150. }
  1151. }
  1152. }
  1153. void cliFunc_keyHold( char* args )
  1154. {
  1155. // Parse codes from arguments
  1156. char* curArgs;
  1157. char* arg1Ptr;
  1158. char* arg2Ptr = args;
  1159. // Process all args
  1160. for ( ;; )
  1161. {
  1162. curArgs = arg2Ptr;
  1163. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1164. // Stop processing args if no more are found
  1165. if ( *arg1Ptr == '\0' )
  1166. break;
  1167. // Ignore non-Scancode numbers
  1168. switch ( arg1Ptr[0] )
  1169. {
  1170. // Scancode
  1171. case 'S':
  1172. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
  1173. break;
  1174. }
  1175. }
  1176. }
  1177. void cliFunc_keyPress( char* args )
  1178. {
  1179. // Parse codes from arguments
  1180. char* curArgs;
  1181. char* arg1Ptr;
  1182. char* arg2Ptr = args;
  1183. // Process all args
  1184. for ( ;; )
  1185. {
  1186. curArgs = arg2Ptr;
  1187. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1188. // Stop processing args if no more are found
  1189. if ( *arg1Ptr == '\0' )
  1190. break;
  1191. // Ignore non-Scancode numbers
  1192. switch ( arg1Ptr[0] )
  1193. {
  1194. // Scancode
  1195. case 'S':
  1196. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
  1197. break;
  1198. }
  1199. }
  1200. }
  1201. void cliFunc_keyRelease( char* args )
  1202. {
  1203. // Parse codes from arguments
  1204. char* curArgs;
  1205. char* arg1Ptr;
  1206. char* arg2Ptr = args;
  1207. // Process all args
  1208. for ( ;; )
  1209. {
  1210. curArgs = arg2Ptr;
  1211. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1212. // Stop processing args if no more are found
  1213. if ( *arg1Ptr == '\0' )
  1214. break;
  1215. // Ignore non-Scancode numbers
  1216. switch ( arg1Ptr[0] )
  1217. {
  1218. // Scancode
  1219. case 'S':
  1220. Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
  1221. break;
  1222. }
  1223. }
  1224. }
  1225. void cliFunc_layerDebug( char *args )
  1226. {
  1227. // Toggle layer debug mode
  1228. layerDebugMode = layerDebugMode ? 0 : 1;
  1229. print( NL );
  1230. info_msg("Layer Debug Mode: ");
  1231. printInt8( layerDebugMode );
  1232. }
  1233. void cliFunc_layerList( char* args )
  1234. {
  1235. print( NL );
  1236. info_msg("Layer List");
  1237. // Iterate through all of the layers and display them
  1238. for ( uint16_t layer = 0; layer < LayerNum; layer++ )
  1239. {
  1240. print( NL "\t" );
  1241. printHex( layer );
  1242. print(" - ");
  1243. // Display layer name
  1244. dPrint( (char*)LayerIndex[ layer ].name );
  1245. // Default map
  1246. if ( layer == 0 )
  1247. print(" \033[1m(default)\033[0m");
  1248. // Layer State
  1249. print( NL "\t\t Layer State: " );
  1250. printHex( LayerState[ layer ] );
  1251. // First -> Last Indices
  1252. print(" First -> Last Indices: ");
  1253. printHex( LayerIndex[ layer ].first );
  1254. print(" -> ");
  1255. printHex( LayerIndex[ layer ].last );
  1256. }
  1257. }
  1258. void cliFunc_layerState( char* args )
  1259. {
  1260. // Parse codes from arguments
  1261. char* curArgs;
  1262. char* arg1Ptr;
  1263. char* arg2Ptr = args;
  1264. uint8_t arg1 = 0;
  1265. uint8_t arg2 = 0;
  1266. // Process first two args
  1267. for ( uint8_t c = 0; c < 2; c++ )
  1268. {
  1269. curArgs = arg2Ptr;
  1270. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1271. // Stop processing args if no more are found
  1272. if ( *arg1Ptr == '\0' )
  1273. break;
  1274. switch ( c )
  1275. {
  1276. // First argument (e.g. L1)
  1277. case 0:
  1278. if ( arg1Ptr[0] != 'L' )
  1279. return;
  1280. arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
  1281. break;
  1282. // Second argument (e.g. 4)
  1283. case 1:
  1284. arg2 = (uint8_t)numToInt( arg1Ptr );
  1285. // Display operation (to indicate that it worked)
  1286. print( NL );
  1287. info_msg("Setting Layer L");
  1288. printInt8( arg1 );
  1289. print(" to - ");
  1290. printHex( arg2 );
  1291. // Set the layer state
  1292. LayerState[ arg1 ] = arg2;
  1293. break;
  1294. }
  1295. }
  1296. }
  1297. void cliFunc_macroDebug( char* args )
  1298. {
  1299. // Toggle macro debug mode
  1300. macroDebugMode = macroDebugMode ? 0 : 1;
  1301. print( NL );
  1302. info_msg("Macro Debug Mode: ");
  1303. printInt8( macroDebugMode );
  1304. }
  1305. void cliFunc_macroList( char* args )
  1306. {
  1307. // Show pending key events
  1308. print( NL );
  1309. info_msg("Pending Key Events: ");
  1310. printInt16( (uint16_t)macroTriggerListBufferSize );
  1311. print(" : ");
  1312. for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
  1313. {
  1314. printHex( macroTriggerListBuffer[ key ].scanCode );
  1315. print(" ");
  1316. }
  1317. // Show pending trigger macros
  1318. print( NL );
  1319. info_msg("Pending Trigger Macros: ");
  1320. printInt16( (uint16_t)macroTriggerMacroPendingListSize );
  1321. print(" : ");
  1322. for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
  1323. {
  1324. printHex( macroTriggerMacroPendingList[ macro ] );
  1325. print(" ");
  1326. }
  1327. // Show pending result macros
  1328. print( NL );
  1329. info_msg("Pending Result Macros: ");
  1330. printInt16( (uint16_t)macroResultMacroPendingListSize );
  1331. print(" : ");
  1332. for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
  1333. {
  1334. printHex( macroResultMacroPendingList[ macro ] );
  1335. print(" ");
  1336. }
  1337. // Show available trigger macro indices
  1338. print( NL );
  1339. info_msg("Trigger Macros Range: T0 -> T");
  1340. printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  1341. // Show available result macro indices
  1342. print( NL );
  1343. info_msg("Result Macros Range: R0 -> R");
  1344. printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
  1345. // Show Trigger to Result Macro Links
  1346. print( NL );
  1347. info_msg("Trigger : Result Macro Pairs");
  1348. for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
  1349. {
  1350. print( NL );
  1351. print("\tT");
  1352. printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
  1353. print(" : R");
  1354. printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
  1355. }
  1356. }
  1357. void cliFunc_macroProc( char* args )
  1358. {
  1359. // Toggle macro pause mode
  1360. macroPauseMode = macroPauseMode ? 0 : 1;
  1361. print( NL );
  1362. info_msg("Macro Processing Mode: ");
  1363. printInt8( macroPauseMode );
  1364. }
  1365. void macroDebugShowTrigger( var_uint_t index )
  1366. {
  1367. // Only proceed if the macro exists
  1368. if ( index >= TriggerMacroNum )
  1369. return;
  1370. // Trigger Macro Show
  1371. const TriggerMacro *macro = &TriggerMacroList[ index ];
  1372. TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
  1373. print( NL );
  1374. info_msg("Trigger Macro Index: ");
  1375. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  1376. print( NL );
  1377. // Read the comboLength for combo in the sequence (sequence of combos)
  1378. var_uint_t pos = 0;
  1379. uint8_t comboLength = macro->guide[ pos ];
  1380. // Iterate through and interpret the guide
  1381. while ( comboLength != 0 )
  1382. {
  1383. // Initial position of the combo
  1384. var_uint_t comboPos = ++pos;
  1385. // Iterate through the combo
  1386. while ( pos < comboLength * TriggerGuideSize + comboPos )
  1387. {
  1388. // Assign TriggerGuide element (key type, state and scancode)
  1389. TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
  1390. // Display guide information about trigger key
  1391. printHex( guide->scanCode );
  1392. print("|");
  1393. printHex( guide->type );
  1394. print("|");
  1395. printHex( guide->state );
  1396. // Increment position
  1397. pos += TriggerGuideSize;
  1398. // Only show combo separator if there are combos left in the sequence element
  1399. if ( pos < comboLength * TriggerGuideSize + comboPos )
  1400. print("+");
  1401. }
  1402. // Read the next comboLength
  1403. comboLength = macro->guide[ pos ];
  1404. // Only show sequence separator if there is another combo to process
  1405. if ( comboLength != 0 )
  1406. print(";");
  1407. }
  1408. // Display current position
  1409. print( NL "Position: " );
  1410. printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
  1411. // Display result macro index
  1412. print( NL "Result Macro Index: " );
  1413. printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
  1414. // Display trigger macro state
  1415. print( NL "Trigger Macro State: " );
  1416. switch ( record->state )
  1417. {
  1418. case TriggerMacro_Press: print("Press"); break;
  1419. case TriggerMacro_Release: print("Release"); break;
  1420. case TriggerMacro_Waiting: print("Waiting"); break;
  1421. }
  1422. }
  1423. void macroDebugShowResult( var_uint_t index )
  1424. {
  1425. // Only proceed if the macro exists
  1426. if ( index >= ResultMacroNum )
  1427. return;
  1428. // Trigger Macro Show
  1429. const ResultMacro *macro = &ResultMacroList[ index ];
  1430. ResultMacroRecord *record = &ResultMacroRecordList[ index ];
  1431. print( NL );
  1432. info_msg("Result Macro Index: ");
  1433. printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
  1434. print( NL );
  1435. // Read the comboLength for combo in the sequence (sequence of combos)
  1436. var_uint_t pos = 0;
  1437. uint8_t comboLength = macro->guide[ pos++ ];
  1438. // Iterate through and interpret the guide
  1439. while ( comboLength != 0 )
  1440. {
  1441. // Function Counter, used to keep track of the combos processed
  1442. var_uint_t funcCount = 0;
  1443. // Iterate through the combo
  1444. while ( funcCount < comboLength )
  1445. {
  1446. // Assign TriggerGuide element (key type, state and scancode)
  1447. ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
  1448. // Display Function Index
  1449. printHex( guide->index );
  1450. print("|");
  1451. // Display Function Ptr Address
  1452. printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
  1453. print("|");
  1454. // Display/Lookup Capability Name (utilize debug mode of capability)
  1455. void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
  1456. capability( 0xFF, 0xFF, 0 );
  1457. // Display Argument(s)
  1458. print("(");
  1459. for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
  1460. {
  1461. // Arguments are only 8 bit values
  1462. printHex( (&guide->args)[ arg ] );
  1463. // Only show arg separator if there are args left
  1464. if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
  1465. print(",");
  1466. }
  1467. print(")");
  1468. // Increment position
  1469. pos += ResultGuideSize( guide );
  1470. // Increment function count
  1471. funcCount++;
  1472. // Only show combo separator if there are combos left in the sequence element
  1473. if ( funcCount < comboLength )
  1474. print("+");
  1475. }
  1476. // Read the next comboLength
  1477. comboLength = macro->guide[ pos++ ];
  1478. // Only show sequence separator if there is another combo to process
  1479. if ( comboLength != 0 )
  1480. print(";");
  1481. }
  1482. // Display current position
  1483. print( NL "Position: " );
  1484. printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
  1485. // Display final trigger state/type
  1486. print( NL "Final Trigger State (State/Type): " );
  1487. printHex( record->state );
  1488. print("/");
  1489. printHex( record->stateType );
  1490. }
  1491. void cliFunc_macroShow( char* args )
  1492. {
  1493. // Parse codes from arguments
  1494. char* curArgs;
  1495. char* arg1Ptr;
  1496. char* arg2Ptr = args;
  1497. // Process all args
  1498. for ( ;; )
  1499. {
  1500. curArgs = arg2Ptr;
  1501. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  1502. // Stop processing args if no more are found
  1503. if ( *arg1Ptr == '\0' )
  1504. break;
  1505. // Ignore invalid codes
  1506. switch ( arg1Ptr[0] )
  1507. {
  1508. // Indexed Trigger Macro
  1509. case 'T':
  1510. macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
  1511. break;
  1512. // Indexed Result Macro
  1513. case 'R':
  1514. macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
  1515. break;
  1516. }
  1517. }
  1518. }
  1519. void cliFunc_macroStep( char* args )
  1520. {
  1521. // Parse number from argument
  1522. // NOTE: Only first argument is used
  1523. char* arg1Ptr;
  1524. char* arg2Ptr;
  1525. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  1526. // Default to 1, if no argument given
  1527. var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
  1528. if ( count == 0 )
  1529. count = 1;
  1530. // Set the macro step counter, negative int's are cast to uint
  1531. macroStepCounter = count;
  1532. }