-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUCR.ahk
2113 lines (1886 loc) · 63.3 KB
/
UCR.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
#SingleInstance force
#include Libraries\JSON.ahk
OutputDebug DBGVIEWCLEAR
SetBatchLines, -1
global UCR ; set UCR as a super-global
new UCRMain()
return
; ======================================================================== MAIN CLASS ===============================================================
Class UCRMain {
Version := "0.0.2" ; The version of the main application
SettingsVersion := "0.0.1" ; The version of the settings file format
_StateNames := {0: "Normal", 1: "InputBind", 2: "GameBind"}
_State := {Normal: 0, InputBind: 1, GameBind: 2}
_GameBindDuration := 0 ; The amount of time to wait in GameBind mode (ms)
_CurrentState := 0 ; The current state of the application
Profiles := [] ; A name-indexed array of instances of _Profile objects
Libraries := {} ; A name indexed array of instances of library objects
CurrentProfile := 0 ; Points to an Instance of the _Profile class which is the current active profile
PluginList := [] ; A list of plugin Types (Lookup to PluginDetails), indexed by order of Plugin Select DDL
PluginDetails := {} ; A name-indexed list of plugin Details (Classname, Description etc). Name is ".Type" property of class
PLUGIN_WIDTH := 680 ; The Width of a plugin
PLUGIN_FRAME_WIDTH := 720 ; The width of the app
TOP_PANEL_HEIGHT := 75 ; The amount of space reserved for the top panel (profile select etc)
GUI_MIN_HEIGHT := 300 ; The minimum height of the app. Required because of the way AHK_H autosize/pos works
CurrentSize := {w: this.PLUGIN_FRAME_WIDTH, h: this.GUI_MIN_HEIGHT} ; The current size of the app.
CurrentPos := {x: "", y: ""} ; The current position of the app.
__New(){
global UCR := this ; Set super-global UCR to point to class instance
Gui +HwndHwnd
this.hwnd := hwnd
str := A_ScriptName
if (A_IsCompiled)
str := StrSplit(str, ".exe")
else
str := StrSplit(str, ".ahk")
this._SettingsFile := A_ScriptDir "\" str.1 ".ini"
; Load the Joystick OEM name DLL
#DllImport,joystick_OEM_name,%A_ScriptDir%\Resources\JoystickOEMName.dll\joystick_OEM_name,double,,CDecl AStr
;~ DllCall("LoadLibrary", Str, A_ScriptDir "\Resources\JoystickOEMName.dll")
;~ if (ErrorLevel != 0){
;~ MsgBox Error Loading \Resources\JoystickOEMName.dll. Exiting...
;~ ExitApp
;~ }
; Provide a common repository of libraries for plugins (vJoy, HID libs etc)
this._LoadLibraries()
; Start the input detection system
this._BindModeHandler := new _BindModeHandler()
this._InputHandler := new _InputHandler()
; Create the Main Gui
this._CreateGui()
; Watch window position and size using MessageFilter thread
this._MessageFilterThread := AhkThread(A_ScriptDir "\Threads\MessageFilterThread.ahk",,1)
While !this._MessageFilterThread.ahkgetvar.autoexecute_done
Sleep 50 ; wait until variable has been set.
fn := this._OnSize.Bind(this)
this._OnSizeCallback := fn ; make sure boundfunc does not go out of scope - the other thread needs it
matchobj := {msg: 0x5, hwnd: this.hwnd}
filterobj := {hwnd: this.hwnd}
this._MessageFilterThread.ahkExec["new MessageFilter(" &fn "," &matchobj "," &filterobj ")"]
matchobj.msg := 0x3
fn := this._OnMove.Bind(this)
this._OnMoveCallback := fn
this._MessageFilterThread.ahkExec["new MessageFilter(" &fn "," &matchobj "," &filterobj ")"]
; Load settings. This will cause all plugins to load.
p := this._LoadSettings()
this._UpdateProfileSelect()
this._ShowGui()
this.Profiles.Global._Activate()
this.ChangeProfile(p, 0)
; Now we have settings from disk, move the window to it's last position and size
}
GuiClose(hwnd){
if (hwnd = this.hwnd)
ExitApp
}
; Libraries can be used to easily add functionality to UCR.
; Place a folder in the Libraries folder eg "MyLib", with an ahk file of the same name (eg "MyLib.ahk") and it will be included.
; It should contain a class definition of the same name (eg "Class MyLib") which will be instantiated and added to the Libraries array
; Once instantiated, the method _UCR_LoadLibrary() will be called on the instance. It has the opportunity to return 1 for OK, 0 for fail
; The class instance will be available for all plugins as UCR.Libraries.MyLib
_LoadLibraries(){
Loop, Files, % A_ScriptDir "\Libraries\*.*", D
{
str := A_LoopFileName
filename := A_ScriptDir "\Libraries\" A_LoopFileName "\" A_LoopFileName ".ahk"
if (FileExist(filename)){
AddFile(filename, 1)
lib := new %A_LoopFileName%()
res := lib._UCR_LoadLibrary()
if (res == 1)
this.Libraries[A_LoopFileName] := lib
}
}
}
_CreateGui(){
Gui, % this.hwnd ":Margin", 0, 0
Gui, % this.hwnd ":+Resize"
Gui, % this.hwnd ":Show", % "Hide w" UCR.PLUGIN_FRAME_WIDTH " h" UCR.GUI_MIN_HEIGHT, % "UCR - Universal Control Remapper v" this.Version
Gui, % this.hwnd ":+Minsize" UCR.PLUGIN_FRAME_WIDTH "x" UCR.GUI_MIN_HEIGHT
Gui, % this.hwnd ":+Maxsize" UCR.PLUGIN_FRAME_WIDTH
Gui, new, HwndHwnd
this.hTopPanel := hwnd
Gui % this.hTopPanel ":-Border"
;Gui % this.hTopPanel ":Show", % "x0 y0 w" UCR.PLUGIN_FRAME_WIDTH " h" UCR.TOP_PANEL_HEIGHT, Main UCR Window
; Profile Select DDL
Gui, % this.hTopPanel ":Add", Text, xm y+10, Current Profile:
Gui, % this.hTopPanel ":Add", DDL, % "x100 yp-5 hwndhProfileSelect w" UCR.PLUGIN_FRAME_WIDTH - 335
this.hProfileSelect := hProfileSelect
fn := this._ProfileSelectChanged.Bind(this)
GuiControl % this.hTopPanel ":+g", % this.hProfileSelect, % fn
Gui, % this.hTopPanel ":Add", Button, % "hwndhAddProfile x+5 yp-1 w50", Add
this.hAddProfile := hAddProfile
fn := this._AddProfile.Bind(this)
GuiControl % this.hTopPanel ":+g", % this.hAddProfile, % fn
Gui, % this.hTopPanel ":Add", Button, % "hwndhDeleteProfile x+5 yp w50", Delete
this.hDeleteProfile := hDeleteProfile
fn := this._DeleteProfile.Bind(this)
GuiControl % this.hTopPanel ":+g", % this.hDeleteProfile, % fn
Gui, % this.hTopPanel ":Add", Button, % "hwndhRenameProfile x+5 yp w50 disabled", Rename
this.hRenameProfile := hRenameProfile
fn := this._RenameProfile.Bind(this)
GuiControl % this.hTopPanel ":+g", % this.hRenameProfile, % fn
Gui, % this.hTopPanel ":Add", Button, % "hwndhCopyProfile x+5 yp w50 disabled", Copy
this.hCopyProfile := hCopyProfile
fn := this._CopyProfile.Bind(this)
GuiControl % this.hTopPanel ":+g", % this.hCopyProfile, % fn
; Add Plugin
Gui, % this.hTopPanel ":Add", Text, xm y+10, Plugin Selection:
Gui, % this.hTopPanel ":Add", DDL, % "x100 yp-5 hwndhPluginSelect AltSubmit w" UCR.PLUGIN_FRAME_WIDTH - 150
this.hPluginSelect := hPluginSelect
Gui, % this.hTopPanel ":Add", Button, % "hwndhAddPlugin x+5 yp-1", Add
this.hAddPlugin := hAddPlugin
fn := this._AddPlugin.Bind(this)
GuiControl % this.hTopPanel ":+g", % this.hAddPlugin, % fn
Gui, % this.hwnd ":Add", Gui, % "w" UCR.PLUGIN_FRAME_WIDTH " h" UCR.TOP_PANEL_HEIGHT, % this.hTopPanel
;Gui, % this.hwnd ":Show"
}
_ShowGui(){
xy := (this.CurrentPos.x != "" && this.CurrentPos.y != "" ? "x" this.CurrentPos.x " y" this.CurrentPos.y : "")
Gui, % this.hwnd ":Show", % xy " h" this.CurrentSize.h
}
_OnMove(wParam, lParam, msg, hwnd){
;this.CurrentPos := {x: LoWord(lParam), y: HiWord(lParam)}
; Use WinGetPos rather than pos in message, as this is the top left of the Gui, not the client rect
WinGetPos, x, y, , , % "ahk_id " this.hwnd
if (x != "" && y != ""){
this.CurrentPos := {x: x, y: y}
this._SaveSettings()
}
}
_OnSize(wParam, lParam, msg, hwnd){
this.CurrentSize.h := HiWord(lParam)
this._SaveSettings()
}
; Called when hProfileSelect changes through user interaction (They selected a new profile)
_ProfileSelectChanged(){
GuiControlGet, name, % this.hTopPanel ":", % this.hProfileSelect
this.ChangeProfile(name)
}
; The user clicked the "Add Plugin" button
_AddPlugin(){
this.CurrentProfile._AddPlugin()
}
; We wish to change profile. This may happen due to user input, or application changing
ChangeProfile(name, save := 1){
if (!ObjHasKey(this.Profiles, name))
return 0
OutputDebug % "Changing Profile from " this.CurrentProfile.Name " to: " name
if (IsObject(this.CurrentProfile)){
if (name = this.CurrentProfile.Name)
return 1
this.CurrentProfile._Hide()
if (!this.CurrentProfile._IsGlobal)
this.CurrentProfile._DeActivate()
}
GuiControl, % this.hTopPanel ":ChooseString", % this.hProfileSelect, % name
this.CurrentProfile := this.Profiles[name]
this.CurrentProfile._Activate()
this.CurrentProfile._Show()
if (save){
this._ProfileChanged(this.CurrentProfile)
}
return 1
}
; Populate hProfileSelect with a list of available profiles
_UpdateProfileSelect(){
profiles := ["Global", "Default"]
;profiles := ["Default"]
for profile in this.Profiles {
if (profile = "Default" || profile = "Global")
continue
profiles.push(profile)
}
str := "|"
max := profiles.length()
Loop % max {
if (A_Index > 1)
str .= "|"
name := this.Profiles[profiles[A_Index]].Name
str .= name
if (name = this.CurrentProfile.Name)
str .= "|"
if (A_Index = max)
str .= "|"
}
GuiControl, % this.hTopPanel ":", % this.hProfileSelect, % str
}
; Update hPluginSelect with a list of available Plugins
_UpdatePluginSelect(){
this.PluginList := []
str := ""
i := 1
for type, obj in this.PluginDetails {
if (i > 1)
str .= "|"
str .= type " - " obj.Description
this.PluginList.push(type)
if (i == 1){
str .= "|"
}
i++
}
GuiControl, % this.hTopPanel ":", % this.hPluginSelect, % str
}
; User clicked add new profile button
_AddProfile(){
name := this._GetUniqueName()
if (name = 0)
return
this.Profiles[name] := new _Profile(name)
this._UpdateProfileSelect()
this.ChangeProfile(Name)
}
; user clicked the Delete Profile button
_DeleteProfile(){
GuiControlGet, name, % this.hTopPanel ":", % this.hProfileSelect
if (name = "Default" || name = "Global")
return
this.Profiles.Delete(name)
this._UpdateProfileSelect()
this.ChangeProfile("Default")
}
_RenameProfile(){
}
_CopyProfile(){
}
; Load a list of available plugins
_LoadPluginList(){
Loop, Files, % A_ScriptDir "\Plugins\*.ahk", FR
{
FileRead,plugincode,% A_LoopFileFullPath
RegExMatch(plugincode,"i)class\s+(\w+)\s+extends\s+_Plugin",classname)
; Check if the classname already exists.
if (IsObject(%classname1%)){
cls := %classname1%
if (cls.base.__Class = "_Plugin"){
; Existing class extends plugin
; Class has been included via other means (eg to debug it), so do not try to include again.
continue
}
}
dllthread := AhkThread("#NoTrayIcon`ntest := new " classname1 "()`ntype := test.type, description := test.description, autoexecute_done := 1`nLoop {`nsleep 10`n}`nclass _Plugin {`n}`n" plugincode)
t := A_TickCount + 1000
While !(autoexecute_done := dllthread.ahkgetvar.autoexecute_done) && A_TickCount < t
Sleep 10
if (autoexecute_done){
Type := dllthread.ahkgetvar.Type
Description := dllthread.ahkgetvar.Description
}
ahkthread_free(dllthread)
dllthread := ""
if (!autoexecute_done){
MsgBox % "Plugin " classname1 " failed to load. Removing from list."
continue
} else if (Type == "" || Description == ""){
MsgBox % "Plugin " classname1 " does not have a type or description. Removing from list."
continue
}
this.PluginDetails[Type] := {Description: Description, ClassName: classname1}
AddFile(A_LoopFileFullPath, 1)
}
}
; Load settings from disk
_LoadSettings(){
this._LoadPluginList()
this._UpdatePluginSelect()
FileRead, j, % this._SettingsFile
if (j = ""){
j := {"CurrentProfile":"Default","Profiles":{"Default":{}, "Global": {}}}
;j := {"CurrentProfile":"Default","Profiles":{"Default":{}}}
} else {
OutputDebug % "Loading JSON from disk"
j := JSON.Load(j)
}
this._Deserialize(j)
return j.CurrentProfile
}
; Save settings to disk
; ToDo: improve. Only the thing that changed needs to be re-serialized. Cache values.
_SaveSettings(){
obj := this._Serialize()
obj.SettingsVersion := this.SettingsVersion
OutputDebug % "Saving JSON to disk"
jdata := JSON.Dump(obj, ,true)
FileDelete, % this._SettingsFile
FileAppend, % jdata, % this._SettingsFile
}
; A child profile changed in some way
_ProfileChanged(profile){
this._SaveSettings()
}
; Turns on or off GameBind mode. In GameBind mode, all outputs are delayed
SetGameBindState(state){
if (state){
if (this._CurrentState == this._State.Normal){
this._CurrentState := this._State.GameBind
return 1
}
} else {
if (this._CurrentState == this._State.GameBind){
this._CurrentState := this._State.Normal
return 1
}
}
return 0
}
; The user selected the "Bind" option from an Input/OutputButton GuiControl,
; or changed an option such as "Wild" in an InputButton
_RequestBinding(hk, delta := 0){
if (delta = 0){
; Change Buttons requested - start Bind Mode.
if (this._CurrentState == this._State.Normal){
this._CurrentState := this._State.InputBind
this.Profiles.Global._SetHotkeyState(0)
hk.ParentPlugin.ParentProfile._SetHotkeyState(0)
this._BindModeHandler.StartBindMode(hk, this._BindModeEnded.Bind(this))
return 1
}
return 0
} else {
; Change option (eg wild, passthrough) requested
bo := hk.value.clone()
for k, v in delta {
bo[k] := v
}
if (this._InputHandler.IsBindable(hk, bo)){
hk.value := bo
this._InputHandler.SetButtonBinding(hk)
}
hk.ParentPlugin.ParentProfile._SetHotkeyState(1)
this.Profiles.Global._SetHotkeyState(1)
}
}
; Bind Mode Ended.
; Decide whether or not binding is valid, and if so set binding and re-enable inputs
_BindModeEnded(hk, bo){
OutputDebug % "Bind Mode Ended: " bo.Buttons[1].code
this._CurrentState := this._State.Normal
if (hk._IsOutput){
hk.value := bo
} else {
if (this._InputHandler.IsBindable(hk, bo)){
hk.value := bo
this._InputHandler.SetButtonBinding(hk)
}
}
this.Profiles.Global._SetHotkeyState(1)
hk.ParentPlugin.ParentProfile._SetHotkeyState(1)
}
; Request an axis binding.
RequestAxisBinding(axis){
this._InputHandler.SetAxisBinding(axis)
}
_GetUniqueName(){
c := 1
; Find a unuqe name to suggest as a new name
while (ObjHasKey(this.Profiles, "Profile " c)){
c++
}
suggestedname := "Profile " c
; Allow user to pick name
choosename := 1
prompt := "Enter a name for the Profile"
while(choosename) {
InputBox, name, Add Profile, % prompt, ,,130,,,,, % suggestedname
if (!ErrorLevel){
if (ObjHasKey(this.Profiles, Name)){
prompt := "Duplicate name chosen, please enter a unique name"
name := suggestedname
} else {
return name
}
} else {
return 0
}
}
}
; Serialize this object down to the bare essentials for loading it's state
_Serialize(){
obj := {CurrentProfile: this.CurrentProfile.Name, CurrentSize: this.CurrentSize, CurrentPos: this.CurrentPos}
obj.Profiles := {}
for name, profile in this.Profiles {
obj.Profiles[name] := profile._Serialize()
}
return obj
}
; Load this object from simple data strutures
_Deserialize(obj){
this.Profiles := {}
for name, profile in obj.Profiles {
this.Profiles[name] := new _Profile(name)
this.Profiles[name]._Deserialize(profile)
this.Profiles[name]._Hide()
}
;this.CurrentProfile := this.Profiles[obj.CurrentProfile]
if (IsObject(obj.CurrentSize))
this.CurrentSize := obj.CurrentSize
if (IsObject(obj.CurrentPos))
this.CurrentPos := obj.CurrentPos
}
; ================================== MOUSEDELTA LIBRARY ========================================
; Instantiate this class and pass it a func name or a Function Object
; The specified function will be called with the delta move for the X and Y axes
; Normally, there is no windows message "mouse stopped", so one is simulated.
; After 10ms of no mouse movement, the callback is called with 0 for X and Y
Class MouseDelta {
__New(callback, timeout := 10){
this.TimeOutDuration := timeout
this.TimeoutFn := this.TimeoutFunc.Bind(this)
this.MoveFn := this.MouseMoved.Bind(this)
this.Callback := callback
}
__Delete(){
this.UnRegister()
}
Register(){
static RIDEV_INPUTSINK := 0x00000100
; Register mouse for WM_INPUT messages.
static DevSize := 8 + A_PtrSize
static RAWINPUTDEVICE := 0
if (RAWINPUTDEVICE == 0){
VarSetCapacity(RAWINPUTDEVICE, DevSize)
NumPut(1, RAWINPUTDEVICE, 0, "UShort")
NumPut(2, RAWINPUTDEVICE, 2, "UShort")
NumPut(RIDEV_INPUTSINK, RAWINPUTDEVICE, 4, "Uint")
; WM_INPUT needs a hwnd to route to, so get the hwnd of the AHK Gui.
; It doesn't matter if the GUI is showing, as long as it exists
NumPut(UCR.hwnd, RAWINPUTDEVICE, 8, "Uint")
}
r := DllCall("RegisterRawInputDevices", "Ptr", &RAWINPUTDEVICE, "UInt", 1, "UInt", DevSize )
OnMessage(0x00FF, this.MoveFn, -1)
}
UnRegister(){
static RIDEV_REMOVE := 0x00000001
static DevSize := 8 + A_PtrSize
fn := this.TimeoutFn
SetTimer, % fn, Off
;RAWINPUTDEVICE := this.RAWINPUTDEVICE
static RAWINPUTDEVICE := 0
if (RAWINPUTDEVICE == 0){
VarSetCapacity(RAWINPUTDEVICE, DevSize)
NumPut(1, RAWINPUTDEVICE, 0, "UShort")
NumPut(2, RAWINPUTDEVICE, 2, "UShort")
NumPut(RIDEV_REMOVE, RAWINPUTDEVICE, 4, "Uint")
}
DllCall("RegisterRawInputDevices", "Ptr", &RAWINPUTDEVICE, "UInt", 0, "UInt", DevSize )
OnMessage(0x00FF, this.MoveFn, 0)
}
SetTimeOut(t){
this.TimeOutDuration := t
}
; Called when the mouse moved.
; Messages tend to contain small (+/- 1) movements, and happen frequently (~20ms)
MouseMoved(wParam, lParam){
; RawInput statics
static DeviceSize := 2 * A_PtrSize, iSize := 0, sz := 0, offsets := {x: (20+A_PtrSize*2), y: (24+A_PtrSize*2)}, uRawInput
static axes := {x: 1, y: 2}
; Find size of rawinput data - only needs to be run the first time.
if (!iSize){
r := DllCall("GetRawInputData", "UInt", lParam, "UInt", 0x10000003, "Ptr", 0, "UInt*", iSize, "UInt", 8 + (A_PtrSize * 2))
VarSetCapacity(uRawInput, iSize)
}
sz := iSize ; param gets overwritten with # of bytes output, so preserve iSize
; Get RawInput data
r := DllCall("GetRawInputData", "UInt", lParam, "UInt", 0x10000003, "Ptr", &uRawInput, "UInt*", sz, "UInt", 8 + (A_PtrSize * 2))
x := NumGet(&uRawInput, offsets.x, "Int")
y := NumGet(&uRawInput, offsets.y, "Int")
this.Callback.(x, y)
; There is no message for "Stopped", so simulate one
fn := this.TimeoutFn
SetTimer, % fn, % -this.TimeOutDuration
}
TimeoutFunc(){
this.Callback.(0, 0)
}
}
}
; =================================================================== INPUT HANDLER ==========================================================
; Manages input (ie keyboard, mouse, joystick) during "normal" operation (ie when not in Bind Mode)
; Holds the "master list" of bound inputs and decides whether or not to allow bindings.
; All actual detection of input is handled in separate threads.
; Each profile has it's own thread of bindings which this class can turn on/off or add/remove bindings.
Class _InputHandler {
RegisteredBindings := {}
__New(){
}
; Set a Button Binding
SetButtonBinding(BtnObj){
; ToDo: Move building of bindstring inside thread? BuildHotkeyString is AHK input-specific, what about XINPUT?
bindstring := this.BuildHotkeyString(BtnObj.value)
; Set binding in Profile's InputThread
BtnObj.ParentPlugin.ParentProfile._InputThread.ahkExec("InputThread.SetButtonBinding(" &BtnObj ",""" bindstring """)")
return 1
}
; Set an Axis Binding
SetAxisBinding(AxisObj){
AxisObj.ParentPlugin.ParentProfile._InputThread.ahkExec("InputThread.SetAxisBinding(" &AxisObj ")")
}
; Check InputButtons for duplicates etc
IsBindable(hk, bo){
; Do not allow bind of LMB with block enabled
if (bo.Block && bo.Buttons.length() = 1 && bo.Buttons[1].Type = 1 && bo.Buttons[1].code == 1){
; ToDo: provide proper notification
SoundBeep
return 0
}
; ToDo: Implement duplicate check
return 1
}
; Turns on or off Hotkey(s)
ChangeHotkeyState(state, hk := 0){
hk.ParentPlugin.ParentProfile._InputThread.ahkExec("InputThread.SetHotkeyState(" state ")")
}
; Builds an AHK hotkey string (eg ~^a) from a BindObject
BuildHotkeyString(bo){
if (!bo.Buttons.Length())
return ""
str := ""
if (bo.Type = 1){
if (bo.Wild)
str .= "*"
if (!bo.Block)
str .= "~"
}
max := bo.Buttons.Length()
Loop % max {
key := bo.Buttons[A_Index]
if (A_Index = max){
islast := 1
nextkey := 0
} else {
islast := 0
nextkey := bo.Buttons[A_Index+1]
}
if (key.IsModifier() && (max > A_Index)){
str .= key.RenderModifier()
} else {
str .= key.BuildKeyName()
}
}
return str
}
; An input event (eg key, mouse, joystick) occured for a bound input
; This will have come from another thread
; ipt will be an object of class _InputButton or _InputAxis
; event will be 0 or 1 for a Button type, or the value of the axis for an axis type
InputEvent(ipt, state){
ipt := Object(ipt) ; Resolve input object back from pointer
if (ipt.__value.Suppress && state && ipt.State > 0){
; ToDo: don't do this check for axes
; Suppress repeats option
return
}
ipt.State := state
if (IsObject(ipt.ChangeStateCallback)){
ipt.ChangeStateCallback.Call(state)
ipt.ParentPlugin.InputEvent(ipt, state)
}
}
_DelayCallback(cb, state){
cb.Call(state)
}
}
; =================================================================== BIND MODE HANDLER ==========================================================
; Prompts the user for input and detects their choice of binding
class _BindModeHandler {
DebugMode := 2
SelectedBinding := 0
BindMode := 0
EndKey := 0
HeldModifiers := {}
ModifierCount := 0
_Callback := 0
_Modifiers := ({91: {s: "#", v: "<"},92: {s: "#", v: ">"}
,160: {s: "+", v: "<"},161: {s: "+", v: ">"}
,162: {s: "^", v: "<"},163: {s: "^", v: ">"}
,164: {s: "!", v: "<"},165: {s: "!", v: ">"}})
__New(){
this._BindModeThread:=AhkThread(A_ScriptDir "\Threads\BindModeThread.ahk",,1) ; Loads the AutoHotkey module and starts the script.
While !this._BindModeThread.ahkgetvar.autoexecute_done
Sleep 50 ; wait until variable has been set.
fn := this._ProcessInput.Bind(this)
this._BindModeCallback := fn ; make sure boundfunc does not go out of scope - the other thread needs it
this._BindModeThread.ahkExec["BindMapper := new _BindMapper(" &fn ")"]
Gui, new, +HwndHwnd
Gui +ToolWindow -Border
this.hBindModePrompt := hwnd
Gui, Add, Text, Center, Press the button(s) you wish to bind to this input.`n`nBind Mode will end when you release a key.
}
StartBindMode(hk, callback){
this._callback := callback
this._OriginalHotkey := hk
this.SelectedBinding := 0
this.BindMode := 1
this.EndKey := 0
this.HeldModifiers := {}
this.ModifierCount := 0
; When detecting an output, tell the Bind Handler to ignore physical joysticks...
; ... as output cannot be "sent" to physical sticks
this.SetHotkeyState(1, !hk._IsOutput)
}
; Turns on or off the hotkeys
SetHotkeyState(state, enablejoystick := 1){
if (state){
Gui, % this.hBindModePrompt ":Show"
} else {
Gui, % this.hBindModePrompt ":Hide"
}
this._BindModeThread.ahkExec["BindMapper.SetHotkeyState(" state "," enablejoystick ")"]
}
; The BindModeThread calls back here
_ProcessInput(e, type, code, deviceid){
;OutputDebug % "e: " e ", type: " type ", code: " code ", deviceid: " deviceid
; Build Key object and pass to ProcessInput
i := new _Button({type: type, code: code, deviceid: deviceid})
this.ProcessInput(i,e)
}
; Called when a key was pressed
ProcessInput(i, e){
if (!this.BindMode)
return
if (i.type > 1){
is_modifier := 0
} else {
is_modifier := i.IsModifier()
; filter repeats
;if (e && (is_modifier ? ObjHasKey(HeldModifiers, i.code) : EndKey) )
if (e && (is_modifier ? ObjHasKey(this.HeldModifiers, i.code) : i.code = this.EndKey.code) )
return
}
;~ ; Are the conditions met for end of Bind Mode? (Up event of non-modifier key)
;~ if ((is_modifier ? (!e && ModifierCount = 1) : !e) && (i.type > 1 ? !ModifierCount : 1) ) {
; Are the conditions met for end of Bind Mode? (Up event of any key)
if (!e){
; End Bind Mode
this.BindMode := 0
this.SetHotkeyState(0)
bindObj := this._OriginalHotkey.value.clone()
bindObj.Buttons := []
for code, key in this.HeldModifiers {
bindObj.Buttons.push(key)
}
bindObj.Buttons.push(this.EndKey)
bindObj.Type := this.EndKey.Type
this._Callback.(this._OriginalHotkey, bindObj)
return
} else {
; Process Key Up or Down event
if (is_modifier){
; modifier went up or down
if (e){
this.HeldModifiers[i.code] := i
this.ModifierCount++
} else {
this.HeldModifiers.Delete(i.code)
this.ModifierCount--
}
} else {
; regular key went down or up
if (i.type > 1 && this.ModifierCount){
; Reject joystick button + modifier - AHK does not support this
if (e)
SoundBeep
} else if (e) {
; Down event of non-modifier key - set end key
this.EndKey := i
}
}
}
; Mouse Wheel u/d/l/r has no Up event, so simulate it to trigger it as an EndKey
if (e && (i.code >= 156 && i.code <= 159)){
this.ProcessInput(i, 0)
}
}
}
; ======================================================================== PROFILE ===============================================================
; The Profile class handles everything to do with Profiles.
; It has it's own GUI (this.hwnd), which is parented to the main GUI.
; The Profile's is parent to 0 or more plugins, which are each an instance of the _Plugin class.
; The Gui of each plugin appears inside the Gui of this profile.
Class _Profile {
Name := ""
Plugins := {}
PluginOrder := []
AssociatedApss := 0
PluginStateSubscriptions := {}
_IsGlobal := 0
__New(name){
this.Name := name
if (this.Name = "global"){
this._IsGlobal := 1
}
this._InputThread := AhkThread(A_ScriptDir "\Threads\ProfileInputThread.ahk",,1) ; Loads the AutoHotkey module and starts the script.
While !this._InputThread.ahkgetvar.autoexecute_done
Sleep 50 ; wait until variable has been set.
fn := UCR._InputHandler.InputEvent.Bind(UCR._InputHandler)
this._InputEventCallback := fn ; ensure BoundFunc does not go out of scope
this._InputThread.ahkExec("InputThread := new _InputThread(" &fn ")")
this._CreateGui()
}
__Delete(){
Gui, % this.hwnd ":Destroy"
}
_CreateGui(){
Gui, +HwndhOld ; Preserve previous default Gui
Gui, Margin, 5, 5
Gui, new, HwndHwnd
this.hwnd := hwnd
try {
Gui, +Scroll
}
Gui, -Caption
Gui, Add, Edit, % "+Hidden hwndhSpacer y0 w2 h10 x" UCR.PLUGIN_WIDTH + 10
this.hSpacer := hSpacer
Gui, Color, 777777
Gui, % UCR.hwnd ":Add", Gui, % "x0 y" UCR.TOP_PANEL_HEIGHT " w" UCR.PLUGIN_FRAME_WIDTH " ah h" UCR.GUI_MIN_HEIGHT - UCR.TOP_PANEL_HEIGHT, % this.hwnd
Gui, % hOld ":Default" ; Restore previous default Gui
}
; The profile became active
_Activate(){
this._SetHotkeyState(1)
Loop % this.PluginOrder.length() {
plugin := this.Plugins[this.PluginOrder[A_Index]]
if (IsFunc(plugin["OnActive"])){
plugin.OnActive()
}
}
}
; The profile went inactive
_DeActivate(){
this._SetHotkeyState(0)
Loop % this.PluginOrder.length() {
plugin := this.Plugins[this.PluginOrder[A_Index]]
if (IsFunc(plugin["OnInactive"])){
plugin.OnInactive()
}
}
}
_SetHotkeyState(state){
this._InputThread.ahkExec("InputThread.SetHotkeyState(" state ")")
}
; Show the GUI
_Show(){
Gui, % this.hwnd ":Show"
}
; Hide the GUI
_Hide(){
Gui, % this.hwnd ":Hide"
}
; User clicked Add Plugin button
_AddPlugin(){
GuiControlGet, idx, % UCR.hTopPanel ":", % UCR.hPluginSelect
plugin := UCR.PluginDetails[UCR.PluginList[idx]].ClassName
name := this._GetUniqueName(plugin)
if (name = 0)
return
this.PluginOrder.push(name)
this.Plugins[name] := new %plugin%(this, name)
this.Plugins[name].Type := plugin
this._LayoutPlugin()
UCR._ProfileChanged(this)
if (IsFunc(this.Plugins[name, "OnActive"]))
this.Plugins[name].OnActive()
}
; Layout a plugin.
; Pass PluginOrder index to lay out, or leave blank to lay out last plugin
_LayoutPlugin(index := -1){
static SCROLLINFO:="UINT cbSize;UINT fMask;int nMin;int nMax;UINT nPage;int nPos;int nTrackPos"
,scroll:=Struct(SCROLLINFO,{cbSize:sizeof(SCROLLINFO),fMask:4})
GetScrollInfo(this.hwnd,true,scroll[])
i := (index = -1 ? this.PluginOrder.length() : index)
name := this.PluginOrder[i]
y := 0
if (i > 1){
ControlGetPos,,wy,,,,% "ahk_id " this.hwnd
prev := this.PluginOrder[i-1]
ControlGetPos,,y,,h,,% "ahk_id " this.Plugins[prev].hFrame
y += h - wy
}
y += 5 - (index=-1 ? 0 : scroll.nPos)
Gui, % this.Plugins[name].hFrame ":Show", % "x5 y" y " w" UCR.PLUGIN_WIDTH
ControlGetPos, , , , h, , % "ahk_id " this.Plugins[name].hFrame
GuiControl, Move, % this.hSpacer, % "h" y + h + scroll.nPos
}
; Lays out all plugins
_LayoutPlugins(){
;~ static SCROLLINFO:="UINT cbSize;UINT fMask;int nMin;int nMax;UINT nPage;int nPos;int nTrackPos"
;~ ,scroll:=Struct(SCROLLINFO,{cbSize:sizeof(SCROLLINFO)})
;~ scroll.fMask:=0x17
;~ GetScrollInfo(this.hwnd,true,scroll[])
;~ scrollPos:=scroll.nPos
max := this.PluginOrder.length()
if (max){
Loop % max{
this._LayoutPlugin(A_Index)
}
;~ GetScrollInfo(this.hwnd,true,scroll[])
;~ scroll.nPos:=scrollPos>scroll.nMax ? scroll.nMax : scrollPos
;~ SendMessage,0x115,0,% LoWord(4)|HiWord(scrollPos>scroll.nMax ? -scroll.nMax : -scrollPos),,% "ahk_id " this.hwnd
} else {
GuiControl, Move, % this.hSpacer, % "h10"
}
}
; Delete a plugin
_RemovePlugin(plugin){
ControlGetPos, , , , height_frame, ,% "ahk_id " plugin.hFrame
Gui, % plugin.hwnd ":Destroy"
Gui, % plugin.hFrame ":Destroy"
Loop % this.PluginOrder.length(){
if (this.PluginOrder[A_Index] = plugin.name){
this.PluginOrder.RemoveAt(A_Index)
break
}
}
ControlGetPos, , , , height_spacer, ,% "ahk_id " this.hSpacer
GuiControl, Move, % this.hSpacer, % "h" height_spacer - height_frame
this.Plugins.Delete(plugin.name)
this._PluginChanged(plugin)
this._LayoutPlugins()
}
; Obtain a profiel-unique name for the plugin
_GetUniqueName(name){
name .= " "
num := 1
while (ObjHasKey(this.Plugins, name num)){
num++
}
name := name num
prompt := "Enter a name for the Plugin"
Loop {
InputBox, name, Add Plugin, % prompt, ,,130,,,,, % name
if (!ErrorLevel){
if (ObjHasKey(this.Plugins, Name)){
prompt := "Duplicate name chosen, please enter a unique name"
name := suggestedname
} else {
return name
}
} else {
return 0
}
}
}
; Save the profile to disk
_Serialize(){
obj := {}
obj.Plugins := {}
obj.PluginOrder := this.PluginOrder
for name, plugin in this.Plugins {
obj.Plugins[name] := plugin._Serialize()
}
return obj
}
; Load the profile from disk
_Deserialize(obj){
Loop % obj.PluginOrder.length() {
name := obj.PluginOrder[A_Index]
this.PluginOrder.push(name)
plugin := obj.Plugins[name]
cls := plugin.Type
if (!IsObject(%cls%)){
msgbox % "Plugin class " cls " not found - removing from profile """ this.Name """"
this.PluginOrder.Pop()
obj.Plugins.Delete(name)
continue
}
this.Plugins[name] := new %cls%(this, name)
this.Plugins[name]._Deserialize(plugin)
this._LayoutPlugin()