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