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 ( LayerState[ layer ] & layerState )
161 LayerState[ layer ] &= ~layerState;
166 LayerState[ layer ] |= 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 ( LayerState[ layer ] == 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 const 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 = LayerState[ layerIndex ] & 0x02;
312 LayerState[ layerIndex ] &= ~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 ( (LayerState[ layerIndex ] & 0x01) ^ (latch>>1) ^ ((LayerState[ layerIndex ] & 0x04)>>2) )
321 nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
323 // Determine if layer has key defined
324 // Make sure scanCode is between layer first and last scancodes
326 && scanCode <= layer->last
327 && scanCode >= layer->first
328 && *map[ scanCode - layer->first ] != 0 )
330 return map[ scanCode - layer->first ];
335 // Do lookup on default layer
336 nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
338 // Lookup default layer
339 const Layer *layer = &LayerIndex[ macroLayerIndexStack[ 0 ] ];
341 // Make sure scanCode is between layer first and last scancodes
343 && scanCode <= layer->last
344 && scanCode >= layer->first
345 && *map[ scanCode - layer->first ] != 0 )
347 return map[ scanCode - layer->first ];
350 // Otherwise no defined Trigger Macro
351 erro_msg("Scan Code has no defined Trigger Macro: ");
352 printHex( scanCode );
357 // Update the scancode key state
363 // * 0x04 - Unpressed (this is currently ignored)
364 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
366 // Only add to macro trigger list if one of three states
369 case 0x01: // Pressed
371 case 0x03: // Released
372 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
373 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
374 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x00; // Normal key
375 macroTriggerListBufferSize++;
381 // Update the scancode analog state
385 // * 0x02-0xFF - Analog value (low to high)
386 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
388 // Only add to macro trigger list if non-off
391 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
392 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
393 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x02; // Analog key
394 macroTriggerListBufferSize++;
403 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
405 // Only add to macro trigger list if non-off
408 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
409 macroTriggerListBuffer[ macroTriggerListBufferSize ].state = state;
410 macroTriggerListBuffer[ macroTriggerListBufferSize ].type = 0x01; // LED key
411 macroTriggerListBufferSize++;
416 // Append result macro to pending list, checking for duplicates
417 // Do nothing if duplicate
418 inline void Macro_appendResultMacroToPendingList( TriggerMacro *triggerMacro )
420 // Lookup result macro index
421 var_uint_t resultMacroIndex = triggerMacro->result;
423 // Iterate through result macro pending list, making sure this macro hasn't been added yet
424 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
426 // If duplicate found, do nothing
427 if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
431 // No duplicates found, add to pending list
432 macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
434 // Lookup scanCode of the last key in the last combo
436 for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
438 pos += TriggerGuideSize * comboLength + 1;
439 comboLength = triggerMacro->guide[ pos ];
442 uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
444 // Lookup scanCode in buffer list for the current state and stateType
445 for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
447 if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
449 ResultMacroList[ resultMacroIndex ].state = macroTriggerListBuffer[ keyIndex ].state;
450 ResultMacroList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
454 // Reset the macro position
455 ResultMacroList[ resultMacroIndex ].pos = 0;
459 // Determine if long ResultMacro (more than 1 seqence element)
460 inline uint8_t Macro_isLongResultMacro( ResultMacro *macro )
462 // Check the second sequence combo length
463 // If non-zero return non-zero (long sequence)
464 // 0 otherwise (short sequence)
465 var_uint_t position = 1;
466 for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
467 position += ResultGuideSize( (ResultGuide*)¯o->guide[ position ] );
468 return macro->guide[ position ];
472 // Determine if long TriggerMacro (more than 1 sequence element)
473 inline uint8_t Macro_isLongTriggerMacro( TriggerMacro *macro )
475 // Check the second sequence combo length
476 // If non-zero return non-zero (long sequence)
477 // 0 otherwise (short sequence)
478 return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
482 // Votes on the given key vs. guide, short macros
483 inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
485 // Depending on key type
486 switch ( guide->type )
490 // For short TriggerMacros completely ignore incorrect keys
491 if ( guide->scanCode == key->scanCode )
493 switch ( key->state )
495 // Correct key, pressed, possible passing
497 return TriggerMacroVote_Pass;
499 // Correct key, held, possible passing or release
501 return TriggerMacroVote_PassRelease;
503 // Correct key, released, possible release
505 return TriggerMacroVote_Release;
509 return TriggerMacroVote_DoNothing;
513 erro_print("LED State Type - Not implemented...");
518 erro_print("Analog State Type - Not implemented...");
521 // Invalid State Type
523 erro_print("Invalid State Type. This is a bug.");
527 // XXX Shouldn't reach here
528 return TriggerMacroVote_Invalid;
532 // Votes on the given key vs. guide, long macros
533 // A long macro is defined as a guide with more than 1 combo
534 inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
536 // Depending on key type
537 switch ( guide->type )
541 // Depending on the state of the buffered key, make voting decision
543 if ( guide->scanCode != key->scanCode )
545 switch ( key->state )
547 // Wrong key, pressed, fail
549 return TriggerMacroVote_Fail;
551 // Wrong key, held, do not pass (no effect)
553 return TriggerMacroVote_DoNothing;
555 // Wrong key released, fail out if pos == 0
557 return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
564 switch ( key->state )
566 // Correct key, pressed, possible passing
568 return TriggerMacroVote_Pass;
570 // Correct key, held, possible passing or release
572 return TriggerMacroVote_PassRelease;
574 // Correct key, released, possible release
576 return TriggerMacroVote_Release;
584 erro_print("LED State Type - Not implemented...");
589 erro_print("Analog State Type - Not implemented...");
592 // Invalid State Type
594 erro_print("Invalid State Type. This is a bug.");
598 // XXX Shouldn't reach here
599 return TriggerMacroVote_Invalid;
603 // Evaluate/Update TriggerMacro
604 inline TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
606 // Lookup TriggerMacro
607 TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
609 // Check if macro has finished and should be incremented sequence elements
610 if ( macro->state == TriggerMacro_Release )
612 macro->state = TriggerMacro_Waiting;
613 macro->pos = macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize + 1;
616 // Current Macro position
617 var_uint_t pos = macro->pos;
619 // Length of the combo being processed
620 uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
622 // If no combo items are left, remove the TriggerMacro from the pending list
623 if ( comboLength == 0 )
625 return TriggerMacroEval_Remove;
628 // Check if this is a long Trigger Macro
629 uint8_t longMacro = Macro_isLongTriggerMacro( macro );
631 // Iterate through the items in the combo, voting the on the key state
632 // If any of the pressed keys do not match, fail the macro
634 // The macro is waiting for input when in the TriggerMacro_Waiting state
635 // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
636 // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
637 // On scan after position increment, change to TriggerMacro_Waiting state
638 // TODO Add support for system LED states (NumLock, CapsLock, etc.)
639 // TODO Add support for analog key states
640 // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
641 // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
642 TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
643 for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
645 // Assign TriggerGuide element (key type, state and scancode)
646 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ comboItem ]);
648 TriggerMacroVote vote = TriggerMacroVote_Invalid;
649 // Iterate through the key buffer, comparing to each key in the combo
650 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
652 // Lookup key information
653 TriggerGuide *keyInfo = ¯oTriggerListBuffer[ key ];
655 // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
656 // Also mask all of the non-passing votes
658 ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
659 : Macro_evalShortTriggerMacroVote( keyInfo, guide );
660 if ( vote >= TriggerMacroVote_Pass )
662 vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
667 // If no pass vote was found after scanning all of the keys
668 // Fail the combo, if this is a short macro (long macros already will have a fail vote)
669 if ( !longMacro && vote < TriggerMacroVote_Pass )
670 vote |= TriggerMacroVote_Fail;
672 // After voting, append to overall vote
676 // If no pass vote was found after scanning the entire combo
677 // And this is the first position in the combo, just remove it (nothing important happened)
678 if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
679 overallVote |= TriggerMacroVote_Fail;
681 // Decide new state of macro after voting
682 // Fail macro, remove from pending list
683 if ( overallVote & TriggerMacroVote_Fail )
685 return TriggerMacroEval_Remove;
687 // Do nothing, incorrect key is being held or released
688 else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
690 // Just doing nothing :)
692 // If passing and in Waiting state, set macro state to Press
693 else if ( overallVote & TriggerMacroVote_Pass
694 && ( macro->state == TriggerMacro_Waiting || macro->state == TriggerMacro_Press ) )
696 macro->state = TriggerMacro_Press;
698 // If in press state, and this is the final combo, send request for ResultMacro
699 // Check to see if the result macro only has a single element
700 // If this result macro has more than 1 key, only send once
701 // TODO Add option to have long macro repeat rate
702 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
704 // Long result macro (more than 1 combo)
705 if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
707 // Only ever trigger result once, on press
708 if ( overallVote == TriggerMacroVote_Pass )
710 return TriggerMacroEval_DoResultAndRemove;
713 // Short result macro
716 // Only trigger result once, on press, if long trigger (more than 1 combo)
717 if ( Macro_isLongTriggerMacro( macro ) )
719 return TriggerMacroEval_DoResultAndRemove;
721 // Otherwise, trigger result continuously
724 return TriggerMacroEval_DoResult;
729 // If ready for transition and in Press state, set to Waiting and increment combo position
730 // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
731 else if ( overallVote & TriggerMacroVote_Release && macro->state == TriggerMacro_Press )
733 macro->state = TriggerMacro_Release;
735 // If this is the last combo in the sequence, remove from the pending list
736 if ( macro->guide[ macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize + 1 ] == 0 )
737 return TriggerMacroEval_Remove;
739 // Otherwise, just remove the macro on key release
740 // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
741 else if ( overallVote & TriggerMacroVote_Release )
743 return TriggerMacroEval_DoResultAndRemove;
746 // If this is a short macro, just remove it
747 // The state can be rebuilt on the next iteration
749 return TriggerMacroEval_Remove;
751 return TriggerMacroEval_DoNothing;
755 // Evaluate/Update ResultMacro
756 inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
758 // Lookup ResultMacro
759 ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
761 // Current Macro position
762 var_uint_t pos = macro->pos;
764 // Length of combo being processed
765 uint8_t comboLength = macro->guide[ pos ];
767 // Function Counter, used to keep track of the combo items processed
768 var_uint_t funcCount = 0;
770 // Combo Item Position within the guide
771 var_uint_t comboItem = pos + 1;
773 // Iterate through the Result Combo
774 while ( funcCount < comboLength )
776 // Assign TriggerGuide element (key type, state and scancode)
777 ResultGuide *guide = (ResultGuide*)(¯o->guide[ comboItem ]);
779 // Do lookup on capability function
780 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
783 capability( macro->state, macro->stateType, &guide->args );
785 // Increment counters
787 comboItem += ResultGuideSize( (ResultGuide*)(¯o->guide[ comboItem ]) );
790 // Move to next item in the sequence
791 macro->pos = comboItem;
793 // If the ResultMacro is finished, remove
794 if ( macro->guide[ comboItem ] == 0 )
796 return ResultMacroEval_Remove;
799 // Otherwise leave the macro in the list
800 return ResultMacroEval_DoNothing;
804 // Update pending trigger list
805 inline void Macro_updateTriggerMacroPendingList()
807 // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
808 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
811 // TODO Analog Switches
812 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
813 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
816 // Lookup Trigger List
817 nat_ptr_t *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode );
819 // Number of Triggers in list
820 nat_ptr_t triggerListSize = triggerList[0];
822 // Iterate over triggerList to see if any TriggerMacros need to be added
823 // First item is the number of items in the TriggerList
824 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
826 // Lookup trigger macro index
827 var_uint_t triggerMacroIndex = triggerList[ macro ];
829 // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
830 // triggerList needs to be added
831 var_uint_t pending = 0;
832 for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
834 // Stop scanning if the trigger macro index is found in the pending list
835 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
839 // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
840 // Add it to the list
841 if ( pending == macroTriggerMacroPendingListSize )
843 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
845 // Reset macro position
846 TriggerMacroList[ triggerMacroIndex ].pos = 0;
847 TriggerMacroList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
854 // Macro Procesing Loop
855 // Called once per USB buffer send
856 inline void Macro_process()
858 // Only do one round of macro processing between Output Module timer sends
859 if ( USBKeys_Sent != 0 )
862 // If the pause flag is set, only process if the step counter is non-zero
863 if ( macroPauseMode )
865 if ( macroStepCounter == 0 )
868 // Proceed, decrementing the step counter
870 dbug_print("Macro Step");
873 // Update pending trigger list, before processing TriggerMacros
874 Macro_updateTriggerMacroPendingList();
876 // Tail pointer for macroTriggerMacroPendingList
877 // Macros must be explicitly re-added
878 var_uint_t macroTriggerMacroPendingListTail = 0;
880 // Iterate through the pending TriggerMacros, processing each of them
881 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
883 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
885 // Trigger Result Macro (purposely falling through)
886 case TriggerMacroEval_DoResult:
887 // Append ResultMacro to PendingList
888 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
891 macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
894 // Trigger Result Macro and Remove (purposely falling through)
895 case TriggerMacroEval_DoResultAndRemove:
896 // Append ResultMacro to PendingList
897 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
899 // Remove Macro from Pending List, nothing to do, removing by default
900 case TriggerMacroEval_Remove:
905 // Update the macroTriggerMacroPendingListSize with the tail pointer
906 macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
909 // Tail pointer for macroResultMacroPendingList
910 // Macros must be explicitly re-added
911 var_uint_t macroResultMacroPendingListTail = 0;
913 // Iterate through the pending ResultMacros, processing each of them
914 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
916 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
918 // Re-add macros to pending list
919 case ResultMacroEval_DoNothing:
921 macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
924 // Remove Macro from Pending List, nothing to do, removing by default
925 case ResultMacroEval_Remove:
930 // Update the macroResultMacroPendingListSize with the tail pointer
931 macroResultMacroPendingListSize = macroResultMacroPendingListTail;
933 // Signal buffer that we've used it
934 Scan_finishedWithMacro( macroTriggerListBufferSize );
936 // Reset TriggerList buffer
937 macroTriggerListBufferSize = 0;
939 // If Macro debug mode is set, clear the USB Buffer
940 if ( macroDebugMode )
942 USBKeys_Modifiers = 0;
948 inline void Macro_setup()
950 // Register Macro CLI dictionary
951 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
953 // Disable Macro debug mode
956 // Disable Macro pause flag
959 // Set Macro step counter to zero
960 macroStepCounter = 0;
962 // Make sure macro trigger buffer is empty
963 macroTriggerListBufferSize = 0;
965 // Initialize TriggerMacro states
966 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
968 TriggerMacroList[ macro ].pos = 0;
969 TriggerMacroList[ macro ].state = TriggerMacro_Waiting;
972 // Initialize ResultMacro states
973 for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
975 ResultMacroList[ macro ].pos = 0;
976 ResultMacroList[ macro ].state = 0;
977 ResultMacroList[ macro ].stateType = 0;
982 // ----- CLI Command Functions -----
984 void cliFunc_capList( char* args )
987 info_msg("Capabilities List");
988 printHex( CapabilitiesNum );
990 // Iterate through all of the capabilities and display them
991 for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
997 // Display/Lookup Capability Name (utilize debug mode of capability)
998 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
999 capability( 0xFF, 0xFF, 0 );
1003 void cliFunc_capSelect( char* args )
1005 // Parse code from argument
1008 char* arg2Ptr = args;
1010 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
1011 var_uint_t totalArgs = 2; // Always at least two args
1014 // Arguments used for keyboard capability function
1015 var_uint_t argSetCount = 0;
1016 uint8_t *argSet = (uint8_t*)args;
1019 for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1022 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1024 // Stop processing args if no more are found
1025 // Extra arguments are ignored
1026 if ( *arg1Ptr == '\0' )
1029 // For the first argument, choose the capability
1030 if ( c == 0 ) switch ( arg1Ptr[0] )
1032 // Keyboard Capability
1034 // Determine capability index
1035 cap = numToInt( &arg1Ptr[1] );
1037 // Lookup the number of args
1038 totalArgs += CapabilitiesList[ cap ].argCount;
1042 // Because allocating memory isn't doable, and the argument count is arbitrary
1043 // The argument pointer is repurposed as the argument list (much smaller anyways)
1044 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1046 // Once all the arguments are prepared, call the keyboard capability function
1047 if ( argSetCount == totalArgs )
1049 // Indicate that the capability was called
1054 printHex( argSet[0] );
1056 printHex( argSet[1] );
1058 printHex( argSet[2] );
1061 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1062 capability( argSet[0], argSet[1], &argSet[2] );
1067 void cliFunc_keyHold( char* args )
1069 // Parse codes from arguments
1072 char* arg2Ptr = args;
1078 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1080 // Stop processing args if no more are found
1081 if ( *arg1Ptr == '\0' )
1084 // Ignore non-Scancode numbers
1085 switch ( arg1Ptr[0] )
1089 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1095 void cliFunc_keyPress( char* args )
1097 // Parse codes from arguments
1100 char* arg2Ptr = args;
1106 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1108 // Stop processing args if no more are found
1109 if ( *arg1Ptr == '\0' )
1112 // Ignore non-Scancode numbers
1113 switch ( arg1Ptr[0] )
1117 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1123 void cliFunc_keyRelease( 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] ), 0x03 ); // Release scancode
1151 void cliFunc_layerList( char* args )
1154 info_msg("Layer List");
1156 // Iterate through all of the layers and display them
1157 for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1163 // Display layer name
1164 dPrint( (char*)LayerIndex[ layer ].name );
1168 print(" \033[1m(default)\033[0m");
1171 print( NL "\t\t Layer State: " );
1172 printHex( LayerState[ layer ] );
1174 // First -> Last Indices
1175 print(" First -> Last Indices: ");
1176 printHex( LayerIndex[ layer ].first );
1178 printHex( LayerIndex[ layer ].last );
1182 void cliFunc_layerState( char* args )
1184 // Parse codes from arguments
1187 char* arg2Ptr = args;
1192 // Process first two args
1193 for ( uint8_t c = 0; c < 2; c++ )
1196 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1198 // Stop processing args if no more are found
1199 if ( *arg1Ptr == '\0' )
1204 // First argument (e.g. L1)
1206 if ( arg1Ptr[0] != 'L' )
1209 arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1211 // Second argument (e.g. 4)
1213 arg2 = (uint8_t)numToInt( arg1Ptr );
1215 // Display operation (to indicate that it worked)
1217 info_msg("Setting Layer L");
1222 // Set the layer state
1223 LayerState[ arg1 ] = arg2;
1229 void cliFunc_macroDebug( char* args )
1231 // Toggle macro debug mode
1232 macroDebugMode = macroDebugMode ? 0 : 1;
1235 info_msg("Macro Debug Mode: ");
1236 printInt8( macroDebugMode );
1239 void cliFunc_macroList( char* args )
1241 // Show pending key events
1243 info_msg("Pending Key Events: ");
1244 printInt16( (uint16_t)macroTriggerListBufferSize );
1246 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1248 printHex( macroTriggerListBuffer[ key ].scanCode );
1252 // Show pending trigger macros
1254 info_msg("Pending Trigger Macros: ");
1255 printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1257 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1259 printHex( macroTriggerMacroPendingList[ macro ] );
1263 // Show pending result macros
1265 info_msg("Pending Result Macros: ");
1266 printInt16( (uint16_t)macroResultMacroPendingListSize );
1268 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1270 printHex( macroResultMacroPendingList[ macro ] );
1274 // Show available trigger macro indices
1276 info_msg("Trigger Macros Range: T0 -> T");
1277 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1279 // Show available result macro indices
1281 info_msg("Result Macros Range: R0 -> R");
1282 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1284 // Show Trigger to Result Macro Links
1286 info_msg("Trigger : Result Macro Pairs");
1287 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1291 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1293 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1297 void cliFunc_macroProc( char* args )
1299 // Toggle macro pause mode
1300 macroPauseMode = macroPauseMode ? 0 : 1;
1303 info_msg("Macro Processing Mode: ");
1304 printInt8( macroPauseMode );
1307 void macroDebugShowTrigger( var_uint_t index )
1309 // Only proceed if the macro exists
1310 if ( index >= TriggerMacroNum )
1313 // Trigger Macro Show
1314 TriggerMacro *macro = &TriggerMacroList[ index ];
1317 info_msg("Trigger Macro Index: ");
1318 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1321 // Read the comboLength for combo in the sequence (sequence of combos)
1323 uint8_t comboLength = macro->guide[ pos ];
1325 // Iterate through and interpret the guide
1326 while ( comboLength != 0 )
1328 // Initial position of the combo
1329 var_uint_t comboPos = ++pos;
1331 // Iterate through the combo
1332 while ( pos < comboLength * TriggerGuideSize + comboPos )
1334 // Assign TriggerGuide element (key type, state and scancode)
1335 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
1337 // Display guide information about trigger key
1338 printHex( guide->scanCode );
1340 printHex( guide->type );
1342 printHex( guide->state );
1344 // Increment position
1345 pos += TriggerGuideSize;
1347 // Only show combo separator if there are combos left in the sequence element
1348 if ( pos < comboLength * TriggerGuideSize + comboPos )
1352 // Read the next comboLength
1353 comboLength = macro->guide[ pos ];
1355 // Only show sequence separator if there is another combo to process
1356 if ( comboLength != 0 )
1360 // Display current position
1361 print( NL "Position: " );
1362 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1364 // Display result macro index
1365 print( NL "Result Macro Index: " );
1366 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1368 // Display trigger macro state
1369 print( NL "Trigger Macro State: " );
1370 switch ( macro->state )
1372 case TriggerMacro_Press: print("Press"); break;
1373 case TriggerMacro_Release: print("Release"); break;
1374 case TriggerMacro_Waiting: print("Waiting"); break;
1378 void macroDebugShowResult( var_uint_t index )
1380 // Only proceed if the macro exists
1381 if ( index >= ResultMacroNum )
1384 // Trigger Macro Show
1385 ResultMacro *macro = &ResultMacroList[ index ];
1388 info_msg("Result Macro Index: ");
1389 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1392 // Read the comboLength for combo in the sequence (sequence of combos)
1394 uint8_t comboLength = macro->guide[ pos++ ];
1396 // Iterate through and interpret the guide
1397 while ( comboLength != 0 )
1399 // Function Counter, used to keep track of the combos processed
1400 var_uint_t funcCount = 0;
1402 // Iterate through the combo
1403 while ( funcCount < comboLength )
1405 // Assign TriggerGuide element (key type, state and scancode)
1406 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
1408 // Display Function Index
1409 printHex( guide->index );
1412 // Display Function Ptr Address
1413 printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1416 // Display/Lookup Capability Name (utilize debug mode of capability)
1417 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1418 capability( 0xFF, 0xFF, 0 );
1420 // Display Argument(s)
1422 for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1424 // Arguments are only 8 bit values
1425 printHex( (&guide->args)[ arg ] );
1427 // Only show arg separator if there are args left
1428 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1433 // Increment position
1434 pos += ResultGuideSize( guide );
1436 // Increment function count
1439 // Only show combo separator if there are combos left in the sequence element
1440 if ( funcCount < comboLength )
1444 // Read the next comboLength
1445 comboLength = macro->guide[ pos++ ];
1447 // Only show sequence separator if there is another combo to process
1448 if ( comboLength != 0 )
1452 // Display current position
1453 print( NL "Position: " );
1454 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1456 // Display final trigger state/type
1457 print( NL "Final Trigger State (State/Type): " );
1458 printHex( macro->state );
1460 printHex( macro->stateType );
1463 void cliFunc_macroShow( char* args )
1465 // Parse codes from arguments
1468 char* arg2Ptr = args;
1474 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1476 // Stop processing args if no more are found
1477 if ( *arg1Ptr == '\0' )
1480 // Ignore invalid codes
1481 switch ( arg1Ptr[0] )
1483 // Indexed Trigger Macro
1485 macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1487 // Indexed Result Macro
1489 macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1495 void cliFunc_macroStep( char* args )
1497 // Parse number from argument
1498 // NOTE: Only first argument is used
1501 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1503 // Default to 1, if no argument given
1504 var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1509 // Set the macro step counter, negative int's are cast to uint
1510 macroStepCounter = count;