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