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