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>
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
125 TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
126 uint8_t macroTriggerListBufferSize = 0;
128 // Pending Trigger Macro Index List
129 // * Any trigger macros that need processing from a previous macro processing loop
130 // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
131 // Possibly could be calculated by the KLL compiler
132 // XXX It may be possible to calculate the worst case using the KLL compiler
133 uint16_t macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
134 uint16_t macroTriggerMacroPendingListSize = 0;
137 // * When modifying layer state and the state is non-0x0, the stack must be adjusted
138 uint16_t macroLayerIndexStack[ LayerNum + 1 ] = { 0 };
139 uint16_t macroLayerIndexStackSize = 0;
141 // Pending Result Macro Index List
142 // * Any result macro that needs processing from a previous macro processing loop
143 uint16_t macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
144 uint16_t macroResultMacroPendingListSize = 0;
148 // ----- Capabilities -----
150 // Sets the given layer with the specified layerState
151 void Macro_layerState( uint8_t state, uint8_t stateType, uint16_t layer, uint8_t layerState )
153 // Is layer in the LayerIndexStack?
154 uint8_t inLayerIndexStack = 0;
155 uint16_t stackItem = 0;
156 while ( stackItem < macroLayerIndexStackSize )
158 // Flag if layer is already in the LayerIndexStack
159 if ( macroLayerIndexStack[ stackItem ] == layer )
161 inLayerIndexStack = 1;
165 // Increment to next item
169 // Toggle Layer State Byte
170 if ( LayerState[ layer ] & layerState )
173 LayerState[ layer ] &= ~layerState;
178 LayerState[ layer ] |= layerState;
181 // If the layer was not in the LayerIndexStack add it
182 if ( !inLayerIndexStack )
184 macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
187 // If the layer is in the LayerIndexStack and the state is 0x00, remove
188 if ( LayerState[ layer ] == 0x00 && inLayerIndexStack )
190 // Remove the layer from the LayerIndexStack
191 // Using the already positioned stackItem variable from the loop above
192 while ( stackItem < macroLayerIndexStackSize )
194 macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
198 // Reduce LayerIndexStack size
199 macroLayerIndexStackSize--;
203 // Modifies the specified Layer control byte
204 // Argument #1: Layer Index -> uint16_t
205 // Argument #2: Layer State -> uint8_t
206 void Macro_layerState_capability( uint8_t state, uint8_t stateType, uint8_t *args )
208 // Display capability name
209 if ( stateType == 0xFF && state == 0xFF )
211 print("Macro_layerState(layerIndex,layerState)");
215 // Only use capability on press or release
217 // XXX This may cause issues, might be better to implement state table here to decide -HaaTa
218 if ( stateType == 0x00 && state == 0x02 ) // Hold condition
221 // Get layer index from arguments
222 // Cast pointer to uint8_t to uint16_t then access that memory location
223 uint16_t layer = *(uint16_t*)(&args[0]);
225 // Get layer toggle byte
226 uint8_t layerState = args[ sizeof(uint16_t) ];
228 Macro_layerState( state, stateType, layer, layerState );
232 // Latches given layer
233 // Argument #1: Layer Index -> uint16_t
234 void Macro_layerLatch_capability( uint8_t state, uint8_t stateType, uint8_t *args )
236 // Display capability name
237 if ( stateType == 0xFF && state == 0xFF )
239 print("Macro_layerLatch(layerIndex)");
243 // Only use capability on press
245 // XXX To make sense, this code be on press or release. Or it could even be a sticky shift (why? dunno) -HaaTa
246 if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
249 // Get layer index from arguments
250 // Cast pointer to uint8_t to uint16_t then access that memory location
251 uint16_t layer = *(uint16_t*)(&args[0]);
253 Macro_layerState( state, stateType, layer, 0x02 );
258 // Argument #1: Layer Index -> uint16_t
259 void Macro_layerLock_capability( uint8_t state, uint8_t stateType, uint8_t *args )
261 // Display capability name
262 if ( stateType == 0xFF && state == 0xFF )
264 print("Macro_layerLock(layerIndex)");
268 // Only use capability on press
270 // XXX Could also be on release, but that's sorta dumb -HaaTa
271 if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
274 // Get layer index from arguments
275 // Cast pointer to uint8_t to uint16_t then access that memory location
276 uint16_t layer = *(uint16_t*)(&args[0]);
278 Macro_layerState( state, stateType, layer, 0x04 );
282 // Shifts given layer
283 // Argument #1: Layer Index -> uint16_t
284 void Macro_layerShift_capability( uint8_t state, uint8_t stateType, uint8_t *args )
286 // Display capability name
287 if ( stateType == 0xFF && state == 0xFF )
289 print("Macro_layerShift(layerIndex)");
293 // Only use capability on press or release
295 if ( stateType == 0x00 && ( state == 0x00 || state == 0x02 ) ) // Only pass press or release conditions
298 // Get layer index from arguments
299 // Cast pointer to uint8_t to uint16_t then access that memory location
300 uint16_t layer = *(uint16_t*)(&args[0]);
302 Macro_layerState( state, stateType, layer, 0x01 );
307 // ----- Functions -----
309 // Looks up the trigger list for the given scan code (from the active layer)
310 // NOTE: Calling function must handle the NULL pointer case
311 nat_ptr_t *Macro_layerLookup( uint8_t scanCode )
313 // If no trigger macro is defined at the given layer, fallthrough to the next layer
314 for ( uint16_t layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
317 const Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
319 // Check if latch has been pressed for this layer
320 // XXX Regardless of whether a key is found, the latch is removed on first lookup
321 uint8_t latch = LayerState[ layerIndex ] & 0x02;
324 LayerState[ layerIndex ] &= ~0x02;
327 // Only use layer, if state is valid
328 // XOR each of the state bits
329 // If only two are enabled, do not use this state
330 if ( (LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x01) ^ (latch>>1) ^ ((LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x04)>>2) )
333 nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
335 // Determine if layer has key defined
336 // Make sure scanCode is between layer first and last scancodes
338 && scanCode <= layer->last
339 && scanCode >= layer->first
340 && *map[ scanCode - layer->first ] != 0 )
342 return map[ scanCode - layer->first ];
347 // Do lookup on default layer
348 nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
350 // Lookup default layer
351 const Layer *layer = &LayerIndex[0];
353 // Make sure scanCode is between layer first and last scancodes
355 && scanCode <= layer->last
356 && scanCode >= layer->first
357 && *map[ scanCode - layer->first ] != 0 )
359 return map[ scanCode - layer->first ];
362 // Otherwise no defined Trigger Macro
363 erro_msg("Scan Code has no defined Trigger Macro: ");
364 printHex( scanCode );
369 // Update the scancode key state
375 // * 0x04 - Unpressed (this is currently ignored)
376 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
378 // Only add to macro trigger list if one of three states
381 case 0x01: // Pressed
383 case 0x03: // Released
384 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
385 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
386 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
387 macroTriggerListBufferSize++;
393 // Update the scancode analog state
397 // * 0x02-0xFF - Analog value (low to high)
398 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
400 // Only add to macro trigger list if non-off
403 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
404 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
405 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
406 macroTriggerListBufferSize++;
415 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
417 // Only add to macro trigger list if non-off
420 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
421 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
422 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
423 macroTriggerListBufferSize++;
428 // Append result macro to pending list, checking for duplicates
429 // Do nothing if duplicate
430 inline void Macro_appendResultMacroToPendingList( const TriggerMacro *triggerMacro )
432 // Lookup result macro index
433 var_uint_t resultMacroIndex = triggerMacro->result;
435 // Iterate through result macro pending list, making sure this macro hasn't been added yet
436 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
438 // If duplicate found, do nothing
439 if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
443 // No duplicates found, add to pending list
444 macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
446 // Lookup scanCode of the last key in the last combo
448 for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
450 pos += TriggerGuideSize * comboLength + 1;
451 comboLength = triggerMacro->guide[ pos ];
454 uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
456 // Lookup scanCode in buffer list for the current state and stateType
457 for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
459 if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
461 ResultMacroRecordList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
462 ResultMacroRecordList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
466 // Reset the macro position
467 ResultMacroRecordList[ resultMacroIndex ].pos = 0;
471 // Determine if long ResultMacro (more than 1 seqence element)
472 inline uint8_t Macro_isLongResultMacro( const ResultMacro *macro )
474 // Check the second sequence combo length
475 // If non-zero return non-zero (long sequence)
476 // 0 otherwise (short sequence)
477 var_uint_t position = 1;
478 for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
479 position += ResultGuideSize( (ResultGuide*)¯o->guide[ position ] );
480 return macro->guide[ position ];
484 // Determine if long TriggerMacro (more than 1 sequence element)
485 inline uint8_t Macro_isLongTriggerMacro( const TriggerMacro *macro )
487 // Check the second sequence combo length
488 // If non-zero return non-zero (long sequence)
489 // 0 otherwise (short sequence)
490 return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
494 // Votes on the given key vs. guide, short macros
495 inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
497 // Depending on key type
498 switch ( guide->type )
502 // For short TriggerMacros completely ignore incorrect keys
503 if ( guide->scanCode == key->scanCode )
505 switch ( key->state )
507 // Correct key, pressed, possible passing
509 return TriggerMacroVote_Pass;
511 // Correct key, held, possible passing or release
513 return TriggerMacroVote_PassRelease;
515 // Correct key, released, possible release
517 return TriggerMacroVote_Release;
521 return TriggerMacroVote_DoNothing;
525 erro_print("LED State Type - Not implemented...");
530 erro_print("Analog State Type - Not implemented...");
533 // Invalid State Type
535 erro_print("Invalid State Type. This is a bug.");
539 // XXX Shouldn't reach here
540 return TriggerMacroVote_Invalid;
544 // Votes on the given key vs. guide, long macros
545 // A long macro is defined as a guide with more than 1 combo
546 inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
548 // Depending on key type
549 switch ( guide->type )
553 // Depending on the state of the buffered key, make voting decision
555 if ( guide->scanCode != key->scanCode )
557 switch ( key->state )
559 // Wrong key, pressed, fail
561 return TriggerMacroVote_Fail;
563 // Wrong key, held, do not pass (no effect)
565 return TriggerMacroVote_DoNothing;
567 // Wrong key released, fail out if pos == 0
569 return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
576 switch ( key->state )
578 // Correct key, pressed, possible passing
580 return TriggerMacroVote_Pass;
582 // Correct key, held, possible passing or release
584 return TriggerMacroVote_PassRelease;
586 // Correct key, released, possible release
588 return TriggerMacroVote_Release;
596 erro_print("LED State Type - Not implemented...");
601 erro_print("Analog State Type - Not implemented...");
604 // Invalid State Type
606 erro_print("Invalid State Type. This is a bug.");
610 // XXX Shouldn't reach here
611 return TriggerMacroVote_Invalid;
615 // Evaluate/Update TriggerMacro
616 inline TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
618 // Lookup TriggerMacro
619 const TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
620 TriggerMacroRecord *record = &TriggerMacroRecordList[ triggerMacroIndex ];
622 // Check if macro has finished and should be incremented sequence elements
623 if ( record->state == TriggerMacro_Release )
625 record->state = TriggerMacro_Waiting;
626 record->pos = record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1;
629 // Current Macro position
630 var_uint_t pos = record->pos;
632 // Length of the combo being processed
633 uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
635 // If no combo items are left, remove the TriggerMacro from the pending list
636 if ( comboLength == 0 )
638 return TriggerMacroEval_Remove;
641 // Check if this is a long Trigger Macro
642 uint8_t longMacro = Macro_isLongTriggerMacro( macro );
644 // Iterate through the items in the combo, voting the on the key state
645 // If any of the pressed keys do not match, fail the macro
647 // The macro is waiting for input when in the TriggerMacro_Waiting state
648 // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
649 // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
650 // On scan after position increment, change to TriggerMacro_Waiting state
651 // TODO Add support for system LED states (NumLock, CapsLock, etc.)
652 // TODO Add support for analog key states
653 // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
654 // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
655 TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
656 for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
658 // Assign TriggerGuide element (key type, state and scancode)
659 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ comboItem ]);
661 TriggerMacroVote vote = TriggerMacroVote_Invalid;
662 // Iterate through the key buffer, comparing to each key in the combo
663 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
665 // Lookup key information
666 TriggerGuide *keyInfo = ¯oTriggerListBuffer[ key ];
668 // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
669 // Also mask all of the non-passing votes
671 ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
672 : Macro_evalShortTriggerMacroVote( keyInfo, guide );
673 if ( vote >= TriggerMacroVote_Pass )
675 vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
680 // If no pass vote was found after scanning all of the keys
681 // Fail the combo, if this is a short macro (long macros already will have a fail vote)
682 if ( !longMacro && vote < TriggerMacroVote_Pass )
683 vote |= TriggerMacroVote_Fail;
685 // After voting, append to overall vote
689 // If no pass vote was found after scanning the entire combo
690 // And this is the first position in the combo, just remove it (nothing important happened)
691 if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
692 overallVote |= TriggerMacroVote_Fail;
694 // Decide new state of macro after voting
695 // Fail macro, remove from pending list
696 if ( overallVote & TriggerMacroVote_Fail )
698 return TriggerMacroEval_Remove;
700 // Do nothing, incorrect key is being held or released
701 else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
703 // Just doing nothing :)
705 // If ready for transition and in Press state, set to Waiting and increment combo position
706 // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
707 else if ( overallVote & TriggerMacroVote_Release && record->state == TriggerMacro_Press )
709 record->state = TriggerMacro_Release;
711 // If this is the last combo in the sequence, remove from the pending list
712 if ( macro->guide[ record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1 ] == 0 )
713 return TriggerMacroEval_DoResultAndRemove;
715 // If passing and in Waiting state, set macro state to Press
716 else if ( overallVote & TriggerMacroVote_Pass
717 && ( record->state == TriggerMacro_Waiting || record->state == TriggerMacro_Press ) )
719 record->state = TriggerMacro_Press;
721 // If in press state, and this is the final combo, send request for ResultMacro
722 // Check to see if the result macro only has a single element
723 // If this result macro has more than 1 key, only send once
724 // TODO Add option to have long macro repeat rate
725 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
727 // Long result macro (more than 1 combo)
728 if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
730 // Only ever trigger result once, on press
731 if ( overallVote == TriggerMacroVote_Pass )
733 return TriggerMacroEval_DoResultAndRemove;
736 // Short result macro
739 // Only trigger result once, on press, if long trigger (more than 1 combo)
740 if ( Macro_isLongTriggerMacro( macro ) )
742 return TriggerMacroEval_DoResultAndRemove;
744 // Otherwise, trigger result continuously
747 return TriggerMacroEval_DoResult;
752 // Otherwise, just remove the macro on key release
753 // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
754 else if ( overallVote & TriggerMacroVote_Release )
756 return TriggerMacroEval_DoResultAndRemove;
759 // If this is a short macro, just remove it
760 // The state can be rebuilt on the next iteration
762 return TriggerMacroEval_Remove;
764 return TriggerMacroEval_DoNothing;
768 // Evaluate/Update ResultMacro
769 inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
771 // Lookup ResultMacro
772 const ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
773 ResultMacroRecord *record = &ResultMacroRecordList[ resultMacroIndex ];
775 // Current Macro position
776 var_uint_t pos = record->pos;
778 // Length of combo being processed
779 uint8_t comboLength = macro->guide[ pos ];
781 // Function Counter, used to keep track of the combo items processed
782 var_uint_t funcCount = 0;
784 // Combo Item Position within the guide
785 var_uint_t comboItem = pos + 1;
787 // Iterate through the Result Combo
788 while ( funcCount < comboLength )
790 // Assign TriggerGuide element (key type, state and scancode)
791 ResultGuide *guide = (ResultGuide*)(¯o->guide[ comboItem ]);
793 // Do lookup on capability function
794 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
797 capability( record->state, record->stateType, &guide->args );
799 // Increment counters
801 comboItem += ResultGuideSize( (ResultGuide*)(¯o->guide[ comboItem ]) );
804 // Move to next item in the sequence
805 record->pos = comboItem;
807 // If the ResultMacro is finished, remove
808 if ( macro->guide[ comboItem ] == 0 )
811 return ResultMacroEval_Remove;
814 // Otherwise leave the macro in the list
815 return ResultMacroEval_DoNothing;
819 // Update pending trigger list
820 inline void Macro_updateTriggerMacroPendingList()
822 // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
823 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
826 // TODO Analog Switches
827 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
828 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
831 // Lookup Trigger List
832 nat_ptr_t *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode );
834 // Number of Triggers in list
835 nat_ptr_t triggerListSize = triggerList[0];
837 // Iterate over triggerList to see if any TriggerMacros need to be added
838 // First item is the number of items in the TriggerList
839 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
841 // Lookup trigger macro index
842 var_uint_t triggerMacroIndex = triggerList[ macro ];
844 // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
845 // triggerList needs to be added
846 var_uint_t pending = 0;
847 for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
849 // Stop scanning if the trigger macro index is found in the pending list
850 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
854 // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
855 // Add it to the list
856 if ( pending == macroTriggerMacroPendingListSize )
858 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
860 // Reset macro position
861 TriggerMacroRecordList[ triggerMacroIndex ].pos = 0;
862 TriggerMacroRecordList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
869 // Macro Procesing Loop
870 // Called once per USB buffer send
871 inline void Macro_process()
873 // Only do one round of macro processing between Output Module timer sends
874 if ( USBKeys_Sent != 0 )
877 // If the pause flag is set, only process if the step counter is non-zero
878 if ( macroPauseMode )
880 if ( macroStepCounter == 0 )
883 // Proceed, decrementing the step counter
885 dbug_print("Macro Step");
888 // Update pending trigger list, before processing TriggerMacros
889 Macro_updateTriggerMacroPendingList();
891 // Tail pointer for macroTriggerMacroPendingList
892 // Macros must be explicitly re-added
893 var_uint_t macroTriggerMacroPendingListTail = 0;
895 // Iterate through the pending TriggerMacros, processing each of them
896 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
898 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
900 // Trigger Result Macro (purposely falling through)
901 case TriggerMacroEval_DoResult:
902 // Append ResultMacro to PendingList
903 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
906 macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
909 // Trigger Result Macro and Remove (purposely falling through)
910 case TriggerMacroEval_DoResultAndRemove:
911 // Append ResultMacro to PendingList
912 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
914 // Remove Macro from Pending List, nothing to do, removing by default
915 case TriggerMacroEval_Remove:
920 // Update the macroTriggerMacroPendingListSize with the tail pointer
921 macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
924 // Tail pointer for macroResultMacroPendingList
925 // Macros must be explicitly re-added
926 var_uint_t macroResultMacroPendingListTail = 0;
928 // Iterate through the pending ResultMacros, processing each of them
929 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
931 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
933 // Re-add macros to pending list
934 case ResultMacroEval_DoNothing:
936 macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
939 // Remove Macro from Pending List, nothing to do, removing by default
940 case ResultMacroEval_Remove:
945 // Update the macroResultMacroPendingListSize with the tail pointer
946 macroResultMacroPendingListSize = macroResultMacroPendingListTail;
948 // Signal buffer that we've used it
949 Scan_finishedWithMacro( macroTriggerListBufferSize );
951 // Reset TriggerList buffer
952 macroTriggerListBufferSize = 0;
954 // If Macro debug mode is set, clear the USB Buffer
955 if ( macroDebugMode )
957 USBKeys_Modifiers = 0;
963 inline void Macro_setup()
965 // Register Macro CLI dictionary
966 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
968 // Disable Macro debug mode
971 // Disable Macro pause flag
974 // Set Macro step counter to zero
975 macroStepCounter = 0;
977 // Make sure macro trigger buffer is empty
978 macroTriggerListBufferSize = 0;
980 // Initialize TriggerMacro states
981 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
983 TriggerMacroRecordList[ macro ].pos = 0;
984 TriggerMacroRecordList[ macro ].state = TriggerMacro_Waiting;
987 // Initialize ResultMacro states
988 for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
990 ResultMacroRecordList[ macro ].pos = 0;
991 ResultMacroRecordList[ macro ].state = 0;
992 ResultMacroRecordList[ macro ].stateType = 0;
997 // ----- CLI Command Functions -----
999 void cliFunc_capList( char* args )
1002 info_msg("Capabilities List");
1003 printHex( CapabilitiesNum );
1005 // Iterate through all of the capabilities and display them
1006 for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
1012 // Display/Lookup Capability Name (utilize debug mode of capability)
1013 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1014 capability( 0xFF, 0xFF, 0 );
1018 void cliFunc_capSelect( char* args )
1020 // Parse code from argument
1023 char* arg2Ptr = args;
1025 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
1026 var_uint_t totalArgs = 2; // Always at least two args
1029 // Arguments used for keyboard capability function
1030 var_uint_t argSetCount = 0;
1031 uint8_t *argSet = (uint8_t*)args;
1034 for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1037 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1039 // Stop processing args if no more are found
1040 // Extra arguments are ignored
1041 if ( *arg1Ptr == '\0' )
1044 // For the first argument, choose the capability
1045 if ( c == 0 ) switch ( arg1Ptr[0] )
1047 // Keyboard Capability
1049 // Determine capability index
1050 cap = numToInt( &arg1Ptr[1] );
1052 // Lookup the number of args
1053 totalArgs += CapabilitiesList[ cap ].argCount;
1057 // Because allocating memory isn't doable, and the argument count is arbitrary
1058 // The argument pointer is repurposed as the argument list (much smaller anyways)
1059 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1061 // Once all the arguments are prepared, call the keyboard capability function
1062 if ( argSetCount == totalArgs )
1064 // Indicate that the capability was called
1069 printHex( argSet[0] );
1071 printHex( argSet[1] );
1073 printHex( argSet[2] );
1076 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1077 capability( argSet[0], argSet[1], &argSet[2] );
1082 void cliFunc_keyHold( char* args )
1084 // Parse codes from arguments
1087 char* arg2Ptr = args;
1093 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1095 // Stop processing args if no more are found
1096 if ( *arg1Ptr == '\0' )
1099 // Ignore non-Scancode numbers
1100 switch ( arg1Ptr[0] )
1104 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1110 void cliFunc_keyPress( char* args )
1112 // Parse codes from arguments
1115 char* arg2Ptr = args;
1121 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1123 // Stop processing args if no more are found
1124 if ( *arg1Ptr == '\0' )
1127 // Ignore non-Scancode numbers
1128 switch ( arg1Ptr[0] )
1132 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1138 void cliFunc_keyRelease( char* args )
1140 // Parse codes from arguments
1143 char* arg2Ptr = args;
1149 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1151 // Stop processing args if no more are found
1152 if ( *arg1Ptr == '\0' )
1155 // Ignore non-Scancode numbers
1156 switch ( arg1Ptr[0] )
1160 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
1166 void cliFunc_layerList( char* args )
1169 info_msg("Layer List");
1171 // Iterate through all of the layers and display them
1172 for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1178 // Display layer name
1179 dPrint( (char*)LayerIndex[ layer ].name );
1183 print(" \033[1m(default)\033[0m");
1186 print( NL "\t\t Layer State: " );
1187 printHex( LayerState[ layer ] );
1189 // First -> Last Indices
1190 print(" First -> Last Indices: ");
1191 printHex( LayerIndex[ layer ].first );
1193 printHex( LayerIndex[ layer ].last );
1197 void cliFunc_layerState( char* args )
1199 // Parse codes from arguments
1202 char* arg2Ptr = args;
1207 // Process first two args
1208 for ( uint8_t c = 0; c < 2; c++ )
1211 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1213 // Stop processing args if no more are found
1214 if ( *arg1Ptr == '\0' )
1219 // First argument (e.g. L1)
1221 if ( arg1Ptr[0] != 'L' )
1224 arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1226 // Second argument (e.g. 4)
1228 arg2 = (uint8_t)numToInt( arg1Ptr );
1230 // Display operation (to indicate that it worked)
1232 info_msg("Setting Layer L");
1237 // Set the layer state
1238 LayerState[ arg1 ] = arg2;
1244 void cliFunc_macroDebug( char* args )
1246 // Toggle macro debug mode
1247 macroDebugMode = macroDebugMode ? 0 : 1;
1250 info_msg("Macro Debug Mode: ");
1251 printInt8( macroDebugMode );
1254 void cliFunc_macroList( char* args )
1256 // Show pending key events
1258 info_msg("Pending Key Events: ");
1259 printInt16( (uint16_t)macroTriggerListBufferSize );
1261 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1263 printHex( macroTriggerListBuffer[ key ].scanCode );
1267 // Show pending trigger macros
1269 info_msg("Pending Trigger Macros: ");
1270 printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1272 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1274 printHex( macroTriggerMacroPendingList[ macro ] );
1278 // Show pending result macros
1280 info_msg("Pending Result Macros: ");
1281 printInt16( (uint16_t)macroResultMacroPendingListSize );
1283 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1285 printHex( macroResultMacroPendingList[ macro ] );
1289 // Show available trigger macro indices
1291 info_msg("Trigger Macros Range: T0 -> T");
1292 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1294 // Show available result macro indices
1296 info_msg("Result Macros Range: R0 -> R");
1297 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1299 // Show Trigger to Result Macro Links
1301 info_msg("Trigger : Result Macro Pairs");
1302 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1306 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1308 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1312 void cliFunc_macroProc( char* args )
1314 // Toggle macro pause mode
1315 macroPauseMode = macroPauseMode ? 0 : 1;
1318 info_msg("Macro Processing Mode: ");
1319 printInt8( macroPauseMode );
1322 void macroDebugShowTrigger( var_uint_t index )
1324 // Only proceed if the macro exists
1325 if ( index >= TriggerMacroNum )
1328 // Trigger Macro Show
1329 const TriggerMacro *macro = &TriggerMacroList[ index ];
1330 TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
1333 info_msg("Trigger Macro Index: ");
1334 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1337 // Read the comboLength for combo in the sequence (sequence of combos)
1339 uint8_t comboLength = macro->guide[ pos ];
1341 // Iterate through and interpret the guide
1342 while ( comboLength != 0 )
1344 // Initial position of the combo
1345 var_uint_t comboPos = ++pos;
1347 // Iterate through the combo
1348 while ( pos < comboLength * TriggerGuideSize + comboPos )
1350 // Assign TriggerGuide element (key type, state and scancode)
1351 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
1353 // Display guide information about trigger key
1354 printHex( guide->scanCode );
1356 printHex( guide->type );
1358 printHex( guide->state );
1360 // Increment position
1361 pos += TriggerGuideSize;
1363 // Only show combo separator if there are combos left in the sequence element
1364 if ( pos < comboLength * TriggerGuideSize + comboPos )
1368 // Read the next comboLength
1369 comboLength = macro->guide[ pos ];
1371 // Only show sequence separator if there is another combo to process
1372 if ( comboLength != 0 )
1376 // Display current position
1377 print( NL "Position: " );
1378 printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1380 // Display result macro index
1381 print( NL "Result Macro Index: " );
1382 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1384 // Display trigger macro state
1385 print( NL "Trigger Macro State: " );
1386 switch ( record->state )
1388 case TriggerMacro_Press: print("Press"); break;
1389 case TriggerMacro_Release: print("Release"); break;
1390 case TriggerMacro_Waiting: print("Waiting"); break;
1394 void macroDebugShowResult( var_uint_t index )
1396 // Only proceed if the macro exists
1397 if ( index >= ResultMacroNum )
1400 // Trigger Macro Show
1401 const ResultMacro *macro = &ResultMacroList[ index ];
1402 ResultMacroRecord *record = &ResultMacroRecordList[ index ];
1405 info_msg("Result Macro Index: ");
1406 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1409 // Read the comboLength for combo in the sequence (sequence of combos)
1411 uint8_t comboLength = macro->guide[ pos++ ];
1413 // Iterate through and interpret the guide
1414 while ( comboLength != 0 )
1416 // Function Counter, used to keep track of the combos processed
1417 var_uint_t funcCount = 0;
1419 // Iterate through the combo
1420 while ( funcCount < comboLength )
1422 // Assign TriggerGuide element (key type, state and scancode)
1423 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
1425 // Display Function Index
1426 printHex( guide->index );
1429 // Display Function Ptr Address
1430 printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1433 // Display/Lookup Capability Name (utilize debug mode of capability)
1434 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1435 capability( 0xFF, 0xFF, 0 );
1437 // Display Argument(s)
1439 for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1441 // Arguments are only 8 bit values
1442 printHex( (&guide->args)[ arg ] );
1444 // Only show arg separator if there are args left
1445 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1450 // Increment position
1451 pos += ResultGuideSize( guide );
1453 // Increment function count
1456 // Only show combo separator if there are combos left in the sequence element
1457 if ( funcCount < comboLength )
1461 // Read the next comboLength
1462 comboLength = macro->guide[ pos++ ];
1464 // Only show sequence separator if there is another combo to process
1465 if ( comboLength != 0 )
1469 // Display current position
1470 print( NL "Position: " );
1471 printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1473 // Display final trigger state/type
1474 print( NL "Final Trigger State (State/Type): " );
1475 printHex( record->state );
1477 printHex( record->stateType );
1480 void cliFunc_macroShow( char* args )
1482 // Parse codes from arguments
1485 char* arg2Ptr = args;
1491 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1493 // Stop processing args if no more are found
1494 if ( *arg1Ptr == '\0' )
1497 // Ignore invalid codes
1498 switch ( arg1Ptr[0] )
1500 // Indexed Trigger Macro
1502 macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1504 // Indexed Result Macro
1506 macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1512 void cliFunc_macroStep( char* args )
1514 // Parse number from argument
1515 // NOTE: Only first argument is used
1518 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1520 // Default to 1, if no argument given
1521 var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1526 // Set the macro step counter, negative int's are cast to uint
1527 macroStepCounter = count;