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