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