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 const char macroCLIDictName[] = "Macro Module Commands";
85 const CLIDictItem macroCLIDict[] = {
86 { "capList", "Prints an indexed list of all non USB keycode capabilities.", cliFunc_capList },
87 { "capSelect", "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B", cliFunc_capSelect },
88 { "keyHold", "Send key-hold events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyHold },
89 { "keyPress", "Send key-press events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyPress },
90 { "keyRelease", "Send key-release event to macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A", cliFunc_keyRelease },
91 { "layerList", "List available layers.", cliFunc_layerList },
92 { "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", cliFunc_layerState },
93 { "macroDebug", "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes.", cliFunc_macroDebug },
94 { "macroList", "List the defined trigger and result macros.", cliFunc_macroList },
95 { "macroProc", "Pause/Resume macro processing.", cliFunc_macroProc },
96 { "macroShow", "Show the macro corresponding to the given index." NL "\t\t\033[35mT16\033[0m Indexed Trigger Macro 0x10, \033[35mR12\033[0m Indexed Result Macro 0x0C", cliFunc_macroShow },
97 { "macroStep", "Do N macro processing steps. Defaults to 1.", cliFunc_macroStep },
98 { 0, 0, 0 } // Null entry for dictionary end
102 // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
103 uint8_t macroDebugMode = 0;
105 // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
106 uint8_t macroPauseMode = 0;
108 // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
109 uint16_t macroStepCounter = 0;
112 // Key Trigger List Buffer
113 TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
114 uint8_t macroTriggerListBufferSize = 0;
116 // Pending Trigger Macro Index List
117 // * Any trigger macros that need processing from a previous macro processing loop
118 // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
119 // Possibly could be calculated by the KLL compiler
120 // XXX It may be possible to calculate the worst case using the KLL compiler
121 uint16_t macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
122 uint16_t macroTriggerMacroPendingListSize = 0;
125 // * When modifying layer state and the state is non-0x0, the stack must be adjusted
126 uint16_t macroLayerIndexStack[ LayerNum + 1 ] = { 0 };
127 uint16_t macroLayerIndexStackSize = 0;
129 // Pending Result Macro Index List
130 // * Any result macro that needs processing from a previous macro processing loop
131 uint16_t macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
132 uint16_t macroResultMacroPendingListSize = 0;
136 // ----- Capabilities -----
138 // Sets the given layer with the specified layerState
139 void Macro_layerState( uint8_t state, uint8_t stateType, uint16_t layer, uint8_t layerState )
141 // Is layer in the LayerIndexStack?
142 uint8_t inLayerIndexStack = 0;
143 uint16_t stackItem = 0;
144 while ( stackItem < macroLayerIndexStackSize )
146 // Flag if layer is already in the LayerIndexStack
147 if ( macroLayerIndexStack[ stackItem ] == layer )
149 inLayerIndexStack = 1;
153 // Increment to next item
157 // Toggle Layer State Byte
158 if ( LayerIndex[ layer ].state & layerState )
161 LayerIndex[ layer ].state &= ~layerState;
166 LayerIndex[ layer ].state |= layerState;
169 // If the layer was not in the LayerIndexStack add it
170 if ( !inLayerIndexStack )
172 macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
175 // If the layer is in the LayerIndexStack and the state is 0x00, remove
176 if ( LayerIndex[ layer ].state == 0x00 && inLayerIndexStack )
178 // Remove the layer from the LayerIndexStack
179 // Using the already positioned stackItem variable from the loop above
180 while ( stackItem < macroLayerIndexStackSize )
182 macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
186 // Reduce LayerIndexStack size
187 macroLayerIndexStackSize--;
191 // Modifies the specified Layer control byte
192 // Argument #1: Layer Index -> uint16_t
193 // Argument #2: Layer State -> uint8_t
194 void Macro_layerState_capability( uint8_t state, uint8_t stateType, uint8_t *args )
196 // Display capability name
197 if ( stateType == 0xFF && state == 0xFF )
199 print("Macro_layerState(layerIndex,layerState)");
203 // Only use capability on press or release
205 // XXX This may cause issues, might be better to implement state table here to decide -HaaTa
206 if ( stateType == 0x00 && state == 0x02 ) // Hold condition
209 // Get layer index from arguments
210 // Cast pointer to uint8_t to uint16_t then access that memory location
211 uint16_t layer = *(uint16_t*)(&args[0]);
213 // Get layer toggle byte
214 uint8_t layerState = args[ sizeof(uint16_t) ];
216 Macro_layerState( state, stateType, layer, layerState );
220 // Latches given layer
221 // Argument #1: Layer Index -> uint16_t
222 void Macro_layerLatch_capability( uint8_t state, uint8_t stateType, uint8_t *args )
224 // Display capability name
225 if ( stateType == 0xFF && state == 0xFF )
227 print("Macro_layerLatch(layerIndex)");
231 // Only use capability on press
233 // XXX To make sense, this code be on press or release. Or it could even be a sticky shift (why? dunno) -HaaTa
234 if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
237 // Get layer index from arguments
238 // Cast pointer to uint8_t to uint16_t then access that memory location
239 uint16_t layer = *(uint16_t*)(&args[0]);
241 Macro_layerState( state, stateType, layer, 0x02 );
246 // Argument #1: Layer Index -> uint16_t
247 void Macro_layerLock_capability( uint8_t state, uint8_t stateType, uint8_t *args )
249 // Display capability name
250 if ( stateType == 0xFF && state == 0xFF )
252 print("Macro_layerLock(layerIndex)");
256 // Only use capability on press
258 // XXX Could also be on release, but that's sorta dumb -HaaTa
259 if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
262 // Get layer index from arguments
263 // Cast pointer to uint8_t to uint16_t then access that memory location
264 uint16_t layer = *(uint16_t*)(&args[0]);
266 Macro_layerState( state, stateType, layer, 0x04 );
270 // Shifts given layer
271 // Argument #1: Layer Index -> uint16_t
272 void Macro_layerShift_capability( uint8_t state, uint8_t stateType, uint8_t *args )
274 // Display capability name
275 if ( stateType == 0xFF && state == 0xFF )
277 print("Macro_layerShift(layerIndex)");
281 // Only use capability on press or release
283 if ( stateType == 0x00 && ( state == 0x00 || state == 0x02 ) ) // Only pass press or release conditions
286 // Get layer index from arguments
287 // Cast pointer to uint8_t to uint16_t then access that memory location
288 uint16_t layer = *(uint16_t*)(&args[0]);
290 Macro_layerState( state, stateType, layer, 0x01 );
295 // ----- Functions -----
297 // Looks up the trigger list for the given scan code (from the active layer)
298 // NOTE: Calling function must handle the NULL pointer case
299 nat_ptr_t *Macro_layerLookup( uint8_t scanCode )
301 // If no trigger macro is defined at the given layer, fallthrough to the next layer
302 for ( uint16_t layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
305 Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
307 // Check if latch has been pressed for this layer
308 // XXX Regardless of whether a key is found, the latch is removed on first lookup
309 uint8_t latch = layer->state & 0x02;
312 layer->state &= ~0x02;
315 // Only use layer, if state is valid
316 // XOR each of the state bits
317 // If only two are enabled, do not use this state
318 if ( (layer->state & 0x01) ^ (latch>>1) ^ ((layer->state & 0x04)>>2) )
321 nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
323 // Determine if layer has key defined
324 if ( map != 0 && *map[ scanCode ] != 0 )
325 return map[ scanCode ];
329 // Do lookup on default layer
330 nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
332 // Determine if layer has key defined
333 if ( map == 0 && *map[ scanCode ] == 0 )
335 erro_msg("Scan Code has no defined Trigger Macro: ");
336 printHex( scanCode );
340 // Return lookup result
341 return map[ scanCode ];
345 // Update the scancode key state
351 // * 0x04 - Unpressed (this is currently ignored)
352 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
354 // Only add to macro trigger list if one of three states
357 case 0x01: // Pressed
359 case 0x03: // Released
360 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
361 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
362 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
363 macroTriggerListBufferSize++;
369 // Update the scancode analog state
373 // * 0x02-0xFF - Analog value (low to high)
374 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
376 // Only add to macro trigger list if non-off
379 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
380 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
381 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
382 macroTriggerListBufferSize++;
391 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
393 // Only add to macro trigger list if non-off
396 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
397 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
398 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
399 macroTriggerListBufferSize++;
404 // Append result macro to pending list, checking for duplicates
405 // Do nothing if duplicate
406 inline void Macro_appendResultMacroToPendingList( TriggerMacro *triggerMacro )
408 // Lookup result macro index
409 var_uint_t resultMacroIndex = triggerMacro->result;
411 // Iterate through result macro pending list, making sure this macro hasn't been added yet
412 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
414 // If duplicate found, do nothing
415 if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
419 // No duplicates found, add to pending list
420 macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
422 // Lookup scanCode of the last key in the last combo
424 for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
426 pos += TriggerGuideSize * comboLength + 1;
427 comboLength = triggerMacro->guide[ pos ];
430 uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
432 // Lookup scanCode in buffer list for the current state and stateType
433 for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
435 if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
437 ResultMacroList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
438 ResultMacroList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
442 // Reset the macro position
443 ResultMacroList[ resultMacroIndex ].pos = 0;
447 // Determine if long ResultMacro (more than 1 seqence element)
448 inline uint8_t Macro_isLongResultMacro( ResultMacro *macro )
450 // Check the second sequence combo length
451 // If non-zero return non-zero (long sequence)
452 // 0 otherwise (short sequence)
453 var_uint_t position = 1;
454 for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
455 position += ResultGuideSize( (ResultGuide*)¯o->guide[ position ] );
456 return macro->guide[ position ];
460 // Determine if long TriggerMacro (more than 1 sequence element)
461 inline uint8_t Macro_isLongTriggerMacro( TriggerMacro *macro )
463 // Check the second sequence combo length
464 // If non-zero return non-zero (long sequence)
465 // 0 otherwise (short sequence)
466 return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
470 // Votes on the given key vs. guide, short macros
471 inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
473 // Depending on key type
474 switch ( guide->type )
478 // For short TriggerMacros completely ignore incorrect keys
479 if ( guide->scanCode == key->scanCode )
481 switch ( key->state )
483 // Correct key, pressed, possible passing
485 return TriggerMacroVote_Pass;
487 // Correct key, held, possible passing or release
489 return TriggerMacroVote_PassRelease;
491 // Correct key, released, possible release
493 return TriggerMacroVote_Release;
497 return TriggerMacroVote_DoNothing;
501 erro_print("LED State Type - Not implemented...");
506 erro_print("Analog State Type - Not implemented...");
509 // Invalid State Type
511 erro_print("Invalid State Type. This is a bug.");
515 // XXX Shouldn't reach here
516 return TriggerMacroVote_Invalid;
520 // Votes on the given key vs. guide, long macros
521 // A long macro is defined as a guide with more than 1 combo
522 inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
524 // Depending on key type
525 switch ( guide->type )
529 // Depending on the state of the buffered key, make voting decision
531 if ( guide->scanCode != key->scanCode )
533 switch ( key->state )
535 // Wrong key, pressed, fail
537 return TriggerMacroVote_Fail;
539 // Wrong key, held, do not pass (no effect)
541 return TriggerMacroVote_DoNothing;
543 // Wrong key released, fail out if pos == 0
545 return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
552 switch ( key->state )
554 // Correct key, pressed, possible passing
556 return TriggerMacroVote_Pass;
558 // Correct key, held, possible passing or release
560 return TriggerMacroVote_PassRelease;
562 // Correct key, released, possible release
564 return TriggerMacroVote_Release;
572 erro_print("LED State Type - Not implemented...");
577 erro_print("Analog State Type - Not implemented...");
580 // Invalid State Type
582 erro_print("Invalid State Type. This is a bug.");
586 // XXX Shouldn't reach here
587 return TriggerMacroVote_Invalid;
591 // Evaluate/Update TriggerMacro
592 inline TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
594 // Lookup TriggerMacro
595 TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
597 // Check if macro has finished and should be incremented sequence elements
598 if ( macro->state == TriggerMacro_Release )
600 macro->state = TriggerMacro_Waiting;
601 macro->pos = macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize + 1;
604 // Current Macro position
605 var_uint_t pos = macro->pos;
607 // Length of the combo being processed
608 uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
610 // If no combo items are left, remove the TriggerMacro from the pending list
611 if ( comboLength == 0 )
613 return TriggerMacroEval_Remove;
616 // Check if this is a long Trigger Macro
617 uint8_t longMacro = Macro_isLongTriggerMacro( macro );
619 // Iterate through the items in the combo, voting the on the key state
620 // If any of the pressed keys do not match, fail the macro
622 // The macro is waiting for input when in the TriggerMacro_Waiting state
623 // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
624 // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
625 // On scan after position increment, change to TriggerMacro_Waiting state
626 // TODO Add support for system LED states (NumLock, CapsLock, etc.)
627 // TODO Add support for analog key states
628 // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
629 // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
630 TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
631 for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
633 // Assign TriggerGuide element (key type, state and scancode)
634 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ comboItem ]);
636 TriggerMacroVote vote = TriggerMacroVote_Invalid;
637 // Iterate through the key buffer, comparing to each key in the combo
638 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
640 // Lookup key information
641 TriggerGuide *keyInfo = ¯oTriggerListBuffer[ key ];
643 // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
644 // Also mask all of the non-passing votes
646 ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
647 : Macro_evalShortTriggerMacroVote( keyInfo, guide );
648 if ( vote >= TriggerMacroVote_Pass )
650 vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
655 // If no pass vote was found after scanning all of the keys
656 // Fail the combo, if this is a short macro (long macros already will have a fail vote)
657 if ( !longMacro && vote < TriggerMacroVote_Pass )
658 vote |= TriggerMacroVote_Fail;
660 // After voting, append to overall vote
664 // If no pass vote was found after scanning the entire combo
665 // And this is the first position in the combo, just remove it (nothing important happened)
666 if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
667 overallVote |= TriggerMacroVote_Fail;
669 // Decide new state of macro after voting
670 // Fail macro, remove from pending list
671 if ( overallVote & TriggerMacroVote_Fail )
673 return TriggerMacroEval_Remove;
675 // Do nothing, incorrect key is being held or released
676 else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
678 // Just doing nothing :)
680 // If passing and in Waiting state, set macro state to Press
681 else if ( overallVote & TriggerMacroVote_Pass
682 && ( macro->state == TriggerMacro_Waiting || macro->state == TriggerMacro_Press ) )
684 macro->state = TriggerMacro_Press;
686 // If in press state, and this is the final combo, send request for ResultMacro
687 // Check to see if the result macro only has a single element
688 // If this result macro has more than 1 key, only send once
689 // TODO Add option to have long macro repeat rate
690 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
692 // Long result macro (more than 1 combo)
693 if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
695 // Only ever trigger result once, on press
696 if ( overallVote == TriggerMacroVote_Pass )
698 return TriggerMacroEval_DoResultAndRemove;
701 // Short result macro
704 // Only trigger result once, on press, if long trigger (more than 1 combo)
705 if ( Macro_isLongTriggerMacro( macro ) )
707 return TriggerMacroEval_DoResultAndRemove;
709 // Otherwise, trigger result continuously
712 return TriggerMacroEval_DoResult;
717 // If ready for transition and in Press state, set to Waiting and increment combo position
718 // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
719 else if ( overallVote & TriggerMacroVote_Release && macro->state == TriggerMacro_Press )
721 macro->state = TriggerMacro_Release;
723 // If this is the last combo in the sequence, remove from the pending list
724 if ( macro->guide[ macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize + 1 ] == 0 )
725 return TriggerMacroEval_Remove;
727 // Otherwise, just remove the macro on key release
728 // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
729 else if ( overallVote & TriggerMacroVote_Release )
731 return TriggerMacroEval_DoResultAndRemove;
734 // If this is a short macro, just remove it
735 // The state can be rebuilt on the next iteration
737 return TriggerMacroEval_Remove;
739 return TriggerMacroEval_DoNothing;
743 // Evaluate/Update ResultMacro
744 inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
746 // Lookup ResultMacro
747 ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
749 // Current Macro position
750 var_uint_t pos = macro->pos;
752 // Length of combo being processed
753 uint8_t comboLength = macro->guide[ pos ];
755 // Function Counter, used to keep track of the combo items processed
756 var_uint_t funcCount = 0;
758 // Combo Item Position within the guide
759 var_uint_t comboItem = pos + 1;
761 // Iterate through the Result Combo
762 while ( funcCount < comboLength )
764 // Assign TriggerGuide element (key type, state and scancode)
765 ResultGuide *guide = (ResultGuide*)(¯o->guide[ comboItem ]);
767 // Do lookup on capability function
768 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
771 capability( macro->state, macro->stateType, &guide->args );
773 // Increment counters
775 comboItem += ResultGuideSize( (ResultGuide*)(¯o->guide[ comboItem ]) );
778 // Move to next item in the sequence
779 macro->pos = comboItem;
781 // If the ResultMacro is finished, remove
782 if ( macro->guide[ comboItem ] == 0 )
784 return ResultMacroEval_Remove;
787 // Otherwise leave the macro in the list
788 return ResultMacroEval_DoNothing;
792 // Update pending trigger list
793 inline void Macro_updateTriggerMacroPendingList()
795 // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
796 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
799 // TODO Analog Switches
800 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
801 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
804 // Lookup Trigger List
805 nat_ptr_t *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode );
807 // Number of Triggers in list
808 nat_ptr_t triggerListSize = triggerList[0];
810 // Iterate over triggerList to see if any TriggerMacros need to be added
811 // First item is the number of items in the TriggerList
812 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
814 // Lookup trigger macro index
815 var_uint_t triggerMacroIndex = triggerList[ macro ];
817 // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
818 // triggerList needs to be added
819 var_uint_t pending = 0;
820 for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
822 // Stop scanning if the trigger macro index is found in the pending list
823 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
827 // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
828 // Add it to the list
829 if ( pending == macroTriggerMacroPendingListSize )
831 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
833 // Reset macro position
834 TriggerMacroList[ triggerMacroIndex ].pos = 0;
835 TriggerMacroList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
842 // Macro Procesing Loop
843 // Called once per USB buffer send
844 inline void Macro_process()
846 // Only do one round of macro processing between Output Module timer sends
847 if ( USBKeys_Sent != 0 )
850 // If the pause flag is set, only process if the step counter is non-zero
851 if ( macroPauseMode )
853 if ( macroStepCounter == 0 )
856 // Proceed, decrementing the step counter
858 dbug_print("Macro Step");
861 // Update pending trigger list, before processing TriggerMacros
862 Macro_updateTriggerMacroPendingList();
864 // Tail pointer for macroTriggerMacroPendingList
865 // Macros must be explicitly re-added
866 var_uint_t macroTriggerMacroPendingListTail = 0;
868 // Iterate through the pending TriggerMacros, processing each of them
869 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
871 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
873 // Trigger Result Macro (purposely falling through)
874 case TriggerMacroEval_DoResult:
875 // Append ResultMacro to PendingList
876 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
879 macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
882 // Trigger Result Macro and Remove (purposely falling through)
883 case TriggerMacroEval_DoResultAndRemove:
884 // Append ResultMacro to PendingList
885 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
887 // Remove Macro from Pending List, nothing to do, removing by default
888 case TriggerMacroEval_Remove:
893 // Update the macroTriggerMacroPendingListSize with the tail pointer
894 macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
897 // Tail pointer for macroResultMacroPendingList
898 // Macros must be explicitly re-added
899 var_uint_t macroResultMacroPendingListTail = 0;
901 // Iterate through the pending ResultMacros, processing each of them
902 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
904 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
906 // Re-add macros to pending list
907 case ResultMacroEval_DoNothing:
909 macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
912 // Remove Macro from Pending List, nothing to do, removing by default
913 case ResultMacroEval_Remove:
918 // Update the macroResultMacroPendingListSize with the tail pointer
919 macroResultMacroPendingListSize = macroResultMacroPendingListTail;
921 // Signal buffer that we've used it
922 Scan_finishedWithMacro( macroTriggerListBufferSize );
924 // Reset TriggerList buffer
925 macroTriggerListBufferSize = 0;
927 // If Macro debug mode is set, clear the USB Buffer
928 if ( macroDebugMode )
930 USBKeys_Modifiers = 0;
936 inline void Macro_setup()
938 // Register Macro CLI dictionary
939 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
941 // Disable Macro debug mode
944 // Disable Macro pause flag
947 // Set Macro step counter to zero
948 macroStepCounter = 0;
950 // Make sure macro trigger buffer is empty
951 macroTriggerListBufferSize = 0;
953 // Initialize TriggerMacro states
954 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
956 TriggerMacroList[ macro ].pos = 0;
957 TriggerMacroList[ macro ].state = TriggerMacro_Waiting;
960 // Initialize ResultMacro states
961 for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
963 ResultMacroList[ macro ].pos = 0;
964 ResultMacroList[ macro ].state = 0;
965 ResultMacroList[ macro ].stateType = 0;
970 // ----- CLI Command Functions -----
972 void cliFunc_capList( char* args )
975 info_msg("Capabilities List");
976 printHex( CapabilitiesNum );
978 // Iterate through all of the capabilities and display them
979 for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
985 // Display/Lookup Capability Name (utilize debug mode of capability)
986 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
987 capability( 0xFF, 0xFF, 0 );
991 void cliFunc_capSelect( char* args )
993 // Parse code from argument
996 char* arg2Ptr = args;
998 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
999 var_uint_t totalArgs = 2; // Always at least two args
1002 // Arguments used for keyboard capability function
1003 var_uint_t argSetCount = 0;
1004 uint8_t *argSet = (uint8_t*)args;
1007 for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1010 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1012 // Stop processing args if no more are found
1013 // Extra arguments are ignored
1014 if ( *arg1Ptr == '\0' )
1017 // For the first argument, choose the capability
1018 if ( c == 0 ) switch ( arg1Ptr[0] )
1020 // Keyboard Capability
1022 // Determine capability index
1023 cap = numToInt( &arg1Ptr[1] );
1025 // Lookup the number of args
1026 totalArgs += CapabilitiesList[ cap ].argCount;
1030 // Because allocating memory isn't doable, and the argument count is arbitrary
1031 // The argument pointer is repurposed as the argument list (much smaller anyways)
1032 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1034 // Once all the arguments are prepared, call the keyboard capability function
1035 if ( argSetCount == totalArgs )
1037 // Indicate that the capability was called
1042 printHex( argSet[0] );
1044 printHex( argSet[1] );
1046 printHex( argSet[2] );
1049 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1050 capability( argSet[0], argSet[1], &argSet[2] );
1055 void cliFunc_keyHold( char* args )
1057 // Parse codes from arguments
1060 char* arg2Ptr = args;
1066 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1068 // Stop processing args if no more are found
1069 if ( *arg1Ptr == '\0' )
1072 // Ignore non-Scancode numbers
1073 switch ( arg1Ptr[0] )
1077 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1083 void cliFunc_keyPress( char* args )
1085 // Parse codes from arguments
1088 char* arg2Ptr = args;
1094 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1096 // Stop processing args if no more are found
1097 if ( *arg1Ptr == '\0' )
1100 // Ignore non-Scancode numbers
1101 switch ( arg1Ptr[0] )
1105 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1111 void cliFunc_keyRelease( char* args )
1113 // Parse codes from arguments
1116 char* arg2Ptr = args;
1122 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1124 // Stop processing args if no more are found
1125 if ( *arg1Ptr == '\0' )
1128 // Ignore non-Scancode numbers
1129 switch ( arg1Ptr[0] )
1133 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
1139 void cliFunc_layerList( char* args )
1142 info_msg("Layer List");
1144 // Iterate through all of the layers and display them
1145 for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1151 // Display layer name
1152 dPrint( (char*)LayerIndex[ layer ].name );
1156 print(" \033[1m(default)\033[0m");
1159 print( NL "\t\t Layer State: " );
1160 printHex( LayerIndex[ layer ].state );
1163 print(" Max Index: ");
1164 printHex( LayerIndex[ layer ].max );
1168 void cliFunc_layerState( char* args )
1170 // Parse codes from arguments
1173 char* arg2Ptr = args;
1178 // Process first two args
1179 for ( uint8_t c = 0; c < 2; c++ )
1182 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1184 // Stop processing args if no more are found
1185 if ( *arg1Ptr == '\0' )
1190 // First argument (e.g. L1)
1192 if ( arg1Ptr[0] != 'L' )
1195 arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1197 // Second argument (e.g. 4)
1199 arg2 = (uint8_t)numToInt( arg1Ptr );
1201 // Display operation (to indicate that it worked)
1203 info_msg("Setting Layer L");
1208 // Set the layer state
1209 LayerIndex[ arg1 ].state = arg2;
1215 void cliFunc_macroDebug( char* args )
1217 // Toggle macro debug mode
1218 macroDebugMode = macroDebugMode ? 0 : 1;
1221 info_msg("Macro Debug Mode: ");
1222 printInt8( macroDebugMode );
1225 void cliFunc_macroList( char* args )
1227 // Show pending key events
1229 info_msg("Pending Key Events: ");
1230 printInt16( (uint16_t)macroTriggerListBufferSize );
1232 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1234 printHex( macroTriggerListBuffer[ key ].scanCode );
1238 // Show pending trigger macros
1240 info_msg("Pending Trigger Macros: ");
1241 printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1243 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1245 printHex( macroTriggerMacroPendingList[ macro ] );
1249 // Show pending result macros
1251 info_msg("Pending Result Macros: ");
1252 printInt16( (uint16_t)macroResultMacroPendingListSize );
1254 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1256 printHex( macroResultMacroPendingList[ macro ] );
1260 // Show available trigger macro indices
1262 info_msg("Trigger Macros Range: T0 -> T");
1263 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1265 // Show available result macro indices
1267 info_msg("Result Macros Range: R0 -> R");
1268 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1270 // Show Trigger to Result Macro Links
1272 info_msg("Trigger : Result Macro Pairs");
1273 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1277 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1279 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1283 void cliFunc_macroProc( char* args )
1285 // Toggle macro pause mode
1286 macroPauseMode = macroPauseMode ? 0 : 1;
1289 info_msg("Macro Processing Mode: ");
1290 printInt8( macroPauseMode );
1293 void macroDebugShowTrigger( var_uint_t index )
1295 // Only proceed if the macro exists
1296 if ( index >= TriggerMacroNum )
1299 // Trigger Macro Show
1300 TriggerMacro *macro = &TriggerMacroList[ index ];
1303 info_msg("Trigger Macro Index: ");
1304 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1307 // Read the comboLength for combo in the sequence (sequence of combos)
1309 uint8_t comboLength = macro->guide[ pos ];
1311 // Iterate through and interpret the guide
1312 while ( comboLength != 0 )
1314 // Initial position of the combo
1315 var_uint_t comboPos = ++pos;
1317 // Iterate through the combo
1318 while ( pos < comboLength * TriggerGuideSize + comboPos )
1320 // Assign TriggerGuide element (key type, state and scancode)
1321 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
1323 // Display guide information about trigger key
1324 printHex( guide->scanCode );
1326 printHex( guide->type );
1328 printHex( guide->state );
1330 // Increment position
1331 pos += TriggerGuideSize;
1333 // Only show combo separator if there are combos left in the sequence element
1334 if ( pos < comboLength * TriggerGuideSize + comboPos )
1338 // Read the next comboLength
1339 comboLength = macro->guide[ pos ];
1341 // Only show sequence separator if there is another combo to process
1342 if ( comboLength != 0 )
1346 // Display current position
1347 print( NL "Position: " );
1348 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1350 // Display result macro index
1351 print( NL "Result Macro Index: " );
1352 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1354 // Display trigger macro state
1355 print( NL "Trigger Macro State: " );
1356 switch ( macro->state )
1358 case TriggerMacro_Press: print("Press"); break;
1359 case TriggerMacro_Release: print("Release"); break;
1360 case TriggerMacro_Waiting: print("Waiting"); break;
1364 void macroDebugShowResult( var_uint_t index )
1366 // Only proceed if the macro exists
1367 if ( index >= ResultMacroNum )
1370 // Trigger Macro Show
1371 ResultMacro *macro = &ResultMacroList[ index ];
1374 info_msg("Result 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 // Function Counter, used to keep track of the combos processed
1386 var_uint_t funcCount = 0;
1388 // Iterate through the combo
1389 while ( funcCount < comboLength )
1391 // Assign TriggerGuide element (key type, state and scancode)
1392 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
1394 // Display Function Index
1395 printHex( guide->index );
1398 // Display Function Ptr Address
1399 printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1402 // Display/Lookup Capability Name (utilize debug mode of capability)
1403 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1404 capability( 0xFF, 0xFF, 0 );
1406 // Display Argument(s)
1408 for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1410 // Arguments are only 8 bit values
1411 printHex( (&guide->args)[ arg ] );
1413 // Only show arg separator if there are args left
1414 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1419 // Increment position
1420 pos += ResultGuideSize( guide );
1422 // Increment function count
1425 // Only show combo separator if there are combos left in the sequence element
1426 if ( funcCount < comboLength )
1430 // Read the next comboLength
1431 comboLength = macro->guide[ pos++ ];
1433 // Only show sequence separator if there is another combo to process
1434 if ( comboLength != 0 )
1438 // Display current position
1439 print( NL "Position: " );
1440 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1442 // Display final trigger state/type
1443 print( NL "Final Trigger State (State/Type): " );
1444 printHex( macro->state );
1446 printHex( macro->stateType );
1449 void cliFunc_macroShow( char* args )
1451 // Parse codes from arguments
1454 char* arg2Ptr = args;
1460 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1462 // Stop processing args if no more are found
1463 if ( *arg1Ptr == '\0' )
1466 // Ignore invalid codes
1467 switch ( arg1Ptr[0] )
1469 // Indexed Trigger Macro
1471 macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1473 // Indexed Result Macro
1475 macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1481 void cliFunc_macroStep( char* args )
1483 // Parse number from argument
1484 // NOTE: Only first argument is used
1487 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1489 // Default to 1, if no argument given
1490 var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1495 // Set the macro step counter, negative int's are cast to uint
1496 macroStepCounter = count;