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[ macroLayerIndexStack[ layerIndex ] ] & 0x01) ^ (latch>>1) ^ ((LayerState[ macroLayerIndexStack[ 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[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 ready for transition and in Press state, set to Waiting and increment combo position
693 // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
694 else if ( overallVote & TriggerMacroVote_Release && macro->state == TriggerMacro_Press )
696 macro->state = TriggerMacro_Release;
698 // If this is the last combo in the sequence, remove from the pending list
699 if ( macro->guide[ macro->pos + macro->guide[ macro->pos ] * TriggerGuideSize + 1 ] == 0 )
700 return TriggerMacroEval_DoResultAndRemove;
702 // If passing and in Waiting state, set macro state to Press
703 else if ( overallVote & TriggerMacroVote_Pass
704 && ( macro->state == TriggerMacro_Waiting || macro->state == TriggerMacro_Press ) )
706 macro->state = TriggerMacro_Press;
708 // If in press state, and this is the final combo, send request for ResultMacro
709 // Check to see if the result macro only has a single element
710 // If this result macro has more than 1 key, only send once
711 // TODO Add option to have long macro repeat rate
712 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
714 // Long result macro (more than 1 combo)
715 if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
717 // Only ever trigger result once, on press
718 if ( overallVote == TriggerMacroVote_Pass )
720 return TriggerMacroEval_DoResultAndRemove;
723 // Short result macro
726 // Only trigger result once, on press, if long trigger (more than 1 combo)
727 if ( Macro_isLongTriggerMacro( macro ) )
729 return TriggerMacroEval_DoResultAndRemove;
731 // Otherwise, trigger result continuously
734 return TriggerMacroEval_DoResult;
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 )
797 return ResultMacroEval_Remove;
800 // Otherwise leave the macro in the list
801 return ResultMacroEval_DoNothing;
805 // Update pending trigger list
806 inline void Macro_updateTriggerMacroPendingList()
808 // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
809 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
812 // TODO Analog Switches
813 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
814 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
817 // Lookup Trigger List
818 nat_ptr_t *triggerList = Macro_layerLookup( macroTriggerListBuffer[ key ].scanCode );
820 // Number of Triggers in list
821 nat_ptr_t triggerListSize = triggerList[0];
823 // Iterate over triggerList to see if any TriggerMacros need to be added
824 // First item is the number of items in the TriggerList
825 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
827 // Lookup trigger macro index
828 var_uint_t triggerMacroIndex = triggerList[ macro ];
830 // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
831 // triggerList needs to be added
832 var_uint_t pending = 0;
833 for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
835 // Stop scanning if the trigger macro index is found in the pending list
836 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
840 // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
841 // Add it to the list
842 if ( pending == macroTriggerMacroPendingListSize )
844 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
846 // Reset macro position
847 TriggerMacroList[ triggerMacroIndex ].pos = 0;
848 TriggerMacroList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
855 // Macro Procesing Loop
856 // Called once per USB buffer send
857 inline void Macro_process()
859 // Only do one round of macro processing between Output Module timer sends
860 if ( USBKeys_Sent != 0 )
863 // If the pause flag is set, only process if the step counter is non-zero
864 if ( macroPauseMode )
866 if ( macroStepCounter == 0 )
869 // Proceed, decrementing the step counter
871 dbug_print("Macro Step");
874 // Update pending trigger list, before processing TriggerMacros
875 Macro_updateTriggerMacroPendingList();
877 // Tail pointer for macroTriggerMacroPendingList
878 // Macros must be explicitly re-added
879 var_uint_t macroTriggerMacroPendingListTail = 0;
881 // Iterate through the pending TriggerMacros, processing each of them
882 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
884 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
886 // Trigger Result Macro (purposely falling through)
887 case TriggerMacroEval_DoResult:
888 // Append ResultMacro to PendingList
889 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
892 macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
895 // Trigger Result Macro and Remove (purposely falling through)
896 case TriggerMacroEval_DoResultAndRemove:
897 // Append ResultMacro to PendingList
898 Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
900 // Remove Macro from Pending List, nothing to do, removing by default
901 case TriggerMacroEval_Remove:
906 // Update the macroTriggerMacroPendingListSize with the tail pointer
907 macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
910 // Tail pointer for macroResultMacroPendingList
911 // Macros must be explicitly re-added
912 var_uint_t macroResultMacroPendingListTail = 0;
914 // Iterate through the pending ResultMacros, processing each of them
915 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
917 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
919 // Re-add macros to pending list
920 case ResultMacroEval_DoNothing:
922 macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
925 // Remove Macro from Pending List, nothing to do, removing by default
926 case ResultMacroEval_Remove:
931 // Update the macroResultMacroPendingListSize with the tail pointer
932 macroResultMacroPendingListSize = macroResultMacroPendingListTail;
934 // Signal buffer that we've used it
935 Scan_finishedWithMacro( macroTriggerListBufferSize );
937 // Reset TriggerList buffer
938 macroTriggerListBufferSize = 0;
940 // If Macro debug mode is set, clear the USB Buffer
941 if ( macroDebugMode )
943 USBKeys_Modifiers = 0;
949 inline void Macro_setup()
951 // Register Macro CLI dictionary
952 CLI_registerDictionary( macroCLIDict, macroCLIDictName );
954 // Disable Macro debug mode
957 // Disable Macro pause flag
960 // Set Macro step counter to zero
961 macroStepCounter = 0;
963 // Make sure macro trigger buffer is empty
964 macroTriggerListBufferSize = 0;
966 // Initialize TriggerMacro states
967 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
969 TriggerMacroList[ macro ].pos = 0;
970 TriggerMacroList[ macro ].state = TriggerMacro_Waiting;
973 // Initialize ResultMacro states
974 for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
976 ResultMacroList[ macro ].pos = 0;
977 ResultMacroList[ macro ].state = 0;
978 ResultMacroList[ macro ].stateType = 0;
983 // ----- CLI Command Functions -----
985 void cliFunc_capList( char* args )
988 info_msg("Capabilities List");
989 printHex( CapabilitiesNum );
991 // Iterate through all of the capabilities and display them
992 for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
998 // Display/Lookup Capability Name (utilize debug mode of capability)
999 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1000 capability( 0xFF, 0xFF, 0 );
1004 void cliFunc_capSelect( char* args )
1006 // Parse code from argument
1009 char* arg2Ptr = args;
1011 // Total number of args to scan (must do a lookup if a keyboard capability is selected)
1012 var_uint_t totalArgs = 2; // Always at least two args
1015 // Arguments used for keyboard capability function
1016 var_uint_t argSetCount = 0;
1017 uint8_t *argSet = (uint8_t*)args;
1020 for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1023 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1025 // Stop processing args if no more are found
1026 // Extra arguments are ignored
1027 if ( *arg1Ptr == '\0' )
1030 // For the first argument, choose the capability
1031 if ( c == 0 ) switch ( arg1Ptr[0] )
1033 // Keyboard Capability
1035 // Determine capability index
1036 cap = numToInt( &arg1Ptr[1] );
1038 // Lookup the number of args
1039 totalArgs += CapabilitiesList[ cap ].argCount;
1043 // Because allocating memory isn't doable, and the argument count is arbitrary
1044 // The argument pointer is repurposed as the argument list (much smaller anyways)
1045 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1047 // Once all the arguments are prepared, call the keyboard capability function
1048 if ( argSetCount == totalArgs )
1050 // Indicate that the capability was called
1055 printHex( argSet[0] );
1057 printHex( argSet[1] );
1059 printHex( argSet[2] );
1062 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1063 capability( argSet[0], argSet[1], &argSet[2] );
1068 void cliFunc_keyHold( char* args )
1070 // Parse codes from arguments
1073 char* arg2Ptr = args;
1079 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1081 // Stop processing args if no more are found
1082 if ( *arg1Ptr == '\0' )
1085 // Ignore non-Scancode numbers
1086 switch ( arg1Ptr[0] )
1090 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1096 void cliFunc_keyPress( char* args )
1098 // Parse codes from arguments
1101 char* arg2Ptr = args;
1107 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1109 // Stop processing args if no more are found
1110 if ( *arg1Ptr == '\0' )
1113 // Ignore non-Scancode numbers
1114 switch ( arg1Ptr[0] )
1118 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1124 void cliFunc_keyRelease( char* args )
1126 // Parse codes from arguments
1129 char* arg2Ptr = args;
1135 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1137 // Stop processing args if no more are found
1138 if ( *arg1Ptr == '\0' )
1141 // Ignore non-Scancode numbers
1142 switch ( arg1Ptr[0] )
1146 Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
1152 void cliFunc_layerList( char* args )
1155 info_msg("Layer List");
1157 // Iterate through all of the layers and display them
1158 for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1164 // Display layer name
1165 dPrint( (char*)LayerIndex[ layer ].name );
1169 print(" \033[1m(default)\033[0m");
1172 print( NL "\t\t Layer State: " );
1173 printHex( LayerState[ layer ] );
1175 // First -> Last Indices
1176 print(" First -> Last Indices: ");
1177 printHex( LayerIndex[ layer ].first );
1179 printHex( LayerIndex[ layer ].last );
1183 void cliFunc_layerState( char* args )
1185 // Parse codes from arguments
1188 char* arg2Ptr = args;
1193 // Process first two args
1194 for ( uint8_t c = 0; c < 2; c++ )
1197 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1199 // Stop processing args if no more are found
1200 if ( *arg1Ptr == '\0' )
1205 // First argument (e.g. L1)
1207 if ( arg1Ptr[0] != 'L' )
1210 arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1212 // Second argument (e.g. 4)
1214 arg2 = (uint8_t)numToInt( arg1Ptr );
1216 // Display operation (to indicate that it worked)
1218 info_msg("Setting Layer L");
1223 // Set the layer state
1224 LayerState[ arg1 ] = arg2;
1230 void cliFunc_macroDebug( char* args )
1232 // Toggle macro debug mode
1233 macroDebugMode = macroDebugMode ? 0 : 1;
1236 info_msg("Macro Debug Mode: ");
1237 printInt8( macroDebugMode );
1240 void cliFunc_macroList( char* args )
1242 // Show pending key events
1244 info_msg("Pending Key Events: ");
1245 printInt16( (uint16_t)macroTriggerListBufferSize );
1247 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1249 printHex( macroTriggerListBuffer[ key ].scanCode );
1253 // Show pending trigger macros
1255 info_msg("Pending Trigger Macros: ");
1256 printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1258 for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1260 printHex( macroTriggerMacroPendingList[ macro ] );
1264 // Show pending result macros
1266 info_msg("Pending Result Macros: ");
1267 printInt16( (uint16_t)macroResultMacroPendingListSize );
1269 for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1271 printHex( macroResultMacroPendingList[ macro ] );
1275 // Show available trigger macro indices
1277 info_msg("Trigger Macros Range: T0 -> T");
1278 printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1280 // Show available result macro indices
1282 info_msg("Result Macros Range: R0 -> R");
1283 printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1285 // Show Trigger to Result Macro Links
1287 info_msg("Trigger : Result Macro Pairs");
1288 for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1292 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1294 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1298 void cliFunc_macroProc( char* args )
1300 // Toggle macro pause mode
1301 macroPauseMode = macroPauseMode ? 0 : 1;
1304 info_msg("Macro Processing Mode: ");
1305 printInt8( macroPauseMode );
1308 void macroDebugShowTrigger( var_uint_t index )
1310 // Only proceed if the macro exists
1311 if ( index >= TriggerMacroNum )
1314 // Trigger Macro Show
1315 TriggerMacro *macro = &TriggerMacroList[ index ];
1318 info_msg("Trigger Macro Index: ");
1319 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1322 // Read the comboLength for combo in the sequence (sequence of combos)
1324 uint8_t comboLength = macro->guide[ pos ];
1326 // Iterate through and interpret the guide
1327 while ( comboLength != 0 )
1329 // Initial position of the combo
1330 var_uint_t comboPos = ++pos;
1332 // Iterate through the combo
1333 while ( pos < comboLength * TriggerGuideSize + comboPos )
1335 // Assign TriggerGuide element (key type, state and scancode)
1336 TriggerGuide *guide = (TriggerGuide*)(¯o->guide[ pos ]);
1338 // Display guide information about trigger key
1339 printHex( guide->scanCode );
1341 printHex( guide->type );
1343 printHex( guide->state );
1345 // Increment position
1346 pos += TriggerGuideSize;
1348 // Only show combo separator if there are combos left in the sequence element
1349 if ( pos < comboLength * TriggerGuideSize + comboPos )
1353 // Read the next comboLength
1354 comboLength = macro->guide[ pos ];
1356 // Only show sequence separator if there is another combo to process
1357 if ( comboLength != 0 )
1361 // Display current position
1362 print( NL "Position: " );
1363 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1365 // Display result macro index
1366 print( NL "Result Macro Index: " );
1367 printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1369 // Display trigger macro state
1370 print( NL "Trigger Macro State: " );
1371 switch ( macro->state )
1373 case TriggerMacro_Press: print("Press"); break;
1374 case TriggerMacro_Release: print("Release"); break;
1375 case TriggerMacro_Waiting: print("Waiting"); break;
1379 void macroDebugShowResult( var_uint_t index )
1381 // Only proceed if the macro exists
1382 if ( index >= ResultMacroNum )
1385 // Trigger Macro Show
1386 ResultMacro *macro = &ResultMacroList[ index ];
1389 info_msg("Result Macro Index: ");
1390 printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1393 // Read the comboLength for combo in the sequence (sequence of combos)
1395 uint8_t comboLength = macro->guide[ pos++ ];
1397 // Iterate through and interpret the guide
1398 while ( comboLength != 0 )
1400 // Function Counter, used to keep track of the combos processed
1401 var_uint_t funcCount = 0;
1403 // Iterate through the combo
1404 while ( funcCount < comboLength )
1406 // Assign TriggerGuide element (key type, state and scancode)
1407 ResultGuide *guide = (ResultGuide*)(¯o->guide[ pos ]);
1409 // Display Function Index
1410 printHex( guide->index );
1413 // Display Function Ptr Address
1414 printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1417 // Display/Lookup Capability Name (utilize debug mode of capability)
1418 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1419 capability( 0xFF, 0xFF, 0 );
1421 // Display Argument(s)
1423 for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1425 // Arguments are only 8 bit values
1426 printHex( (&guide->args)[ arg ] );
1428 // Only show arg separator if there are args left
1429 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1434 // Increment position
1435 pos += ResultGuideSize( guide );
1437 // Increment function count
1440 // Only show combo separator if there are combos left in the sequence element
1441 if ( funcCount < comboLength )
1445 // Read the next comboLength
1446 comboLength = macro->guide[ pos++ ];
1448 // Only show sequence separator if there is another combo to process
1449 if ( comboLength != 0 )
1453 // Display current position
1454 print( NL "Position: " );
1455 printInt16( (uint16_t)macro->pos ); // Hopefully large enough :P (can't assume 32-bit)
1457 // Display final trigger state/type
1458 print( NL "Final Trigger State (State/Type): " );
1459 printHex( macro->state );
1461 printHex( macro->stateType );
1464 void cliFunc_macroShow( char* args )
1466 // Parse codes from arguments
1469 char* arg2Ptr = args;
1475 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1477 // Stop processing args if no more are found
1478 if ( *arg1Ptr == '\0' )
1481 // Ignore invalid codes
1482 switch ( arg1Ptr[0] )
1484 // Indexed Trigger Macro
1486 macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1488 // Indexed Result Macro
1490 macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1496 void cliFunc_macroStep( char* args )
1498 // Parse number from argument
1499 // NOTE: Only first argument is used
1502 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1504 // Default to 1, if no argument given
1505 var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1510 // Set the macro step counter, negative int's are cast to uint
1511 macroStepCounter = count;