]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Macro/PartialMap/macro.c
Fixing first and last element bug for layers.
[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[ layerIndex ] & 0x01) ^ (latch>>1) ^ ((LayerState[ 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[ macroLayerIndexStack[ 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 passing and in Waiting state, set macro state to Press
693         else if ( overallVote & TriggerMacroVote_Pass
694              && ( macro->state == TriggerMacro_Waiting || macro->state == TriggerMacro_Press ) )
695         {
696                 macro->state = TriggerMacro_Press;
697
698                 // If in press state, and this is the final combo, send request for ResultMacro
699                 // Check to see if the result macro only has a single element
700                 // If this result macro has more than 1 key, only send once
701                 // TODO Add option to have long macro repeat rate
702                 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
703                 {
704                         // Long result macro (more than 1 combo)
705                         if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
706                         {
707                                 // Only ever trigger result once, on press
708                                 if ( overallVote == TriggerMacroVote_Pass )
709                                 {
710                                         return TriggerMacroEval_DoResultAndRemove;
711                                 }
712                         }
713                         // Short result macro
714                         else
715                         {
716                                 // Only trigger result once, on press, if long trigger (more than 1 combo)
717                                 if ( Macro_isLongTriggerMacro( macro ) )
718                                 {
719                                         return TriggerMacroEval_DoResultAndRemove;
720                                 }
721                                 // Otherwise, trigger result continuously
722                                 else
723                                 {
724                                         return TriggerMacroEval_DoResult;
725                                 }
726                         }
727                 }
728         }
729         // If ready for transition and in Press state, set to Waiting and increment combo position
730         // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
731         else if ( overallVote & TriggerMacroVote_Release && macro->state == TriggerMacro_Press )
732         {
733                 macro->state = TriggerMacro_Release;
734
735                 // If this is the last combo in the sequence, remove from the pending list
736                 if ( macro->guide[ macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize + 1 ] == 0 )
737                         return TriggerMacroEval_Remove;
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                 return ResultMacroEval_Remove;
797         }
798
799         // Otherwise leave the macro in the list
800         return ResultMacroEval_DoNothing;
801 }
802
803
804 // Update pending trigger list
805 inline void Macro_updateTriggerMacroPendingList()
806 {
807         // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
808         for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
809         {
810                 // TODO LED States
811                 // TODO Analog Switches
812                 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
813                 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
814                         continue;
815
816                 // Lookup Trigger List
817                 nat_ptr_t *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode );
818
819                 // Number of Triggers in list
820                 nat_ptr_t triggerListSize = triggerList[0];
821
822                 // Iterate over triggerList to see if any TriggerMacros need to be added
823                 // First item is the number of items in the TriggerList
824                 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
825                 {
826                         // Lookup trigger macro index
827                         var_uint_t triggerMacroIndex = triggerList[ macro ];
828
829                         // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
830                         //  triggerList needs to be added
831                         var_uint_t pending = 0;
832                         for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
833                         {
834                                 // Stop scanning if the trigger macro index is found in the pending list
835                                 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
836                                         break;
837                         }
838
839                         // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
840                         // Add it to the list
841                         if ( pending == macroTriggerMacroPendingListSize )
842                         {
843                                 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
844
845                                 // Reset macro position
846                                 TriggerMacroList[ triggerMacroIndex ].pos   = 0;
847                                 TriggerMacroList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
848                         }
849                 }
850         }
851 }
852
853
854 // Macro Procesing Loop
855 // Called once per USB buffer send
856 inline void Macro_process()
857 {
858         // Only do one round of macro processing between Output Module timer sends
859         if ( USBKeys_Sent != 0 )
860                 return;
861
862         // If the pause flag is set, only process if the step counter is non-zero
863         if ( macroPauseMode )
864         {
865                 if ( macroStepCounter == 0 )
866                         return;
867
868                 // Proceed, decrementing the step counter
869                 macroStepCounter--;
870                 dbug_print("Macro Step");
871         }
872
873         // Update pending trigger list, before processing TriggerMacros
874         Macro_updateTriggerMacroPendingList();
875
876         // Tail pointer for macroTriggerMacroPendingList
877         // Macros must be explicitly re-added
878         var_uint_t macroTriggerMacroPendingListTail = 0;
879
880         // Iterate through the pending TriggerMacros, processing each of them
881         for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
882         {
883                 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
884                 {
885                 // Trigger Result Macro (purposely falling through)
886                 case TriggerMacroEval_DoResult:
887                         // Append ResultMacro to PendingList
888                         Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
889
890                 default:
891                         macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
892                         break;
893
894                 // Trigger Result Macro and Remove (purposely falling through)
895                 case TriggerMacroEval_DoResultAndRemove:
896                         // Append ResultMacro to PendingList
897                         Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
898
899                 // Remove Macro from Pending List, nothing to do, removing by default
900                 case TriggerMacroEval_Remove:
901                         break;
902                 }
903         }
904
905         // Update the macroTriggerMacroPendingListSize with the tail pointer
906         macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
907
908
909         // Tail pointer for macroResultMacroPendingList
910         // Macros must be explicitly re-added
911         var_uint_t macroResultMacroPendingListTail = 0;
912
913         // Iterate through the pending ResultMacros, processing each of them
914         for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
915         {
916                 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
917                 {
918                 // Re-add macros to pending list
919                 case ResultMacroEval_DoNothing:
920                 default:
921                         macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
922                         break;
923
924                 // Remove Macro from Pending List, nothing to do, removing by default
925                 case ResultMacroEval_Remove:
926                         break;
927                 }
928         }
929
930         // Update the macroResultMacroPendingListSize with the tail pointer
931         macroResultMacroPendingListSize = macroResultMacroPendingListTail;
932
933         // Signal buffer that we've used it
934         Scan_finishedWithMacro( macroTriggerListBufferSize );
935
936         // Reset TriggerList buffer
937         macroTriggerListBufferSize = 0;
938
939         // If Macro debug mode is set, clear the USB Buffer
940         if ( macroDebugMode )
941         {
942                 USBKeys_Modifiers = 0;
943                 USBKeys_Sent = 0;
944         }
945 }
946
947
948 inline void Macro_setup()
949 {
950         // Register Macro CLI dictionary
951         CLI_registerDictionary( macroCLIDict, macroCLIDictName );
952
953         // Disable Macro debug mode
954         macroDebugMode = 0;
955
956         // Disable Macro pause flag
957         macroPauseMode = 0;
958
959         // Set Macro step counter to zero
960         macroStepCounter = 0;
961
962         // Make sure macro trigger buffer is empty
963         macroTriggerListBufferSize = 0;
964
965         // Initialize TriggerMacro states
966         for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
967         {
968                 TriggerMacroList[ macro ].pos   = 0;
969                 TriggerMacroList[ macro ].state = TriggerMacro_Waiting;
970         }
971
972         // Initialize ResultMacro states
973         for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
974         {
975                 ResultMacroList[ macro ].pos       = 0;
976                 ResultMacroList[ macro ].state     = 0;
977                 ResultMacroList[ macro ].stateType = 0;
978         }
979 }
980
981
982 // ----- CLI Command Functions -----
983
984 void cliFunc_capList( char* args )
985 {
986         print( NL );
987         info_msg("Capabilities List");
988         printHex( CapabilitiesNum );
989
990         // Iterate through all of the capabilities and display them
991         for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
992         {
993                 print( NL "\t" );
994                 printHex( cap );
995                 print(" - ");
996
997                 // Display/Lookup Capability Name (utilize debug mode of capability)
998                 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
999                 capability( 0xFF, 0xFF, 0 );
1000         }
1001 }
1002
1003 void cliFunc_capSelect( char* args )
1004 {
1005         // Parse code from argument
1006         char* curArgs;
1007         char* arg1Ptr;
1008         char* arg2Ptr = args;
1009
1010         // Total number of args to scan (must do a lookup if a keyboard capability is selected)
1011         var_uint_t totalArgs = 2; // Always at least two args
1012         var_uint_t cap = 0;
1013
1014         // Arguments used for keyboard capability function
1015         var_uint_t argSetCount = 0;
1016         uint8_t *argSet = (uint8_t*)args;
1017
1018         // Process all args
1019         for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1020         {
1021                 curArgs = arg2Ptr;
1022                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1023
1024                 // Stop processing args if no more are found
1025                 // Extra arguments are ignored
1026                 if ( *arg1Ptr == '\0' )
1027                         break;
1028
1029                 // For the first argument, choose the capability
1030                 if ( c == 0 ) switch ( arg1Ptr[0] )
1031                 {
1032                 // Keyboard Capability
1033                 case 'K':
1034                         // Determine capability index
1035                         cap = numToInt( &arg1Ptr[1] );
1036
1037                         // Lookup the number of args
1038                         totalArgs += CapabilitiesList[ cap ].argCount;
1039                         continue;
1040                 }
1041
1042                 // Because allocating memory isn't doable, and the argument count is arbitrary
1043                 // The argument pointer is repurposed as the argument list (much smaller anyways)
1044                 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1045
1046                 // Once all the arguments are prepared, call the keyboard capability function
1047                 if ( argSetCount == totalArgs )
1048                 {
1049                         // Indicate that the capability was called
1050                         print( NL );
1051                         info_msg("K");
1052                         printInt8( cap );
1053                         print(" - ");
1054                         printHex( argSet[0] );
1055                         print(" - ");
1056                         printHex( argSet[1] );
1057                         print(" - ");
1058                         printHex( argSet[2] );
1059                         print( "..." NL );
1060
1061                         void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1062                         capability( argSet[0], argSet[1], &argSet[2] );
1063                 }
1064         }
1065 }
1066
1067 void cliFunc_keyHold( char* args )
1068 {
1069         // Parse codes from arguments
1070         char* curArgs;
1071         char* arg1Ptr;
1072         char* arg2Ptr = args;
1073
1074         // Process all args
1075         for ( ;; )
1076         {
1077                 curArgs = arg2Ptr;
1078                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1079
1080                 // Stop processing args if no more are found
1081                 if ( *arg1Ptr == '\0' )
1082                         break;
1083
1084                 // Ignore non-Scancode numbers
1085                 switch ( arg1Ptr[0] )
1086                 {
1087                 // Scancode
1088                 case 'S':
1089                         Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1090                         break;
1091                 }
1092         }
1093 }
1094
1095 void cliFunc_keyPress( char* args )
1096 {
1097         // Parse codes from arguments
1098         char* curArgs;
1099         char* arg1Ptr;
1100         char* arg2Ptr = args;
1101
1102         // Process all args
1103         for ( ;; )
1104         {
1105                 curArgs = arg2Ptr;
1106                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1107
1108                 // Stop processing args if no more are found
1109                 if ( *arg1Ptr == '\0' )
1110                         break;
1111
1112                 // Ignore non-Scancode numbers
1113                 switch ( arg1Ptr[0] )
1114                 {
1115                 // Scancode
1116                 case 'S':
1117                         Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1118                         break;
1119                 }
1120         }
1121 }
1122
1123 void cliFunc_keyRelease( char* args )
1124 {
1125         // Parse codes from arguments
1126         char* curArgs;
1127         char* arg1Ptr;
1128         char* arg2Ptr = args;
1129
1130         // Process all args
1131         for ( ;; )
1132         {
1133                 curArgs = arg2Ptr;
1134                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1135
1136                 // Stop processing args if no more are found
1137                 if ( *arg1Ptr == '\0' )
1138                         break;
1139
1140                 // Ignore non-Scancode numbers
1141                 switch ( arg1Ptr[0] )
1142                 {
1143                 // Scancode
1144                 case 'S':
1145                         Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
1146                         break;
1147                 }
1148         }
1149 }
1150
1151 void cliFunc_layerList( char* args )
1152 {
1153         print( NL );
1154         info_msg("Layer List");
1155
1156         // Iterate through all of the layers and display them
1157         for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1158         {
1159                 print( NL "\t" );
1160                 printHex( layer );
1161                 print(" - ");
1162
1163                 // Display layer name
1164                 dPrint( (char*)LayerIndex[ layer ].name );
1165
1166                 // Default map
1167                 if ( layer == 0 )
1168                         print(" \033[1m(default)\033[0m");
1169
1170                 // Layer State
1171                 print( NL "\t\t Layer State: " );
1172                 printHex( LayerState[ layer ] );
1173
1174                 // First -> Last Indices
1175                 print(" First -> Last Indices: ");
1176                 printHex( LayerIndex[ layer ].first );
1177                 print(" -> ");
1178                 printHex( LayerIndex[ layer ].last );
1179         }
1180 }
1181
1182 void cliFunc_layerState( char* args )
1183 {
1184         // Parse codes from arguments
1185         char* curArgs;
1186         char* arg1Ptr;
1187         char* arg2Ptr = args;
1188
1189         uint8_t arg1 = 0;
1190         uint8_t arg2 = 0;
1191
1192         // Process first two args
1193         for ( uint8_t c = 0; c < 2; c++ )
1194         {
1195                 curArgs = arg2Ptr;
1196                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1197
1198                 // Stop processing args if no more are found
1199                 if ( *arg1Ptr == '\0' )
1200                         break;
1201
1202                 switch ( c )
1203                 {
1204                 // First argument (e.g. L1)
1205                 case 0:
1206                         if ( arg1Ptr[0] != 'L' )
1207                                 return;
1208
1209                         arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1210                         break;
1211                 // Second argument (e.g. 4)
1212                 case 1:
1213                         arg2 = (uint8_t)numToInt( arg1Ptr );
1214
1215                         // Display operation (to indicate that it worked)
1216                         print( NL );
1217                         info_msg("Setting Layer L");
1218                         printInt8( arg1 );
1219                         print(" to - ");
1220                         printHex( arg2 );
1221
1222                         // Set the layer state
1223                         LayerState[ arg1 ] = arg2;
1224                         break;
1225                 }
1226         }
1227 }
1228
1229 void cliFunc_macroDebug( char* args )
1230 {
1231         // Toggle macro debug mode
1232         macroDebugMode = macroDebugMode ? 0 : 1;
1233
1234         print( NL );
1235         info_msg("Macro Debug Mode: ");
1236         printInt8( macroDebugMode );
1237 }
1238
1239 void cliFunc_macroList( char* args )
1240 {
1241         // Show pending key events
1242         print( NL );
1243         info_msg("Pending Key Events: ");
1244         printInt16( (uint16_t)macroTriggerListBufferSize );
1245         print(" : ");
1246         for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1247         {
1248                 printHex( macroTriggerListBuffer[ key ].scanCode );
1249                 print(" ");
1250         }
1251
1252         // Show pending trigger macros
1253         print( NL );
1254         info_msg("Pending Trigger Macros: ");
1255         printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1256         print(" : ");
1257         for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1258         {
1259                 printHex( macroTriggerMacroPendingList[ macro ] );
1260                 print(" ");
1261         }
1262
1263         // Show pending result macros
1264         print( NL );
1265         info_msg("Pending Result Macros: ");
1266         printInt16( (uint16_t)macroResultMacroPendingListSize );
1267         print(" : ");
1268         for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1269         {
1270                 printHex( macroResultMacroPendingList[ macro ] );
1271                 print(" ");
1272         }
1273
1274         // Show available trigger macro indices
1275         print( NL );
1276         info_msg("Trigger Macros Range: T0 -> T");
1277         printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1278
1279         // Show available result macro indices
1280         print( NL );
1281         info_msg("Result  Macros Range: R0 -> R");
1282         printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1283
1284         // Show Trigger to Result Macro Links
1285         print( NL );
1286         info_msg("Trigger : Result Macro Pairs");
1287         for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1288         {
1289                 print( NL );
1290                 print("\tT");
1291                 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1292                 print(" : R");
1293                 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1294         }
1295 }
1296
1297 void cliFunc_macroProc( char* args )
1298 {
1299         // Toggle macro pause mode
1300         macroPauseMode = macroPauseMode ? 0 : 1;
1301
1302         print( NL );
1303         info_msg("Macro Processing Mode: ");
1304         printInt8( macroPauseMode );
1305 }
1306
1307 void macroDebugShowTrigger( var_uint_t index )
1308 {
1309         // Only proceed if the macro exists
1310         if ( index >= TriggerMacroNum )
1311                 return;
1312
1313         // Trigger Macro Show
1314         TriggerMacro *macro = &TriggerMacroList[ index ];
1315
1316         print( NL );
1317         info_msg("Trigger Macro Index: ");
1318         printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1319         print( NL );
1320
1321         // Read the comboLength for combo in the sequence (sequence of combos)
1322         var_uint_t pos = 0;
1323         uint8_t comboLength = macro->guide[ pos ];
1324
1325         // Iterate through and interpret the guide
1326         while ( comboLength != 0 )
1327         {
1328                 // Initial position of the combo
1329                 var_uint_t comboPos = ++pos;
1330
1331                 // Iterate through the combo
1332                 while ( pos < comboLength * TriggerGuideSize + comboPos )
1333                 {
1334                         // Assign TriggerGuide element (key type, state and scancode)
1335                         TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
1336
1337                         // Display guide information about trigger key
1338                         printHex( guide->scanCode );
1339                         print("|");
1340                         printHex( guide->type );
1341                         print("|");
1342                         printHex( guide->state );
1343
1344                         // Increment position
1345                         pos += TriggerGuideSize;
1346
1347                         // Only show combo separator if there are combos left in the sequence element
1348                         if ( pos < comboLength * TriggerGuideSize + comboPos )
1349                                 print("+");
1350                 }
1351
1352                 // Read the next comboLength
1353                 comboLength = macro->guide[ pos ];
1354
1355                 // Only show sequence separator if there is another combo to process
1356                 if ( comboLength != 0 )
1357                         print(";");
1358         }
1359
1360         // Display current position
1361         print( NL "Position: " );
1362         printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1363
1364         // Display result macro index
1365         print( NL "Result Macro Index: " );
1366         printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1367
1368         // Display trigger macro state
1369         print( NL "Trigger Macro State: " );
1370         switch ( macro->state )
1371         {
1372         case TriggerMacro_Press:   print("Press");   break;
1373         case TriggerMacro_Release: print("Release"); break;
1374         case TriggerMacro_Waiting: print("Waiting"); break;
1375         }
1376 }
1377
1378 void macroDebugShowResult( var_uint_t index )
1379 {
1380         // Only proceed if the macro exists
1381         if ( index >= ResultMacroNum )
1382                 return;
1383
1384         // Trigger Macro Show
1385         ResultMacro *macro = &ResultMacroList[ index ];
1386
1387         print( NL );
1388         info_msg("Result Macro Index: ");
1389         printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1390         print( NL );
1391
1392         // Read the comboLength for combo in the sequence (sequence of combos)
1393         var_uint_t pos = 0;
1394         uint8_t comboLength = macro->guide[ pos++ ];
1395
1396         // Iterate through and interpret the guide
1397         while ( comboLength != 0 )
1398         {
1399                 // Function Counter, used to keep track of the combos processed
1400                 var_uint_t funcCount = 0;
1401
1402                 // Iterate through the combo
1403                 while ( funcCount < comboLength )
1404                 {
1405                         // Assign TriggerGuide element (key type, state and scancode)
1406                         ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
1407
1408                         // Display Function Index
1409                         printHex( guide->index );
1410                         print("|");
1411
1412                         // Display Function Ptr Address
1413                         printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1414                         print("|");
1415
1416                         // Display/Lookup Capability Name (utilize debug mode of capability)
1417                         void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1418                         capability( 0xFF, 0xFF, 0 );
1419
1420                         // Display Argument(s)
1421                         print("(");
1422                         for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1423                         {
1424                                 // Arguments are only 8 bit values
1425                                 printHex( (&guide->args)[ arg ] );
1426
1427                                 // Only show arg separator if there are args left
1428                                 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1429                                         print(",");
1430                         }
1431                         print(")");
1432
1433                         // Increment position
1434                         pos += ResultGuideSize( guide );
1435
1436                         // Increment function count
1437                         funcCount++;
1438
1439                         // Only show combo separator if there are combos left in the sequence element
1440                         if ( funcCount < comboLength )
1441                                 print("+");
1442                 }
1443
1444                 // Read the next comboLength
1445                 comboLength = macro->guide[ pos++ ];
1446
1447                 // Only show sequence separator if there is another combo to process
1448                 if ( comboLength != 0 )
1449                         print(";");
1450         }
1451
1452         // Display current position
1453         print( NL "Position: " );
1454         printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1455
1456         // Display final trigger state/type
1457         print( NL "Final Trigger State (State/Type): " );
1458         printHex( macro->state );
1459         print("/");
1460         printHex( macro->stateType );
1461 }
1462
1463 void cliFunc_macroShow( char* args )
1464 {
1465         // Parse codes from arguments
1466         char* curArgs;
1467         char* arg1Ptr;
1468         char* arg2Ptr = args;
1469
1470         // Process all args
1471         for ( ;; )
1472         {
1473                 curArgs = arg2Ptr;
1474                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1475
1476                 // Stop processing args if no more are found
1477                 if ( *arg1Ptr == '\0' )
1478                         break;
1479
1480                 // Ignore invalid codes
1481                 switch ( arg1Ptr[0] )
1482                 {
1483                 // Indexed Trigger Macro
1484                 case 'T':
1485                         macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1486                         break;
1487                 // Indexed Result Macro
1488                 case 'R':
1489                         macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1490                         break;
1491                 }
1492         }
1493 }
1494
1495 void cliFunc_macroStep( char* args )
1496 {
1497         // Parse number from argument
1498         //  NOTE: Only first argument is used
1499         char* arg1Ptr;
1500         char* arg2Ptr;
1501         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1502
1503         // Default to 1, if no argument given
1504         var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1505
1506         if ( count == 0 )
1507                 count = 1;
1508
1509         // Set the macro step counter, negative int's are cast to uint
1510         macroStepCounter = count;
1511 }
1512