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