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