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