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