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 using a list of TriggerGuides
397 // TODO Handle led state and analog
398 inline void Macro_triggerState( void *triggers, uint8_t num )
400 // Copy each of the TriggerGuides to the TriggerListBuffer
401 for ( uint8_t c = 0; c < num; c++ )
402 macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = ((TriggerGuide*)triggers)[ c ];
406 // Update the scancode key state
412 // * 0x04 - Unpressed (this is currently ignored)
413 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
415 // Only add to macro trigger list if one of three states
418 case 0x01: // Pressed
420 case 0x03: // Released
421 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
422 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
423 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
424 macroTriggerListBufferSize++;
430 // Update the scancode analog state
434 // * 0x02-0xFF - Analog value (low to high)
435 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
437 // Only add to macro trigger list if non-off
440 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
441 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
442 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
443 macroTriggerListBufferSize++;
452 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
454 // Only add to macro trigger list if non-off
457 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
458 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
459 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
460 macroTriggerListBufferSize++;
465 // Append result macro to pending list, checking for duplicates
466 // Do nothing if duplicate
467 inline void Macro_appendResultMacroToPendingList( const TriggerMacro *triggerMacro )
469 // Lookup result macro index
470 var_uint_t resultMacroIndex = triggerMacro->result;
472 // Iterate through result macro pending list, making sure this macro hasn't been added yet
473 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
475 // If duplicate found, do nothing
476 if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
480 // No duplicates found, add to pending list
481 macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
483 // Lookup scanCode of the last key in the last combo
485 for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
487 pos += TriggerGuideSize * comboLength + 1;
488 comboLength = triggerMacro->guide[ pos ];
491 uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
493 // Lookup scanCode in buffer list for the current state and stateType
494 for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
496 if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
498 ResultMacroRecordList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
499 ResultMacroRecordList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
503 // Reset the macro position
504 ResultMacroRecordList[ resultMacroIndex ].pos = 0;
508 // Determine if long ResultMacro (more than 1 seqence element)
509 inline uint8_t Macro_isLongResultMacro( const ResultMacro *macro )
511 // Check the second sequence combo length
512 // If non-zero return non-zero (long sequence)
513 // 0 otherwise (short sequence)
514 var_uint_t position = 1;
515 for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
516 position += ResultGuideSize( (ResultGuide*)¯o->guide[ position ] );
517 return macro->guide[ position ];
521 // Determine if long TriggerMacro (more than 1 sequence element)
522 inline uint8_t Macro_isLongTriggerMacro( const TriggerMacro *macro )
524 // Check the second sequence combo length
525 // If non-zero return non-zero (long sequence)
526 // 0 otherwise (short sequence)
527 return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
531 // Votes on the given key vs. guide, short macros
532 inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
534 // Depending on key type
535 switch ( guide->type )
539 // For short TriggerMacros completely ignore incorrect keys
540 if ( guide->scanCode == key->scanCode )
542 switch ( key->state )
544 // Correct key, pressed, possible passing
546 return TriggerMacroVote_Pass;
548 // Correct key, held, possible passing or release
550 return TriggerMacroVote_PassRelease;
552 // Correct key, released, possible release
554 return TriggerMacroVote_Release;
558 return TriggerMacroVote_DoNothing;
562 erro_print("LED State Type - Not implemented...");
567 erro_print("Analog State Type - Not implemented...");
570 // Invalid State Type
572 erro_print("Invalid State Type. This is a bug.");
576 // XXX Shouldn't reach here
577 return TriggerMacroVote_Invalid;
581 // Votes on the given key vs. guide, long macros
582 // A long macro is defined as a guide with more than 1 combo
583 inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
585 // Depending on key type
586 switch ( guide->type )
590 // Depending on the state of the buffered key, make voting decision
592 if ( guide->scanCode != key->scanCode )
594 switch ( key->state )
596 // Wrong key, pressed, fail
598 return TriggerMacroVote_Fail;
600 // Wrong key, held, do not pass (no effect)
602 return TriggerMacroVote_DoNothing;
604 // Wrong key released, fail out if pos == 0
606 return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
613 switch ( key->state )
615 // Correct key, pressed, possible passing
617 return TriggerMacroVote_Pass;
619 // Correct key, held, possible passing or release
621 return TriggerMacroVote_PassRelease;
623 // Correct key, released, possible release
625 return TriggerMacroVote_Release;
633 erro_print("LED State Type - Not implemented...");
638 erro_print("Analog State Type - Not implemented...");
641 // Invalid State Type
643 erro_print("Invalid State Type. This is a bug.");
647 // XXX Shouldn't reach here
648 return TriggerMacroVote_Invalid;
652 // Evaluate/Update TriggerMacro
653 TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
655 // Lookup TriggerMacro
656 const TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
657 TriggerMacroRecord *record = &TriggerMacroRecordList[ triggerMacroIndex ];
659 // Check if macro has finished and should be incremented sequence elements
660 if ( record->state == TriggerMacro_Release )
662 record->state = TriggerMacro_Waiting;
663 record->pos = record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1;
666 // Current Macro position
667 var_uint_t pos = record->pos;
669 // Length of the combo being processed
670 uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
672 // If no combo items are left, remove the TriggerMacro from the pending list
673 if ( comboLength == 0 )
675 return TriggerMacroEval_Remove;
678 // Check if this is a long Trigger Macro
679 uint8_t longMacro = Macro_isLongTriggerMacro( macro );
681 // Iterate through the items in the combo, voting the on the key state
682 // If any of the pressed keys do not match, fail the macro
684 // The macro is waiting for input when in the TriggerMacro_Waiting state
685 // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
686 // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
687 // On scan after position increment, change to TriggerMacro_Waiting state
688 // TODO Add support for system LED states (NumLock, CapsLock, etc.)
689 // TODO Add support for analog key states
690 // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
691 // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
692 TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
693 for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
695 // Assign TriggerGuide element (key type, state and scancode)
696 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ comboItem ]);
698 TriggerMacroVote vote = TriggerMacroVote_Invalid;
699 // Iterate through the key buffer, comparing to each key in the combo
700 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
702 // Lookup key information
703 TriggerGuide *keyInfo = ¯oTriggerListBuffer[ key ];
705 // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
706 // Also mask all of the non-passing votes
708 ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
709 : Macro_evalShortTriggerMacroVote( keyInfo, guide );
710 if ( vote >= TriggerMacroVote_Pass )
712 vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
717 // If no pass vote was found after scanning all of the keys
718 // Fail the combo, if this is a short macro (long macros already will have a fail vote)
719 if ( !longMacro && vote < TriggerMacroVote_Pass )
720 vote |= TriggerMacroVote_Fail;
722 // After voting, append to overall vote
726 // If no pass vote was found after scanning the entire combo
727 // And this is the first position in the combo, just remove it (nothing important happened)
728 if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
729 overallVote |= TriggerMacroVote_Fail;
731 // Decide new state of macro after voting
732 // Fail macro, remove from pending list
733 if ( overallVote & TriggerMacroVote_Fail )
735 return TriggerMacroEval_Remove;
737 // Do nothing, incorrect key is being held or released
738 else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
740 // Just doing nothing :)
742 // If ready for transition and in Press state, set to Waiting and increment combo position
743 // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
744 else if ( overallVote & TriggerMacroVote_Release && record->state == TriggerMacro_Press )
746 record->state = TriggerMacro_Release;
748 // If this is the last combo in the sequence, remove from the pending list
749 if ( macro->guide[ record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1 ] == 0 )
750 return TriggerMacroEval_DoResultAndRemove;
752 // If passing and in Waiting state, set macro state to Press
753 else if ( overallVote & TriggerMacroVote_Pass
754 && ( record->state == TriggerMacro_Waiting || record->state == TriggerMacro_Press ) )
756 record->state = TriggerMacro_Press;
758 // If in press state, and this is the final combo, send request for ResultMacro
759 // Check to see if the result macro only has a single element
760 // If this result macro has more than 1 key, only send once
761 // TODO Add option to have long macro repeat rate
762 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
764 // Long result macro (more than 1 combo)
765 if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
767 // Only ever trigger result once, on press
768 if ( overallVote == TriggerMacroVote_Pass )
770 return TriggerMacroEval_DoResultAndRemove;
773 // Short result macro
776 // Only trigger result once, on press, if long trigger (more than 1 combo)
777 if ( Macro_isLongTriggerMacro( macro ) )
779 return TriggerMacroEval_DoResultAndRemove;
781 // Otherwise, trigger result continuously
784 return TriggerMacroEval_DoResult;
789 // Otherwise, just remove the macro on key release
790 // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
791 else if ( overallVote & TriggerMacroVote_Release )
793 return TriggerMacroEval_DoResultAndRemove;
796 // If this is a short macro, just remove it
797 // The state can be rebuilt on the next iteration
799 return TriggerMacroEval_Remove;
801 return TriggerMacroEval_DoNothing;
805 // Evaluate/Update ResultMacro
806 inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
808 // Lookup ResultMacro
809 const ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
810 ResultMacroRecord *record = &ResultMacroRecordList[ resultMacroIndex ];
812 // Current Macro position
813 var_uint_t pos = record->pos;
815 // Length of combo being processed
816 uint8_t comboLength = macro->guide[ pos ];
818 // Function Counter, used to keep track of the combo items processed
819 var_uint_t funcCount = 0;
821 // Combo Item Position within the guide
822 var_uint_t comboItem = pos + 1;
824 // Iterate through the Result Combo
825 while ( funcCount < comboLength )
827 // Assign TriggerGuide element (key type, state and scancode)
828 ResultGuide *guide = (ResultGuide*)(¯o->guide[ comboItem ]);
830 // Do lookup on capability function
831 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
834 capability( record->state, record->stateType, &guide->args );
836 // Increment counters
838 comboItem += ResultGuideSize( (ResultGuide*)(¯o->guide[ comboItem ]) );
841 // Move to next item in the sequence
842 record->pos = comboItem;
844 // If the ResultMacro is finished, remove
845 if ( macro->guide[ comboItem ] == 0 )
848 return ResultMacroEval_Remove;
851 // Otherwise leave the macro in the list
852 return ResultMacroEval_DoNothing;
856 // Update pending trigger list
857 inline void Macro_updateTriggerMacroPendingList()
859 // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
860 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
863 // TODO Analog Switches
864 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
865 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
869 // If this is a release case, indicate to layer lookup for possible latch expiry
870 uint8_t latch_expire = macroTriggerListBuffer[ key ].state == 0x03;
872 // Lookup Trigger List
873 nat_ptr_t *triggerList = Macro_layerLookup( ¯oTriggerListBuffer[ key ], latch_expire );
875 // Number of Triggers in list
876 nat_ptr_t triggerListSize = triggerList[0];
878 // Iterate over triggerList to see if any TriggerMacros need to be added
879 // First item is the number of items in the TriggerList
880 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
882 // Lookup trigger macro index
883 var_uint_t triggerMacroIndex = triggerList[ macro ];
885 // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
886 // triggerList needs to be added
887 var_uint_t pending = 0;
888 for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
890 // Stop scanning if the trigger macro index is found in the pending list
891 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
895 // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
896 // Add it to the list
897 if ( pending == macroTriggerMacroPendingListSize )
899 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
901 // Reset macro position
902 TriggerMacroRecordList[ triggerMacroIndex ].pos = 0;
903 TriggerMacroRecordList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
910 // Macro Procesing Loop
911 // Called once per USB buffer send
912 inline void Macro_process()
914 // Only do one round of macro processing between Output Module timer sends
915 if ( USBKeys_Sent != 0 )
918 // If the pause flag is set, only process if the step counter is non-zero
919 if ( macroPauseMode )
921 if ( macroStepCounter == 0 )
924 // Proceed, decrementing the step counter
926 dbug_print("Macro Step");
929 // Update pending trigger list, before processing TriggerMacros
930 Macro_updateTriggerMacroPendingList();
932 // Tail pointer for macroTriggerMacroPendingList
933 // Macros must be explicitly re-added
934 var_uint_t macroTriggerMacroPendingListTail = 0;
936 // Iterate through the pending TriggerMacros, processing each of them
937 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
939 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
941 // Trigger Result Macro (purposely falling through)
942 case TriggerMacroEval_DoResult:
943 // Append ResultMacro to PendingList
944 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
947 macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
950 // Trigger Result Macro and Remove (purposely falling through)
951 case TriggerMacroEval_DoResultAndRemove:
952 // Append ResultMacro to PendingList
953 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
955 // Remove Macro from Pending List, nothing to do, removing by default
956 case TriggerMacroEval_Remove:
961 // Update the macroTriggerMacroPendingListSize with the tail pointer
962 macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
965 // Tail pointer for macroResultMacroPendingList
966 // Macros must be explicitly re-added
967 var_uint_t macroResultMacroPendingListTail = 0;
969 // Iterate through the pending ResultMacros, processing each of them
970 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
972 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
974 // Re-add macros to pending list
975 case ResultMacroEval_DoNothing:
977 macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
980 // Remove Macro from Pending List, nothing to do, removing by default
981 case ResultMacroEval_Remove:
986 // Update the macroResultMacroPendingListSize with the tail pointer
987 macroResultMacroPendingListSize = macroResultMacroPendingListTail;
989 // Signal buffer that we've used it
990 Scan_finishedWithMacro( macroTriggerListBufferSize );
992 // Reset TriggerList buffer
993 macroTriggerListBufferSize = 0;
995 // If Macro debug mode is set, clear the USB Buffer
996 if ( macroDebugMode )
998 USBKeys_Modifiers = 0;
1004 inline void Macro_setup()
1006 // Register Macro CLI dictionary
1007 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
1009 // Disable Macro debug mode
1012 // Disable Macro pause flag
1015 // Set Macro step counter to zero
1016 macroStepCounter = 0;
1018 // Make sure macro trigger buffer is empty
1019 macroTriggerListBufferSize = 0;
1021 // Initialize TriggerMacro states
1022 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1024 TriggerMacroRecordList[ macro ].pos = 0;
1025 TriggerMacroRecordList[ macro ].state = TriggerMacro_Waiting;
1028 // Initialize ResultMacro states
1029 for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
1031 ResultMacroRecordList[ macro ].pos = 0;
1032 ResultMacroRecordList[ macro ].state = 0;
1033 ResultMacroRecordList[ macro ].stateType = 0;
1038 // ----- CLI Command Functions -----
1040 void cliFunc_capList( char* args )
1043 info_msg("Capabilities List ");
1044 printHex( CapabilitiesNum );
1046 // Iterate through all of the capabilities and display them
1047 for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
1053 // Display/Lookup Capability Name (utilize debug mode of capability)
1054 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1055 capability( 0xFF, 0xFF, 0 );
1059 void cliFunc_capSelect( char* args )
1061 // Parse code from argument
1064 char* arg2Ptr = args;
1066 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
1067 var_uint_t totalArgs = 2; // Always at least two args
1070 // Arguments used for keyboard capability function
1071 var_uint_t argSetCount = 0;
1072 uint8_t *argSet = (uint8_t*)args;
1075 for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1078 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1080 // Stop processing args if no more are found
1081 // Extra arguments are ignored
1082 if ( *arg1Ptr == '\0' )
1085 // For the first argument, choose the capability
1086 if ( c == 0 ) switch ( arg1Ptr[0] )
1088 // Keyboard Capability
1090 // Determine capability index
1091 cap = numToInt( &arg1Ptr[1] );
1093 // Lookup the number of args
1094 totalArgs += CapabilitiesList[ cap ].argCount;
1098 // Because allocating memory isn't doable, and the argument count is arbitrary
1099 // The argument pointer is repurposed as the argument list (much smaller anyways)
1100 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1102 // Once all the arguments are prepared, call the keyboard capability function
1103 if ( argSetCount == totalArgs )
1105 // Indicate that the capability was called
1110 printHex( argSet[0] );
1112 printHex( argSet[1] );
1114 printHex( argSet[2] );
1117 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1118 capability( argSet[0], argSet[1], &argSet[2] );
1123 void cliFunc_keyHold( char* args )
1125 // Parse codes from arguments
1128 char* arg2Ptr = args;
1134 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1136 // Stop processing args if no more are found
1137 if ( *arg1Ptr == '\0' )
1140 // Ignore non-Scancode numbers
1141 switch ( arg1Ptr[0] )
1145 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1151 void cliFunc_keyPress( char* args )
1153 // Parse codes from arguments
1156 char* arg2Ptr = args;
1162 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1164 // Stop processing args if no more are found
1165 if ( *arg1Ptr == '\0' )
1168 // Ignore non-Scancode numbers
1169 switch ( arg1Ptr[0] )
1173 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1179 void cliFunc_keyRelease( char* args )
1181 // Parse codes from arguments
1184 char* arg2Ptr = args;
1190 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1192 // Stop processing args if no more are found
1193 if ( *arg1Ptr == '\0' )
1196 // Ignore non-Scancode numbers
1197 switch ( arg1Ptr[0] )
1201 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
1207 void cliFunc_layerList( char* args )
1210 info_msg("Layer List");
1212 // Iterate through all of the layers and display them
1213 for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1219 // Display layer name
1220 dPrint( (char*)LayerIndex[ layer ].name );
1224 print(" \033[1m(default)\033[0m");
1227 print( NL "\t\t Layer State: " );
1228 printHex( LayerState[ layer ] );
1230 // First -> Last Indices
1231 print(" First -> Last Indices: ");
1232 printHex( LayerIndex[ layer ].first );
1234 printHex( LayerIndex[ layer ].last );
1238 void cliFunc_layerState( char* args )
1240 // Parse codes from arguments
1243 char* arg2Ptr = args;
1248 // Process first two args
1249 for ( uint8_t c = 0; c < 2; c++ )
1252 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1254 // Stop processing args if no more are found
1255 if ( *arg1Ptr == '\0' )
1260 // First argument (e.g. L1)
1262 if ( arg1Ptr[0] != 'L' )
1265 arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1267 // Second argument (e.g. 4)
1269 arg2 = (uint8_t)numToInt( arg1Ptr );
1271 // Display operation (to indicate that it worked)
1273 info_msg("Setting Layer L");
1278 // Set the layer state
1279 LayerState[ arg1 ] = arg2;
1285 void cliFunc_macroDebug( char* args )
1287 // Toggle macro debug mode
1288 macroDebugMode = macroDebugMode ? 0 : 1;
1291 info_msg("Macro Debug Mode: ");
1292 printInt8( macroDebugMode );
1295 void cliFunc_macroList( char* args )
1297 // Show pending key events
1299 info_msg("Pending Key Events: ");
1300 printInt16( (uint16_t)macroTriggerListBufferSize );
1302 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1304 printHex( macroTriggerListBuffer[ key ].scanCode );
1308 // Show pending trigger macros
1310 info_msg("Pending Trigger Macros: ");
1311 printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1313 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1315 printHex( macroTriggerMacroPendingList[ macro ] );
1319 // Show pending result macros
1321 info_msg("Pending Result Macros: ");
1322 printInt16( (uint16_t)macroResultMacroPendingListSize );
1324 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1326 printHex( macroResultMacroPendingList[ macro ] );
1330 // Show available trigger macro indices
1332 info_msg("Trigger Macros Range: T0 -> T");
1333 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1335 // Show available result macro indices
1337 info_msg("Result Macros Range: R0 -> R");
1338 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1340 // Show Trigger to Result Macro Links
1342 info_msg("Trigger : Result Macro Pairs");
1343 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1347 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1349 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1353 void cliFunc_macroProc( char* args )
1355 // Toggle macro pause mode
1356 macroPauseMode = macroPauseMode ? 0 : 1;
1359 info_msg("Macro Processing Mode: ");
1360 printInt8( macroPauseMode );
1363 void macroDebugShowTrigger( var_uint_t index )
1365 // Only proceed if the macro exists
1366 if ( index >= TriggerMacroNum )
1369 // Trigger Macro Show
1370 const TriggerMacro *macro = &TriggerMacroList[ index ];
1371 TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
1374 info_msg("Trigger Macro Index: ");
1375 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1378 // Read the comboLength for combo in the sequence (sequence of combos)
1380 uint8_t comboLength = macro->guide[ pos ];
1382 // Iterate through and interpret the guide
1383 while ( comboLength != 0 )
1385 // Initial position of the combo
1386 var_uint_t comboPos = ++pos;
1388 // Iterate through the combo
1389 while ( pos < comboLength * TriggerGuideSize + comboPos )
1391 // Assign TriggerGuide element (key type, state and scancode)
1392 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
1394 // Display guide information about trigger key
1395 printHex( guide->scanCode );
1397 printHex( guide->type );
1399 printHex( guide->state );
1401 // Increment position
1402 pos += TriggerGuideSize;
1404 // Only show combo separator if there are combos left in the sequence element
1405 if ( pos < comboLength * TriggerGuideSize + comboPos )
1409 // Read the next comboLength
1410 comboLength = macro->guide[ pos ];
1412 // Only show sequence separator if there is another combo to process
1413 if ( comboLength != 0 )
1417 // Display current position
1418 print( NL "Position: " );
1419 printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1421 // Display result macro index
1422 print( NL "Result Macro Index: " );
1423 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1425 // Display trigger macro state
1426 print( NL "Trigger Macro State: " );
1427 switch ( record->state )
1429 case TriggerMacro_Press: print("Press"); break;
1430 case TriggerMacro_Release: print("Release"); break;
1431 case TriggerMacro_Waiting: print("Waiting"); break;
1435 void macroDebugShowResult( var_uint_t index )
1437 // Only proceed if the macro exists
1438 if ( index >= ResultMacroNum )
1441 // Trigger Macro Show
1442 const ResultMacro *macro = &ResultMacroList[ index ];
1443 ResultMacroRecord *record = &ResultMacroRecordList[ index ];
1446 info_msg("Result Macro Index: ");
1447 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1450 // Read the comboLength for combo in the sequence (sequence of combos)
1452 uint8_t comboLength = macro->guide[ pos++ ];
1454 // Iterate through and interpret the guide
1455 while ( comboLength != 0 )
1457 // Function Counter, used to keep track of the combos processed
1458 var_uint_t funcCount = 0;
1460 // Iterate through the combo
1461 while ( funcCount < comboLength )
1463 // Assign TriggerGuide element (key type, state and scancode)
1464 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
1466 // Display Function Index
1467 printHex( guide->index );
1470 // Display Function Ptr Address
1471 printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1474 // Display/Lookup Capability Name (utilize debug mode of capability)
1475 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1476 capability( 0xFF, 0xFF, 0 );
1478 // Display Argument(s)
1480 for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1482 // Arguments are only 8 bit values
1483 printHex( (&guide->args)[ arg ] );
1485 // Only show arg separator if there are args left
1486 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1491 // Increment position
1492 pos += ResultGuideSize( guide );
1494 // Increment function count
1497 // Only show combo separator if there are combos left in the sequence element
1498 if ( funcCount < comboLength )
1502 // Read the next comboLength
1503 comboLength = macro->guide[ pos++ ];
1505 // Only show sequence separator if there is another combo to process
1506 if ( comboLength != 0 )
1510 // Display current position
1511 print( NL "Position: " );
1512 printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1514 // Display final trigger state/type
1515 print( NL "Final Trigger State (State/Type): " );
1516 printHex( record->state );
1518 printHex( record->stateType );
1521 void cliFunc_macroShow( char* args )
1523 // Parse codes from arguments
1526 char* arg2Ptr = args;
1532 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1534 // Stop processing args if no more are found
1535 if ( *arg1Ptr == '\0' )
1538 // Ignore invalid codes
1539 switch ( arg1Ptr[0] )
1541 // Indexed Trigger Macro
1543 macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1545 // Indexed Result Macro
1547 macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1553 void cliFunc_macroStep( char* args )
1555 // Parse number from argument
1556 // NOTE: Only first argument is used
1559 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1561 // Default to 1, if no argument given
1562 var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1567 // Set the macro step counter, negative int's are cast to uint
1568 macroStepCounter = count;