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_layerLatch( char* args );
46 void cliFunc_layerList ( char* args );
47 void cliFunc_layerLock ( char* args );
48 void cliFunc_macroDebug( char* args );
49 void cliFunc_macroList ( char* args );
50 void cliFunc_macroProc ( char* args );
51 void cliFunc_macroShow ( char* args );
52 void cliFunc_macroStep ( char* args );
56 // ----- Variables -----
58 // Macro Module command dictionary
59 char* macroCLIDictName = "Macro Module Commands";
60 CLIDictItem macroCLIDict[] = {
61 { "capList", "Prints an indexed list of all non USB keycode capabilities.", cliFunc_capList },
62 { "capSelect", "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B", cliFunc_capSelect },
63 { "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 },
64 { "keyRelease", "Release a key-press from the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyRelease },
65 { "layerLatch", "Latch the specified indexed layer." NL "\t\t\033[35mL15\033[0m Indexed Layer 0x0F", cliFunc_layerLatch },
66 { "layerList", "List available layers.", cliFunc_layerList },
67 { "layerLock", "Lock the specified indexed layer." NL "\t\t\033[35mL2\033[0m Indexed Layer 0x02", cliFunc_layerLock },
68 { "macroDebug", "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes.", cliFunc_macroDebug },
69 { "macroList", "List the defined trigger and result macros.", cliFunc_macroList },
70 { "macroProc", "Pause/Resume macro processing.", cliFunc_macroProc },
71 { "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 },
72 { "macroStep", "Do N macro processing steps. Defaults to 1.", cliFunc_macroStep },
73 { 0, 0, 0 } // Null entry for dictionary end
77 // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
78 uint8_t macroDebugMode = 0;
80 // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
81 uint8_t macroPauseMode = 0;
83 // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
84 unsigned int macroStepCounter = 0;
87 // Key Trigger List Buffer
88 // * Item 1: scan code
91 uint8_t macroTriggerListBuffer[MaxScanCode * 2] = { 0 }; // Each key has a state to be cached
92 uint8_t macroTriggerListBufferSize = 0;
94 // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
95 // Possibly could be calculated by the KLL compiler
96 // XXX It may be possible to calculate the worst case using the KLL compiler
97 TriggerMacro *triggerMacroPendingList[TriggerMacroNum];
101 // ----- Functions -----
103 // Looks up the trigger list for the given scan code (from the active layer)
104 unsigned int *Macro_layerLookup( uint8_t scanCode )
106 // TODO - No layer fallthrough lookup
107 return default_scanMap[ scanCode ];
111 // Update the scancode key state
117 // * 0x04 - Unpressed (this is currently ignored)
118 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
120 // Only add to macro trigger list if one of three states
123 case 0x01: // Pressed
125 case 0x03: // Released
126 macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = scanCode;
127 macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = state;
133 // Update the scancode analog state
137 // * 0x02-0xFF - Analog value (low to high)
138 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
149 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
155 // Evaluate/Update the TriggerMacro
156 void Macro_evalTriggerMacro( TriggerMacro *triggerMacro )
158 // Which combo in the sequence is being evaluated
159 unsigned int comboPos = triggerMacro->pos;
161 // If combo length is more than 1, cancel trigger macro if an incorrect key is found
162 uint8_t comboLength = triggerMacro->guide[ comboPos ];
164 // Iterate over list of keys currently pressed
165 for ( uint8_t keyPressed = 0; keyPressed < macroTriggerListBufferSize; keyPressed += 2 )
167 // Compare with keys in combo
168 for ( unsigned int comboKey = 0; comboKey < comboLength; comboKey++ )
170 // Lookup key in combo
171 uint8_t guideKey = triggerMacro->guide[ comboPos + comboKey + 2 ]; // TODO Only Press/Hold/Release atm
174 if ( comboLength == 1 )
176 // If key matches and only 1 key pressed, increment the TriggerMacro combo position
177 if ( guideKey == macroTriggerListBuffer[ keyPressed ] && macroTriggerListBufferSize == 1 )
179 triggerMacro->pos += comboLength * 2 + 1;
180 // TODO check if TriggerMacro is finished, register ResultMacro
184 // If key does not match or more than 1 key pressed, reset the TriggerMacro combo position
185 triggerMacro->pos = 0;
201 inline void Macro_bufferAdd( uint8_t byte )
203 // Make sure we haven't overflowed the key buffer
204 // Default function for adding keys to the KeyIndex_Buffer, does a DefaultMap_Lookup
205 if ( KeyIndex_BufferUsed < KEYBOARD_BUFFER )
207 uint8_t key = DefaultMap_Lookup[byte];
208 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
210 // Key already in the buffer
211 if ( KeyIndex_Buffer[c] == key )
216 KeyIndex_Buffer[KeyIndex_BufferUsed++] = key;
220 inline void Macro_bufferRemove( uint8_t byte )
222 uint8_t key = DefaultMap_Lookup[byte];
224 // Check for the released key, and shift the other keys lower on the buffer
225 for ( uint8_t c = 0; c < KeyIndex_BufferUsed; c++ )
227 // Key to release found
228 if ( KeyIndex_Buffer[c] == key )
230 // Shift keys from c position
231 for ( uint8_t k = c; k < KeyIndex_BufferUsed - 1; k++ )
232 KeyIndex_Buffer[k] = KeyIndex_Buffer[k + 1];
235 KeyIndex_BufferUsed--;
241 // Error case (no key to release)
242 erro_msg("Could not find key to release: ");
247 inline void Macro_finishWithUSBBuffer( uint8_t sentKeys )
251 inline void Macro_process()
253 // Only do one round of macro processing between Output Module timer sends
254 if ( USBKeys_Sent != 0 )
257 // If the pause flag is set, only process if the step counter is non-zero
258 if ( macroPauseMode && macroStepCounter == 0 )
262 // Proceed, decrementing the step counter
268 // Loop through macro trigger buffer
269 for ( uint8_t index = 0; index < macroTriggerListBufferSize; index += 2 )
271 // Get scanCode, first item of macroTriggerListBuffer pairs
272 uint8_t scanCode = macroTriggerListBuffer[ index ];
274 // Lookup trigger list for this key
275 unsigned int *triggerList = Macro_layerLookup( scanCode );
277 // The first element is the length of the trigger list
278 unsigned int triggerListSize = triggerList[0];
280 // Loop through the trigger list
281 for ( unsigned int trigger = 0; trigger < triggerListSize; trigger++ )
283 // Lookup TriggerMacro
284 TriggerMacro *triggerMacro = (TriggerMacro*)triggerList[ trigger + 1 ];
286 // Get triggered state of scan code, second item of macroTriggerListBuffer pairs
287 uint8_t state = macroTriggerListBuffer[ index + 1 ];
290 Macro_evalTriggerMacro( triggerMacro );
299 // Loop through input buffer
300 for ( uint8_t index = 0; index < KeyIndex_BufferUsed && !macroDebugMode; index++ )
303 //printInt8( KeyIndex_BufferUsed );
304 // Get the keycode from the buffer
305 uint8_t key = KeyIndex_Buffer[index];
307 // Set the modifier bit if this key is a modifier
308 if ( (key & KEY_LCTRL) == KEY_LCTRL ) // AND with 0xE0
310 USBKeys_Modifiers |= 1 << (key ^ KEY_LCTRL); // Left shift 1 by key XOR 0xE0
312 // Modifier processed, move on to the next key
317 if ( USBKeys_Sent >= USBKeys_MaxSize )
319 warn_msg("USB Key limit reached");
324 // Allow ignoring keys with 0's
327 USBKeys_Array[USBKeys_Sent++] = key;
331 // Key was not mapped
332 erro_msg( "Key not mapped... - " );
339 // Signal buffer that we've used it
340 Scan_finishedWithBuffer( KeyIndex_BufferUsed );
342 // If Macro debug mode is set, clear the USB Buffer
343 if ( macroDebugMode )
345 USBKeys_Modifiers = 0;
350 inline void Macro_setup()
352 // Register Macro CLI dictionary
353 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
355 // Disable Macro debug mode
358 // Disable Macro pause flag
361 // Set Macro step counter to zero
362 macroStepCounter = 0;
364 // Make sure macro trigger buffer is empty
365 macroTriggerListBufferSize = 0;
369 // ----- CLI Command Functions -----
371 void cliFunc_capList( char* args )
374 info_msg("Capabilities List");
376 // Iterate through all of the capabilities and display them
377 for ( unsigned int cap = 0; cap < CapabilitiesNum; cap++ )
383 // Display/Lookup Capability Name (utilize debug mode of capability)
384 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
385 capability( 0xFF, 0xFF, 0 );
389 void cliFunc_capSelect( char* args )
391 // Parse code from argument
394 char* arg2Ptr = args;
396 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
397 unsigned int totalArgs = 2; // Always at least two args
398 unsigned int cap = 0;
400 // Arguments used for keyboard capability function
401 unsigned int argSetCount = 0;
402 uint8_t *argSet = (uint8_t*)args;
405 for ( unsigned int c = 0; argSetCount < totalArgs; c++ )
408 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
410 // Stop processing args if no more are found
411 // Extra arguments are ignored
412 if ( *arg1Ptr == '\0' )
415 // For the first argument, choose the capability
416 if ( c == 0 ) switch ( arg1Ptr[0] )
418 // Keyboard Capability
420 // Determine capability index
421 cap = decToInt( &arg1Ptr[1] );
423 // Lookup the number of args
424 totalArgs += CapabilitiesList[ cap ].argCount;
428 // Because allocating memory isn't doable, and the argument count is arbitrary
429 // The argument pointer is repurposed as the argument list (much smaller anyways)
430 argSet[ argSetCount++ ] = (uint8_t)decToInt( arg1Ptr );
432 // Once all the arguments are prepared, call the keyboard capability function
433 if ( argSetCount == totalArgs )
435 // Indicate that the capability was called
440 printHex( argSet[0] );
442 printHex( argSet[1] );
444 printHex( argSet[2] );
447 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
448 capability( argSet[0], argSet[1], &argSet[2] );
453 void cliFunc_keyPress( char* args )
455 // Parse codes from arguments
458 char* arg2Ptr = args;
464 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
466 // Stop processing args if no more are found
467 if ( *arg1Ptr == '\0' )
470 // Ignore non-Scancode numbers
471 switch ( arg1Ptr[0] )
475 Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
481 void cliFunc_keyRelease( char* args )
483 // Parse codes from arguments
486 char* arg2Ptr = args;
492 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
494 // Stop processing args if no more are found
495 if ( *arg1Ptr == '\0' )
498 // Ignore non-Scancode numbers
499 switch ( arg1Ptr[0] )
503 Macro_keyState( (uint8_t)decToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
509 void cliFunc_layerLatch( char* args )
514 void cliFunc_layerList( char* args )
519 void cliFunc_layerLock( char* args )
524 void cliFunc_macroDebug( char* args )
526 // Toggle macro debug mode
527 macroDebugMode = macroDebugMode ? 0 : 1;
530 info_msg("Macro Debug Mode: ");
531 printInt8( macroDebugMode );
534 void cliFunc_macroList( char* args )
536 // Show available trigger macro indices
538 info_msg("Trigger Macros Range: T0 -> T");
539 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
541 // Show available result macro indices
543 info_msg("Result Macros Range: R0 -> R");
544 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
546 // Show Trigger to Result Macro Links
548 info_msg("Trigger : Result Macro Pairs");
549 for ( unsigned int macro = 0; macro < TriggerMacroNum; macro++ )
553 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
555 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
559 void cliFunc_macroProc( char* args )
561 // Toggle macro pause mode
562 macroPauseMode = macroPauseMode ? 0 : 1;
565 info_msg("Macro Processing Mode: ");
566 printInt8( macroPauseMode );
569 void macroDebugShowTrigger( unsigned int index )
571 // Only proceed if the macro exists
572 if ( index >= TriggerMacroNum )
575 // Trigger Macro Show
576 TriggerMacro *macro = &TriggerMacroList[ index ];
579 info_msg("Trigger Macro Index: ");
580 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
583 // Read the comboLength for combo in the sequence (sequence of combos)
584 unsigned int pos = 0;
585 uint8_t comboLength = macro->guide[ pos ];
587 // Iterate through and interpret the guide
588 while ( comboLength != 0 )
590 // Initial position of the combo
591 unsigned int comboPos = ++pos;
593 // Iterate through the combo
594 while ( pos < comboLength * TriggerGuideSize + comboPos )
596 // Assign TriggerGuide element (key type, state and scancode)
597 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
599 // Display guide information about trigger key
600 printHex( guide->scancode );
602 printHex( guide->type );
604 printHex( guide->state );
606 // Increment position
607 pos += TriggerGuideSize;
609 // Only show combo separator if there are combos left in the sequence element
610 if ( pos < comboLength * TriggerGuideSize + comboPos )
614 // Read the next comboLength
615 comboLength = macro->guide[ pos ];
617 // Only show sequence separator if there is another combo to process
618 if ( comboLength != 0 )
622 // Display current position
623 print( NL "Position: " );
624 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
626 // Display result macro index
627 print( NL "Result Macro Index: " );
628 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
631 void macroDebugShowResult( unsigned int index )
633 // Only proceed if the macro exists
634 if ( index >= ResultMacroNum )
637 // Trigger Macro Show
638 ResultMacro *macro = &ResultMacroList[ index ];
641 info_msg("Result Macro Index: ");
642 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
645 // Read the comboLength for combo in the sequence (sequence of combos)
646 unsigned int pos = 0;
647 uint8_t comboLength = macro->guide[ pos++ ];
649 // Iterate through and interpret the guide
650 while ( comboLength != 0 )
652 // Function Counter, used to keep track of the combos processed
653 unsigned int funcCount = 0;
655 // Iterate through the combo
656 while ( funcCount < comboLength )
658 // Assign TriggerGuide element (key type, state and scancode)
659 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
661 // Display Function Index
662 printHex( guide->index );
665 // Display Function Ptr Address
666 printHex( (unsigned int)CapabilitiesList[ guide->index ].func );
669 // Display/Lookup Capability Name (utilize debug mode of capability)
670 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
671 capability( 0xFF, 0xFF, 0 );
673 // Display Argument(s)
675 for ( unsigned int arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
677 // Arguments are only 8 bit values
678 printHex( (&guide->args)[ arg ] );
680 // Only show arg separator if there are args left
681 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
686 // Increment position
687 pos += ResultGuideSize( guide );
689 // Increment function count
692 // Only show combo separator if there are combos left in the sequence element
693 if ( funcCount < comboLength )
697 // Read the next comboLength
698 comboLength = macro->guide[ pos++ ];
700 // Only show sequence separator if there is another combo to process
701 if ( comboLength != 0 )
705 // Display current position
706 print( NL "Position: " );
707 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
709 // Display final trigger state/type
710 print( NL "Final Trigger State (State/Type): " );
711 printHex( macro->state );
713 printHex( macro->stateType );
716 void cliFunc_macroShow( char* args )
718 // Parse codes from arguments
721 char* arg2Ptr = args;
727 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
729 // Stop processing args if no more are found
730 if ( *arg1Ptr == '\0' )
733 // Ignore invalid codes
734 switch ( arg1Ptr[0] )
736 // Indexed Trigger Macro
738 macroDebugShowTrigger( decToInt( &arg1Ptr[1] ) );
740 // Indexed Result Macro
742 macroDebugShowResult( decToInt( &arg1Ptr[1] ) );
748 void cliFunc_macroStep( char* args )
750 // Parse number from argument
751 // NOTE: Only first argument is used
754 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
756 // Set the macro step counter, negative int's are cast to uint
757 macroStepCounter = (unsigned int)decToInt( arg1Ptr );