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