]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Macro/PartialMap/macro.c
Merge pull request #27 from smasher816/wakeup-devel
[kiibohd-controller.git] / Macro / PartialMap / macro.c
1 /* Copyright (C) 2014-2015 by Jacob Alexander
2  *
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.
7  *
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.
12  *
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/>.
15  */
16
17 // ----- Includes -----
18
19 // Compiler Includes
20 #include <Lib/MacroLib.h>
21
22 // Project Includes
23 #include <cli.h>
24 #include <led.h>
25 #include <print.h>
26 #include <scan_loop.h>
27
28 // Keymaps
29 #include "usb_hid.h"
30 #include <generatedKeymap.h> // Generated using kll at compile time, in build directory
31
32 // Local Includes
33 #include "macro.h"
34
35
36
37 // ----- Function Declarations -----
38
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 );
51
52
53
54 // ----- Enums -----
55
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
65 } TriggerMacroVote;
66
67 typedef enum TriggerMacroEval {
68         TriggerMacroEval_DoNothing,
69         TriggerMacroEval_DoResult,
70         TriggerMacroEval_DoResultAndRemove,
71         TriggerMacroEval_Remove,
72 } TriggerMacroEval;
73
74 typedef enum ResultMacroEval {
75         ResultMacroEval_DoNothing,
76         ResultMacroEval_Remove,
77 } ResultMacroEval;
78
79
80
81 // ----- Variables -----
82
83 // Macro Module command dictionary
84 CLIDict_Entry( capList,     "Prints an indexed list of all non USB keycode capabilities." );
85 CLIDict_Entry( capSelect,   "Triggers the specified capabilities. First two args are state and stateType." NL "\t\t\033[35mK11\033[0m Keyboard Capability 0x0B" );
86 CLIDict_Entry( keyHold,     "Send key-hold events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
87 CLIDict_Entry( keyPress,    "Send key-press events to the macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
88 CLIDict_Entry( keyRelease,  "Send key-release event to macro module. Duplicates have undefined behaviour." NL "\t\t\033[35mS10\033[0m Scancode 0x0A" );
89 CLIDict_Entry( layerList,   "List available layers." );
90 CLIDict_Entry( layerState,  "Modify specified indexed layer state <layer> <state byte>." NL "\t\t\033[35mL2\033[0m Indexed Layer 0x02" NL "\t\t0 Off, 1 Shift, 2 Latch, 4 Lock States" );
91 CLIDict_Entry( macroDebug,  "Disables/Enables sending USB keycodes to the Output Module and prints U/K codes." );
92 CLIDict_Entry( macroList,   "List the defined trigger and result macros." );
93 CLIDict_Entry( macroProc,   "Pause/Resume macro processing." );
94 CLIDict_Entry( macroShow,   "Show the macro corresponding to the given index." NL "\t\t\033[35mT16\033[0m Indexed Trigger Macro 0x10, \033[35mR12\033[0m Indexed Result Macro 0x0C" );
95 CLIDict_Entry( macroStep,   "Do N macro processing steps. Defaults to 1." );
96
97 CLIDict_Def( macroCLIDict, "Macro Module Commands" ) = {
98         CLIDict_Item( capList ),
99         CLIDict_Item( capSelect ),
100         CLIDict_Item( keyHold ),
101         CLIDict_Item( keyPress ),
102         CLIDict_Item( keyRelease ),
103         CLIDict_Item( layerList ),
104         CLIDict_Item( layerState ),
105         CLIDict_Item( macroDebug ),
106         CLIDict_Item( macroList ),
107         CLIDict_Item( macroProc ),
108         CLIDict_Item( macroShow ),
109         CLIDict_Item( macroStep ),
110         { 0, 0, 0 } // Null entry for dictionary end
111 };
112
113
114 // Macro debug flag - If set, clears the USB Buffers after signalling processing completion
115 uint8_t macroDebugMode = 0;
116
117 // Macro pause flag - If set, the macro module pauses processing, unless unset, or the step counter is non-zero
118 uint8_t macroPauseMode = 0;
119
120 // Macro step counter - If non-zero, the step counter counts down every time the macro module does one processing loop
121 uint16_t macroStepCounter = 0;
122
123
124 // Key Trigger List Buffer and Layer Cache
125 // The layer cache is set on press only, hold and release events refer to the value set on press
126 TriggerGuide macroTriggerListBuffer[ MaxScanCode ];
127 uint8_t macroTriggerListBufferSize = 0;
128 var_uint_t macroTriggerListLayerCache[ MaxScanCode ];
129
130 // Pending Trigger Macro Index List
131 //  * Any trigger macros that need processing from a previous macro processing loop
132 // TODO, figure out a good way to scale this array size without wasting too much memory, but not rejecting macros
133 //       Possibly could be calculated by the KLL compiler
134 // XXX It may be possible to calculate the worst case using the KLL compiler
135 uint16_t macroTriggerMacroPendingList[ TriggerMacroNum ] = { 0 };
136 uint16_t macroTriggerMacroPendingListSize = 0;
137
138 // Layer Index Stack
139 //  * When modifying layer state and the state is non-0x0, the stack must be adjusted
140 uint16_t macroLayerIndexStack[ LayerNum + 1 ] = { 0 };
141 uint16_t macroLayerIndexStackSize = 0;
142
143 // Pending Result Macro Index List
144 //  * Any result macro that needs processing from a previous macro processing loop
145 uint16_t macroResultMacroPendingList[ ResultMacroNum ] = { 0 };
146 uint16_t macroResultMacroPendingListSize = 0;
147
148
149
150 // ----- Capabilities -----
151
152 // Sets the given layer with the specified layerState
153 void Macro_layerState( uint8_t state, uint8_t stateType, uint16_t layer, uint8_t layerState )
154 {
155         // Ignore if layer does not exist
156         if ( layer >= LayerNum )
157                 return;
158
159         // Is layer in the LayerIndexStack?
160         uint8_t inLayerIndexStack = 0;
161         uint16_t stackItem = 0;
162         while ( stackItem < macroLayerIndexStackSize )
163         {
164                 // Flag if layer is already in the LayerIndexStack
165                 if ( macroLayerIndexStack[ stackItem ] == layer )
166                 {
167                         inLayerIndexStack = 1;
168                         break;
169                 }
170
171                 // Increment to next item
172                 stackItem++;
173         }
174
175         // Toggle Layer State Byte
176         if ( LayerState[ layer ] & layerState )
177         {
178                 // Unset
179                 LayerState[ layer ] &= ~layerState;
180         }
181         else
182         {
183                 // Set
184                 LayerState[ layer ] |= layerState;
185         }
186
187         // If the layer was not in the LayerIndexStack add it
188         if ( !inLayerIndexStack )
189         {
190                 macroLayerIndexStack[ macroLayerIndexStackSize++ ] = layer;
191         }
192
193         // If the layer is in the LayerIndexStack and the state is 0x00, remove
194         if ( LayerState[ layer ] == 0x00 && inLayerIndexStack )
195         {
196                 // Remove the layer from the LayerIndexStack
197                 // Using the already positioned stackItem variable from the loop above
198                 while ( stackItem < macroLayerIndexStackSize )
199                 {
200                         macroLayerIndexStack[ stackItem ] = macroLayerIndexStack[ stackItem + 1 ];
201                         stackItem++;
202                 }
203
204                 // Reduce LayerIndexStack size
205                 macroLayerIndexStackSize--;
206         }
207 }
208
209 // Modifies the specified Layer control byte
210 // Argument #1: Layer Index -> uint16_t
211 // Argument #2: Layer State -> uint8_t
212 void Macro_layerState_capability( uint8_t state, uint8_t stateType, uint8_t *args )
213 {
214         // Display capability name
215         if ( stateType == 0xFF && state == 0xFF )
216         {
217                 print("Macro_layerState(layerIndex,layerState)");
218                 return;
219         }
220
221         // Only use capability on press or release
222         // TODO Analog
223         // XXX This may cause issues, might be better to implement state table here to decide -HaaTa
224         if ( stateType == 0x00 && state == 0x02 ) // Hold condition
225                 return;
226
227         // Get layer index from arguments
228         // Cast pointer to uint8_t to uint16_t then access that memory location
229         uint16_t layer = *(uint16_t*)(&args[0]);
230
231         // Get layer toggle byte
232         uint8_t layerState = args[ sizeof(uint16_t) ];
233
234         Macro_layerState( state, stateType, layer, layerState );
235 }
236
237
238 // Latches given layer
239 // Argument #1: Layer Index -> uint16_t
240 void Macro_layerLatch_capability( uint8_t state, uint8_t stateType, uint8_t *args )
241 {
242         // Display capability name
243         if ( stateType == 0xFF && state == 0xFF )
244         {
245                 print("Macro_layerLatch(layerIndex)");
246                 return;
247         }
248
249         // Only use capability on press
250         // TODO Analog
251         if ( stateType == 0x00 && state != 0x03 ) // Only on release
252                 return;
253
254         // Get layer index from arguments
255         // Cast pointer to uint8_t to uint16_t then access that memory location
256         uint16_t layer = *(uint16_t*)(&args[0]);
257
258         Macro_layerState( state, stateType, layer, 0x02 );
259 }
260
261
262 // Locks given layer
263 // Argument #1: Layer Index -> uint16_t
264 void Macro_layerLock_capability( uint8_t state, uint8_t stateType, uint8_t *args )
265 {
266         // Display capability name
267         if ( stateType == 0xFF && state == 0xFF )
268         {
269                 print("Macro_layerLock(layerIndex)");
270                 return;
271         }
272
273         // Only use capability on press
274         // TODO Analog
275         // XXX Could also be on release, but that's sorta dumb -HaaTa
276         if ( stateType == 0x00 && state != 0x01 ) // All normal key conditions except press
277                 return;
278
279         // Get layer index from arguments
280         // Cast pointer to uint8_t to uint16_t then access that memory location
281         uint16_t layer = *(uint16_t*)(&args[0]);
282
283         Macro_layerState( state, stateType, layer, 0x04 );
284 }
285
286
287 // Shifts given layer
288 // Argument #1: Layer Index -> uint16_t
289 void Macro_layerShift_capability( uint8_t state, uint8_t stateType, uint8_t *args )
290 {
291         // Display capability name
292         if ( stateType == 0xFF && state == 0xFF )
293         {
294                 print("Macro_layerShift(layerIndex)");
295                 return;
296         }
297
298         // Only use capability on press or release
299         // TODO Analog
300         if ( stateType == 0x00 && ( state == 0x00 || state == 0x02 ) ) // Only pass press or release conditions
301                 return;
302
303         // Get layer index from arguments
304         // Cast pointer to uint8_t to uint16_t then access that memory location
305         uint16_t layer = *(uint16_t*)(&args[0]);
306
307         Macro_layerState( state, stateType, layer, 0x01 );
308 }
309
310
311
312 // ----- Functions -----
313
314 // Looks up the trigger list for the given scan code (from the active layer)
315 // NOTE: Calling function must handle the NULL pointer case
316 nat_ptr_t *Macro_layerLookup( TriggerGuide *guide, uint8_t latch_expire )
317 {
318         uint8_t scanCode = guide->scanCode;
319
320         // TODO Analog
321         // If a normal key, and not pressed, do a layer cache lookup
322         if ( guide->type == 0x00 && guide->state != 0x01 )
323         {
324                 // Cached layer
325                 var_uint_t cachedLayer = macroTriggerListLayerCache[ scanCode ];
326
327                 // Lookup map, then layer
328                 nat_ptr_t **map = (nat_ptr_t**)LayerIndex[ cachedLayer ].triggerMap;
329                 const Layer *layer = &LayerIndex[ cachedLayer ];
330
331                 return map[ scanCode - layer->first ];
332         }
333
334         // If no trigger macro is defined at the given layer, fallthrough to the next layer
335         for ( uint16_t layerIndex = 0; layerIndex < macroLayerIndexStackSize; layerIndex++ )
336         {
337                 // Lookup Layer
338                 const Layer *layer = &LayerIndex[ macroLayerIndexStack[ layerIndex ] ];
339
340                 // Check if latch has been pressed for this layer
341                 // XXX Regardless of whether a key is found, the latch is removed on first lookup
342                 uint8_t latch = LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x02;
343                 if ( latch && latch_expire )
344                 {
345                         Macro_layerState( 0, 0, macroLayerIndexStack[ layerIndex ], 0x02 );
346                 }
347
348                 // Only use layer, if state is valid
349                 // XOR each of the state bits
350                 // If only two are enabled, do not use this state
351                 if ( (LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x01) ^ (latch>>1) ^ ((LayerState[ macroLayerIndexStack[ layerIndex ] ] & 0x04)>>2) )
352                 {
353                         // Lookup layer
354                         nat_ptr_t **map = (nat_ptr_t**)layer->triggerMap;
355
356                         // Determine if layer has key defined
357                         // Make sure scanCode is between layer first and last scancodes
358                         if ( map != 0
359                           && scanCode <= layer->last
360                           && scanCode >= layer->first
361                           && *map[ scanCode - layer->first ] != 0 )
362                         {
363                                 // Set the layer cache
364                                 macroTriggerListLayerCache[ scanCode ] = macroLayerIndexStack[ layerIndex ];
365
366                                 return map[ scanCode - layer->first ];
367                         }
368                 }
369         }
370
371         // Do lookup on default layer
372         nat_ptr_t **map = (nat_ptr_t**)LayerIndex[0].triggerMap;
373
374         // Lookup default layer
375         const Layer *layer = &LayerIndex[0];
376
377         // Make sure scanCode is between layer first and last scancodes
378         if ( map != 0
379           && scanCode <= layer->last
380           && scanCode >= layer->first
381           && *map[ scanCode - layer->first ] != 0 )
382         {
383                 // Set the layer cache to default map
384                 macroTriggerListLayerCache[ scanCode ] = 0;
385
386                 return map[ scanCode - layer->first ];
387         }
388
389         // Otherwise no defined Trigger Macro
390         erro_msg("Scan Code has no defined Trigger Macro: ");
391         printHex( scanCode );
392         return 0;
393 }
394
395
396 // Update the scancode using a list of TriggerGuides
397 // TODO Handle led state and analog
398 inline void Macro_triggerState( void *triggers, uint8_t num )
399 {
400         // Copy each of the TriggerGuides to the TriggerListBuffer
401         for ( uint8_t c = 0; c < num; c++ )
402                 macroTriggerListBuffer[ macroTriggerListBufferSize++ ] = ((TriggerGuide*)triggers)[ c ];
403 }
404
405
406 // Update the scancode key state
407 // States:
408 //   * 0x00 - Off
409 //   * 0x01 - Pressed
410 //   * 0x02 - Held
411 //   * 0x03 - Released
412 //   * 0x04 - Unpressed (this is currently ignored)
413 inline void Macro_keyState( uint8_t scanCode, uint8_t state )
414 {
415         // Only add to macro trigger list if one of three states
416         switch ( state )
417         {
418         case 0x01: // Pressed
419         case 0x02: // Held
420         case 0x03: // Released
421                 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
422                 macroTriggerListBuffer[ macroTriggerListBufferSize ].state    = state;
423                 macroTriggerListBuffer[ macroTriggerListBufferSize ].type     = 0x00; // Normal key
424                 macroTriggerListBufferSize++;
425                 break;
426         }
427 }
428
429
430 // Update the scancode analog state
431 // States:
432 //   * 0x00      - Off
433 //   * 0x01      - Released
434 //   * 0x02-0xFF - Analog value (low to high)
435 inline void Macro_analogState( uint8_t scanCode, uint8_t state )
436 {
437         // Only add to macro trigger list if non-off
438         if ( state != 0x00 )
439         {
440                 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = scanCode;
441                 macroTriggerListBuffer[ macroTriggerListBufferSize ].state    = state;
442                 macroTriggerListBuffer[ macroTriggerListBufferSize ].type     = 0x02; // Analog key
443                 macroTriggerListBufferSize++;
444         }
445 }
446
447
448 // Update led state
449 // States:
450 //   * 0x00 - Off
451 //   * 0x01 - On
452 inline void Macro_ledState( uint8_t ledCode, uint8_t state )
453 {
454         // Only add to macro trigger list if non-off
455         if ( state != 0x00 )
456         {
457                 macroTriggerListBuffer[ macroTriggerListBufferSize ].scanCode = ledCode;
458                 macroTriggerListBuffer[ macroTriggerListBufferSize ].state    = state;
459                 macroTriggerListBuffer[ macroTriggerListBufferSize ].type     = 0x01; // LED key
460                 macroTriggerListBufferSize++;
461         }
462 }
463
464
465 // Append result macro to pending list, checking for duplicates
466 // Do nothing if duplicate
467 inline void Macro_appendResultMacroToPendingList( const TriggerMacro *triggerMacro )
468 {
469         // Lookup result macro index
470         var_uint_t resultMacroIndex = triggerMacro->result;
471
472         // Iterate through result macro pending list, making sure this macro hasn't been added yet
473         for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
474         {
475                 // If duplicate found, do nothing
476                 if ( macroResultMacroPendingList[ macro ] == resultMacroIndex )
477                         return;
478         }
479
480         // No duplicates found, add to pending list
481         macroResultMacroPendingList[ macroResultMacroPendingListSize++ ] = resultMacroIndex;
482
483         // Lookup scanCode of the last key in the last combo
484         var_uint_t pos = 0;
485         for ( uint8_t comboLength = triggerMacro->guide[0]; comboLength > 0; )
486         {
487                 pos += TriggerGuideSize * comboLength + 1;
488                 comboLength = triggerMacro->guide[ pos ];
489         }
490
491         uint8_t scanCode = ((TriggerGuide*)&triggerMacro->guide[ pos - TriggerGuideSize ])->scanCode;
492
493         // Lookup scanCode in buffer list for the current state and stateType
494         for ( uint8_t keyIndex = 0; keyIndex < macroTriggerListBufferSize; keyIndex++ )
495         {
496                 if ( macroTriggerListBuffer[ keyIndex ].scanCode == scanCode )
497                 {
498                         ResultMacroRecordList[ resultMacroIndex ].state     = macroTriggerListBuffer[ keyIndex ].state;
499                         ResultMacroRecordList[ resultMacroIndex ].stateType = macroTriggerListBuffer[ keyIndex ].type;
500                 }
501         }
502
503         // Reset the macro position
504         ResultMacroRecordList[ resultMacroIndex ].pos = 0;
505 }
506
507
508 // Determine if long ResultMacro (more than 1 seqence element)
509 inline uint8_t Macro_isLongResultMacro( const ResultMacro *macro )
510 {
511         // Check the second sequence combo length
512         // If non-zero return non-zero (long sequence)
513         // 0 otherwise (short sequence)
514         var_uint_t position = 1;
515         for ( var_uint_t result = 0; result < macro->guide[0]; result++ )
516                 position += ResultGuideSize( (ResultGuide*)&macro->guide[ position ] );
517         return macro->guide[ position ];
518 }
519
520
521 // Determine if long TriggerMacro (more than 1 sequence element)
522 inline uint8_t Macro_isLongTriggerMacro( const TriggerMacro *macro )
523 {
524         // Check the second sequence combo length
525         // If non-zero return non-zero (long sequence)
526         // 0 otherwise (short sequence)
527         return macro->guide[ macro->guide[0] * TriggerGuideSize + 1 ];
528 }
529
530
531 // Votes on the given key vs. guide, short macros
532 inline TriggerMacroVote Macro_evalShortTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
533 {
534         // Depending on key type
535         switch ( guide->type )
536         {
537         // Normal State Type
538         case 0x00:
539                 // For short TriggerMacros completely ignore incorrect keys
540                 if ( guide->scanCode == key->scanCode )
541                 {
542                         switch ( key->state )
543                         {
544                         // Correct key, pressed, possible passing
545                         case 0x01:
546                                 return TriggerMacroVote_Pass;
547
548                         // Correct key, held, possible passing or release
549                         case 0x02:
550                                 return TriggerMacroVote_PassRelease;
551
552                         // Correct key, released, possible release
553                         case 0x03:
554                                 return TriggerMacroVote_Release;
555                         }
556                 }
557
558                 return TriggerMacroVote_DoNothing;
559
560         // LED State Type
561         case 0x01:
562                 erro_print("LED State Type - Not implemented...");
563                 break;
564
565         // Analog State Type
566         case 0x02:
567                 erro_print("Analog State Type - Not implemented...");
568                 break;
569
570         // Invalid State Type
571         default:
572                 erro_print("Invalid State Type. This is a bug.");
573                 break;
574         }
575
576         // XXX Shouldn't reach here
577         return TriggerMacroVote_Invalid;
578 }
579
580
581 // Votes on the given key vs. guide, long macros
582 // A long macro is defined as a guide with more than 1 combo
583 inline TriggerMacroVote Macro_evalLongTriggerMacroVote( TriggerGuide *key, TriggerGuide *guide )
584 {
585         // Depending on key type
586         switch ( guide->type )
587         {
588         // Normal State Type
589         case 0x00:
590                 // Depending on the state of the buffered key, make voting decision
591                 // Incorrect key
592                 if ( guide->scanCode != key->scanCode )
593                 {
594                         switch ( key->state )
595                         {
596                         // Wrong key, pressed, fail
597                         case 0x01:
598                                 return TriggerMacroVote_Fail;
599
600                         // Wrong key, held, do not pass (no effect)
601                         case 0x02:
602                                 return TriggerMacroVote_DoNothing;
603
604                         // Wrong key released, fail out if pos == 0
605                         case 0x03:
606                                 return TriggerMacroVote_DoNothing | TriggerMacroVote_DoNothingRelease;
607                         }
608                 }
609
610                 // Correct key
611                 else
612                 {
613                         switch ( key->state )
614                         {
615                         // Correct key, pressed, possible passing
616                         case 0x01:
617                                 return TriggerMacroVote_Pass;
618
619                         // Correct key, held, possible passing or release
620                         case 0x02:
621                                 return TriggerMacroVote_PassRelease;
622
623                         // Correct key, released, possible release
624                         case 0x03:
625                                 return TriggerMacroVote_Release;
626                         }
627                 }
628
629                 break;
630
631         // LED State Type
632         case 0x01:
633                 erro_print("LED State Type - Not implemented...");
634                 break;
635
636         // Analog State Type
637         case 0x02:
638                 erro_print("Analog State Type - Not implemented...");
639                 break;
640
641         // Invalid State Type
642         default:
643                 erro_print("Invalid State Type. This is a bug.");
644                 break;
645         }
646
647         // XXX Shouldn't reach here
648         return TriggerMacroVote_Invalid;
649 }
650
651
652 // Evaluate/Update TriggerMacro
653 TriggerMacroEval Macro_evalTriggerMacro( var_uint_t triggerMacroIndex )
654 {
655         // Lookup TriggerMacro
656         const TriggerMacro *macro = &TriggerMacroList[ triggerMacroIndex ];
657         TriggerMacroRecord *record = &TriggerMacroRecordList[ triggerMacroIndex ];
658
659         // Check if macro has finished and should be incremented sequence elements
660         if ( record->state == TriggerMacro_Release )
661         {
662                 record->state = TriggerMacro_Waiting;
663                 record->pos = record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1;
664         }
665
666         // Current Macro position
667         var_uint_t pos = record->pos;
668
669         // Length of the combo being processed
670         uint8_t comboLength = macro->guide[ pos ] * TriggerGuideSize;
671
672         // If no combo items are left, remove the TriggerMacro from the pending list
673         if ( comboLength == 0 )
674         {
675                 return TriggerMacroEval_Remove;
676         }
677
678         // Check if this is a long Trigger Macro
679         uint8_t longMacro = Macro_isLongTriggerMacro( macro );
680
681         // Iterate through the items in the combo, voting the on the key state
682         // If any of the pressed keys do not match, fail the macro
683         //
684         // The macro is waiting for input when in the TriggerMacro_Waiting state
685         // Once all keys have been pressed/held (only those keys), entered TriggerMacro_Press state (passing)
686         // Transition to the next combo (if it exists) when a single key is released (TriggerMacro_Release state)
687         // On scan after position increment, change to TriggerMacro_Waiting state
688         // TODO Add support for system LED states (NumLock, CapsLock, etc.)
689         // TODO Add support for analog key states
690         // TODO Add support for 0x00 Key state (not pressing a key, not all that useful in general)
691         // TODO Add support for Press/Hold/Release differentiation when evaluating (not sure if useful)
692         TriggerMacroVote overallVote = TriggerMacroVote_Invalid;
693         for ( uint8_t comboItem = pos + 1; comboItem < pos + comboLength + 1; comboItem += TriggerGuideSize )
694         {
695                 // Assign TriggerGuide element (key type, state and scancode)
696                 TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ comboItem ]);
697
698                 TriggerMacroVote vote = TriggerMacroVote_Invalid;
699                 // Iterate through the key buffer, comparing to each key in the combo
700                 for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
701                 {
702                         // Lookup key information
703                         TriggerGuide *keyInfo = &macroTriggerListBuffer[ key ];
704
705                         // If vote is a pass (>= 0x08, no more keys in the combo need to be looked at)
706                         // Also mask all of the non-passing votes
707                         vote |= longMacro
708                                 ? Macro_evalLongTriggerMacroVote( keyInfo, guide )
709                                 : Macro_evalShortTriggerMacroVote( keyInfo, guide );
710                         if ( vote >= TriggerMacroVote_Pass )
711                         {
712                                 vote &= TriggerMacroVote_Release | TriggerMacroVote_PassRelease | TriggerMacroVote_Pass;
713                                 break;
714                         }
715                 }
716
717                 // If no pass vote was found after scanning all of the keys
718                 // Fail the combo, if this is a short macro (long macros already will have a fail vote)
719                 if ( !longMacro && vote < TriggerMacroVote_Pass )
720                         vote |= TriggerMacroVote_Fail;
721
722                 // After voting, append to overall vote
723                 overallVote |= vote;
724         }
725
726         // If no pass vote was found after scanning the entire combo
727         // And this is the first position in the combo, just remove it (nothing important happened)
728         if ( longMacro && overallVote & TriggerMacroVote_DoNothingRelease && pos == 0 )
729                 overallVote |= TriggerMacroVote_Fail;
730
731         // Decide new state of macro after voting
732         // Fail macro, remove from pending list
733         if ( overallVote & TriggerMacroVote_Fail )
734         {
735                 return TriggerMacroEval_Remove;
736         }
737         // Do nothing, incorrect key is being held or released
738         else if ( overallVote & TriggerMacroVote_DoNothing && longMacro )
739         {
740                 // Just doing nothing :)
741         }
742         // If ready for transition and in Press state, set to Waiting and increment combo position
743         // Position is incremented (and possibly remove the macro from the pending list) on the next iteration
744         else if ( overallVote & TriggerMacroVote_Release && record->state == TriggerMacro_Press )
745         {
746                 record->state = TriggerMacro_Release;
747
748                 // If this is the last combo in the sequence, remove from the pending list
749                 if ( macro->guide[ record->pos + macro->guide[ record->pos ] * TriggerGuideSize + 1 ] == 0 )
750                         return TriggerMacroEval_DoResultAndRemove;
751         }
752         // If passing and in Waiting state, set macro state to Press
753         else if ( overallVote & TriggerMacroVote_Pass
754              && ( record->state == TriggerMacro_Waiting || record->state == TriggerMacro_Press ) )
755         {
756                 record->state = TriggerMacro_Press;
757
758                 // If in press state, and this is the final combo, send request for ResultMacro
759                 // Check to see if the result macro only has a single element
760                 // If this result macro has more than 1 key, only send once
761                 // TODO Add option to have long macro repeat rate
762                 if ( macro->guide[ pos + comboLength + 1 ] == 0 )
763                 {
764                         // Long result macro (more than 1 combo)
765                         if ( Macro_isLongResultMacro( &ResultMacroList[ macro->result ] ) )
766                         {
767                                 // Only ever trigger result once, on press
768                                 if ( overallVote == TriggerMacroVote_Pass )
769                                 {
770                                         return TriggerMacroEval_DoResultAndRemove;
771                                 }
772                         }
773                         // Short result macro
774                         else
775                         {
776                                 // Only trigger result once, on press, if long trigger (more than 1 combo)
777                                 if ( Macro_isLongTriggerMacro( macro ) )
778                                 {
779                                         return TriggerMacroEval_DoResultAndRemove;
780                                 }
781                                 // Otherwise, trigger result continuously
782                                 else
783                                 {
784                                         return TriggerMacroEval_DoResult;
785                                 }
786                         }
787                 }
788         }
789         // Otherwise, just remove the macro on key release
790         // One more result has to be called to indicate to the ResultMacro that the key transitioned to the release state
791         else if ( overallVote & TriggerMacroVote_Release )
792         {
793                 return TriggerMacroEval_DoResultAndRemove;
794         }
795
796         // If this is a short macro, just remove it
797         // The state can be rebuilt on the next iteration
798         if ( !longMacro )
799                 return TriggerMacroEval_Remove;
800
801         return TriggerMacroEval_DoNothing;
802 }
803
804
805 // Evaluate/Update ResultMacro
806 inline ResultMacroEval Macro_evalResultMacro( var_uint_t resultMacroIndex )
807 {
808         // Lookup ResultMacro
809         const ResultMacro *macro = &ResultMacroList[ resultMacroIndex ];
810         ResultMacroRecord *record = &ResultMacroRecordList[ resultMacroIndex ];
811
812         // Current Macro position
813         var_uint_t pos = record->pos;
814
815         // Length of combo being processed
816         uint8_t comboLength = macro->guide[ pos ];
817
818         // Function Counter, used to keep track of the combo items processed
819         var_uint_t funcCount = 0;
820
821         // Combo Item Position within the guide
822         var_uint_t comboItem = pos + 1;
823
824         // Iterate through the Result Combo
825         while ( funcCount < comboLength )
826         {
827                 // Assign TriggerGuide element (key type, state and scancode)
828                 ResultGuide *guide = (ResultGuide*)(&macro->guide[ comboItem ]);
829
830                 // Do lookup on capability function
831                 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
832
833                 // Call capability
834                 capability( record->state, record->stateType, &guide->args );
835
836                 // Increment counters
837                 funcCount++;
838                 comboItem += ResultGuideSize( (ResultGuide*)(&macro->guide[ comboItem ]) );
839         }
840
841         // Move to next item in the sequence
842         record->pos = comboItem;
843
844         // If the ResultMacro is finished, remove
845         if ( macro->guide[ comboItem ] == 0 )
846         {
847                 record->pos = 0;
848                 return ResultMacroEval_Remove;
849         }
850
851         // Otherwise leave the macro in the list
852         return ResultMacroEval_DoNothing;
853 }
854
855
856 // Update pending trigger list
857 inline void Macro_updateTriggerMacroPendingList()
858 {
859         // Iterate over the macroTriggerListBuffer to add any new Trigger Macros to the pending list
860         for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
861         {
862                 // TODO LED States
863                 // TODO Analog Switches
864                 // Only add TriggerMacro to pending list if key was pressed (not held, released or off)
865                 if ( macroTriggerListBuffer[ key ].state == 0x00 && macroTriggerListBuffer[ key ].state != 0x01 )
866                         continue;
867
868                 // TODO Analog
869                 // If this is a release case, indicate to layer lookup for possible latch expiry
870                 uint8_t latch_expire = macroTriggerListBuffer[ key ].state == 0x03;
871
872                 // Lookup Trigger List
873                 nat_ptr_t *triggerList = Macro_layerLookup( &macroTriggerListBuffer[ key ], latch_expire );
874
875                 // Number of Triggers in list
876                 nat_ptr_t triggerListSize = triggerList[0];
877
878                 // Iterate over triggerList to see if any TriggerMacros need to be added
879                 // First item is the number of items in the TriggerList
880                 for ( var_uint_t macro = 1; macro < triggerListSize + 1; macro++ )
881                 {
882                         // Lookup trigger macro index
883                         var_uint_t triggerMacroIndex = triggerList[ macro ];
884
885                         // Iterate over macroTriggerMacroPendingList to see if any macro in the scancode's
886                         //  triggerList needs to be added
887                         var_uint_t pending = 0;
888                         for ( ; pending < macroTriggerMacroPendingListSize; pending++ )
889                         {
890                                 // Stop scanning if the trigger macro index is found in the pending list
891                                 if ( macroTriggerMacroPendingList[ pending ] == triggerMacroIndex )
892                                         break;
893                         }
894
895                         // If the triggerMacroIndex (macro) was not found in the macroTriggerMacroPendingList
896                         // Add it to the list
897                         if ( pending == macroTriggerMacroPendingListSize )
898                         {
899                                 macroTriggerMacroPendingList[ macroTriggerMacroPendingListSize++ ] = triggerMacroIndex;
900
901                                 // Reset macro position
902                                 TriggerMacroRecordList[ triggerMacroIndex ].pos   = 0;
903                                 TriggerMacroRecordList[ triggerMacroIndex ].state = TriggerMacro_Waiting;
904                         }
905                 }
906         }
907 }
908
909
910 // Macro Procesing Loop
911 // Called once per USB buffer send
912 inline void Macro_process()
913 {
914         // Only do one round of macro processing between Output Module timer sends
915         if ( USBKeys_Sent != 0 )
916                 return;
917
918         // If the pause flag is set, only process if the step counter is non-zero
919         if ( macroPauseMode )
920         {
921                 if ( macroStepCounter == 0 )
922                         return;
923
924                 // Proceed, decrementing the step counter
925                 macroStepCounter--;
926                 dbug_print("Macro Step");
927         }
928
929         // Update pending trigger list, before processing TriggerMacros
930         Macro_updateTriggerMacroPendingList();
931
932         // Tail pointer for macroTriggerMacroPendingList
933         // Macros must be explicitly re-added
934         var_uint_t macroTriggerMacroPendingListTail = 0;
935
936         // Iterate through the pending TriggerMacros, processing each of them
937         for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
938         {
939                 switch ( Macro_evalTriggerMacro( macroTriggerMacroPendingList[ macro ] ) )
940                 {
941                 // Trigger Result Macro (purposely falling through)
942                 case TriggerMacroEval_DoResult:
943                         // Append ResultMacro to PendingList
944                         Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
945
946                 default:
947                         macroTriggerMacroPendingList[ macroTriggerMacroPendingListTail++ ] = macroTriggerMacroPendingList[ macro ];
948                         break;
949
950                 // Trigger Result Macro and Remove (purposely falling through)
951                 case TriggerMacroEval_DoResultAndRemove:
952                         // Append ResultMacro to PendingList
953                         Macro_appendResultMacroToPendingList( &TriggerMacroList[ macroTriggerMacroPendingList[ macro ] ] );
954
955                 // Remove Macro from Pending List, nothing to do, removing by default
956                 case TriggerMacroEval_Remove:
957                         break;
958                 }
959         }
960
961         // Update the macroTriggerMacroPendingListSize with the tail pointer
962         macroTriggerMacroPendingListSize = macroTriggerMacroPendingListTail;
963
964
965         // Tail pointer for macroResultMacroPendingList
966         // Macros must be explicitly re-added
967         var_uint_t macroResultMacroPendingListTail = 0;
968
969         // Iterate through the pending ResultMacros, processing each of them
970         for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
971         {
972                 switch ( Macro_evalResultMacro( macroResultMacroPendingList[ macro ] ) )
973                 {
974                 // Re-add macros to pending list
975                 case ResultMacroEval_DoNothing:
976                 default:
977                         macroResultMacroPendingList[ macroResultMacroPendingListTail++ ] = macroResultMacroPendingList[ macro ];
978                         break;
979
980                 // Remove Macro from Pending List, nothing to do, removing by default
981                 case ResultMacroEval_Remove:
982                         break;
983                 }
984         }
985
986         // Update the macroResultMacroPendingListSize with the tail pointer
987         macroResultMacroPendingListSize = macroResultMacroPendingListTail;
988
989         // Signal buffer that we've used it
990         Scan_finishedWithMacro( macroTriggerListBufferSize );
991
992         // Reset TriggerList buffer
993         macroTriggerListBufferSize = 0;
994
995         // If Macro debug mode is set, clear the USB Buffer
996         if ( macroDebugMode )
997         {
998                 USBKeys_Modifiers = 0;
999                 USBKeys_Sent = 0;
1000         }
1001 }
1002
1003
1004 inline void Macro_setup()
1005 {
1006         // Register Macro CLI dictionary
1007         CLI_registerDictionary( macroCLIDict, macroCLIDictName );
1008
1009         // Disable Macro debug mode
1010         macroDebugMode = 0;
1011
1012         // Disable Macro pause flag
1013         macroPauseMode = 0;
1014
1015         // Set Macro step counter to zero
1016         macroStepCounter = 0;
1017
1018         // Make sure macro trigger buffer is empty
1019         macroTriggerListBufferSize = 0;
1020
1021         // Initialize TriggerMacro states
1022         for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1023         {
1024                 TriggerMacroRecordList[ macro ].pos   = 0;
1025                 TriggerMacroRecordList[ macro ].state = TriggerMacro_Waiting;
1026         }
1027
1028         // Initialize ResultMacro states
1029         for ( var_uint_t macro = 0; macro < ResultMacroNum; macro++ )
1030         {
1031                 ResultMacroRecordList[ macro ].pos       = 0;
1032                 ResultMacroRecordList[ macro ].state     = 0;
1033                 ResultMacroRecordList[ macro ].stateType = 0;
1034         }
1035 }
1036
1037
1038 // ----- CLI Command Functions -----
1039
1040 void cliFunc_capList( char* args )
1041 {
1042         print( NL );
1043         info_msg("Capabilities List ");
1044         printHex( CapabilitiesNum );
1045
1046         // Iterate through all of the capabilities and display them
1047         for ( var_uint_t cap = 0; cap < CapabilitiesNum; cap++ )
1048         {
1049                 print( NL "\t" );
1050                 printHex( cap );
1051                 print(" - ");
1052
1053                 // Display/Lookup Capability Name (utilize debug mode of capability)
1054                 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1055                 capability( 0xFF, 0xFF, 0 );
1056         }
1057 }
1058
1059 void cliFunc_capSelect( char* args )
1060 {
1061         // Parse code from argument
1062         char* curArgs;
1063         char* arg1Ptr;
1064         char* arg2Ptr = args;
1065
1066         // Total number of args to scan (must do a lookup if a keyboard capability is selected)
1067         var_uint_t totalArgs = 2; // Always at least two args
1068         var_uint_t cap = 0;
1069
1070         // Arguments used for keyboard capability function
1071         var_uint_t argSetCount = 0;
1072         uint8_t *argSet = (uint8_t*)args;
1073
1074         // Process all args
1075         for ( var_uint_t c = 0; argSetCount < totalArgs; c++ )
1076         {
1077                 curArgs = arg2Ptr;
1078                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1079
1080                 // Stop processing args if no more are found
1081                 // Extra arguments are ignored
1082                 if ( *arg1Ptr == '\0' )
1083                         break;
1084
1085                 // For the first argument, choose the capability
1086                 if ( c == 0 ) switch ( arg1Ptr[0] )
1087                 {
1088                 // Keyboard Capability
1089                 case 'K':
1090                         // Determine capability index
1091                         cap = numToInt( &arg1Ptr[1] );
1092
1093                         // Lookup the number of args
1094                         totalArgs += CapabilitiesList[ cap ].argCount;
1095                         continue;
1096                 }
1097
1098                 // Because allocating memory isn't doable, and the argument count is arbitrary
1099                 // The argument pointer is repurposed as the argument list (much smaller anyways)
1100                 argSet[ argSetCount++ ] = (uint8_t)numToInt( arg1Ptr );
1101
1102                 // Once all the arguments are prepared, call the keyboard capability function
1103                 if ( argSetCount == totalArgs )
1104                 {
1105                         // Indicate that the capability was called
1106                         print( NL );
1107                         info_msg("K");
1108                         printInt8( cap );
1109                         print(" - ");
1110                         printHex( argSet[0] );
1111                         print(" - ");
1112                         printHex( argSet[1] );
1113                         print(" - ");
1114                         printHex( argSet[2] );
1115                         print( "..." NL );
1116
1117                         void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ cap ].func);
1118                         capability( argSet[0], argSet[1], &argSet[2] );
1119                 }
1120         }
1121 }
1122
1123 void cliFunc_keyHold( char* args )
1124 {
1125         // Parse codes from arguments
1126         char* curArgs;
1127         char* arg1Ptr;
1128         char* arg2Ptr = args;
1129
1130         // Process all args
1131         for ( ;; )
1132         {
1133                 curArgs = arg2Ptr;
1134                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1135
1136                 // Stop processing args if no more are found
1137                 if ( *arg1Ptr == '\0' )
1138                         break;
1139
1140                 // Ignore non-Scancode numbers
1141                 switch ( arg1Ptr[0] )
1142                 {
1143                 // Scancode
1144                 case 'S':
1145                         Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x02 ); // Hold scancode
1146                         break;
1147                 }
1148         }
1149 }
1150
1151 void cliFunc_keyPress( char* args )
1152 {
1153         // Parse codes from arguments
1154         char* curArgs;
1155         char* arg1Ptr;
1156         char* arg2Ptr = args;
1157
1158         // Process all args
1159         for ( ;; )
1160         {
1161                 curArgs = arg2Ptr;
1162                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1163
1164                 // Stop processing args if no more are found
1165                 if ( *arg1Ptr == '\0' )
1166                         break;
1167
1168                 // Ignore non-Scancode numbers
1169                 switch ( arg1Ptr[0] )
1170                 {
1171                 // Scancode
1172                 case 'S':
1173                         Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x01 ); // Press scancode
1174                         break;
1175                 }
1176         }
1177 }
1178
1179 void cliFunc_keyRelease( char* args )
1180 {
1181         // Parse codes from arguments
1182         char* curArgs;
1183         char* arg1Ptr;
1184         char* arg2Ptr = args;
1185
1186         // Process all args
1187         for ( ;; )
1188         {
1189                 curArgs = arg2Ptr;
1190                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1191
1192                 // Stop processing args if no more are found
1193                 if ( *arg1Ptr == '\0' )
1194                         break;
1195
1196                 // Ignore non-Scancode numbers
1197                 switch ( arg1Ptr[0] )
1198                 {
1199                 // Scancode
1200                 case 'S':
1201                         Macro_keyState( (uint8_t)numToInt( &arg1Ptr[1] ), 0x03 ); // Release scancode
1202                         break;
1203                 }
1204         }
1205 }
1206
1207 void cliFunc_layerList( char* args )
1208 {
1209         print( NL );
1210         info_msg("Layer List");
1211
1212         // Iterate through all of the layers and display them
1213         for ( uint16_t layer = 0; layer < LayerNum; layer++ )
1214         {
1215                 print( NL "\t" );
1216                 printHex( layer );
1217                 print(" - ");
1218
1219                 // Display layer name
1220                 dPrint( (char*)LayerIndex[ layer ].name );
1221
1222                 // Default map
1223                 if ( layer == 0 )
1224                         print(" \033[1m(default)\033[0m");
1225
1226                 // Layer State
1227                 print( NL "\t\t Layer State: " );
1228                 printHex( LayerState[ layer ] );
1229
1230                 // First -> Last Indices
1231                 print(" First -> Last Indices: ");
1232                 printHex( LayerIndex[ layer ].first );
1233                 print(" -> ");
1234                 printHex( LayerIndex[ layer ].last );
1235         }
1236 }
1237
1238 void cliFunc_layerState( char* args )
1239 {
1240         // Parse codes from arguments
1241         char* curArgs;
1242         char* arg1Ptr;
1243         char* arg2Ptr = args;
1244
1245         uint8_t arg1 = 0;
1246         uint8_t arg2 = 0;
1247
1248         // Process first two args
1249         for ( uint8_t c = 0; c < 2; c++ )
1250         {
1251                 curArgs = arg2Ptr;
1252                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1253
1254                 // Stop processing args if no more are found
1255                 if ( *arg1Ptr == '\0' )
1256                         break;
1257
1258                 switch ( c )
1259                 {
1260                 // First argument (e.g. L1)
1261                 case 0:
1262                         if ( arg1Ptr[0] != 'L' )
1263                                 return;
1264
1265                         arg1 = (uint8_t)numToInt( &arg1Ptr[1] );
1266                         break;
1267                 // Second argument (e.g. 4)
1268                 case 1:
1269                         arg2 = (uint8_t)numToInt( arg1Ptr );
1270
1271                         // Display operation (to indicate that it worked)
1272                         print( NL );
1273                         info_msg("Setting Layer L");
1274                         printInt8( arg1 );
1275                         print(" to - ");
1276                         printHex( arg2 );
1277
1278                         // Set the layer state
1279                         LayerState[ arg1 ] = arg2;
1280                         break;
1281                 }
1282         }
1283 }
1284
1285 void cliFunc_macroDebug( char* args )
1286 {
1287         // Toggle macro debug mode
1288         macroDebugMode = macroDebugMode ? 0 : 1;
1289
1290         print( NL );
1291         info_msg("Macro Debug Mode: ");
1292         printInt8( macroDebugMode );
1293 }
1294
1295 void cliFunc_macroList( char* args )
1296 {
1297         // Show pending key events
1298         print( NL );
1299         info_msg("Pending Key Events: ");
1300         printInt16( (uint16_t)macroTriggerListBufferSize );
1301         print(" : ");
1302         for ( uint8_t key = 0; key < macroTriggerListBufferSize; key++ )
1303         {
1304                 printHex( macroTriggerListBuffer[ key ].scanCode );
1305                 print(" ");
1306         }
1307
1308         // Show pending trigger macros
1309         print( NL );
1310         info_msg("Pending Trigger Macros: ");
1311         printInt16( (uint16_t)macroTriggerMacroPendingListSize );
1312         print(" : ");
1313         for ( var_uint_t macro = 0; macro < macroTriggerMacroPendingListSize; macro++ )
1314         {
1315                 printHex( macroTriggerMacroPendingList[ macro ] );
1316                 print(" ");
1317         }
1318
1319         // Show pending result macros
1320         print( NL );
1321         info_msg("Pending Result Macros: ");
1322         printInt16( (uint16_t)macroResultMacroPendingListSize );
1323         print(" : ");
1324         for ( var_uint_t macro = 0; macro < macroResultMacroPendingListSize; macro++ )
1325         {
1326                 printHex( macroResultMacroPendingList[ macro ] );
1327                 print(" ");
1328         }
1329
1330         // Show available trigger macro indices
1331         print( NL );
1332         info_msg("Trigger Macros Range: T0 -> T");
1333         printInt16( (uint16_t)TriggerMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1334
1335         // Show available result macro indices
1336         print( NL );
1337         info_msg("Result  Macros Range: R0 -> R");
1338         printInt16( (uint16_t)ResultMacroNum - 1 ); // Hopefully large enough :P (can't assume 32-bit)
1339
1340         // Show Trigger to Result Macro Links
1341         print( NL );
1342         info_msg("Trigger : Result Macro Pairs");
1343         for ( var_uint_t macro = 0; macro < TriggerMacroNum; macro++ )
1344         {
1345                 print( NL );
1346                 print("\tT");
1347                 printInt16( (uint16_t)macro ); // Hopefully large enough :P (can't assume 32-bit)
1348                 print(" : R");
1349                 printInt16( (uint16_t)TriggerMacroList[ macro ].result ); // Hopefully large enough :P (can't assume 32-bit)
1350         }
1351 }
1352
1353 void cliFunc_macroProc( char* args )
1354 {
1355         // Toggle macro pause mode
1356         macroPauseMode = macroPauseMode ? 0 : 1;
1357
1358         print( NL );
1359         info_msg("Macro Processing Mode: ");
1360         printInt8( macroPauseMode );
1361 }
1362
1363 void macroDebugShowTrigger( var_uint_t index )
1364 {
1365         // Only proceed if the macro exists
1366         if ( index >= TriggerMacroNum )
1367                 return;
1368
1369         // Trigger Macro Show
1370         const TriggerMacro *macro = &TriggerMacroList[ index ];
1371         TriggerMacroRecord *record = &TriggerMacroRecordList[ index ];
1372
1373         print( NL );
1374         info_msg("Trigger Macro Index: ");
1375         printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1376         print( NL );
1377
1378         // Read the comboLength for combo in the sequence (sequence of combos)
1379         var_uint_t pos = 0;
1380         uint8_t comboLength = macro->guide[ pos ];
1381
1382         // Iterate through and interpret the guide
1383         while ( comboLength != 0 )
1384         {
1385                 // Initial position of the combo
1386                 var_uint_t comboPos = ++pos;
1387
1388                 // Iterate through the combo
1389                 while ( pos < comboLength * TriggerGuideSize + comboPos )
1390                 {
1391                         // Assign TriggerGuide element (key type, state and scancode)
1392                         TriggerGuide *guide = (TriggerGuide*)(&macro->guide[ pos ]);
1393
1394                         // Display guide information about trigger key
1395                         printHex( guide->scanCode );
1396                         print("|");
1397                         printHex( guide->type );
1398                         print("|");
1399                         printHex( guide->state );
1400
1401                         // Increment position
1402                         pos += TriggerGuideSize;
1403
1404                         // Only show combo separator if there are combos left in the sequence element
1405                         if ( pos < comboLength * TriggerGuideSize + comboPos )
1406                                 print("+");
1407                 }
1408
1409                 // Read the next comboLength
1410                 comboLength = macro->guide[ pos ];
1411
1412                 // Only show sequence separator if there is another combo to process
1413                 if ( comboLength != 0 )
1414                         print(";");
1415         }
1416
1417         // Display current position
1418         print( NL "Position: " );
1419         printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1420
1421         // Display result macro index
1422         print( NL "Result Macro Index: " );
1423         printInt16( (uint16_t)macro->result ); // Hopefully large enough :P (can't assume 32-bit)
1424
1425         // Display trigger macro state
1426         print( NL "Trigger Macro State: " );
1427         switch ( record->state )
1428         {
1429         case TriggerMacro_Press:   print("Press");   break;
1430         case TriggerMacro_Release: print("Release"); break;
1431         case TriggerMacro_Waiting: print("Waiting"); break;
1432         }
1433 }
1434
1435 void macroDebugShowResult( var_uint_t index )
1436 {
1437         // Only proceed if the macro exists
1438         if ( index >= ResultMacroNum )
1439                 return;
1440
1441         // Trigger Macro Show
1442         const ResultMacro *macro = &ResultMacroList[ index ];
1443         ResultMacroRecord *record = &ResultMacroRecordList[ index ];
1444
1445         print( NL );
1446         info_msg("Result Macro Index: ");
1447         printInt16( (uint16_t)index ); // Hopefully large enough :P (can't assume 32-bit)
1448         print( NL );
1449
1450         // Read the comboLength for combo in the sequence (sequence of combos)
1451         var_uint_t pos = 0;
1452         uint8_t comboLength = macro->guide[ pos++ ];
1453
1454         // Iterate through and interpret the guide
1455         while ( comboLength != 0 )
1456         {
1457                 // Function Counter, used to keep track of the combos processed
1458                 var_uint_t funcCount = 0;
1459
1460                 // Iterate through the combo
1461                 while ( funcCount < comboLength )
1462                 {
1463                         // Assign TriggerGuide element (key type, state and scancode)
1464                         ResultGuide *guide = (ResultGuide*)(&macro->guide[ pos ]);
1465
1466                         // Display Function Index
1467                         printHex( guide->index );
1468                         print("|");
1469
1470                         // Display Function Ptr Address
1471                         printHex( (nat_ptr_t)CapabilitiesList[ guide->index ].func );
1472                         print("|");
1473
1474                         // Display/Lookup Capability Name (utilize debug mode of capability)
1475                         void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(CapabilitiesList[ guide->index ].func);
1476                         capability( 0xFF, 0xFF, 0 );
1477
1478                         // Display Argument(s)
1479                         print("(");
1480                         for ( var_uint_t arg = 0; arg < CapabilitiesList[ guide->index ].argCount; arg++ )
1481                         {
1482                                 // Arguments are only 8 bit values
1483                                 printHex( (&guide->args)[ arg ] );
1484
1485                                 // Only show arg separator if there are args left
1486                                 if ( arg + 1 < CapabilitiesList[ guide->index ].argCount )
1487                                         print(",");
1488                         }
1489                         print(")");
1490
1491                         // Increment position
1492                         pos += ResultGuideSize( guide );
1493
1494                         // Increment function count
1495                         funcCount++;
1496
1497                         // Only show combo separator if there are combos left in the sequence element
1498                         if ( funcCount < comboLength )
1499                                 print("+");
1500                 }
1501
1502                 // Read the next comboLength
1503                 comboLength = macro->guide[ pos++ ];
1504
1505                 // Only show sequence separator if there is another combo to process
1506                 if ( comboLength != 0 )
1507                         print(";");
1508         }
1509
1510         // Display current position
1511         print( NL "Position: " );
1512         printInt16( (uint16_t)record->pos ); // Hopefully large enough :P (can't assume 32-bit)
1513
1514         // Display final trigger state/type
1515         print( NL "Final Trigger State (State/Type): " );
1516         printHex( record->state );
1517         print("/");
1518         printHex( record->stateType );
1519 }
1520
1521 void cliFunc_macroShow( char* args )
1522 {
1523         // Parse codes from arguments
1524         char* curArgs;
1525         char* arg1Ptr;
1526         char* arg2Ptr = args;
1527
1528         // Process all args
1529         for ( ;; )
1530         {
1531                 curArgs = arg2Ptr;
1532                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1533
1534                 // Stop processing args if no more are found
1535                 if ( *arg1Ptr == '\0' )
1536                         break;
1537
1538                 // Ignore invalid codes
1539                 switch ( arg1Ptr[0] )
1540                 {
1541                 // Indexed Trigger Macro
1542                 case 'T':
1543                         macroDebugShowTrigger( numToInt( &arg1Ptr[1] ) );
1544                         break;
1545                 // Indexed Result Macro
1546                 case 'R':
1547                         macroDebugShowResult( numToInt( &arg1Ptr[1] ) );
1548                         break;
1549                 }
1550         }
1551 }
1552
1553 void cliFunc_macroStep( char* args )
1554 {
1555         // Parse number from argument
1556         //  NOTE: Only first argument is used
1557         char* arg1Ptr;
1558         char* arg2Ptr;
1559         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1560
1561         // Default to 1, if no argument given
1562         var_uint_t count = (var_uint_t)numToInt( arg1Ptr );
1563
1564         if ( count == 0 )
1565                 count = 1;
1566
1567         // Set the macro step counter, negative int's are cast to uint
1568         macroStepCounter = count;
1569 }
1570