-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeyChord.ahk
1364 lines (1239 loc) · 46.4 KB
/
KeyChord.ahk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires AutoHotKey v2.0
/**
* KeyChord.ahk
*
* @version 1.5
* @author Komrad Toast (komrad.toast@hotmail.com)
* @see https://autohotkey.com/boards/viewtopic.php?f=83&t=131037
* @license
* Copyright (c) 2024 Tyler J. Colby (Komrad Toast)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/
/**
* Represents an action that can be executed as part of a KeyChord.
* ___
* A KCAction encapsulates a key, a command, an optional condition that must be met in order to
* execute the command, and an optional short description of what the KCAction does.
* ___
* @constructor `KCAction(key, command, condition?, description?)`
* @property {String} Key The key that must be pressed in order to execute the command.
* @property {KeyChord|Action|String|Integer|Float|Number|Func|BoundFunc|Closure|Enumerator} Command The command to be executed when the Action is executed.
* @property {Boolean|String|Integer|Float|Number|Func|BoundFunc|Closure|Enumerator} [Condition=True] The condition that must be met in order to execute the command. Defaults to `True`.
* @property {String} [Description="Description not set."] The description of what the Action does. Defaults to "Description not set.".
* @method `Execute()`: `Void` Executes the command if the condition is met.
* @method `ToString()`: `String` Returns a string representation of the Action.
* @method `Equals(action)`: `Boolean` Returns `True` if the specified object is equal to this Action.
* @method `EqualsStaticObject(object)`: `Boolean` Returns `True` if the specified object is equivalent to a KCAction.
**/
class KCAction
{
/**
* Returns the key in a more readable format. Like `Ctrl+Win`, instead of `^#`
*
* ```
* action := KCAction("^#a", "Test command", True, "Test description")
* MsgBox(action.ReadableKey) ; This will display "Ctrl+Win+a"
* ```
* ___
* @returns {String} The key in a readable format.
**/
ReadableKey
{
get
{
replacements := Map("<", "L", ">", "R", "+", "Shift+", "^", "Ctrl+", "!", "Alt+", "#", "Win+")
return RegExReplace(this.Key, "([<>+^!#])", "ReplaceModifier")
}
}
Key := ""
Command := () => ""
Condition := True
Description := ""
/**
* Creates a new KCAction instance.
*
* ```
* action := KCAction("a", "Test command", True, "Test description")
* ```
* ___
* @param {String} key The key associated with this action.
* @param {KeyChord|Action|String|Integer|Float|Number|Func|BoundFunc|Closure|Enumerator} command The command to be executed when `key` is pressed.
* @param {Any} condition The condition to evaluate before executing. Must evaluate to true to execute the command.
* @param {String} description A description of the action.
**/
__New(key, command, condition := True, description := "Description not set.")
{
if !(Type(key) == "String" and key != "")
throw ValueError("Key must be a non-empty String", -1, "Key: " Type(key))
this.Key := key
switch Type(command)
{
case "KeyChord", "String", "Integer", "Number", "Float", "Func", "BoundFunc", "Closure", "Enumerator":
this.Command := command
default: ; Array, Buffer, Error, File, Gui, InputHoot, Map, Menu, RegexMapInfo, VarRef, ComValue, any other custom class, or any other object
throw ValueError("Command must be or evaluate to a KeyChord, String, Integer, Number, Float, KeyChord, Func, BoundFunc, Closure, or Enumerator", -1, "Command: " Type(command))
}
switch Type(condition)
{
case "String", "Integer", "Number", "Float", "Func", "BoundFunc", "Closure", "Enumerator":
this.Condition := condition
default: ; Array, Buffer, Error, File, Gui, InputHoot, Map, Menu, RegexMapInfo, VarRef, ComValue, any other custom class, or any other object
throw ValueError("Condition must be or evaluate to a String, Integer, Number, Float, KeyChord, Func, BoundFunc, Closure, or Enumerator", -1, "Condition: " Type(condition))
}
if (IsSet(description) and Type(description) == "String")
this.Description := description
else if !(Type(description) == "String")
throw ValueError("Description must be or evaluate to a String", -1, "Description: " Type(description))
return
}
/**
* Callout function for use in the `ReadableKey` property.
* Added for compatibility with AHK versions >= 2.0.
* ___
* Replaces modifier symbols with their corresponding key names.
* @param {string} match - The matched modifier symbol.
* @param {string} _ - Unused parameter.
* @param {string} __ - Unused parameter.
* @returns {string} The key name corresponding to the modifier symbol.
**/
ReplaceModifier(m, _, __)
{
static replacements := Map("<", "Left", ">", "Right", "+", "Shift", "^", "Ctrl", "!", "Alt", "#", "Win")
return replacements[m]
}
/**
* Checks if the action's condition is true.
*
* ```
* action := KCAction("a", "Test command", True, "Test description")
*
* if action.IsTrue()
* MsgBox("The condition is true") ; This will display
* ```
* ___
* @param {Any} value The value to check (defaults to the action's condition).
* @returns {Boolean} True if the condition is true, False otherwise.
**/
IsTrue(value := this.Condition)
{
switch Type(value)
{
case "Boolean":
return ((value) ? True : False)
case "String":
return ((value != "") ? True : False)
case "Integer", "Float", "Number":
return ((value != 0) ? True : False)
case "Func", "BoundFunc", "Closure", "Enumerator":
return this.IsTrue(value.Call())
default: ; Array, Buffer, Error, File, Gui, InputHoot, Map, Menu, RegexMapInfo, VarRef, ComValue, any other custom class, or any other object
throw ValueError("Condition must be or evaluate to a Boolean, String, Integer, Float, Number, Func, BoundFunc, Closure, or Enumerator", -1, "Condition: " Type(value))
}
}
/**
* Executes the action if its condition is true.
*
* ```
* action := KCAction("a", "Test command", True, "Test description") ; The condition is true
* action.Execute() ; This will execute the command ("Test command" will be sent as text to the active window)
* ```
* ___
* @param {Number} timeout The timeout for execution.
* @param {String} parent_key The parent key string.
**/
Execute(timeout, parent_key)
{
if this.IsTrue()
{
switch Type(this.Command)
{
Case "KeyChord":
return KCManager.Execute(this.Command, , timeout, parent_key)
Case "String", "Integer", "Boolean", "Number", "Float":
Send(this.Command)
return parent_key
Case "Func", "BoundFunc", "Closure", "Enumerator":
this.Command.Call()
return parent_key
Default: ; Array, Buffer, Error, File, Gui, InputHoot, Map, Menu, RegexMapInfo, VarRef, ComValue, any other custom class, or any other object
throw ValueError("Command must be a KeyChord, String, Integer, Boolean, Number, Float, Func, BoundFunc, Closure, or Enumerator", -1, "Command: " Type(this.Command))
}
}
}
/**
* Returns a string representation of the KCAction.
*
* ```
* action := KCAction("a", "Test command", True, "Test description")
* MsgBox(action.ToString())
* ```
* ___
* @returns {String} A string describing the KCAction.
**/
ToString(indent := "")
{
switch Type(this.Command)
{
case "String", "Integer", "Number", "Float":
command := this.Command
case "KeyChord", "Func", "BoundFunc", "Closure", "Enumerator":
command := Type(this.Command)
default: ; Array, Buffer, Error, File, Gui, InputHoot, Map, Menu, RegexMapInfo, VarRef, ComValue, any other custom class, or any other object
command := Type(this.Command)
}
switch Type(this.Condition)
{
case "String", "Integer", "Number", "Float", "Boolean":
condition := (this.Condition ? "True" : "False")
case "Func", "BoundFunc", "Closure", "Enumerator":
condition := (this.Condition.Call() ? "True" : "False")
default: ; Array, Buffer, Error, File, Gui, InputHoot, Map, Menu, RegexMapInfo, VarRef, ComValue, any other custom class, or any other object
condition := Type(this.Condition)
}
out_str := "`n" indent ";------------------------------;"
out_str .= "`n" indent "Key := `"" this.ReadableKey "`""
out_str .= "`n" indent "Command := `"" command "`""
out_str .= "`n" indent "Condition := " condition
out_str .= "`n" indent "Description := `"" this.Description "`""
if (this.Command is KeyChord)
{
out_str .= this.Command.ToString(indent . "`t")
}
return out_str
}
/**
* Compares this `KCAction` with another for equality. All four properties must be _exactly_ the same on both `KCActions`.
*
* ```
* action1 := KCAction("a", "Test command", True, "Test description")
* action2 := KCAction("a", "Test command", True, "Test description")
* action3 := KCAction("a", "Test command", True, "I'm different!")
*
* if (action1.Equals(action2))
* MsgBox("action1 is equal to action2") ; This will execute
*
* if (action1.Equals(action3))
* MsgBox("action1 is equal to action3") ; This won't execute
*
* ```
* ___
* @param {KCAction} other - The other KCAction to compare with.
* @returns {Boolean} True if the actions are equal, False otherwise.
**/
Equals(action)
{
return this.Key == action.Key
and this.Command == action.Command
and this.Condition == action.Condition
and this.Description == action.Description
}
/**
* Checks if an object is equivalent to a KCAction.
* The object in question must have a Key and Command property to be considered "Equal" to a KCAction.
*
* ```
* testObj = { Key: "a", Command: "Test command" }
*
* if (KCAction.EqualsObject(testObj))
* MsgBox("testObj is equivalent to a KCAction")
* ```
* ___
* @param {Object} obj - The object to check.
* @returns {Boolean} True if the object is equivalent to a KCAction, False otherwise.
**/
static EqualsObject(obj)
{
if (obj is Object)
if obj.HasOwnProp("Key") and obj.HasOwnProp("Command")
return True
return False
}
}
; Credit to nperovic on GitHub for the "MouseHook.ahk" script
; that inspired and heavily influenced the KCInputHook class.
; https://github.com/nperovic/MouseHook
/**
* An input hook that captures keyboard and mouse input.
*
* ```ahk2
* kcHook := KCInputHook() ; Create an instance of KCInputHook
* loop
* {
* kcHook.Start() ; Start the KCInputHook
* Result := kcHook.Wait(5000) ; Wait 5 seconds for user input
* kcHook.Stop() ; Stop the KCInputHook
* MsgBox(result) ; Display the result
* } until (Result == "Escape") ; Exit the loop if the user presses the Escape key
* ```
* ___
* @constructor `KCInputHook()`
* @property {String} Result The result of the input hook (includes modifiers).
* @property {String} Modifiers The modifiers that were pressed.
* @property {Boolean} IsCapturing Whether the input hook is currently capturing input.
**/
class KCInputHook
{
_mouseLLHook := 0
_mouseLLProc := 0
_keyboardLLHook := 0
_keyboardLLProc := 0
Result := ""
Modifiers := ""
IsCapturing := False
/**
* Starts the KCInputHook capturing
*/
Start()
{
Sleep(300) ; Sleep to give any keys that were pressed time to reset.
this._mouseLLProc := CallbackCreate(this._mouseLLFunc.Bind(this), "F", 3)
this._keyboardLLProc := CallbackCreate(this._keyboardLLFunc.Bind(this), "F", 3)
this._mouseLLHook := DllCall("SetWindowsHookEx", "Int", 14, "Ptr", this._mouseLLProc, "Ptr", 0, "UInt", 0, "Ptr")
this._keyboardLLHook := DllCall("SetWindowsHookEx", "Int", 13, "Ptr", this._keyboardLLProc, "Ptr", 0, "UInt", 0, "Ptr")
this.IsCapturing := True
}
/**
* Stops and resets the KCInputHook
*/
Stop()
{
this.IsCapturing := False
if (this._mouseLLHook)
DllCall("UnhookWindowsHookEx", "Ptr", this._mouseLLHook)
if (this._keyboardLLHook)
DllCall("UnhookWindowsHookEx", "Ptr", this._keyboardLLHook)
if (this._mouseLLProc)
CallbackFree(this._mouseLLProc)
if (this._keyboardLLProc)
CallbackFree(this._keyboardLLProc)
this.Clear()
}
/**
* Makes sure all variables are reset
*/
Clear()
{
this._mouseLLHook := 0
this._mouseLLProc := 0
this._keyboardLLHook := 0
this._keyboardLLProc := 0
this.Result := ""
this.Modifiers := ""
this.IsCapturing := False
}
/**
* Low-Level Mouse Function
* @param nCode
* @param wParam
* @param lParam
* @returns {Integer | Float | String}
*/
_mouseLLFunc(nCode, wParam, lParam)
{
if (nCode >= 0 && this.IsCapturing)
{
mouseData := NumGet(lParam + 8, "Int")
switch wParam
{
case 0x0201: this.Result := "LButton"
case 0x0204: this.Result := "RButton"
case 0x0207: this.Result := "MButton"
case 0x020B:
xButton := (mouseData >> 16) & 0xFFFF
this.Result := xButton == 1 ? "XButton1" : "XButton2"
case 0x020A: this.Result := mouseData > 0 ? "WheelUp" : "WheelDown"
case 0x020E: this.Result := mouseData > 0 ? "WheelRight" : "WheelLeft"
}
if (this.Result != "")
{
return 1 ; Block the event
}
}
return DllCall("CallNextHookEx", "Ptr", 0, "Int", nCode, "Ptr", wParam, "Ptr", lParam, "Ptr")
}
/**
* Low-Level Keyboard function
* @param nCode
* @param wParam
* @param lParam
* @returns {Integer | Float | String}
*/
_keyboardLLFunc(nCode, wParam, lParam)
{
if (nCode >= 0 && this.IsCapturing)
{
vk := NumGet(lParam + 0, "UChar")
sc := NumGet(lParam + 4, "UShort")
key := GetKeyName(Format("vk{:x}sc{:x}", vk, sc))
if (this.IsModifierKey(key))
{
if (wParam == 0x100 || wParam == 0x104) ; WM_KEYDOWN or WM_SYSKEYDOWN
{
this.UpdateModifiers(key, True)
}
else if (wParam == 0x101 || wParam == 0x105) ; WM_KEYUP or WM_SYSKEYUP
{
this.UpdateModifiers(key, False)
}
}
else
{
if (wParam == 0x100 || wParam == 0x104) ; WM_KEYDOWN or WM_SYSKEYDOWN
{
this.Result := key
}
else if (wParam == 0x101 || wParam == 0x105) ; WM_KEYUP or WM_SYSKEYUP
{
this.Result := ""
}
}
return 1 ; Block the event
}
return DllCall("CallNextHookEx", "Ptr", 0, "Int", nCode, "Ptr", wParam, "Ptr", lParam, "Ptr")
}
/**
* Checks whether a given key is a modifier key
* @param key The key to check
* @returns {Integer}
*/
IsModifierKey(key)
{
static modifierKeys := ["LControl", "RControl", "LAlt", "RAlt", "LShift", "RShift", "LWin", "RWin"]
for _key in modifierKeys
if (key == _key)
return True
return False
}
/**
* Updates the active modifiers
* @param key The modifier to update
* @param isKeyDown Whether the key is being pressed or released
*/
UpdateModifiers(key, isKeyDown)
{
modMap := Map(
"LControl", "<^", "RControl", ">^",
"LAlt", "<!", "RAlt", ">!",
"LShift", "<+", "RShift", ">+",
"LWin", "<#", "RWin", ">#"
)
if (isKeyDown)
{
if (!InStr(this.Modifiers, modMap[key]))
this.Modifiers .= modMap[key]
}
else
{
this.Modifiers := StrReplace(this.Modifiers, modMap[key], "")
}
}
/**
* Wait for input and return captured keys / mouse buttons
* @param {Number} timeout How long the KCInputHook should wait for input in milliseconds. Default is -1 for indefinite.
* @returns {String}
*/
Wait(timeout := -1)
{
startTime := A_TickCount
loop
{
if (timeout > 0 && A_TickCount - startTime > timeout)
{
this.IsCapturing := False
return "Timeout"
}
if (this.Result != "")
{
finalResult := this.Modifiers . this.Result
this.Result := ""
this.IsCapturing := False
return finalResult
}
Sleep(10)
}
}
}
/**
* KeyChord class
* This class provides a way to map keys to commands or nested key Chords.
* It allows for executing commands or nested key Chords based on user input.
*
* @constructor `KeyChord(timeout?)`
* @property {Boolean} [RemindKeys=True] Whether to remind the user of the keys in the KeyChord.
* @property {Integer} Length The number of actions in the KeyChord.
* @method `Execute()`: `Void` Execute the chord.
**/
class KeyChord
{
RemindKeys := True
/**
* Gets the number of actions in the KeyChord.
* @returns {Integer} The number of actions.
**/
Length => this._keyList.Length
/**
* Initializes a new instance of the KeyChord class
* @param {KCAction} args* (Optional) A list of KCAction objects to add to the KeyChord.
**/
__New(actions*)
{
this._keyList := []
this._commandList := []
this._conditionList := []
this._descriptionList := []
for action in actions
this.AddActions(action)
}
/**
* Gets or Sets an Item in the KeyChord.
* @param name The key to get the value of.
* @returns {KCAction} The action associated with the key
**/
__Item[name]
{
get
{
if (name is String)
name := this.FirstIndexOf(name)
else if not (name is Integer)
throw ValueError("Invalid key type. Must be String or Integer", -1, "name: " Type(name))
else if (name < 1) or (name > this.Length)
throw ValueError("Index out of range", -1, "name: " name)
return KCAction(this._keyList[name], this._commandList[name], this._conditionList[name], this._descriptionList[name])
}
set
{
if !this._keyList.Has(name)
{
this._keyList.Push(value.Key)
this._commandList.Push(value.Command)
this._conditionList.Push(value.Condition)
this._descriptionList.Push(value.Description)
}
}
}
/**
* Gets an Enumerator for the KeyChord.
* Credit goes to Descolada, who made a forum post that really cleared up the way "__Enum" works for me.
* @param {Integer} num The number of elements to return.
* @returns {Func} A closure that returns the requested number of elements.
**/
__Enum(num)
{
i := 0
len := this._keyList.Length
; KCAction object
one(&x)
{
if ++i > len
return False
x := KCAction(this._keyList[i], this._commandList[i], this._conditionList[i], this._descriptionList[i])
return True
}
; Index, Key
two(&x?, &y?)
{
if ++i > len
return False
x := i
y := this._keyList[i]
return True
}
; Index, Key, Command
three(&x?, &y?, &z?)
{
if ++i > len
return False
x := i
y := this._keyList[i]
z := this._commandList[i]
return True
}
; Index, Key, Command, Condition
four(&w?, &x?, &y?, &z?)
{
if ++i > len
return False
w := i
x := this._keyList[i]
y := this._commandList[i]
z := this._conditionList[i]
return True
}
; Index, Key, Command, Condition, Description
five(&v?, &w?, &x?, &y?, &z?)
{
if ++i > len
return False
v := i
w := this._keyList[i]
x := this._commandList[i]
y := this._conditionList[i]
z := this._descriptionList[i]
return True
}
switch (num)
{
case 1 : return one
case 2 : return two
case 3 : return three
case 4 : return four
case 5 : return five
default: return Error("Invalid number of elements requested")
}
}
/**
* Adds one or more KCAction objects to the KeyChord.
* @param {KCAction[]} actions* - The KCAction objects to add.
**/
AddActions(actions*)
{
for action in actions
{
if (action is KCAction) or (KCAction.EqualsObject(action))
{
if !this._keyList.Has(action.Key)
{
this._keyList.Push(action.Key)
this._commandList.Push(action.Command)
if action.HasOwnProp("Condition")
this._conditionList.Push(action.Condition)
else
this._conditionList.Push(True)
if action.HasOwnProp("Description")
this._descriptionList.Push(action.Description)
else
this._descriptionList.Push("Description not set.")
}
else
throw ValueError("Key already exists", -1, "key: " action.Key)
}
else
throw ValueError("Argument is not, or is not convertible to, a KCAction", -1, "action: " Type(action))
}
}
/**
* Sets a key-action pair in the KeyChord
* @param {String} key The key which the user will press to execute `action`
* @param {Any} action The action to execute when the user presses `key`
* @param {String} [description="Description not set."] A description of the action
* @param {String} [condition=True] A condition to evaluate before executing the action
**/
Set(key, action, condition := True, description := "Description not set.")
{
if !this._keyList.Has(key)
{
this._keyList.Push(key)
this._commandList.Push(action)
this._conditionList.Push(condition)
this._descriptionList.Push(description)
}
else
{
index := this.FirstIndexOf(key)
this._commandList[index] := action
this._conditionList[index] := condition
this._descriptionList[index] := description
}
}
/**
* Gets a `KCAction` from the KeyChord, given a key
* @param {String} key The key to get the action for
* @returns {KCAction}
**/
Get(key)
{
index := this.FirstIndexOf(key)
if this.Has(key)
{
return KCAction(this._keyList[index],
this._commandList[index],
this._conditionList[index],
this._descriptionList[index])
}
else
{
throw ValueError("Key not found", -1, "key: " key)
}
}
/**
* Checks if the KeyChord contains a key
* @param {String} key The key to check for
* @returns {Boolean}
**/
Has(key)
{
unsidedKey := RegExReplace(key, "(<|>)*", "")
for ,k in this._keyList
if KeyChord.MatchKey(k, key) or KeyChord.MatchKey(k, unsidedKey)
return True
return False
}
/**
* Removes an action by key.
* @param {String} key - The key of the action to remove.
**/
Remove(key)
{
if this.Has(key)
{
index := this.FirstIndexOf(key)
this._keyList.RemoveAt(index)
this._commandList.RemoveAt(index)
this._conditionList.RemoveAt(index)
this._descriptionList.RemoveAt(index)
}
}
/**
* Removes all actions from the KeyChord.
**/
Clear()
{
this._keyList.Clear()
this._commandList.Clear()
this._conditionList.Clear()
this._descriptionList.Clear()
}
/**
* Merges this KeyChord with another KeyChord.
* @param {KeyChord} otherKeyChord - The KeyChord to merge with.
* @returns {KeyChord} A new KeyChord containing the merged actions.
**/
Merge(keychords*)
{
for chord in keychords
for action in chord
this.AddActions(action)
return this
}
/**
* Returns a new KeyChord with actions sorted alphabetically by key.
* @returns {KeyChord} A new KeyChord with sorted actions.
**/
SortByKey()
{
sortedKeyChord := KeyChord()
sortedKeys := this._keyList.Clone()
sortedKeys.Sort()
for key in sortedKeys
sortedKeyChord.AddActions(this.Get(key))
return sortedKeyChord
}
/**
* Validates all actions in the KeyChord.
*
* ```
* testChord := KeyChord( ... ) ; Build Your KeyChord
* if !testChord.ValidateAll()
* MsgBox("Invalid KeyChord")
* ```
*
* @returns {Boolean} True if all actions are valid, False otherwise.
**/
ValidateAll()
{
for action in this
{
if !(action is KCAction)
return false
if !action.Key or !action.Command
return false
}
return true
}
/**
* Creates a deep copy of the KeyChord. Includes all Nested chords.
* @returns {KeyChord} A new KeyChord with copied actions.
**/
Clone()
{
newKeyChord := KeyChord()
for action in this
{
newCommand := action.Command is KeyChord ? action.Command.Clone() : action.Command
newAction := KCAction(action.Key, newCommand, action.Condition, action.Description)
newKeyChord.AddActions(newAction)
}
return newKeyChord
}
/**
* Finds indexes of actions that match a given comparison function.
*
* For example, the `FirstIndexOf()` method uses this function to find the first occurrence of a key:
* ```
* FirstIndexOf(key) => this.FindIndexes((action) => action.Key == key)[1]
* ```
*
* @param {Function} comparisonFunc A function that takes an action and returns true if it matches the criteria.
* @returns {Array} An array of indexes where matching actions are found.
**/
FindIndexes(comparisonFunc)
{
indexes := []
for action in this
if comparisonFunc(action)
indexes.Push(A_Index)
return indexes
}
/**
* Finds the index of the first occurrence of a key.
* @param {String} key The key to search for.
* @returns {Integer} The index of the first occurrence of the key, or 0 if not found.
**/
FirstIndexOf(key) => this.FindIndexes((action) => action.Key == key)[1]
/**
* Finds the index of the last occurrence of a key.
* @param {String} key The key to search for.
* @returns {Integer} The index of the last occurrence of the key, or 0 if not found.
**/
LastIndexOf(key) => this.FindIndexes((action) => action.Key == key)[-1]
/**
* Finds all indexes of a key.
* @param {String} key The key to search for.
* @returns {Array} An array of all indexes where the key is found.
**/
AllIndexesOf(key) => this.FindIndexes((action) => action.Key == key)
/**
* Transforms the KeyChord by applying a function to each action.
* @param {Function} func - The function to apply to each action.
* @param {Boolean} [filterMode=false] - If true, filters out actions for which func returns false.
* @returns {KeyChord} A new KeyChord with transformed actions.
*
* Mapping Example:
* ```ahk2
* ; Appends "!!" to the end of the description of every action in the KeyChord
* newKeyChord = keyChord.Transform((action) => ( action.Description .= "!!", return action ))
*
* ; Sets every action's condition to False
* newKeyChord = keyChord.Transform((action) => ( action.Condition := False, return action ))
* ```
* Filtering example:
* ```ahk2
* ; Filters out actions with key "Esc"
* filteredKeyChord = keyChord.Transform(action => action.Key != "Esc", true)
*
* ; Returns only the actions whos conditions are True
* filteredKeyChord = keyChord.Transform(action => action.IsTrue(), true)
*
* ; Returns only the actions whos Commands are of the type "String"
* filteredKeyChord = keyChord.Transform(action => (action.Command is "String"), true)
* ```
**/
Transform(func, filterMode := false)
{
newKeyChord := KeyChord()
for action in this
{
if (filterMode)
{
if (func(action))
newKeyChord.AddActions(action)
}
else
{
newAction := func(action)
if (newAction is KCAction)
newKeyChord.AddActions(newAction)
else
throw ValueError("Transform function must return a KCAction object when not in filter mode")
}
}
return newKeyChord
}
/**
* Finds all actions with true conditions for a given key.
*
* @param {String} key The key to search for.
* @returns {KeyChord} The matching actions.
**/
FindTrue(key) => this.Transform((action) => ((action.Key == key) or (action.Key == RegExReplace(key, "(<|>)*", ""))) and action.IsTrue(), True)
/**
* Finds the first action with a true condition for a given key.
*
* @param {String} key - The key to match.
* @returns {KCAction|undefined} The first matching action, or undefined if none found.
**/
FirstTrue(key)
{
result := this.FindTrue(key)
if result.Length > 0
return result[1]
else
KCManager.TimedToolTip("Error: Key not found.`nKey: " key, 3)
}
/**
* Finds the last action with a true condition for a given key.
*
* @param {String} key - The key to match.
* @returns {KCAction|undefined} The last matching action, or undefined if none found.
**/
LastTrue(key)
{
result := this.FindTrue(key)
if result.Length > 0
return result[-1]
else
KCManager.TimedToolTip("Error: Key not found.`nKey: " key, 3)
}
/**
* Returns all commands of a specific type.
*
* ```
* testChord := KeyChord( ... )
* commands := testChord.GetCommandsByType("String")
* for command in commands
* MsgBox(command)
* ```
*
* @param {String} type - The type of commands to return.
* @returns {Array} An array of commands of the specified type.
*/
GetCommandsByType(type) => this.Transform((action) => (action.Command is type), True)
/**
* Returns a string representation of the KeyChord, including nested KeyChords.
*
* ```
* chord := KeyChord(KCAction("a", "Test command", True, "Test description"), KCAction("b", "Test command", True, "Test description"))
* MsgBox(chord.ToString())
* ```
*
* @param {String} [indent=""] The indentation string for formatting nested structures.
* @returns {String} A formatted string representation of the KeyChord.
**/
ToString(indent := "")
{
out_str := ""