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