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