]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Macro/PartialMap/macro.c
Adding generic layerToggle and USB Key Output capabilities.
[kiibohd-controller.git] / Macro / PartialMap / macro.c
1 /* Copyright (C) 2014 by Jacob Alexander
2  *
3  * This file is free software: you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation, either version 3 of the License, or
6  * (at your option) any later version.
7  *
8  * This file is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this file.  If not, see <http://www.gnu.org/licenses/>.
15  */
16
17 // ----- Includes -----
18
19 // Compiler Includes
20 #include <Lib/MacroLib.h>
21
22 // Project Includes
23 #include <cli.h>
24 #include <led.h>
25 #include <print.h>
26 #include <scan_loop.h>
27
28 // Keymaps
29 #include "usb_hid.h"
30 #include <defaultMap.h>
31 #include "generatedKeymap.h" // TODO Use actual generated version
32
33 // Local Includes
34 #include "macro.h"
35
36
37
38 // ----- Function Declarations -----
39
40 void cliFunc_capList   ( char* args );
41 void cliFunc_capSelect ( char* args );
42 void cliFunc_keyPress  ( char* args );
43 void cliFunc_keyRelease( char* args );
44 void cliFunc_layerList ( char* args );
45 void cliFunc_layerState( char* args );
46 void cliFunc_macroDebug( char* args );
47 void cliFunc_macroList ( char* args );
48 void cliFunc_macroProc ( char* args );
49 void cliFunc_macroShow ( char* args );
50 void cliFunc_macroStep ( char* args );
51
52
53
54 // ----- Enums -----
55
56 // Bit positions are important, passes (correct key) always trump incorrect key votes
57 typedef enum TriggerMacroVote {
58         TriggerMacroVote_Release      = 0x8, // Correct key
59         TriggerMacroVote_PassRelease  = 0xC, // Correct key (both pass and release)
60         TriggerMacroVote_Pass         = 0x4, // Correct key
61         TriggerMacroVote_DoNothing    = 0x2, // Incorrect key
62         TriggerMacroVote_Fail         = 0x1, // Incorrect key
63         TriggerMacroVote_Invalid      = 0x0, // Invalid state
64 } TriggerMacroVote;
65
66 typedef enum TriggerMacroEval {
67         TriggerMacroEval_DoNothing,
68         TriggerMacroEval_DoResult,
69         TriggerMacroEval_DoResultAndRemove,
70         TriggerMacroEval_Remove,
71 } TriggerMacroEval;
72
73 typedef enum ResultMacroEval {
74         ResultMacroEval_DoNothing,
75         ResultMacroEval_Remove,
76 } ResultMacroEval;
77
78
79
80 // ----- Variables -----
81
82 // Macro Module command dictionary
83 char*       macroCLIDictName = "Macro Module Commands";
84 CLIDictItem macroCLIDict[] = {
85         { "capList",     "Prints an indexed list of all non USB keycode capabilities.", cliFunc_capList },
86         { "capSelect",   "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B", cliFunc_capSelect },
87         { "keyPress",    "Send key-presses to the macro module. Held until released. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyPress },
88         { "keyRelease",  "Release a key-press from the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyRelease },
89         { "layerList",   "List available layers.", cliFunc_layerList },
90         { "layerState",  "Modify specified indexed layer state <layer> <state byte>." NL "\t\t\033[35mL2\033[0m Indexed Layer 0x02" NL "\t\t0 Off, 1 Shift, 2 Latch, 4 Lock States", cliFunc_layerState },
91         { "macroDebug",  "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes.", cliFunc_macroDebug },
92         { "macroList",   "List the defined trigger and result macros.", cliFunc_macroList },
93         { "macroProc",   "Pause/Resume macro processing.", cliFunc_macroProc },
94         { "macroShow",   "Show the macro corresponding to the given index." NL "\t\t\033[35mT16\033[0m Indexed Trigger Macro 0x10, \033[35mR12\033[0m Indexed Result Macro 0x0C", cliFunc_macroShow },
95         { "macroStep",   "Do N macro processing steps. Defaults to 1.", cliFunc_macroStep },
96         { 0, 0, 0 } // Null entry for dictionary end
97 };
98
99
100 // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
101 uint8_t macroDebugMode = 0;
102
103 // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
104 uint8_t macroPauseMode = 0;
105
106 // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
107 unsigned int macroStepCounter = 0;
108
109
110 // Key Trigger List Buffer
111 TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
112 uint8_t macroTriggerListBufferSize = 0;
113
114 // Pending Trigger Macro Index List
115 //  * Any trigger macros that need processing from a previous macro processing loop
116 // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
117 //       Possibly could be calculated by the KLL compiler
118 // XXX It may be possible to calculate the worst case using the KLL compiler
119 unsigned int macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
120 unsigned int macroTriggerMacroPendingListSize = 0;
121
122 // Layer Index Stack
123 //  * When modifying layer state and the state is non-0x0, the stack must be adjusted
124 unsigned int macroLayerIndexStack[ LayerNum ] = { 0 };
125 unsigned int macroLayerIndexStackSize = 0;
126
127 // Pending Result Macro Index List
128 //  * Any result macro that needs processing from a previous macro processing loop
129 unsigned int macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
130 unsigned int macroResultMacroPendingListSize = 0;
131
132
133
134 // ----- Capabilities -----
135
136 // Modifies the specified Layer control byte
137 // Argument #1: Layer Index -> unsigned int
138 // Argument #2: Toggle byte -> uint8_t
139 void Macro_layerStateToggle_capability( uint8_t state, uint8_t stateType, uint8_t *args )
140 {
141         // Display capability name
142         if ( stateType == 0xFF && state == 0xFF )
143         {
144                 print("Macro_layerState(layerIndex,toggleByte)");
145                 return;
146         }
147
148         // Get layer index from arguments
149         unsigned int layer = (unsigned int)(&args[0]);
150
151         // Get layer toggle byte
152         uint8_t toggleByte = args[ sizeof(unsigned int) ];
153
154         // Is layer in the LayerIndexStack?
155         uint8_t inLayerIndexStack = 0;
156         unsigned int stackItem = 0;
157         while ( stackItem < macroLayerIndexStackSize )
158         {
159                 // Flag if layer is already in the LayerIndexStack
160                 if ( macroLayerIndexStack[ stackItem ] == layer )
161                 {
162                         inLayerIndexStack = 1;
163                         break;
164                 }
165
166                 // Increment to next item
167                 stackItem++;
168         }
169
170         // Toggle Layer State Byte
171         if ( LayerIndex[ layer ].state & toggleByte )
172         {
173                 // Unset
174                 LayerIndex[ layer ].state &= ~toggleByte;
175         }
176         else
177         {
178                 // Set
179                 LayerIndex[ layer ].state |= toggleByte;
180         }
181
182         // If the layer was not in the LayerIndexStack add it
183         if ( !inLayerIndexStack )
184         {
185                 macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
186         }
187
188         // If the layer is in the LayerIndexStack and the state is 0x00, remove
189         if ( LayerIndex[ layer ].state == 0x00 && inLayerIndexStack )
190         {
191                 // Remove the layer from the LayerIndexStack
192                 // Using the already positioned stackItem variable from the loop above
193                 while ( stackItem < macroLayerIndexStackSize )
194                 {
195                         macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
196                         stackItem++;
197                 }
198
199                 // Reduce LayerIndexStack size
200                 macroLayerIndexStackSize--;
201         }
202 }
203
204
205
206 // ----- Functions -----
207
208 // Looks up the trigger list for the given scan code (from the active layer)
209 // NOTE: Calling function must handle the NULL pointer case
210 unsigned int *Macro_layerLookup( uint8_t scanCode )
211 {
212         // If no trigger macro is defined at the given layer, fallthrough to the next layer
213         for ( unsigned int layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
214         {
215                 // Lookup Layer
216                 Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
217
218                 // Check if latch has been pressed for this layer
219                 // XXX Regardless of whether a key is found, the latch is removed on first lookup
220                 uint8_t latch = layer->state & 0x02;
221                 if ( latch )
222                 {
223                         layer->state &= ~0x02;
224                 }
225
226                 // Only use layer, if state is valid
227                 // XOR each of the state bits
228                 // If only two are enabled, do not use this state
229                 if ( (layer->state & 0x01) ^ (latch>>1) ^ ((layer->state & 0x04)>>2) )
230                 {
231                         // Lookup layer
232                         unsigned int **map = layer->triggerMap;
233
234                         // Determine if layer has key defined
235                         if ( map != 0 && *map[ scanCode ] != 0 )
236                                 return map[ scanCode ];
237                 }
238         }
239
240         // Do lookup on default layer
241         unsigned int **map = LayerIndex[0].triggerMap;
242
243         // Determine if layer has key defined
244         if ( map == 0 && *map[ scanCode ] == 0 )
245         {
246                 erro_msg("Scan Code has no defined Trigger Macro: ");
247                 printHex( scanCode );
248                 return 0;
249         }
250
251         // Return lookup result
252         return map[ scanCode ];
253 }
254
255
256 // Update the scancode key state
257 // States:
258 //   * 0x00 - Off
259 //   * 0x01 - Pressed
260 //   * 0x02 - Held
261 //   * 0x03 - Released
262 //   * 0x04 - Unpressed (this is currently ignored)
263 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
264 {
265         // Only add to macro trigger list if one of three states
266         switch ( state )
267         {
268         case 0x01: // Pressed
269         case 0x02: // Held
270         case 0x03: // Released
271                 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
272                 macroTriggerListBuffer[ macroTriggerListBufferSize ].state    = state;
273                 macroTriggerListBuffer[ macroTriggerListBufferSize ].type     = 0x00; // Normal key
274                 macroTriggerListBufferSize++;
275                 break;
276         }
277 }
278
279
280 // Update the scancode analog state
281 // States:
282 //   * 0x00      - Off
283 //   * 0x01      - Released
284 //   * 0x02-0xFF - Analog value (low to high)
285 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
286 {
287         // Only add to macro trigger list if non-off
288         if ( state != 0x00 )
289         {
290                 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
291                 macroTriggerListBuffer[ macroTriggerListBufferSize ].state    = state;
292                 macroTriggerListBuffer[ macroTriggerListBufferSize ].type     = 0x02; // Analog key
293                 macroTriggerListBufferSize++;
294         }
295 }
296
297
298 // Update led state
299 // States:
300 //   * 0x00 - Off
301 //   * 0x01 - On
302 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
303 {
304         // Only add to macro trigger list if non-off
305         if ( state != 0x00 )
306         {
307                 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
308                 macroTriggerListBuffer[ macroTriggerListBufferSize ].state    = state;
309                 macroTriggerListBuffer[ macroTriggerListBufferSize ].type     = 0x01; // LED key
310                 macroTriggerListBufferSize++;
311         }
312 }
313
314
315 // Append result macro to pending list, checking for duplicates
316 // Do nothing if duplicate
317 inline void Macro_appendResultMacroToPendingList( unsigned int resultMacroIndex )
318 {
319         // Iterate through result macro pending list, making sure this macro hasn't been added yet
320         for ( unsigned int macro = 0; macro < macroResultMacroPendingListSize; macro++ )
321         {
322                 // If duplicate found, do nothing
323                 if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
324                         return;
325         }
326
327         // No duplicates found, add to pending list
328         macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
329 }
330
331
332 // Determine if long ResultMacro (more than 1 seqence element)
333 inline uint8_t Macro_isLongResultMacro( ResultMacro *macro )
334 {
335         // Check the second sequence combo length
336         // If non-zero return 1 (long sequence)
337         // 0 otherwise (short sequence)
338         return macro->guide[ macro->guide[0] * ResultGuideSize( (ResultGuide*)macro->guide ) ] > 0 ? 1 : 0;
339 }
340
341
342 // Votes on the given key vs. guide
343 inline TriggerMacroVote Macro_evalTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
344 {
345         // Depending on key type
346         switch ( guide->type )
347         {
348         // Normal State Type
349         case 0x00:
350                 // Depending on the state of the buffered key, make voting decision
351                 // Incorrect key
352                 if ( guide->scanCode != key->scanCode )
353                 {
354                         switch ( key->state )
355                         {
356                         // Wrong key, pressed, fail
357                         case 0x01:
358                                 return TriggerMacroVote_Fail;
359
360                         // Wrong key, held or released, do not pass (no effect)
361                         case 0x02:
362                         case 0x03:
363                                 return TriggerMacroVote_DoNothing;
364                         }
365                 }
366
367                 // Correct key
368                 else
369                 {
370                         switch ( key->state )
371                         {
372                         // Correct key, pressed, possible passing
373                         case 0x01:
374                                 return TriggerMacroVote_Pass;
375
376                         // Correct key, held, possible passing or release
377                         case 0x02:
378                                 return TriggerMacroVote_PassRelease;
379
380                         // Correct key, released, possible release
381                         case 0x03:
382                                 return TriggerMacroVote_Release;
383                         }
384                 }
385
386                 break;
387
388         // LED State Type
389         case 0x01:
390                 erro_print("LED State Type - Not implemented...");
391                 break;
392
393         // Analog State Type
394         case 0x02:
395                 erro_print("Analog State Type - Not implemented...");
396                 break;
397
398         // Invalid State Type
399         default:
400                 erro_print("Invalid State Type. This is a bug.");
401                 break;
402         }
403
404         // XXX Shouldn't reach here
405         return TriggerMacroVote_Invalid;
406 }
407
408
409 // Evaluate/Update TriggerMacro
410 inline TriggerMacroEval Macro_evalTriggerMacro( unsigned int triggerMacroIndex )
411 {
412         // Lookup TriggerMacro
413         TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
414
415         // Check if macro has finished and should be incremented sequence elements
416         if ( macro->state == TriggerMacro_Release )
417         {
418                 macro->state = TriggerMacro_Waiting;
419                 macro->pos = macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize;
420         }
421
422         // Current Macro position
423         unsigned int pos = macro->pos;
424
425         // Length of the combo being processed
426         uint8_t comboLength = macro->guide[ pos ];
427
428         // If no combo items are left, remove the TriggerMacro from the pending list
429         if ( comboLength == 0 )
430         {
431                 return TriggerMacroEval_Remove;
432         }
433
434         // Iterate through the key buffer, comparing to each key in the combo
435         // If any of the pressed keys do not match, fail the macro
436         //
437         // The macro is waiting for input when in the TriggerMacro_Waiting state
438         // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
439         // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
440         // On scan after position increment, change to TriggerMacro_Waiting state
441         // TODO Add support for system LED states (NumLock, CapsLock, etc.)
442         // TODO Add support for analog key states
443         // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
444         // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
445         TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
446         for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
447         {
448                 // Lookup key information
449                 TriggerGuide *keyInfo = &macroTriggerListBuffer[ key ];
450
451                 // Iterate through the items in the combo, voting the on the key state
452                 TriggerMacroVote vote = TriggerMacroVote_Invalid;
453                 for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
454                 {
455                         // Assign TriggerGuide element (key type, state and scancode)
456                         TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ comboItem ]);
457
458                         // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
459                         // Also mask all of the non-passing votes
460                         vote |= Macro_evalTriggerMacroVote( keyInfo, guide );
461                         if ( vote >= TriggerMacroVote_Pass )
462                         {
463                                 vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
464                                 break;
465                         }
466                 }
467
468                 // After voting, append to overall vote
469                 overallVote |= vote;
470         }
471
472         // Decide new state of macro after voting
473         // Fail macro, remove from pending list
474         if ( overallVote & TriggerMacroVote_Fail )
475         {
476                 return TriggerMacroEval_Remove;
477         }
478         // Do nothing, incorrect key is being held or released
479         else if ( overallVote & TriggerMacroVote_DoNothing )
480         {
481                 // Just doing nothing :)
482         }
483         // If passing and in Waiting state, set macro state to Press
484         else if ( overallVote & TriggerMacroVote_Pass && macro->state == TriggerMacro_Waiting )
485         {
486                 macro->state = TriggerMacro_Press;
487
488                 // If in press state, and this is the final combo, send request for ResultMacro
489                 // Check to see if the result macro only has a single element
490                 // If this result macro has more than 1 key, only send once
491                 // TODO Add option to have macro repeat rate
492                 if ( macro->guide[ pos + comboLength ] == 0 )
493                 {
494                         // Long Macro, only send once (more than 1 sequence item)
495                         // Short Macro (only 1 sequence item)
496                         return Macro_isLongResultMacro( &ResultMacroList[ macro->result ] )
497                                 ? TriggerMacroEval_DoResult
498                                 : TriggerMacroEval_DoResultAndRemove;
499                 }
500
501         }
502         // If ready for transition and in Press state, set to Waiting and increment combo position
503         // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
504         else if ( overallVote & TriggerMacroVote_Release && macro->state == TriggerMacro_Press )
505         {
506                 macro->state = TriggerMacro_Release;
507         }
508
509         return TriggerMacroEval_DoNothing;
510 }
511
512
513 // Evaluate/Update ResultMacro
514 inline ResultMacroEval Macro_evalResultMacro( unsigned int resultMacroIndex )
515 {
516         // Lookup ResultMacro
517         ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
518
519         // Current Macro position
520         unsigned int pos = macro->pos;
521
522         // Length of combo being processed
523         uint8_t comboLength = macro->guide[ pos ];
524
525         // If no combo items are left, remove the ResultMacro from the pending list
526         if ( comboLength == 0 )
527         {
528                 return ResultMacroEval_Remove;
529         }
530
531         // Function Counter, used to keep track of the combo items processed
532         unsigned int funcCount = 0;
533
534         // Combo Item Position within the guide
535         unsigned int comboItem = pos + 1;
536
537         // Iterate through the Result Combo
538         while ( funcCount < comboLength )
539         {
540                 // Assign TriggerGuide element (key type, state and scancode)
541                 ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
542
543                 // Do lookup on capability function
544                 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
545
546                 // Call capability
547                 capability( macro->state, macro->stateType, &guide->args );
548
549                 // Increment counters
550                 funcCount++;
551                 comboItem += ResultGuideSize( (ResultGuide*)(&macro->guide[ comboItem ]) );
552         }
553
554         // Move to next item in the sequence
555         macro->pos = comboItem;
556
557         // If the ResultMacro is finished, it will be removed on the next iteration
558         return ResultMacroEval_DoNothing;
559 }
560
561
562 // Update pending trigger list
563 void Macro_updateTriggerMacroPendingList()
564 {
565         // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
566         for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
567         {
568                 // Lookup Trigger List
569                 unsigned int *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode );
570
571                 // Number of Triggers in list
572                 unsigned int triggerListSize = triggerList[0];
573
574                 // Iterate over triggerList to see if any TriggerMacros need to be added
575                 // First item is the number of items in the TriggerList
576                 for ( unsigned int macro = 1; macro < triggerListSize + 1; macro++ )
577                 {
578                         // Lookup trigger macro index
579                         unsigned int triggerMacroIndex = triggerList[ macro ];
580
581                         // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
582                         //  triggerList needs to be added
583                         unsigned int pending = 0;
584                         for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
585                         {
586                                 // Stop scanning if the trigger macro index is found in the pending list
587                                 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
588                                         break;
589                         }
590
591                         // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
592                         // Add it to the list
593                         if ( pending == macroTriggerMacroPendingListSize )
594                         {
595                                 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
596                         }
597                 }
598         }
599 }
600
601
602 // Macro Procesing Loop
603 // Called once per USB buffer send
604 inline void Macro_process()
605 {
606         // Only do one round of macro processing between Output Module timer sends
607         if ( USBKeys_Sent != 0 )
608                 return;
609
610         // If the pause flag is set, only process if the step counter is non-zero
611         if ( macroPauseMode )
612         {
613                 if ( macroStepCounter == 0 )
614                         return;
615
616                 // Proceed, decrementing the step counter
617                 macroStepCounter--;
618         }
619
620         // Update pending trigger list, before processing TriggerMacros
621         Macro_updateTriggerMacroPendingList();
622
623         // Tail pointer for macroTriggerMacroPendingList
624         // Macros must be explicitly re-added
625         unsigned int macroTriggerMacroPendingListTail = 0;
626
627         // Iterate through the pending TriggerMacros, processing each of them
628         for ( unsigned int macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
629         {
630                 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
631                 {
632                 // Trigger Result Macro (purposely falling through)
633                 case TriggerMacroEval_DoResult:
634                         // Append ResultMacro to PendingList
635                         Macro_appendResultMacroToPendingList( TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ].result );
636
637                 // Otherwise, just re-add
638                 default:
639                         macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
640                         break;
641
642                 // Trigger Result Macro and Remove (purposely falling through)
643                 case TriggerMacroEval_DoResultAndRemove:
644                         // Append ResultMacro to PendingList
645                         Macro_appendResultMacroToPendingList( TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ].result );
646
647                 // Remove Macro from Pending List, nothing to do, removing by default
648                 case TriggerMacroEval_Remove:
649                         break;
650                 }
651         }
652
653         // Update the macroTriggerMacroPendingListSize with the tail pointer
654         macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
655
656
657         // Tail pointer for macroResultMacroPendingList
658         // Macros must be explicitly re-added
659         unsigned int macroResultMacroPendingListTail = 0;
660
661         // Iterate through the pending ResultMacros, processing each of them
662         for ( unsigned int macro = 0; macro < macroResultMacroPendingListSize; macro++ )
663         {
664                 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
665                 {
666                 // Re-add macros to pending list
667                 case ResultMacroEval_DoNothing:
668                 default:
669                         macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
670                         break;
671
672                 // Remove Macro from Pending List, nothing to do, removing by default
673                 case ResultMacroEval_Remove:
674                         break;
675                 }
676         }
677
678         // Update the macroResultMacroPendingListSize with the tail pointer
679         macroResultMacroPendingListSize = macroResultMacroPendingListTail;
680
681         // Signal buffer that we've used it
682         Scan_finishedWithMacro( macroTriggerListBufferSize );
683
684         // Reset TriggerList buffer
685         macroTriggerListBufferSize = 0;
686
687         // If Macro debug mode is set, clear the USB Buffer
688         if ( macroDebugMode )
689         {
690                 USBKeys_Modifiers = 0;
691                 USBKeys_Sent = 0;
692         }
693 }
694
695
696 inline void Macro_setup()
697 {
698         // Register Macro CLI dictionary
699         CLI_registerDictionary( macroCLIDict, macroCLIDictName );
700
701         // Disable Macro debug mode
702         macroDebugMode = 0;
703
704         // Disable Macro pause flag
705         macroPauseMode = 0;
706
707         // Set Macro step counter to zero
708         macroStepCounter = 0;
709
710         // Make sure macro trigger buffer is empty
711         macroTriggerListBufferSize = 0;
712
713         // Initialize TriggerMacro states
714         for ( unsigned int macro = 0; macro < TriggerMacroNum; macro++ )
715         {
716                 TriggerMacroList[ macro ].result = 0;
717                 TriggerMacroList[ macro ].pos    = 0;
718                 TriggerMacroList[ macro ].state  = TriggerMacro_Waiting;
719         }
720
721         // Initialize ResultMacro states
722         for ( unsigned int macro = 0; macro < ResultMacroNum; macro++ )
723         {
724                 ResultMacroList[ macro ].pos       = 0;
725                 ResultMacroList[ macro ].state     = 0;
726                 ResultMacroList[ macro ].stateType = 0;
727         }
728 }
729
730
731 // ----- CLI Command Functions -----
732
733 void cliFunc_capList( char* args )
734 {
735         print( NL );
736         info_msg("Capabilities List");
737
738         // Iterate through all of the capabilities and display them
739         for ( unsigned int cap = 0; cap < CapabilitiesNum; cap++ )
740         {
741                 print( NL "\t" );
742                 printHex( cap );
743                 print(" - ");
744
745                 // Display/Lookup Capability Name (utilize debug mode of capability)
746                 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
747                 capability( 0xFF, 0xFF, 0 );
748         }
749 }
750
751 void cliFunc_capSelect( char* args )
752 {
753         // Parse code from argument
754         char* curArgs;
755         char* arg1Ptr;
756         char* arg2Ptr = args;
757
758         // Total number of args to scan (must do a lookup if a keyboard capability is selected)
759         unsigned int totalArgs = 2; // Always at least two args
760         unsigned int cap = 0;
761
762         // Arguments used for keyboard capability function
763         unsigned int argSetCount = 0;
764         uint8_t *argSet = (uint8_t*)args;
765
766         // Process all args
767         for ( unsigned int c = 0; argSetCount < totalArgs; c++ )
768         {
769                 curArgs = arg2Ptr;
770                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
771
772                 // Stop processing args if no more are found
773                 // Extra arguments are ignored
774                 if ( *arg1Ptr == '\0' )
775                         break;
776
777                 // For the first argument, choose the capability
778                 if ( c == 0 ) switch ( arg1Ptr[0] )
779                 {
780                 // Keyboard Capability
781                 case 'K':
782                         // Determine capability index
783                         cap = decToInt( &arg1Ptr[1] );
784
785                         // Lookup the number of args
786                         totalArgs += CapabilitiesList[ cap ].argCount;
787                         continue;
788                 }
789
790                 // Because allocating memory isn't doable, and the argument count is arbitrary
791                 // The argument pointer is repurposed as the argument list (much smaller anyways)
792                 argSet[ argSetCount++ ] = (uint8_t)decToInt( arg1Ptr );
793
794                 // Once all the arguments are prepared, call the keyboard capability function
795                 if ( argSetCount == totalArgs )
796                 {
797                         // Indicate that the capability was called
798                         print( NL );
799                         info_msg("K");
800                         printInt8( cap );
801                         print(" - ");
802                         printHex( argSet[0] );
803                         print(" - ");
804                         printHex( argSet[1] );
805                         print(" - ");
806                         printHex( argSet[2] );
807                         print( "..." NL );
808
809                         void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
810                         capability( argSet[0], argSet[1], &argSet[2] );
811                 }
812         }
813 }
814
815 void cliFunc_keyPress( char* args )
816 {
817         // Parse codes from arguments
818         char* curArgs;
819         char* arg1Ptr;
820         char* arg2Ptr = args;
821
822         // Process all args
823         for ( ;; )
824         {
825                 curArgs = arg2Ptr;
826                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
827
828                 // Stop processing args if no more are found
829                 if ( *arg1Ptr == '\0' )
830                         break;
831
832                 // Ignore non-Scancode numbers
833                 switch ( arg1Ptr[0] )
834                 {
835                 // Scancode
836                 case 'S':
837                         Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
838                         break;
839                 }
840         }
841 }
842
843 void cliFunc_keyRelease( char* args )
844 {
845         // Parse codes from arguments
846         char* curArgs;
847         char* arg1Ptr;
848         char* arg2Ptr = args;
849
850         // Process all args
851         for ( ;; )
852         {
853                 curArgs = arg2Ptr;
854                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
855
856                 // Stop processing args if no more are found
857                 if ( *arg1Ptr == '\0' )
858                         break;
859
860                 // Ignore non-Scancode numbers
861                 switch ( arg1Ptr[0] )
862                 {
863                 // Scancode
864                 case 'S':
865                         Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
866                         break;
867                 }
868         }
869 }
870
871 void cliFunc_layerList( char* args )
872 {
873         print( NL );
874         info_msg("Layer List");
875
876         // Iterate through all of the layers and display them
877         for ( unsigned int layer = 0; layer < LayerNum; layer++ )
878         {
879                 print( NL "\t" );
880                 printHex( layer );
881                 print(" - ");
882
883                 // Display layer name
884                 dPrint( LayerIndex[ layer ].name );
885
886                 // Default map
887                 if ( layer == 0 )
888                         print(" \033[1m(default)\033[0m");
889
890                 // Layer State
891                 print( NL "\t\t Layer State: " );
892                 printHex( LayerIndex[ layer ].state );
893
894                 // Max Index
895                 print(" Max Index: ");
896                 printHex( LayerIndex[ layer ].max );
897         }
898 }
899
900 void cliFunc_layerState( char* args )
901 {
902         // Parse codes from arguments
903         char* curArgs;
904         char* arg1Ptr;
905         char* arg2Ptr = args;
906
907         uint8_t arg1 = 0;
908         uint8_t arg2 = 0;
909
910         // Process first two args
911         for ( uint8_t c = 0; c < 2; c++ )
912         {
913                 curArgs = arg2Ptr;
914                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
915
916                 // Stop processing args if no more are found
917                 if ( *arg1Ptr == '\0' )
918                         break;
919
920                 switch ( c )
921                 {
922                 // First argument (e.g. L1)
923                 case 0:
924                         if ( arg1Ptr[0] != 'L' )
925                                 return;
926
927                         arg1 = (uint8_t)decToInt( &arg1Ptr[1] );
928                         break;
929                 // Second argument (e.g. 4)
930                 case 1:
931                         arg2 = (uint8_t)decToInt( arg1Ptr );
932
933                         // Display operation (to indicate that it worked)
934                         print( NL );
935                         info_msg("Setting Layer L");
936                         printInt8( arg1 );
937                         print(" to - ");
938                         printHex( arg2 );
939
940                         // Set the layer state
941                         LayerIndex[ arg1 ].state = arg2;
942                         break;
943                 }
944         }
945 }
946
947 void cliFunc_macroDebug( char* args )
948 {
949         // Toggle macro debug mode
950         macroDebugMode = macroDebugMode ? 0 : 1;
951
952         print( NL );
953         info_msg("Macro Debug Mode: ");
954         printInt8( macroDebugMode );
955 }
956
957 void cliFunc_macroList( char* args )
958 {
959         // Show available trigger macro indices
960         print( NL );
961         info_msg("Trigger Macros Range: T0 -> T");
962         printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
963
964         // Show available result macro indices
965         print( NL );
966         info_msg("Result  Macros Range: R0 -> R");
967         printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
968
969         // Show Trigger to Result Macro Links
970         print( NL );
971         info_msg("Trigger : Result Macro Pairs");
972         for ( unsigned int macro = 0; macro < TriggerMacroNum; macro++ )
973         {
974                 print( NL );
975                 print("\tT");
976                 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
977                 print(" : R");
978                 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
979         }
980 }
981
982 void cliFunc_macroProc( char* args )
983 {
984         // Toggle macro pause mode
985         macroPauseMode = macroPauseMode ? 0 : 1;
986
987         print( NL );
988         info_msg("Macro Processing Mode: ");
989         printInt8( macroPauseMode );
990 }
991
992 void macroDebugShowTrigger( unsigned int index )
993 {
994         // Only proceed if the macro exists
995         if ( index >= TriggerMacroNum )
996                 return;
997
998         // Trigger Macro Show
999         TriggerMacro *macro = &TriggerMacroList[ index ];
1000
1001         print( NL );
1002         info_msg("Trigger Macro Index: ");
1003         printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1004         print( NL );
1005
1006         // Read the comboLength for combo in the sequence (sequence of combos)
1007         unsigned int pos = 0;
1008         uint8_t comboLength = macro->guide[ pos ];
1009
1010         // Iterate through and interpret the guide
1011         while ( comboLength != 0 )
1012         {
1013                 // Initial position of the combo
1014                 unsigned int comboPos = ++pos;
1015
1016                 // Iterate through the combo
1017                 while ( pos < comboLength * TriggerGuideSize + comboPos )
1018                 {
1019                         // Assign TriggerGuide element (key type, state and scancode)
1020                         TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
1021
1022                         // Display guide information about trigger key
1023                         printHex( guide->scanCode );
1024                         print("|");
1025                         printHex( guide->type );
1026                         print("|");
1027                         printHex( guide->state );
1028
1029                         // Increment position
1030                         pos += TriggerGuideSize;
1031
1032                         // Only show combo separator if there are combos left in the sequence element
1033                         if ( pos < comboLength * TriggerGuideSize + comboPos )
1034                                 print("+");
1035                 }
1036
1037                 // Read the next comboLength
1038                 comboLength = macro->guide[ pos ];
1039
1040                 // Only show sequence separator if there is another combo to process
1041                 if ( comboLength != 0 )
1042                         print(";");
1043         }
1044
1045         // Display current position
1046         print( NL "Position: " );
1047         printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1048
1049         // Display result macro index
1050         print( NL "Result Macro Index: " );
1051         printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1052 }
1053
1054 void macroDebugShowResult( unsigned int index )
1055 {
1056         // Only proceed if the macro exists
1057         if ( index >= ResultMacroNum )
1058                 return;
1059
1060         // Trigger Macro Show
1061         ResultMacro *macro = &ResultMacroList[ index ];
1062
1063         print( NL );
1064         info_msg("Result Macro Index: ");
1065         printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1066         print( NL );
1067
1068         // Read the comboLength for combo in the sequence (sequence of combos)
1069         unsigned int pos = 0;
1070         uint8_t comboLength = macro->guide[ pos++ ];
1071
1072         // Iterate through and interpret the guide
1073         while ( comboLength != 0 )
1074         {
1075                 // Function Counter, used to keep track of the combos processed
1076                 unsigned int funcCount = 0;
1077
1078                 // Iterate through the combo
1079                 while ( funcCount < comboLength )
1080                 {
1081                         // Assign TriggerGuide element (key type, state and scancode)
1082                         ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
1083
1084                         // Display Function Index
1085                         printHex( guide->index );
1086                         print("|");
1087
1088                         // Display Function Ptr Address
1089                         printHex( (unsigned int)CapabilitiesList[ guide->index ].func );
1090                         print("|");
1091
1092                         // Display/Lookup Capability Name (utilize debug mode of capability)
1093                         void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1094                         capability( 0xFF, 0xFF, 0 );
1095
1096                         // Display Argument(s)
1097                         print("(");
1098                         for ( unsigned int arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1099                         {
1100                                 // Arguments are only 8 bit values
1101                                 printHex( (&guide->args)[ arg ] );
1102
1103                                 // Only show arg separator if there are args left
1104                                 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1105                                         print(",");
1106                         }
1107                         print(")");
1108
1109                         // Increment position
1110                         pos += ResultGuideSize( guide );
1111
1112                         // Increment function count
1113                         funcCount++;
1114
1115                         // Only show combo separator if there are combos left in the sequence element
1116                         if ( funcCount < comboLength )
1117                                 print("+");
1118                 }
1119
1120                 // Read the next comboLength
1121                 comboLength = macro->guide[ pos++ ];
1122
1123                 // Only show sequence separator if there is another combo to process
1124                 if ( comboLength != 0 )
1125                         print(";");
1126         }
1127
1128         // Display current position
1129         print( NL "Position: " );
1130         printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1131
1132         // Display final trigger state/type
1133         print( NL "Final Trigger State (State/Type): " );
1134         printHex( macro->state );
1135         print("/");
1136         printHex( macro->stateType );
1137 }
1138
1139 void cliFunc_macroShow( char* args )
1140 {
1141         // Parse codes from arguments
1142         char* curArgs;
1143         char* arg1Ptr;
1144         char* arg2Ptr = args;
1145
1146         // Process all args
1147         for ( ;; )
1148         {
1149                 curArgs = arg2Ptr;
1150                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1151
1152                 // Stop processing args if no more are found
1153                 if ( *arg1Ptr == '\0' )
1154                         break;
1155
1156                 // Ignore invalid codes
1157                 switch ( arg1Ptr[0] )
1158                 {
1159                 // Indexed Trigger Macro
1160                 case 'T':
1161                         macroDebugShowTrigger( decToInt( &arg1Ptr[1] ) );
1162                         break;
1163                 // Indexed Result Macro
1164                 case 'R':
1165                         macroDebugShowResult( decToInt( &arg1Ptr[1] ) );
1166                         break;
1167                 }
1168         }
1169 }
1170
1171 void cliFunc_macroStep( char* args )
1172 {
1173         // Parse number from argument
1174         //  NOTE: Only first argument is used
1175         char* arg1Ptr;
1176         char* arg2Ptr;
1177         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1178
1179         // Set the macro step counter, negative int's are cast to uint
1180         macroStepCounter = (unsigned int)decToInt( arg1Ptr );
1181 }
1182