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