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