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