1 /* Copyright (C) 2014 by Jacob Alexander
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.
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.
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/>.
17 // ----- Includes -----
20 #include <Lib/MacroLib.h>
26 #include <scan_loop.h>
27 #include <output_com.h>
31 #include <defaultMap.h>
32 #include "generatedKeymap.h" // TODO Use actual generated version
39 // ----- Function Declarations -----
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 );
55 // ----- Variables -----
57 // Macro Module command dictionary
58 char* macroCLIDictName = "Macro Module Commands";
59 CLIDictItem macroCLIDict[] = {
60 { "capList", "Prints an indexed list of all non USB keycode capabilities.", cliFunc_capList },
61 { "capSelect", "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B", cliFunc_capSelect },
62 { "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 },
63 { "keyRelease", "Release a key-press from the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyRelease },
64 { "layerList", "List available layers.", cliFunc_layerList },
65 { "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 },
66 { "macroDebug", "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes.", cliFunc_macroDebug },
67 { "macroList", "List the defined trigger and result macros.", cliFunc_macroList },
68 { "macroProc", "Pause/Resume macro processing.", cliFunc_macroProc },
69 { "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 },
70 { "macroStep", "Do N macro processing steps. Defaults to 1.", cliFunc_macroStep },
71 { 0, 0, 0 } // Null entry for dictionary end
75 // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
76 uint8_t macroDebugMode = 0;
78 // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
79 uint8_t macroPauseMode = 0;
81 // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
82 unsigned int macroStepCounter = 0;
85 // Key Trigger List Buffer
86 TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
87 uint8_t macroTriggerListBufferSize = 0;
89 // Pending Trigger Macro Index List
90 // * Any trigger macros that need processing from a previous macro processing loop
91 // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
92 // Possibly could be calculated by the KLL compiler
93 // XXX It may be possible to calculate the worst case using the KLL compiler
94 unsigned int macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
95 unsigned int macroTriggerMacroPendingListSize = 0;
98 // * When modifying layer state and the state is non-0x0, the stack must be adjusted
99 unsigned int macroLayerIndexStack[ LayerNum ] = { 0 };
100 unsigned int macroLayerIndexStackSize = 0;
102 // Pending Result Macro Index List
103 // * Any result macro that needs processing from a previous macro processing loop
104 unsigned int macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
105 unsigned int macroResultMacroPendingListSize = 0;
109 // ----- Functions -----
111 // Looks up the trigger list for the given scan code (from the active layer)
112 // NOTE: Calling function must handle the NULL pointer case
113 unsigned int *Macro_layerLookup( uint8_t scanCode )
115 // If no trigger macro is defined at the given layer, fallthrough to the next layer
116 for ( unsigned int layer = 0; layer < macroLayerIndexStackSize; layer++ )
119 unsigned int **map = LayerIndex[ macroLayerIndexStack[ layer ] ].triggerMap;
121 // Determine if layer has key defined
122 if ( map != 0 && *map[ scanCode ] != 0 )
123 return map[ scanCode ];
126 // Do lookup on default layer
127 unsigned int **map = LayerIndex[0].triggerMap;
129 // Determine if layer has key defined
130 if ( map == 0 && *map[ scanCode ] == 0 )
132 erro_msg("Scan Code has no defined Trigger Macro: ");
133 printHex( scanCode );
137 // Return lookup result
138 return map[ scanCode ];
142 // Update the scancode key state
148 // * 0x04 - Unpressed (this is currently ignored)
149 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
151 // Only add to macro trigger list if one of three states
154 case 0x01: // Pressed
156 case 0x03: // Released
157 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
158 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
159 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
160 macroTriggerListBufferSize++;
166 // Update the scancode analog state
170 // * 0x02-0xFF - Analog value (low to high)
171 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
173 // Only add to macro trigger list if non-off
176 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
177 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
178 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
179 macroTriggerListBufferSize++;
188 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
190 // Only add to macro trigger list if non-off
193 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
194 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
195 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
196 macroTriggerListBufferSize++;
201 // Evaluate/Update TriggerMacro
202 void Macro_evalTriggerMacro( TriggerMacro *triggerMacro )
204 // Which combo in the sequence is being evaluated
205 unsigned int comboPos = triggerMacro->pos;
207 // If combo length is more than 1, cancel trigger macro if an incorrect key is found
208 uint8_t comboLength = triggerMacro->guide[ comboPos ];
210 // Iterate over list of keys currently pressed
211 for ( uint8_t keyPressed = 0; keyPressed < macroTriggerListBufferSize; keyPressed++ )
213 // Compare with keys in combo
214 for ( unsigned int comboKey = 0; comboKey < comboLength; comboKey++ )
216 // Lookup key in combo
217 uint8_t guideKey = triggerMacro->guide[ comboPos + comboKey + 2 ]; // TODO Only Press/Hold/Release atm
220 if ( comboLength == 1 )
222 // If key matches and only 1 key pressed, increment the TriggerMacro combo position
223 if ( guideKey == macroTriggerListBuffer[ keyPressed ].scanCode && macroTriggerListBufferSize == 1 )
225 triggerMacro->pos += comboLength * 2 + 1;
226 // TODO check if TriggerMacro is finished, register ResultMacro
230 // If key does not match or more than 1 key pressed, reset the TriggerMacro combo position
231 triggerMacro->pos = 0;
244 // Evaluate/Update ResultMacro
245 void Macro_evalResultMacro( ResultMacro *resultMacro )
251 // Called immediately after USB has finished sending a buffer
252 inline void Macro_finishWithUSBBuffer( uint8_t sentKeys )
254 // XXX Currently not used to trigger anything (with this particular Macro module)
258 // Macro Procesing Loop
259 // Called once per USB buffer send
260 inline void Macro_process()
262 // Only do one round of macro processing between Output Module timer sends
263 if ( USBKeys_Sent != 0 )
266 // If the pause flag is set, only process if the step counter is non-zero
267 if ( macroPauseMode && macroStepCounter == 0 )
271 // Proceed, decrementing the step counter
277 // Loop through macro trigger buffer
278 for ( uint8_t index = 0; index < macroTriggerListBufferSize; index++ )
280 // Get scanCode, first item of macroTriggerListBuffer pairs
281 uint8_t scanCode = macroTriggerListBuffer[ index ].scanCode;
283 // Lookup trigger list for this key
284 unsigned int *triggerList = Macro_layerLookup( scanCode );
286 // Skip, if no trigger list
287 if ( triggerList == 0 )
290 // The first element is the length of the trigger list
291 unsigned int triggerListSize = triggerList[0];
293 // Loop through the trigger list
294 for ( unsigned int trigger = 0; trigger < triggerListSize; trigger++ )
296 // Lookup TriggerMacro
297 TriggerMacro *triggerMacro = (TriggerMacro*)triggerList[ trigger + 1 ];
299 // Get triggered state of scan code, second item of macroTriggerListBuffer pairs
300 uint8_t state = macroTriggerListBuffer[ index ].state;
303 Macro_evalTriggerMacro( triggerMacro );
312 // Loop through input buffer
313 for ( uint8_t index = 0; index < KeyIndex_BufferUsed && !macroDebugMode; index++ )
316 //printInt8( KeyIndex_BufferUsed );
317 // Get the keycode from the buffer
318 uint8_t key = KeyIndex_Buffer[index];
320 // Set the modifier bit if this key is a modifier
321 if ( (key & KEY_LCTRL) == KEY_LCTRL ) // AND with 0xE0
323 USBKeys_Modifiers |= 1 << (key ^ KEY_LCTRL); // Left shift 1 by key XOR 0xE0
325 // Modifier processed, move on to the next key
330 if ( USBKeys_Sent >= USBKeys_MaxSize )
332 warn_msg("USB Key limit reached");
337 // Allow ignoring keys with 0's
340 USBKeys_Array[USBKeys_Sent++] = key;
344 // Key was not mapped
345 erro_msg( "Key not mapped... - " );
352 // Signal buffer that we've used it
353 Scan_finishedWithBuffer( KeyIndex_BufferUsed );
355 // If Macro debug mode is set, clear the USB Buffer
356 if ( macroDebugMode )
358 USBKeys_Modifiers = 0;
364 inline void Macro_setup()
366 // Register Macro CLI dictionary
367 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
369 // Disable Macro debug mode
372 // Disable Macro pause flag
375 // Set Macro step counter to zero
376 macroStepCounter = 0;
378 // Make sure macro trigger buffer is empty
379 macroTriggerListBufferSize = 0;
383 // ----- CLI Command Functions -----
385 void cliFunc_capList( char* args )
388 info_msg("Capabilities List");
390 // Iterate through all of the capabilities and display them
391 for ( unsigned int cap = 0; cap < CapabilitiesNum; cap++ )
397 // Display/Lookup Capability Name (utilize debug mode of capability)
398 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
399 capability( 0xFF, 0xFF, 0 );
403 void cliFunc_capSelect( char* args )
405 // Parse code from argument
408 char* arg2Ptr = args;
410 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
411 unsigned int totalArgs = 2; // Always at least two args
412 unsigned int cap = 0;
414 // Arguments used for keyboard capability function
415 unsigned int argSetCount = 0;
416 uint8_t *argSet = (uint8_t*)args;
419 for ( unsigned int c = 0; argSetCount < totalArgs; c++ )
422 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
424 // Stop processing args if no more are found
425 // Extra arguments are ignored
426 if ( *arg1Ptr == '\0' )
429 // For the first argument, choose the capability
430 if ( c == 0 ) switch ( arg1Ptr[0] )
432 // Keyboard Capability
434 // Determine capability index
435 cap = decToInt( &arg1Ptr[1] );
437 // Lookup the number of args
438 totalArgs += CapabilitiesList[ cap ].argCount;
442 // Because allocating memory isn't doable, and the argument count is arbitrary
443 // The argument pointer is repurposed as the argument list (much smaller anyways)
444 argSet[ argSetCount++ ] = (uint8_t)decToInt( arg1Ptr );
446 // Once all the arguments are prepared, call the keyboard capability function
447 if ( argSetCount == totalArgs )
449 // Indicate that the capability was called
454 printHex( argSet[0] );
456 printHex( argSet[1] );
458 printHex( argSet[2] );
461 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
462 capability( argSet[0], argSet[1], &argSet[2] );
467 void cliFunc_keyPress( char* args )
469 // Parse codes from arguments
472 char* arg2Ptr = args;
478 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
480 // Stop processing args if no more are found
481 if ( *arg1Ptr == '\0' )
484 // Ignore non-Scancode numbers
485 switch ( arg1Ptr[0] )
489 Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
495 void cliFunc_keyRelease( char* args )
497 // Parse codes from arguments
500 char* arg2Ptr = args;
506 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
508 // Stop processing args if no more are found
509 if ( *arg1Ptr == '\0' )
512 // Ignore non-Scancode numbers
513 switch ( arg1Ptr[0] )
517 Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
523 void cliFunc_layerList( char* args )
526 info_msg("Layer List");
528 // Iterate through all of the layers and display them
529 for ( unsigned int layer = 0; layer < LayerNum; layer++ )
535 // Display layer name
536 dPrint( LayerIndex[ layer ].name );
540 print(" \033[1m(default)\033[0m");
543 print( NL "\t\t Layer State: " );
544 printHex( LayerIndex[ layer ].state );
547 print(" Max Index: ");
548 printHex( LayerIndex[ layer ].max );
552 void cliFunc_layerState( char* args )
554 // Parse codes from arguments
557 char* arg2Ptr = args;
562 // Process first two args
563 for ( uint8_t c = 0; c < 2; c++ )
566 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
568 // Stop processing args if no more are found
569 if ( *arg1Ptr == '\0' )
574 // First argument (e.g. L1)
576 if ( arg1Ptr[0] != 'L' )
579 arg1 = (uint8_t)decToInt( &arg1Ptr[1] );
581 // Second argument (e.g. 4)
583 arg2 = (uint8_t)decToInt( arg1Ptr );
585 // Display operation (to indicate that it worked)
587 info_msg("Setting Layer L");
592 // Set the layer state
593 LayerIndex[ arg1 ].state = arg2;
599 void cliFunc_macroDebug( char* args )
601 // Toggle macro debug mode
602 macroDebugMode = macroDebugMode ? 0 : 1;
605 info_msg("Macro Debug Mode: ");
606 printInt8( macroDebugMode );
609 void cliFunc_macroList( char* args )
611 // Show available trigger macro indices
613 info_msg("Trigger Macros Range: T0 -> T");
614 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
616 // Show available result macro indices
618 info_msg("Result Macros Range: R0 -> R");
619 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
621 // Show Trigger to Result Macro Links
623 info_msg("Trigger : Result Macro Pairs");
624 for ( unsigned int macro = 0; macro < TriggerMacroNum; macro++ )
628 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
630 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
634 void cliFunc_macroProc( char* args )
636 // Toggle macro pause mode
637 macroPauseMode = macroPauseMode ? 0 : 1;
640 info_msg("Macro Processing Mode: ");
641 printInt8( macroPauseMode );
644 void macroDebugShowTrigger( unsigned int index )
646 // Only proceed if the macro exists
647 if ( index >= TriggerMacroNum )
650 // Trigger Macro Show
651 TriggerMacro *macro = &TriggerMacroList[ index ];
654 info_msg("Trigger Macro Index: ");
655 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
658 // Read the comboLength for combo in the sequence (sequence of combos)
659 unsigned int pos = 0;
660 uint8_t comboLength = macro->guide[ pos ];
662 // Iterate through and interpret the guide
663 while ( comboLength != 0 )
665 // Initial position of the combo
666 unsigned int comboPos = ++pos;
668 // Iterate through the combo
669 while ( pos < comboLength * TriggerGuideSize + comboPos )
671 // Assign TriggerGuide element (key type, state and scancode)
672 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
674 // Display guide information about trigger key
675 printHex( guide->scanCode );
677 printHex( guide->type );
679 printHex( guide->state );
681 // Increment position
682 pos += TriggerGuideSize;
684 // Only show combo separator if there are combos left in the sequence element
685 if ( pos < comboLength * TriggerGuideSize + comboPos )
689 // Read the next comboLength
690 comboLength = macro->guide[ pos ];
692 // Only show sequence separator if there is another combo to process
693 if ( comboLength != 0 )
697 // Display current position
698 print( NL "Position: " );
699 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
701 // Display result macro index
702 print( NL "Result Macro Index: " );
703 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
706 void macroDebugShowResult( unsigned int index )
708 // Only proceed if the macro exists
709 if ( index >= ResultMacroNum )
712 // Trigger Macro Show
713 ResultMacro *macro = &ResultMacroList[ index ];
716 info_msg("Result Macro Index: ");
717 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
720 // Read the comboLength for combo in the sequence (sequence of combos)
721 unsigned int pos = 0;
722 uint8_t comboLength = macro->guide[ pos++ ];
724 // Iterate through and interpret the guide
725 while ( comboLength != 0 )
727 // Function Counter, used to keep track of the combos processed
728 unsigned int funcCount = 0;
730 // Iterate through the combo
731 while ( funcCount < comboLength )
733 // Assign TriggerGuide element (key type, state and scancode)
734 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
736 // Display Function Index
737 printHex( guide->index );
740 // Display Function Ptr Address
741 printHex( (unsigned int)CapabilitiesList[ guide->index ].func );
744 // Display/Lookup Capability Name (utilize debug mode of capability)
745 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
746 capability( 0xFF, 0xFF, 0 );
748 // Display Argument(s)
750 for ( unsigned int arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
752 // Arguments are only 8 bit values
753 printHex( (&guide->args)[ arg ] );
755 // Only show arg separator if there are args left
756 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
761 // Increment position
762 pos += ResultGuideSize( guide );
764 // Increment function count
767 // Only show combo separator if there are combos left in the sequence element
768 if ( funcCount < comboLength )
772 // Read the next comboLength
773 comboLength = macro->guide[ pos++ ];
775 // Only show sequence separator if there is another combo to process
776 if ( comboLength != 0 )
780 // Display current position
781 print( NL "Position: " );
782 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
784 // Display final trigger state/type
785 print( NL "Final Trigger State (State/Type): " );
786 printHex( macro->state );
788 printHex( macro->stateType );
791 void cliFunc_macroShow( char* args )
793 // Parse codes from arguments
796 char* arg2Ptr = args;
802 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
804 // Stop processing args if no more are found
805 if ( *arg1Ptr == '\0' )
808 // Ignore invalid codes
809 switch ( arg1Ptr[0] )
811 // Indexed Trigger Macro
813 macroDebugShowTrigger( decToInt( &arg1Ptr[1] ) );
815 // Indexed Result Macro
817 macroDebugShowResult( decToInt( &arg1Ptr[1] ) );
823 void cliFunc_macroStep( char* args )
825 // Parse number from argument
826 // NOTE: Only first argument is used
829 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
831 // Set the macro step counter, negative int's are cast to uint
832 macroStepCounter = (unsigned int)decToInt( arg1Ptr );