1 /* Copyright (C) 2014-2015 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>
30 #include <generatedKeymap.h> // Generated using kll at compile time, in build directory
37 // ----- Function Declarations -----
39 void cliFunc_capList ( char* args );
40 void cliFunc_capSelect ( char* args );
41 void cliFunc_keyHold ( char* args );
42 void cliFunc_keyPress ( char* args );
43 void cliFunc_keyRelease( char* args );
44 void cliFunc_layerList ( char* args );
45 void cliFunc_layerState( char* args );
46 void cliFunc_macroDebug( char* args );
47 void cliFunc_macroList ( char* args );
48 void cliFunc_macroProc ( char* args );
49 void cliFunc_macroShow ( char* args );
50 void cliFunc_macroStep ( char* args );
56 // Bit positions are important, passes (correct key) always trump incorrect key votes
57 typedef enum TriggerMacroVote {
58 TriggerMacroVote_Release = 0x10, // Correct key
59 TriggerMacroVote_PassRelease = 0x18, // Correct key (both pass and release)
60 TriggerMacroVote_Pass = 0x8, // Correct key
61 TriggerMacroVote_DoNothingRelease = 0x4, // Incorrect key
62 TriggerMacroVote_DoNothing = 0x2, // Incorrect key
63 TriggerMacroVote_Fail = 0x1, // Incorrect key
64 TriggerMacroVote_Invalid = 0x0, // Invalid state
67 typedef enum TriggerMacroEval {
68 TriggerMacroEval_DoNothing,
69 TriggerMacroEval_DoResult,
70 TriggerMacroEval_DoResultAndRemove,
71 TriggerMacroEval_Remove,
74 typedef enum ResultMacroEval {
75 ResultMacroEval_DoNothing,
76 ResultMacroEval_Remove,
81 // ----- Variables -----
83 // Macro Module command dictionary
84 CLIDict_Entry( capList, "Prints an indexed list of all non USB keycode capabilities." );
85 CLIDict_Entry( capSelect, "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B" );
86 CLIDict_Entry( keyHold, "Send key-hold events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
87 CLIDict_Entry( keyPress, "Send key-press events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
88 CLIDict_Entry( keyRelease, "Send key-release event to macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
89 CLIDict_Entry( layerList, "List available layers." );
90 CLIDict_Entry( 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" );
91 CLIDict_Entry( macroDebug, "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes." );
92 CLIDict_Entry( macroList, "List the defined trigger and result macros." );
93 CLIDict_Entry( macroProc, "Pause/Resume macro processing." );
94 CLIDict_Entry( 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" );
95 CLIDict_Entry( macroStep, "Do N macro processing steps. Defaults to 1." );
97 CLIDict_Def( macroCLIDict, "Macro Module Commands" ) = {
98 CLIDict_Item( capList ),
99 CLIDict_Item( capSelect ),
100 CLIDict_Item( keyHold ),
101 CLIDict_Item( keyPress ),
102 CLIDict_Item( keyRelease ),
103 CLIDict_Item( layerList ),
104 CLIDict_Item( layerState ),
105 CLIDict_Item( macroDebug ),
106 CLIDict_Item( macroList ),
107 CLIDict_Item( macroProc ),
108 CLIDict_Item( macroShow ),
109 CLIDict_Item( macroStep ),
110 { 0, 0, 0 } // Null entry for dictionary end
114 // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
115 uint8_t macroDebugMode = 0;
117 // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
118 uint8_t macroPauseMode = 0;
120 // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
121 uint16_t macroStepCounter = 0;
124 // Key Trigger List Buffer and Layer Cache
125 // The layer cache is set on press only, hold and release events refer to the value set on press
126 TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
127 uint8_t macroTriggerListBufferSize = 0;
128 var_uint_t macroTriggerListLayerCache[ MaxScanCode ];
130 // Pending Trigger Macro Index List
131 // * Any trigger macros that need processing from a previous macro processing loop
132 // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
133 // Possibly could be calculated by the KLL compiler
134 // XXX It may be possible to calculate the worst case using the KLL compiler
135 uint16_t macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
136 uint16_t macroTriggerMacroPendingListSize = 0;
139 // * When modifying layer state and the state is non-0x0, the stack must be adjusted
140 uint16_t macroLayerIndexStack[ LayerNum + 1 ] = { 0 };
141 uint16_t macroLayerIndexStackSize = 0;
143 // Pending Result Macro Index List
144 // * Any result macro that needs processing from a previous macro processing loop
145 uint16_t macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
146 uint16_t macroResultMacroPendingListSize = 0;
150 // ----- Capabilities -----
152 // Sets the given layer with the specified layerState
153 void Macro_layerState( uint8_t state, uint8_t stateType, uint16_t layer, uint8_t layerState )
155 // Ignore if layer does not exist
156 if ( layer >= LayerNum )
159 // Is layer in the LayerIndexStack?
160 uint8_t inLayerIndexStack = 0;
161 uint16_t stackItem = 0;
162 while ( stackItem < macroLayerIndexStackSize )
164 // Flag if layer is already in the LayerIndexStack
165 if ( macroLayerIndexStack[ stackItem ] == layer )
167 inLayerIndexStack = 1;
171 // Increment to next item
175 // Toggle Layer State Byte
176 if ( LayerState[ layer ] & layerState )
179 LayerState[ layer ] &= ~layerState;
184 LayerState[ layer ] |= layerState;
187 // If the layer was not in the LayerIndexStack add it
188 if ( !inLayerIndexStack )
190 macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
193 // If the layer is in the LayerIndexStack and the state is 0x00, remove
194 if ( LayerState[ layer ] == 0x00 && inLayerIndexStack )
196 // Remove the layer from the LayerIndexStack
197 // Using the already positioned stackItem variable from the loop above
198 while ( stackItem < macroLayerIndexStackSize )
200 macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
204 // Reduce LayerIndexStack size
205 macroLayerIndexStackSize--;
209 // Modifies the specified Layer control byte
210 // Argument #1: Layer Index -> uint16_t
211 // Argument #2: Layer State -> uint8_t
212 void Macro_layerState_capability( uint8_t state, uint8_t stateType, uint8_t *args )
214 // Display capability name
215 if ( stateType == 0xFF && state == 0xFF )
217 print("Macro_layerState(layerIndex,layerState)");
221 // Only use capability on press or release
223 // XXX This may cause issues, might be better to implement state table here to decide -HaaTa
224 if ( stateType == 0x00 && state == 0x02 ) // Hold condition
227 // Get layer index from arguments
228 // Cast pointer to uint8_t to uint16_t then access that memory location
229 uint16_t layer = *(uint16_t*)(&args[0]);
231 // Get layer toggle byte
232 uint8_t layerState = args[ sizeof(uint16_t) ];
234 Macro_layerState( state, stateType, layer, layerState );
238 // Latches given layer
239 // Argument #1: Layer Index -> uint16_t
240 void Macro_layerLatch_capability( uint8_t state, uint8_t stateType, uint8_t *args )
242 // Display capability name
243 if ( stateType == 0xFF && state == 0xFF )
245 print("Macro_layerLatch(layerIndex)");
249 // Only use capability on press
251 if ( stateType == 0x00 && state != 0x03 ) // Only on release
254 // Get layer index from arguments
255 // Cast pointer to uint8_t to uint16_t then access that memory location
256 uint16_t layer = *(uint16_t*)(&args[0]);
258 Macro_layerState( state, stateType, layer, 0x02 );
263 // Argument #1: Layer Index -> uint16_t
264 void Macro_layerLock_capability( uint8_t state, uint8_t stateType, uint8_t *args )
266 // Display capability name
267 if ( stateType == 0xFF && state == 0xFF )
269 print("Macro_layerLock(layerIndex)");
273 // Only use capability on press
275 // XXX Could also be on release, but that's sorta dumb -HaaTa
276 if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
279 // Get layer index from arguments
280 // Cast pointer to uint8_t to uint16_t then access that memory location
281 uint16_t layer = *(uint16_t*)(&args[0]);
283 Macro_layerState( state, stateType, layer, 0x04 );
287 // Shifts given layer
288 // Argument #1: Layer Index -> uint16_t
289 void Macro_layerShift_capability( uint8_t state, uint8_t stateType, uint8_t *args )
291 // Display capability name
292 if ( stateType == 0xFF && state == 0xFF )
294 print("Macro_layerShift(layerIndex)");
298 // Only use capability on press or release
300 if ( stateType == 0x00 && ( state == 0x00 || state == 0x02 ) ) // Only pass press or release conditions
303 // Get layer index from arguments
304 // Cast pointer to uint8_t to uint16_t then access that memory location
305 uint16_t layer = *(uint16_t*)(&args[0]);
307 Macro_layerState( state, stateType, layer, 0x01 );
312 // ----- Functions -----
314 // Looks up the trigger list for the given scan code (from the active layer)
315 // NOTE: Calling function must handle the NULL pointer case
316 nat_ptr_t *Macro_layerLookup( TriggerGuide *guide, uint8_t latch_expire )
318 uint8_t scanCode = guide->scanCode;
321 // If a normal key, and not pressed, do a layer cache lookup
322 if ( guide->type == 0x00 && guide->state != 0x01 )
325 var_uint_t cachedLayer = macroTriggerListLayerCache[ scanCode ];
327 // Lookup map, then layer
328 nat_ptr_t **map = (nat_ptr_t**)LayerIndex[ cachedLayer ].triggerMap;
329 const Layer *layer = &LayerIndex[ cachedLayer ];
331 return map[ scanCode - layer->first ];
334 // If no trigger macro is defined at the given layer, fallthrough to the next layer
335 for ( uint16_t layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
338 const Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
340 // Check if latch has been pressed for this layer
341 // XXX Regardless of whether a key is found, the latch is removed on first lookup
342 uint8_t latch = LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x02;
343 if ( latch && latch_expire )
345 Macro_layerState( 0, 0, macroLayerIndexStack[ layerIndex ], 0x02 );
348 // Only use layer, if state is valid
349 // XOR each of the state bits
350 // If only two are enabled, do not use this state
351 if ( (LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x01) ^ (latch>>1) ^ ((LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x04)>>2) )
354 nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
356 // Determine if layer has key defined
357 // Make sure scanCode is between layer first and last scancodes
359 && scanCode <= layer->last
360 && scanCode >= layer->first
361 && *map[ scanCode - layer->first ] != 0 )
363 // Set the layer cache
364 macroTriggerListLayerCache[ scanCode ] = macroLayerIndexStack[ layerIndex ];
366 return map[ scanCode - layer->first ];
371 // Do lookup on default layer
372 nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
374 // Lookup default layer
375 const Layer *layer = &LayerIndex[0];
377 // Make sure scanCode is between layer first and last scancodes
379 && scanCode <= layer->last
380 && scanCode >= layer->first
381 && *map[ scanCode - layer->first ] != 0 )
383 // Set the layer cache to default map
384 macroTriggerListLayerCache[ scanCode ] = 0;
386 return map[ scanCode - layer->first ];
389 // Otherwise no defined Trigger Macro
390 erro_msg("Scan Code has no defined Trigger Macro: ");
391 printHex( scanCode );
396 // Update the scancode key state
402 // * 0x04 - Unpressed (this is currently ignored)
403 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
405 // Only add to macro trigger list if one of three states
408 case 0x01: // Pressed
410 case 0x03: // Released
411 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
412 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
413 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
414 macroTriggerListBufferSize++;
420 // Update the scancode analog state
424 // * 0x02-0xFF - Analog value (low to high)
425 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
427 // Only add to macro trigger list if non-off
430 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
431 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
432 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
433 macroTriggerListBufferSize++;
442 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
444 // Only add to macro trigger list if non-off
447 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
448 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
449 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
450 macroTriggerListBufferSize++;
455 // Append result macro to pending list, checking for duplicates
456 // Do nothing if duplicate
457 inline void Macro_appendResultMacroToPendingList( const TriggerMacro *triggerMacro )
459 // Lookup result macro index
460 var_uint_t resultMacroIndex = triggerMacro->result;
462 // Iterate through result macro pending list, making sure this macro hasn't been added yet
463 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
465 // If duplicate found, do nothing
466 if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
470 // No duplicates found, add to pending list
471 macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
473 // Lookup scanCode of the last key in the last combo
475 for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
477 pos += TriggerGuideSize * comboLength + 1;
478 comboLength = triggerMacro->guide[ pos ];
481 uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
483 // Lookup scanCode in buffer list for the current state and stateType
484 for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
486 if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
488 ResultMacroRecordList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
489 ResultMacroRecordList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
493 // Reset the macro position
494 ResultMacroRecordList[ resultMacroIndex ].pos = 0;
498 // Determine if long ResultMacro (more than 1 seqence element)
499 inline uint8_t Macro_isLongResultMacro( const ResultMacro *macro )
501 // Check the second sequence combo length
502 // If non-zero return non-zero (long sequence)
503 // 0 otherwise (short sequence)
504 var_uint_t position = 1;
505 for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
506 position += ResultGuideSize( (ResultGuide*)¯o->guide[ position ] );
507 return macro->guide[ position ];
511 // Determine if long TriggerMacro (more than 1 sequence element)
512 inline uint8_t Macro_isLongTriggerMacro( const TriggerMacro *macro )
514 // Check the second sequence combo length
515 // If non-zero return non-zero (long sequence)
516 // 0 otherwise (short sequence)
517 return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
521 // Votes on the given key vs. guide, short macros
522 inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
524 // Depending on key type
525 switch ( guide->type )
529 // For short TriggerMacros completely ignore incorrect keys
530 if ( guide->scanCode == key->scanCode )
532 switch ( key->state )
534 // Correct key, pressed, possible passing
536 return TriggerMacroVote_Pass;
538 // Correct key, held, possible passing or release
540 return TriggerMacroVote_PassRelease;
542 // Correct key, released, possible release
544 return TriggerMacroVote_Release;
548 return TriggerMacroVote_DoNothing;
552 erro_print("LED State Type - Not implemented...");
557 erro_print("Analog State Type - Not implemented...");
560 // Invalid State Type
562 erro_print("Invalid State Type. This is a bug.");
566 // XXX Shouldn't reach here
567 return TriggerMacroVote_Invalid;
571 // Votes on the given key vs. guide, long macros
572 // A long macro is defined as a guide with more than 1 combo
573 inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
575 // Depending on key type
576 switch ( guide->type )
580 // Depending on the state of the buffered key, make voting decision
582 if ( guide->scanCode != key->scanCode )
584 switch ( key->state )
586 // Wrong key, pressed, fail
588 return TriggerMacroVote_Fail;
590 // Wrong key, held, do not pass (no effect)
592 return TriggerMacroVote_DoNothing;
594 // Wrong key released, fail out if pos == 0
596 return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
603 switch ( key->state )
605 // Correct key, pressed, possible passing
607 return TriggerMacroVote_Pass;
609 // Correct key, held, possible passing or release
611 return TriggerMacroVote_PassRelease;
613 // Correct key, released, possible release
615 return TriggerMacroVote_Release;
623 erro_print("LED State Type - Not implemented...");
628 erro_print("Analog State Type - Not implemented...");
631 // Invalid State Type
633 erro_print("Invalid State Type. This is a bug.");
637 // XXX Shouldn't reach here
638 return TriggerMacroVote_Invalid;
642 // Evaluate/Update TriggerMacro
643 TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
645 // Lookup TriggerMacro
646 const TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
647 TriggerMacroRecord *record = &TriggerMacroRecordList[ triggerMacroIndex ];
649 // Check if macro has finished and should be incremented sequence elements
650 if ( record->state == TriggerMacro_Release )
652 record->state = TriggerMacro_Waiting;
653 record->pos = record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1;
656 // Current Macro position
657 var_uint_t pos = record->pos;
659 // Length of the combo being processed
660 uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
662 // If no combo items are left, remove the TriggerMacro from the pending list
663 if ( comboLength == 0 )
665 return TriggerMacroEval_Remove;
668 // Check if this is a long Trigger Macro
669 uint8_t longMacro = Macro_isLongTriggerMacro( macro );
671 // Iterate through the items in the combo, voting the on the key state
672 // If any of the pressed keys do not match, fail the macro
674 // The macro is waiting for input when in the TriggerMacro_Waiting state
675 // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
676 // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
677 // On scan after position increment, change to TriggerMacro_Waiting state
678 // TODO Add support for system LED states (NumLock, CapsLock, etc.)
679 // TODO Add support for analog key states
680 // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
681 // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
682 TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
683 for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
685 // Assign TriggerGuide element (key type, state and scancode)
686 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ comboItem ]);
688 TriggerMacroVote vote = TriggerMacroVote_Invalid;
689 // Iterate through the key buffer, comparing to each key in the combo
690 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
692 // Lookup key information
693 TriggerGuide *keyInfo = ¯oTriggerListBuffer[ key ];
695 // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
696 // Also mask all of the non-passing votes
698 ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
699 : Macro_evalShortTriggerMacroVote( keyInfo, guide );
700 if ( vote >= TriggerMacroVote_Pass )
702 vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
707 // If no pass vote was found after scanning all of the keys
708 // Fail the combo, if this is a short macro (long macros already will have a fail vote)
709 if ( !longMacro && vote < TriggerMacroVote_Pass )
710 vote |= TriggerMacroVote_Fail;
712 // After voting, append to overall vote
716 // If no pass vote was found after scanning the entire combo
717 // And this is the first position in the combo, just remove it (nothing important happened)
718 if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
719 overallVote |= TriggerMacroVote_Fail;
721 // Decide new state of macro after voting
722 // Fail macro, remove from pending list
723 if ( overallVote & TriggerMacroVote_Fail )
725 return TriggerMacroEval_Remove;
727 // Do nothing, incorrect key is being held or released
728 else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
730 // Just doing nothing :)
732 // If ready for transition and in Press state, set to Waiting and increment combo position
733 // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
734 else if ( overallVote & TriggerMacroVote_Release && record->state == TriggerMacro_Press )
736 record->state = TriggerMacro_Release;
738 // If this is the last combo in the sequence, remove from the pending list
739 if ( macro->guide[ record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1 ] == 0 )
740 return TriggerMacroEval_DoResultAndRemove;
742 // If passing and in Waiting state, set macro state to Press
743 else if ( overallVote & TriggerMacroVote_Pass
744 && ( record->state == TriggerMacro_Waiting || record->state == TriggerMacro_Press ) )
746 record->state = TriggerMacro_Press;
748 // If in press state, and this is the final combo, send request for ResultMacro
749 // Check to see if the result macro only has a single element
750 // If this result macro has more than 1 key, only send once
751 // TODO Add option to have long macro repeat rate
752 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
754 // Long result macro (more than 1 combo)
755 if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
757 // Only ever trigger result once, on press
758 if ( overallVote == TriggerMacroVote_Pass )
760 return TriggerMacroEval_DoResultAndRemove;
763 // Short result macro
766 // Only trigger result once, on press, if long trigger (more than 1 combo)
767 if ( Macro_isLongTriggerMacro( macro ) )
769 return TriggerMacroEval_DoResultAndRemove;
771 // Otherwise, trigger result continuously
774 return TriggerMacroEval_DoResult;
779 // Otherwise, just remove the macro on key release
780 // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
781 else if ( overallVote & TriggerMacroVote_Release )
783 return TriggerMacroEval_DoResultAndRemove;
786 // If this is a short macro, just remove it
787 // The state can be rebuilt on the next iteration
789 return TriggerMacroEval_Remove;
791 return TriggerMacroEval_DoNothing;
795 // Evaluate/Update ResultMacro
796 inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
798 // Lookup ResultMacro
799 const ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
800 ResultMacroRecord *record = &ResultMacroRecordList[ resultMacroIndex ];
802 // Current Macro position
803 var_uint_t pos = record->pos;
805 // Length of combo being processed
806 uint8_t comboLength = macro->guide[ pos ];
808 // Function Counter, used to keep track of the combo items processed
809 var_uint_t funcCount = 0;
811 // Combo Item Position within the guide
812 var_uint_t comboItem = pos + 1;
814 // Iterate through the Result Combo
815 while ( funcCount < comboLength )
817 // Assign TriggerGuide element (key type, state and scancode)
818 ResultGuide *guide = (ResultGuide*)(¯o->guide[ comboItem ]);
820 // Do lookup on capability function
821 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
824 capability( record->state, record->stateType, &guide->args );
826 // Increment counters
828 comboItem += ResultGuideSize( (ResultGuide*)(¯o->guide[ comboItem ]) );
831 // Move to next item in the sequence
832 record->pos = comboItem;
834 // If the ResultMacro is finished, remove
835 if ( macro->guide[ comboItem ] == 0 )
838 return ResultMacroEval_Remove;
841 // Otherwise leave the macro in the list
842 return ResultMacroEval_DoNothing;
846 // Update pending trigger list
847 inline void Macro_updateTriggerMacroPendingList()
849 // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
850 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
853 // TODO Analog Switches
854 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
855 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
859 // If this is a release case, indicate to layer lookup for possible latch expiry
860 uint8_t latch_expire = macroTriggerListBuffer[ key ].state == 0x03;
862 // Lookup Trigger List
863 nat_ptr_t *triggerList = Macro_layerLookup( ¯oTriggerListBuffer[ key ], latch_expire );
865 // Number of Triggers in list
866 nat_ptr_t triggerListSize = triggerList[0];
868 // Iterate over triggerList to see if any TriggerMacros need to be added
869 // First item is the number of items in the TriggerList
870 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
872 // Lookup trigger macro index
873 var_uint_t triggerMacroIndex = triggerList[ macro ];
875 // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
876 // triggerList needs to be added
877 var_uint_t pending = 0;
878 for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
880 // Stop scanning if the trigger macro index is found in the pending list
881 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
885 // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
886 // Add it to the list
887 if ( pending == macroTriggerMacroPendingListSize )
889 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
891 // Reset macro position
892 TriggerMacroRecordList[ triggerMacroIndex ].pos = 0;
893 TriggerMacroRecordList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
900 // Macro Procesing Loop
901 // Called once per USB buffer send
902 inline void Macro_process()
904 // Only do one round of macro processing between Output Module timer sends
905 if ( USBKeys_Sent != 0 )
908 // If the pause flag is set, only process if the step counter is non-zero
909 if ( macroPauseMode )
911 if ( macroStepCounter == 0 )
914 // Proceed, decrementing the step counter
916 dbug_print("Macro Step");
919 // Update pending trigger list, before processing TriggerMacros
920 Macro_updateTriggerMacroPendingList();
922 // Tail pointer for macroTriggerMacroPendingList
923 // Macros must be explicitly re-added
924 var_uint_t macroTriggerMacroPendingListTail = 0;
926 // Iterate through the pending TriggerMacros, processing each of them
927 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
929 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
931 // Trigger Result Macro (purposely falling through)
932 case TriggerMacroEval_DoResult:
933 // Append ResultMacro to PendingList
934 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
937 macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
940 // Trigger Result Macro and Remove (purposely falling through)
941 case TriggerMacroEval_DoResultAndRemove:
942 // Append ResultMacro to PendingList
943 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
945 // Remove Macro from Pending List, nothing to do, removing by default
946 case TriggerMacroEval_Remove:
951 // Update the macroTriggerMacroPendingListSize with the tail pointer
952 macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
955 // Tail pointer for macroResultMacroPendingList
956 // Macros must be explicitly re-added
957 var_uint_t macroResultMacroPendingListTail = 0;
959 // Iterate through the pending ResultMacros, processing each of them
960 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
962 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
964 // Re-add macros to pending list
965 case ResultMacroEval_DoNothing:
967 macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
970 // Remove Macro from Pending List, nothing to do, removing by default
971 case ResultMacroEval_Remove:
976 // Update the macroResultMacroPendingListSize with the tail pointer
977 macroResultMacroPendingListSize = macroResultMacroPendingListTail;
979 // Signal buffer that we've used it
980 Scan_finishedWithMacro( macroTriggerListBufferSize );
982 // Reset TriggerList buffer
983 macroTriggerListBufferSize = 0;
985 // If Macro debug mode is set, clear the USB Buffer
986 if ( macroDebugMode )
988 USBKeys_Modifiers = 0;
994 inline void Macro_setup()
996 // Register Macro CLI dictionary
997 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
999 // Disable Macro debug mode
1002 // Disable Macro pause flag
1005 // Set Macro step counter to zero
1006 macroStepCounter = 0;
1008 // Make sure macro trigger buffer is empty
1009 macroTriggerListBufferSize = 0;
1011 // Initialize TriggerMacro states
1012 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1014 TriggerMacroRecordList[ macro ].pos = 0;
1015 TriggerMacroRecordList[ macro ].state = TriggerMacro_Waiting;
1018 // Initialize ResultMacro states
1019 for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
1021 ResultMacroRecordList[ macro ].pos = 0;
1022 ResultMacroRecordList[ macro ].state = 0;
1023 ResultMacroRecordList[ macro ].stateType = 0;
1028 // ----- CLI Command Functions -----
1030 void cliFunc_capList( char* args )
1033 info_msg("Capabilities List ");
1034 printHex( CapabilitiesNum );
1036 // Iterate through all of the capabilities and display them
1037 for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
1043 // Display/Lookup Capability Name (utilize debug mode of capability)
1044 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1045 capability( 0xFF, 0xFF, 0 );
1049 void cliFunc_capSelect( char* args )
1051 // Parse code from argument
1054 char* arg2Ptr = args;
1056 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
1057 var_uint_t totalArgs = 2; // Always at least two args
1060 // Arguments used for keyboard capability function
1061 var_uint_t argSetCount = 0;
1062 uint8_t *argSet = (uint8_t*)args;
1065 for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1068 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1070 // Stop processing args if no more are found
1071 // Extra arguments are ignored
1072 if ( *arg1Ptr == '\0' )
1075 // For the first argument, choose the capability
1076 if ( c == 0 ) switch ( arg1Ptr[0] )
1078 // Keyboard Capability
1080 // Determine capability index
1081 cap = numToInt( &arg1Ptr[1] );
1083 // Lookup the number of args
1084 totalArgs += CapabilitiesList[ cap ].argCount;
1088 // Because allocating memory isn't doable, and the argument count is arbitrary
1089 // The argument pointer is repurposed as the argument list (much smaller anyways)
1090 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1092 // Once all the arguments are prepared, call the keyboard capability function
1093 if ( argSetCount == totalArgs )
1095 // Indicate that the capability was called
1100 printHex( argSet[0] );
1102 printHex( argSet[1] );
1104 printHex( argSet[2] );
1107 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1108 capability( argSet[0], argSet[1], &argSet[2] );
1113 void cliFunc_keyHold( char* args )
1115 // Parse codes from arguments
1118 char* arg2Ptr = args;
1124 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1126 // Stop processing args if no more are found
1127 if ( *arg1Ptr == '\0' )
1130 // Ignore non-Scancode numbers
1131 switch ( arg1Ptr[0] )
1135 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1141 void cliFunc_keyPress( char* args )
1143 // Parse codes from arguments
1146 char* arg2Ptr = args;
1152 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1154 // Stop processing args if no more are found
1155 if ( *arg1Ptr == '\0' )
1158 // Ignore non-Scancode numbers
1159 switch ( arg1Ptr[0] )
1163 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1169 void cliFunc_keyRelease( char* args )
1171 // Parse codes from arguments
1174 char* arg2Ptr = args;
1180 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1182 // Stop processing args if no more are found
1183 if ( *arg1Ptr == '\0' )
1186 // Ignore non-Scancode numbers
1187 switch ( arg1Ptr[0] )
1191 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
1197 void cliFunc_layerList( char* args )
1200 info_msg("Layer List");
1202 // Iterate through all of the layers and display them
1203 for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1209 // Display layer name
1210 dPrint( (char*)LayerIndex[ layer ].name );
1214 print(" \033[1m(default)\033[0m");
1217 print( NL "\t\t Layer State: " );
1218 printHex( LayerState[ layer ] );
1220 // First -> Last Indices
1221 print(" First -> Last Indices: ");
1222 printHex( LayerIndex[ layer ].first );
1224 printHex( LayerIndex[ layer ].last );
1228 void cliFunc_layerState( char* args )
1230 // Parse codes from arguments
1233 char* arg2Ptr = args;
1238 // Process first two args
1239 for ( uint8_t c = 0; c < 2; c++ )
1242 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1244 // Stop processing args if no more are found
1245 if ( *arg1Ptr == '\0' )
1250 // First argument (e.g. L1)
1252 if ( arg1Ptr[0] != 'L' )
1255 arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1257 // Second argument (e.g. 4)
1259 arg2 = (uint8_t)numToInt( arg1Ptr );
1261 // Display operation (to indicate that it worked)
1263 info_msg("Setting Layer L");
1268 // Set the layer state
1269 LayerState[ arg1 ] = arg2;
1275 void cliFunc_macroDebug( char* args )
1277 // Toggle macro debug mode
1278 macroDebugMode = macroDebugMode ? 0 : 1;
1281 info_msg("Macro Debug Mode: ");
1282 printInt8( macroDebugMode );
1285 void cliFunc_macroList( char* args )
1287 // Show pending key events
1289 info_msg("Pending Key Events: ");
1290 printInt16( (uint16_t)macroTriggerListBufferSize );
1292 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1294 printHex( macroTriggerListBuffer[ key ].scanCode );
1298 // Show pending trigger macros
1300 info_msg("Pending Trigger Macros: ");
1301 printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1303 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1305 printHex( macroTriggerMacroPendingList[ macro ] );
1309 // Show pending result macros
1311 info_msg("Pending Result Macros: ");
1312 printInt16( (uint16_t)macroResultMacroPendingListSize );
1314 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1316 printHex( macroResultMacroPendingList[ macro ] );
1320 // Show available trigger macro indices
1322 info_msg("Trigger Macros Range: T0 -> T");
1323 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1325 // Show available result macro indices
1327 info_msg("Result Macros Range: R0 -> R");
1328 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1330 // Show Trigger to Result Macro Links
1332 info_msg("Trigger : Result Macro Pairs");
1333 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1337 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1339 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1343 void cliFunc_macroProc( char* args )
1345 // Toggle macro pause mode
1346 macroPauseMode = macroPauseMode ? 0 : 1;
1349 info_msg("Macro Processing Mode: ");
1350 printInt8( macroPauseMode );
1353 void macroDebugShowTrigger( var_uint_t index )
1355 // Only proceed if the macro exists
1356 if ( index >= TriggerMacroNum )
1359 // Trigger Macro Show
1360 const TriggerMacro *macro = &TriggerMacroList[ index ];
1361 TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
1364 info_msg("Trigger Macro Index: ");
1365 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1368 // Read the comboLength for combo in the sequence (sequence of combos)
1370 uint8_t comboLength = macro->guide[ pos ];
1372 // Iterate through and interpret the guide
1373 while ( comboLength != 0 )
1375 // Initial position of the combo
1376 var_uint_t comboPos = ++pos;
1378 // Iterate through the combo
1379 while ( pos < comboLength * TriggerGuideSize + comboPos )
1381 // Assign TriggerGuide element (key type, state and scancode)
1382 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
1384 // Display guide information about trigger key
1385 printHex( guide->scanCode );
1387 printHex( guide->type );
1389 printHex( guide->state );
1391 // Increment position
1392 pos += TriggerGuideSize;
1394 // Only show combo separator if there are combos left in the sequence element
1395 if ( pos < comboLength * TriggerGuideSize + comboPos )
1399 // Read the next comboLength
1400 comboLength = macro->guide[ pos ];
1402 // Only show sequence separator if there is another combo to process
1403 if ( comboLength != 0 )
1407 // Display current position
1408 print( NL "Position: " );
1409 printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1411 // Display result macro index
1412 print( NL "Result Macro Index: " );
1413 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1415 // Display trigger macro state
1416 print( NL "Trigger Macro State: " );
1417 switch ( record->state )
1419 case TriggerMacro_Press: print("Press"); break;
1420 case TriggerMacro_Release: print("Release"); break;
1421 case TriggerMacro_Waiting: print("Waiting"); break;
1425 void macroDebugShowResult( var_uint_t index )
1427 // Only proceed if the macro exists
1428 if ( index >= ResultMacroNum )
1431 // Trigger Macro Show
1432 const ResultMacro *macro = &ResultMacroList[ index ];
1433 ResultMacroRecord *record = &ResultMacroRecordList[ index ];
1436 info_msg("Result Macro Index: ");
1437 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1440 // Read the comboLength for combo in the sequence (sequence of combos)
1442 uint8_t comboLength = macro->guide[ pos++ ];
1444 // Iterate through and interpret the guide
1445 while ( comboLength != 0 )
1447 // Function Counter, used to keep track of the combos processed
1448 var_uint_t funcCount = 0;
1450 // Iterate through the combo
1451 while ( funcCount < comboLength )
1453 // Assign TriggerGuide element (key type, state and scancode)
1454 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
1456 // Display Function Index
1457 printHex( guide->index );
1460 // Display Function Ptr Address
1461 printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1464 // Display/Lookup Capability Name (utilize debug mode of capability)
1465 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1466 capability( 0xFF, 0xFF, 0 );
1468 // Display Argument(s)
1470 for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1472 // Arguments are only 8 bit values
1473 printHex( (&guide->args)[ arg ] );
1475 // Only show arg separator if there are args left
1476 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1481 // Increment position
1482 pos += ResultGuideSize( guide );
1484 // Increment function count
1487 // Only show combo separator if there are combos left in the sequence element
1488 if ( funcCount < comboLength )
1492 // Read the next comboLength
1493 comboLength = macro->guide[ pos++ ];
1495 // Only show sequence separator if there is another combo to process
1496 if ( comboLength != 0 )
1500 // Display current position
1501 print( NL "Position: " );
1502 printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1504 // Display final trigger state/type
1505 print( NL "Final Trigger State (State/Type): " );
1506 printHex( record->state );
1508 printHex( record->stateType );
1511 void cliFunc_macroShow( char* args )
1513 // Parse codes from arguments
1516 char* arg2Ptr = args;
1522 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1524 // Stop processing args if no more are found
1525 if ( *arg1Ptr == '\0' )
1528 // Ignore invalid codes
1529 switch ( arg1Ptr[0] )
1531 // Indexed Trigger Macro
1533 macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1535 // Indexed Result Macro
1537 macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1543 void cliFunc_macroStep( char* args )
1545 // Parse number from argument
1546 // NOTE: Only first argument is used
1549 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1551 // Default to 1, if no argument given
1552 var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1557 // Set the macro step counter, negative int's are cast to uint
1558 macroStepCounter = count;