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 // Ignore if layer does not exist
154 if ( layer >= LayerNum )
157 // Is layer in the LayerIndexStack?
158 uint8_t inLayerIndexStack = 0;
159 uint16_t stackItem = 0;
160 while ( stackItem < macroLayerIndexStackSize )
162 // Flag if layer is already in the LayerIndexStack
163 if ( macroLayerIndexStack[ stackItem ] == layer )
165 inLayerIndexStack = 1;
169 // Increment to next item
173 // Toggle Layer State Byte
174 if ( LayerState[ layer ] & layerState )
177 LayerState[ layer ] &= ~layerState;
182 LayerState[ layer ] |= layerState;
185 // If the layer was not in the LayerIndexStack add it
186 if ( !inLayerIndexStack )
188 macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
191 // If the layer is in the LayerIndexStack and the state is 0x00, remove
192 if ( LayerState[ layer ] == 0x00 && inLayerIndexStack )
194 // Remove the layer from the LayerIndexStack
195 // Using the already positioned stackItem variable from the loop above
196 while ( stackItem < macroLayerIndexStackSize )
198 macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
202 // Reduce LayerIndexStack size
203 macroLayerIndexStackSize--;
207 // Modifies the specified Layer control byte
208 // Argument #1: Layer Index -> uint16_t
209 // Argument #2: Layer State -> uint8_t
210 void Macro_layerState_capability( uint8_t state, uint8_t stateType, uint8_t *args )
212 // Display capability name
213 if ( stateType == 0xFF && state == 0xFF )
215 print("Macro_layerState(layerIndex,layerState)");
219 // Only use capability on press or release
221 // XXX This may cause issues, might be better to implement state table here to decide -HaaTa
222 if ( stateType == 0x00 && state == 0x02 ) // Hold condition
225 // Get layer index from arguments
226 // Cast pointer to uint8_t to uint16_t then access that memory location
227 uint16_t layer = *(uint16_t*)(&args[0]);
229 // Get layer toggle byte
230 uint8_t layerState = args[ sizeof(uint16_t) ];
232 Macro_layerState( state, stateType, layer, layerState );
236 // Latches given layer
237 // Argument #1: Layer Index -> uint16_t
238 void Macro_layerLatch_capability( uint8_t state, uint8_t stateType, uint8_t *args )
240 // Display capability name
241 if ( stateType == 0xFF && state == 0xFF )
243 print("Macro_layerLatch(layerIndex)");
247 // Only use capability on press
249 if ( stateType == 0x00 && state != 0x03 ) // Only on release
252 // Get layer index from arguments
253 // Cast pointer to uint8_t to uint16_t then access that memory location
254 uint16_t layer = *(uint16_t*)(&args[0]);
256 Macro_layerState( state, stateType, layer, 0x02 );
261 // Argument #1: Layer Index -> uint16_t
262 void Macro_layerLock_capability( uint8_t state, uint8_t stateType, uint8_t *args )
264 // Display capability name
265 if ( stateType == 0xFF && state == 0xFF )
267 print("Macro_layerLock(layerIndex)");
271 // Only use capability on press
273 // XXX Could also be on release, but that's sorta dumb -HaaTa
274 if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
277 // Get layer index from arguments
278 // Cast pointer to uint8_t to uint16_t then access that memory location
279 uint16_t layer = *(uint16_t*)(&args[0]);
281 Macro_layerState( state, stateType, layer, 0x04 );
285 // Shifts given layer
286 // Argument #1: Layer Index -> uint16_t
287 void Macro_layerShift_capability( uint8_t state, uint8_t stateType, uint8_t *args )
289 // Display capability name
290 if ( stateType == 0xFF && state == 0xFF )
292 print("Macro_layerShift(layerIndex)");
296 // Only use capability on press or release
298 if ( stateType == 0x00 && ( state == 0x00 || state == 0x02 ) ) // Only pass press or release conditions
301 // Get layer index from arguments
302 // Cast pointer to uint8_t to uint16_t then access that memory location
303 uint16_t layer = *(uint16_t*)(&args[0]);
305 Macro_layerState( state, stateType, layer, 0x01 );
310 // ----- Functions -----
312 // Looks up the trigger list for the given scan code (from the active layer)
313 // NOTE: Calling function must handle the NULL pointer case
314 nat_ptr_t *Macro_layerLookup( uint8_t scanCode, uint8_t latch_expire )
316 // If no trigger macro is defined at the given layer, fallthrough to the next layer
317 for ( uint16_t layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
320 const Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
322 // Check if latch has been pressed for this layer
323 // XXX Regardless of whether a key is found, the latch is removed on first lookup
324 uint8_t latch = LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x02;
325 if ( latch && latch_expire )
327 Macro_layerState( 0, 0, macroLayerIndexStack[ layerIndex ], 0x02 );
330 // Only use layer, if state is valid
331 // XOR each of the state bits
332 // If only two are enabled, do not use this state
333 if ( (LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x01) ^ (latch>>1) ^ ((LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x04)>>2) )
336 nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
338 // Determine if layer has key defined
339 // Make sure scanCode is between layer first and last scancodes
341 && scanCode <= layer->last
342 && scanCode >= layer->first
343 && *map[ scanCode - layer->first ] != 0 )
345 return map[ scanCode - layer->first ];
350 // Do lookup on default layer
351 nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
353 // Lookup default layer
354 const Layer *layer = &LayerIndex[0];
356 // Make sure scanCode is between layer first and last scancodes
358 && scanCode <= layer->last
359 && scanCode >= layer->first
360 && *map[ scanCode - layer->first ] != 0 )
362 return map[ scanCode - layer->first ];
365 // Otherwise no defined Trigger Macro
366 erro_msg("Scan Code has no defined Trigger Macro: ");
367 printHex( scanCode );
372 // Update the scancode key state
378 // * 0x04 - Unpressed (this is currently ignored)
379 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
381 // Only add to macro trigger list if one of three states
384 case 0x01: // Pressed
386 case 0x03: // Released
387 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
388 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
389 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
390 macroTriggerListBufferSize++;
396 // Update the scancode analog state
400 // * 0x02-0xFF - Analog value (low to high)
401 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
403 // Only add to macro trigger list if non-off
406 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
407 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
408 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
409 macroTriggerListBufferSize++;
418 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
420 // Only add to macro trigger list if non-off
423 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
424 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
425 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
426 macroTriggerListBufferSize++;
431 // Append result macro to pending list, checking for duplicates
432 // Do nothing if duplicate
433 inline void Macro_appendResultMacroToPendingList( const TriggerMacro *triggerMacro )
435 // Lookup result macro index
436 var_uint_t resultMacroIndex = triggerMacro->result;
438 // Iterate through result macro pending list, making sure this macro hasn't been added yet
439 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
441 // If duplicate found, do nothing
442 if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
446 // No duplicates found, add to pending list
447 macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
449 // Lookup scanCode of the last key in the last combo
451 for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
453 pos += TriggerGuideSize * comboLength + 1;
454 comboLength = triggerMacro->guide[ pos ];
457 uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
459 // Lookup scanCode in buffer list for the current state and stateType
460 for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
462 if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
464 ResultMacroRecordList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
465 ResultMacroRecordList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
469 // Reset the macro position
470 ResultMacroRecordList[ resultMacroIndex ].pos = 0;
474 // Determine if long ResultMacro (more than 1 seqence element)
475 inline uint8_t Macro_isLongResultMacro( const ResultMacro *macro )
477 // Check the second sequence combo length
478 // If non-zero return non-zero (long sequence)
479 // 0 otherwise (short sequence)
480 var_uint_t position = 1;
481 for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
482 position += ResultGuideSize( (ResultGuide*)¯o->guide[ position ] );
483 return macro->guide[ position ];
487 // Determine if long TriggerMacro (more than 1 sequence element)
488 inline uint8_t Macro_isLongTriggerMacro( const TriggerMacro *macro )
490 // Check the second sequence combo length
491 // If non-zero return non-zero (long sequence)
492 // 0 otherwise (short sequence)
493 return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
497 // Votes on the given key vs. guide, short macros
498 inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
500 // Depending on key type
501 switch ( guide->type )
505 // For short TriggerMacros completely ignore incorrect keys
506 if ( guide->scanCode == key->scanCode )
508 switch ( key->state )
510 // Correct key, pressed, possible passing
512 return TriggerMacroVote_Pass;
514 // Correct key, held, possible passing or release
516 return TriggerMacroVote_PassRelease;
518 // Correct key, released, possible release
520 return TriggerMacroVote_Release;
524 return TriggerMacroVote_DoNothing;
528 erro_print("LED State Type - Not implemented...");
533 erro_print("Analog State Type - Not implemented...");
536 // Invalid State Type
538 erro_print("Invalid State Type. This is a bug.");
542 // XXX Shouldn't reach here
543 return TriggerMacroVote_Invalid;
547 // Votes on the given key vs. guide, long macros
548 // A long macro is defined as a guide with more than 1 combo
549 inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
551 // Depending on key type
552 switch ( guide->type )
556 // Depending on the state of the buffered key, make voting decision
558 if ( guide->scanCode != key->scanCode )
560 switch ( key->state )
562 // Wrong key, pressed, fail
564 return TriggerMacroVote_Fail;
566 // Wrong key, held, do not pass (no effect)
568 return TriggerMacroVote_DoNothing;
570 // Wrong key released, fail out if pos == 0
572 return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
579 switch ( key->state )
581 // Correct key, pressed, possible passing
583 return TriggerMacroVote_Pass;
585 // Correct key, held, possible passing or release
587 return TriggerMacroVote_PassRelease;
589 // Correct key, released, possible release
591 return TriggerMacroVote_Release;
599 erro_print("LED State Type - Not implemented...");
604 erro_print("Analog State Type - Not implemented...");
607 // Invalid State Type
609 erro_print("Invalid State Type. This is a bug.");
613 // XXX Shouldn't reach here
614 return TriggerMacroVote_Invalid;
618 // Evaluate/Update TriggerMacro
619 TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
621 // Lookup TriggerMacro
622 const TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
623 TriggerMacroRecord *record = &TriggerMacroRecordList[ triggerMacroIndex ];
625 // Check if macro has finished and should be incremented sequence elements
626 if ( record->state == TriggerMacro_Release )
628 record->state = TriggerMacro_Waiting;
629 record->pos = record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1;
632 // Current Macro position
633 var_uint_t pos = record->pos;
635 // Length of the combo being processed
636 uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
638 // If no combo items are left, remove the TriggerMacro from the pending list
639 if ( comboLength == 0 )
641 return TriggerMacroEval_Remove;
644 // Check if this is a long Trigger Macro
645 uint8_t longMacro = Macro_isLongTriggerMacro( macro );
647 // Iterate through the items in the combo, voting the on the key state
648 // If any of the pressed keys do not match, fail the macro
650 // The macro is waiting for input when in the TriggerMacro_Waiting state
651 // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
652 // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
653 // On scan after position increment, change to TriggerMacro_Waiting state
654 // TODO Add support for system LED states (NumLock, CapsLock, etc.)
655 // TODO Add support for analog key states
656 // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
657 // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
658 TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
659 for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
661 // Assign TriggerGuide element (key type, state and scancode)
662 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ comboItem ]);
664 TriggerMacroVote vote = TriggerMacroVote_Invalid;
665 // Iterate through the key buffer, comparing to each key in the combo
666 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
668 // Lookup key information
669 TriggerGuide *keyInfo = ¯oTriggerListBuffer[ key ];
671 // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
672 // Also mask all of the non-passing votes
674 ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
675 : Macro_evalShortTriggerMacroVote( keyInfo, guide );
676 if ( vote >= TriggerMacroVote_Pass )
678 vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
683 // If no pass vote was found after scanning all of the keys
684 // Fail the combo, if this is a short macro (long macros already will have a fail vote)
685 if ( !longMacro && vote < TriggerMacroVote_Pass )
686 vote |= TriggerMacroVote_Fail;
688 // After voting, append to overall vote
692 // If no pass vote was found after scanning the entire combo
693 // And this is the first position in the combo, just remove it (nothing important happened)
694 if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
695 overallVote |= TriggerMacroVote_Fail;
697 // Decide new state of macro after voting
698 // Fail macro, remove from pending list
699 if ( overallVote & TriggerMacroVote_Fail )
701 return TriggerMacroEval_Remove;
703 // Do nothing, incorrect key is being held or released
704 else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
706 // Just doing nothing :)
708 // If ready for transition and in Press state, set to Waiting and increment combo position
709 // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
710 else if ( overallVote & TriggerMacroVote_Release && record->state == TriggerMacro_Press )
712 record->state = TriggerMacro_Release;
714 // If this is the last combo in the sequence, remove from the pending list
715 if ( macro->guide[ record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1 ] == 0 )
716 return TriggerMacroEval_DoResultAndRemove;
718 // If passing and in Waiting state, set macro state to Press
719 else if ( overallVote & TriggerMacroVote_Pass
720 && ( record->state == TriggerMacro_Waiting || record->state == TriggerMacro_Press ) )
722 record->state = TriggerMacro_Press;
724 // If in press state, and this is the final combo, send request for ResultMacro
725 // Check to see if the result macro only has a single element
726 // If this result macro has more than 1 key, only send once
727 // TODO Add option to have long macro repeat rate
728 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
730 // Long result macro (more than 1 combo)
731 if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
733 // Only ever trigger result once, on press
734 if ( overallVote == TriggerMacroVote_Pass )
736 return TriggerMacroEval_DoResultAndRemove;
739 // Short result macro
742 // Only trigger result once, on press, if long trigger (more than 1 combo)
743 if ( Macro_isLongTriggerMacro( macro ) )
745 return TriggerMacroEval_DoResultAndRemove;
747 // Otherwise, trigger result continuously
750 return TriggerMacroEval_DoResult;
755 // Otherwise, just remove the macro on key release
756 // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
757 else if ( overallVote & TriggerMacroVote_Release )
759 return TriggerMacroEval_DoResultAndRemove;
762 // If this is a short macro, just remove it
763 // The state can be rebuilt on the next iteration
765 return TriggerMacroEval_Remove;
767 return TriggerMacroEval_DoNothing;
771 // Evaluate/Update ResultMacro
772 inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
774 // Lookup ResultMacro
775 const ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
776 ResultMacroRecord *record = &ResultMacroRecordList[ resultMacroIndex ];
778 // Current Macro position
779 var_uint_t pos = record->pos;
781 // Length of combo being processed
782 uint8_t comboLength = macro->guide[ pos ];
784 // Function Counter, used to keep track of the combo items processed
785 var_uint_t funcCount = 0;
787 // Combo Item Position within the guide
788 var_uint_t comboItem = pos + 1;
790 // Iterate through the Result Combo
791 while ( funcCount < comboLength )
793 // Assign TriggerGuide element (key type, state and scancode)
794 ResultGuide *guide = (ResultGuide*)(¯o->guide[ comboItem ]);
796 // Do lookup on capability function
797 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
800 capability( record->state, record->stateType, &guide->args );
802 // Increment counters
804 comboItem += ResultGuideSize( (ResultGuide*)(¯o->guide[ comboItem ]) );
807 // Move to next item in the sequence
808 record->pos = comboItem;
810 // If the ResultMacro is finished, remove
811 if ( macro->guide[ comboItem ] == 0 )
814 return ResultMacroEval_Remove;
817 // Otherwise leave the macro in the list
818 return ResultMacroEval_DoNothing;
822 // Update pending trigger list
823 inline void Macro_updateTriggerMacroPendingList()
825 // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
826 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
829 // TODO Analog Switches
830 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
831 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
835 // If this is a release case, indicate to layer lookup for possible latch expiry
836 uint8_t latch_expire = macroTriggerListBuffer[ key ].state == 0x03;
838 // Lookup Trigger List
839 nat_ptr_t *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode, latch_expire );
841 // Number of Triggers in list
842 nat_ptr_t triggerListSize = triggerList[0];
844 // Iterate over triggerList to see if any TriggerMacros need to be added
845 // First item is the number of items in the TriggerList
846 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
848 // Lookup trigger macro index
849 var_uint_t triggerMacroIndex = triggerList[ macro ];
851 // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
852 // triggerList needs to be added
853 var_uint_t pending = 0;
854 for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
856 // Stop scanning if the trigger macro index is found in the pending list
857 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
861 // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
862 // Add it to the list
863 if ( pending == macroTriggerMacroPendingListSize )
865 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
867 // Reset macro position
868 TriggerMacroRecordList[ triggerMacroIndex ].pos = 0;
869 TriggerMacroRecordList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
876 // Macro Procesing Loop
877 // Called once per USB buffer send
878 inline void Macro_process()
880 // Only do one round of macro processing between Output Module timer sends
881 if ( USBKeys_Sent != 0 )
884 // If the pause flag is set, only process if the step counter is non-zero
885 if ( macroPauseMode )
887 if ( macroStepCounter == 0 )
890 // Proceed, decrementing the step counter
892 dbug_print("Macro Step");
895 // Update pending trigger list, before processing TriggerMacros
896 Macro_updateTriggerMacroPendingList();
898 // Tail pointer for macroTriggerMacroPendingList
899 // Macros must be explicitly re-added
900 var_uint_t macroTriggerMacroPendingListTail = 0;
902 // Iterate through the pending TriggerMacros, processing each of them
903 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
905 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
907 // Trigger Result Macro (purposely falling through)
908 case TriggerMacroEval_DoResult:
909 // Append ResultMacro to PendingList
910 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
913 macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
916 // Trigger Result Macro and Remove (purposely falling through)
917 case TriggerMacroEval_DoResultAndRemove:
918 // Append ResultMacro to PendingList
919 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
921 // Remove Macro from Pending List, nothing to do, removing by default
922 case TriggerMacroEval_Remove:
927 // Update the macroTriggerMacroPendingListSize with the tail pointer
928 macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
931 // Tail pointer for macroResultMacroPendingList
932 // Macros must be explicitly re-added
933 var_uint_t macroResultMacroPendingListTail = 0;
935 // Iterate through the pending ResultMacros, processing each of them
936 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
938 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
940 // Re-add macros to pending list
941 case ResultMacroEval_DoNothing:
943 macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
946 // Remove Macro from Pending List, nothing to do, removing by default
947 case ResultMacroEval_Remove:
952 // Update the macroResultMacroPendingListSize with the tail pointer
953 macroResultMacroPendingListSize = macroResultMacroPendingListTail;
955 // Signal buffer that we've used it
956 Scan_finishedWithMacro( macroTriggerListBufferSize );
958 // Reset TriggerList buffer
959 macroTriggerListBufferSize = 0;
961 // If Macro debug mode is set, clear the USB Buffer
962 if ( macroDebugMode )
964 USBKeys_Modifiers = 0;
970 inline void Macro_setup()
972 // Register Macro CLI dictionary
973 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
975 // Disable Macro debug mode
978 // Disable Macro pause flag
981 // Set Macro step counter to zero
982 macroStepCounter = 0;
984 // Make sure macro trigger buffer is empty
985 macroTriggerListBufferSize = 0;
987 // Initialize TriggerMacro states
988 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
990 TriggerMacroRecordList[ macro ].pos = 0;
991 TriggerMacroRecordList[ macro ].state = TriggerMacro_Waiting;
994 // Initialize ResultMacro states
995 for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
997 ResultMacroRecordList[ macro ].pos = 0;
998 ResultMacroRecordList[ macro ].state = 0;
999 ResultMacroRecordList[ macro ].stateType = 0;
1004 // ----- CLI Command Functions -----
1006 void cliFunc_capList( char* args )
1009 info_msg("Capabilities List ");
1010 printHex( CapabilitiesNum );
1012 // Iterate through all of the capabilities and display them
1013 for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
1019 // Display/Lookup Capability Name (utilize debug mode of capability)
1020 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1021 capability( 0xFF, 0xFF, 0 );
1025 void cliFunc_capSelect( char* args )
1027 // Parse code from argument
1030 char* arg2Ptr = args;
1032 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
1033 var_uint_t totalArgs = 2; // Always at least two args
1036 // Arguments used for keyboard capability function
1037 var_uint_t argSetCount = 0;
1038 uint8_t *argSet = (uint8_t*)args;
1041 for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1044 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1046 // Stop processing args if no more are found
1047 // Extra arguments are ignored
1048 if ( *arg1Ptr == '\0' )
1051 // For the first argument, choose the capability
1052 if ( c == 0 ) switch ( arg1Ptr[0] )
1054 // Keyboard Capability
1056 // Determine capability index
1057 cap = numToInt( &arg1Ptr[1] );
1059 // Lookup the number of args
1060 totalArgs += CapabilitiesList[ cap ].argCount;
1064 // Because allocating memory isn't doable, and the argument count is arbitrary
1065 // The argument pointer is repurposed as the argument list (much smaller anyways)
1066 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1068 // Once all the arguments are prepared, call the keyboard capability function
1069 if ( argSetCount == totalArgs )
1071 // Indicate that the capability was called
1076 printHex( argSet[0] );
1078 printHex( argSet[1] );
1080 printHex( argSet[2] );
1083 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1084 capability( argSet[0], argSet[1], &argSet[2] );
1089 void cliFunc_keyHold( char* args )
1091 // Parse codes from arguments
1094 char* arg2Ptr = args;
1100 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1102 // Stop processing args if no more are found
1103 if ( *arg1Ptr == '\0' )
1106 // Ignore non-Scancode numbers
1107 switch ( arg1Ptr[0] )
1111 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1117 void cliFunc_keyPress( char* args )
1119 // Parse codes from arguments
1122 char* arg2Ptr = args;
1128 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1130 // Stop processing args if no more are found
1131 if ( *arg1Ptr == '\0' )
1134 // Ignore non-Scancode numbers
1135 switch ( arg1Ptr[0] )
1139 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1145 void cliFunc_keyRelease( char* args )
1147 // Parse codes from arguments
1150 char* arg2Ptr = args;
1156 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1158 // Stop processing args if no more are found
1159 if ( *arg1Ptr == '\0' )
1162 // Ignore non-Scancode numbers
1163 switch ( arg1Ptr[0] )
1167 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
1173 void cliFunc_layerList( char* args )
1176 info_msg("Layer List");
1178 // Iterate through all of the layers and display them
1179 for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1185 // Display layer name
1186 dPrint( (char*)LayerIndex[ layer ].name );
1190 print(" \033[1m(default)\033[0m");
1193 print( NL "\t\t Layer State: " );
1194 printHex( LayerState[ layer ] );
1196 // First -> Last Indices
1197 print(" First -> Last Indices: ");
1198 printHex( LayerIndex[ layer ].first );
1200 printHex( LayerIndex[ layer ].last );
1204 void cliFunc_layerState( char* args )
1206 // Parse codes from arguments
1209 char* arg2Ptr = args;
1214 // Process first two args
1215 for ( uint8_t c = 0; c < 2; c++ )
1218 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1220 // Stop processing args if no more are found
1221 if ( *arg1Ptr == '\0' )
1226 // First argument (e.g. L1)
1228 if ( arg1Ptr[0] != 'L' )
1231 arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1233 // Second argument (e.g. 4)
1235 arg2 = (uint8_t)numToInt( arg1Ptr );
1237 // Display operation (to indicate that it worked)
1239 info_msg("Setting Layer L");
1244 // Set the layer state
1245 LayerState[ arg1 ] = arg2;
1251 void cliFunc_macroDebug( char* args )
1253 // Toggle macro debug mode
1254 macroDebugMode = macroDebugMode ? 0 : 1;
1257 info_msg("Macro Debug Mode: ");
1258 printInt8( macroDebugMode );
1261 void cliFunc_macroList( char* args )
1263 // Show pending key events
1265 info_msg("Pending Key Events: ");
1266 printInt16( (uint16_t)macroTriggerListBufferSize );
1268 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1270 printHex( macroTriggerListBuffer[ key ].scanCode );
1274 // Show pending trigger macros
1276 info_msg("Pending Trigger Macros: ");
1277 printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1279 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1281 printHex( macroTriggerMacroPendingList[ macro ] );
1285 // Show pending result macros
1287 info_msg("Pending Result Macros: ");
1288 printInt16( (uint16_t)macroResultMacroPendingListSize );
1290 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1292 printHex( macroResultMacroPendingList[ macro ] );
1296 // Show available trigger macro indices
1298 info_msg("Trigger Macros Range: T0 -> T");
1299 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1301 // Show available result macro indices
1303 info_msg("Result Macros Range: R0 -> R");
1304 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1306 // Show Trigger to Result Macro Links
1308 info_msg("Trigger : Result Macro Pairs");
1309 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1313 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1315 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1319 void cliFunc_macroProc( char* args )
1321 // Toggle macro pause mode
1322 macroPauseMode = macroPauseMode ? 0 : 1;
1325 info_msg("Macro Processing Mode: ");
1326 printInt8( macroPauseMode );
1329 void macroDebugShowTrigger( var_uint_t index )
1331 // Only proceed if the macro exists
1332 if ( index >= TriggerMacroNum )
1335 // Trigger Macro Show
1336 const TriggerMacro *macro = &TriggerMacroList[ index ];
1337 TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
1340 info_msg("Trigger Macro Index: ");
1341 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1344 // Read the comboLength for combo in the sequence (sequence of combos)
1346 uint8_t comboLength = macro->guide[ pos ];
1348 // Iterate through and interpret the guide
1349 while ( comboLength != 0 )
1351 // Initial position of the combo
1352 var_uint_t comboPos = ++pos;
1354 // Iterate through the combo
1355 while ( pos < comboLength * TriggerGuideSize + comboPos )
1357 // Assign TriggerGuide element (key type, state and scancode)
1358 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
1360 // Display guide information about trigger key
1361 printHex( guide->scanCode );
1363 printHex( guide->type );
1365 printHex( guide->state );
1367 // Increment position
1368 pos += TriggerGuideSize;
1370 // Only show combo separator if there are combos left in the sequence element
1371 if ( pos < comboLength * TriggerGuideSize + comboPos )
1375 // Read the next comboLength
1376 comboLength = macro->guide[ pos ];
1378 // Only show sequence separator if there is another combo to process
1379 if ( comboLength != 0 )
1383 // Display current position
1384 print( NL "Position: " );
1385 printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1387 // Display result macro index
1388 print( NL "Result Macro Index: " );
1389 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1391 // Display trigger macro state
1392 print( NL "Trigger Macro State: " );
1393 switch ( record->state )
1395 case TriggerMacro_Press: print("Press"); break;
1396 case TriggerMacro_Release: print("Release"); break;
1397 case TriggerMacro_Waiting: print("Waiting"); break;
1401 void macroDebugShowResult( var_uint_t index )
1403 // Only proceed if the macro exists
1404 if ( index >= ResultMacroNum )
1407 // Trigger Macro Show
1408 const ResultMacro *macro = &ResultMacroList[ index ];
1409 ResultMacroRecord *record = &ResultMacroRecordList[ index ];
1412 info_msg("Result Macro Index: ");
1413 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1416 // Read the comboLength for combo in the sequence (sequence of combos)
1418 uint8_t comboLength = macro->guide[ pos++ ];
1420 // Iterate through and interpret the guide
1421 while ( comboLength != 0 )
1423 // Function Counter, used to keep track of the combos processed
1424 var_uint_t funcCount = 0;
1426 // Iterate through the combo
1427 while ( funcCount < comboLength )
1429 // Assign TriggerGuide element (key type, state and scancode)
1430 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
1432 // Display Function Index
1433 printHex( guide->index );
1436 // Display Function Ptr Address
1437 printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1440 // Display/Lookup Capability Name (utilize debug mode of capability)
1441 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1442 capability( 0xFF, 0xFF, 0 );
1444 // Display Argument(s)
1446 for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1448 // Arguments are only 8 bit values
1449 printHex( (&guide->args)[ arg ] );
1451 // Only show arg separator if there are args left
1452 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1457 // Increment position
1458 pos += ResultGuideSize( guide );
1460 // Increment function count
1463 // Only show combo separator if there are combos left in the sequence element
1464 if ( funcCount < comboLength )
1468 // Read the next comboLength
1469 comboLength = macro->guide[ pos++ ];
1471 // Only show sequence separator if there is another combo to process
1472 if ( comboLength != 0 )
1476 // Display current position
1477 print( NL "Position: " );
1478 printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1480 // Display final trigger state/type
1481 print( NL "Final Trigger State (State/Type): " );
1482 printHex( record->state );
1484 printHex( record->stateType );
1487 void cliFunc_macroShow( char* args )
1489 // Parse codes from arguments
1492 char* arg2Ptr = args;
1498 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1500 // Stop processing args if no more are found
1501 if ( *arg1Ptr == '\0' )
1504 // Ignore invalid codes
1505 switch ( arg1Ptr[0] )
1507 // Indexed Trigger Macro
1509 macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1511 // Indexed Result Macro
1513 macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1519 void cliFunc_macroStep( char* args )
1521 // Parse number from argument
1522 // NOTE: Only first argument is used
1525 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1527 // Default to 1, if no argument given
1528 var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1533 // Set the macro step counter, negative int's are cast to uint
1534 macroStepCounter = count;