-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGamepadPhoenix.cs
2020 lines (1890 loc) · 118 KB
/
GamepadPhoenix.cs
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
/* Gamepad Phoenix
* Copyright (c) 2021-2023 Bernhard Schelling
*
* Gamepad Phoenix is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* Gamepad Phoenix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Gamepad Phoenix.
* If not, see <http://www.gnu.org/licenses/>.
*/
using System.Windows.Forms;
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using GamepadPhoenix;
[assembly: System.Reflection.AssemblyTitle("Gamepad Phoenix")]
[assembly: System.Reflection.AssemblyProduct("Gamepad Phoenix")]
[assembly: System.Reflection.AssemblyVersion("0.9.5")]
[assembly: System.Reflection.AssemblyFileVersion("0.9.5")]
[assembly: System.Reflection.AssemblyCopyright("(C) 2021-2023 Bernhard Schelling")]
[assembly: System.Runtime.InteropServices.ComVisible(false)]
namespace GamepadPhoenix
{
[Flags]
public enum GPOption : ushort
{
None = 0,
[System.ComponentModel.Description("Map D-Pad to Left Stick")]
DPadToLStick = 0x1,
[System.ComponentModel.Description("Swap A and B Buttons")]
SwapAandB = 0x2,
[System.ComponentModel.Description("Swap L1/R1 and L2/R2")]
SwapL1R1andL2R2 = 0x4,
[System.ComponentModel.Description("DirectInput: Map Triggers to Buttons instead of Analog Axis")]
DI_TriggersToButtons = 0x10,
[System.ComponentModel.Description("DirectInput: Map D-Pad to Buttons instead of Point of View Hat")]
DI_POVtoButtons = 0x20,
[System.ComponentModel.Description("Use Indirect Loading (Prepare redirector DLL to allow external stores/launchers)")]
IndirectLoading = 0x100,
[System.ComponentModel.Description("Disable XInput (return no connected controllers)")]
Disable_XInput = 0x200,
[System.ComponentModel.Description("Disable DirectInput (return no joystick or only fake XInput gamepads)")]
Disable_DirectInput = 0x400,
[System.ComponentModel.Description("Disable MMSys (return no joystick or only fake XInput gamepads)")]
Disable_MMSys = 0x800,
[System.ComponentModel.Description("Disable RawInput (return no device connected)")]
Disable_RawInput = 0x1000,
[System.ComponentModel.Description("Force game window to borderless fullscreen")]
FullscreenWindow = 0x4000,
}
internal enum GPIDInterface
{
NONE,
KEYBOARD,
DINPUT,
XINPUT,
WII,
MOUSE,
CAPTURE_NEXT_KEY,
}
internal enum GPIDSource
{
NONE = 0,
ALL = (1 << (int)GPIDInterface.XINPUT) | (1 << (int)GPIDInterface.DINPUT) | (1 << (int)GPIDInterface.WII) | (1 << (int)GPIDInterface.KEYBOARD) | (1 << (int)GPIDInterface.MOUSE),
GAMEPADS = (1 << (int)GPIDInterface.XINPUT) | (1 << (int)GPIDInterface.DINPUT) | (1 << (int)GPIDInterface.WII),
XINPUT = (1 << (int)GPIDInterface.XINPUT),
DINPUT = (1 << (int)GPIDInterface.DINPUT),
WII = (1 << (int)GPIDInterface.WII),
KEYBOARD = (1 << (int)GPIDInterface.KEYBOARD),
MOUSE = (1 << (int)GPIDInterface.MOUSE),
};
internal enum GPIndices : byte
{
LSTICK_U, LSTICK_D, LSTICK_L, LSTICK_R, RSTICK_U, RSTICK_D, RSTICK_L, RSTICK_R,
TRIGGER_L, TRIGGER_R, DPAD_U, DPAD_D, DPAD_L, DPAD_R, BTN_A, BTN_B, BTN_X, BTN_Y, BTN_L, BTN_R,
BTN_BACK, BTN_START, BTN_LSTICK, BTN_RSTICK, _MAX,
};
internal enum GPCals : byte
{
LDEADZONE, LLIMIT, LANTI, LSENS, LSHIFTH, LSHIFTV,
RDEADZONE, RLIMIT, RANTI, RSENS, RSHIFTH, RSHIFTV, _MAX
};
internal class GPGamepad
{
internal const int NUM_GAMEPADS = 4, NUM_INDICES = (int)GPIndices._MAX, NUM_CALS = (int)GPCals._MAX;
internal const uint GPID_CAPTURE_NEXT_KEY = (uint)GPIDInterface.CAPTURE_NEXT_KEY << GPID_SHIFT_INTF;
internal const uint GPID_KEYBOARD_DEVICE = (uint)GPIDInterface.KEYBOARD << GPID_SHIFT_INTF;
internal const uint GPID_MOUSE_DEVICE = (uint)GPIDInterface.MOUSE << GPID_SHIFT_INTF;
internal uint[] IDs = new uint[NUM_INDICES];
internal ushort[] Vals = new ushort[NUM_INDICES];
internal sbyte[] Cals = new sbyte[NUM_CALS];
internal List<uint> UndoBuffer = new List<uint>();
internal int UndoIndex = 0;
int Index;
GCHandle hIDs, hVals, hCals;
IntPtr ptrIDs, ptrVals, ptrCals;
internal bool Used, DrawnPressed;
internal GPIndices Pressed;
internal bool IsPressed(GPIndices idx) { return ((Vals[(int)idx] & 0x8000) != 0); }
internal GPGamepad(int idx)
{
Index = idx;
hIDs = GCHandle.Alloc(IDs, GCHandleType.Pinned); ptrIDs = Marshal.UnsafeAddrOfPinnedArrayElement(IDs, 0);
hVals = GCHandle.Alloc(Vals, GCHandleType.Pinned); ptrVals = Marshal.UnsafeAddrOfPinnedArrayElement(Vals, 0);
hCals = GCHandle.Alloc(Cals, GCHandleType.Pinned); ptrCals = Marshal.UnsafeAddrOfPinnedArrayElement(Cals, 0);
Used = Funcs.UIGetPad(Index, ptrIDs, ptrCals);
}
const int GPID_SHIFT_INTF = 29, GPID_SHIFT_DEVNUM = 8, GPID_BITS_DEV = (GPID_SHIFT_INTF - GPID_SHIFT_DEVNUM);
internal static uint GPIDMake(GPIDInterface intf_num, uint dev_num, ushort obj_num) { return (((uint)intf_num) << GPID_SHIFT_INTF) | ((uint)dev_num << GPID_SHIFT_DEVNUM) | ((uint)obj_num); }
internal static GPIDInterface GPIDGetInterface(uint id) { return (GPIDInterface)(id >> GPID_SHIFT_INTF); }
internal static uint GPIDGetDevNum(uint id) { return (id >> GPID_SHIFT_DEVNUM) & ((1 << GPID_BITS_DEV)-1); }
internal static byte GPIDGetObjNum(uint id) { return unchecked((byte)id); }
internal static GPIDInterface GPIDUniqueIntfDevNum(uint[] src)
{
uint sameIntfDev = 0;
foreach (uint id in src)
{
if (id == 0) continue;
uint intfDev = (id & ~(uint)((1 << GPID_SHIFT_DEVNUM) - 1));
if (sameIntfDev == 0) sameIntfDev = intfDev;
else if (sameIntfDev != intfDev) return GPIDInterface.NONE;
}
return (sameIntfDev != 0 && sameIntfDev != GPID_KEYBOARD_DEVICE && sameIntfDev != GPID_MOUSE_DEVICE ? GPIDGetInterface(sameIntfDev) : GPIDInterface.NONE);
}
void Refresh(bool setPad = false, bool dontUpdateUndo = false)
{
if (setPad) Funcs.UISetPad(Index, ptrIDs, ptrCals);
Used = false;
foreach (uint id in IDs) { if (id != 0) { Used = true; break; } }
if (dontUpdateUndo) return;
UndoBuffer.RemoveRange(UndoIndex, UndoBuffer.Count - UndoIndex);
bool addUndo = (UndoBuffer.Count == 0);
if (!addUndo) { for (int i = 0; i != NUM_INDICES; i++) { if (IDs[i] != UndoBuffer[UndoBuffer.Count - NUM_INDICES + i]) { addUndo = true; break; } } }
if (!addUndo) return;
UndoBuffer.AddRange(IDs);
UndoIndex = UndoBuffer.Count;
}
// LSTICK_U LSTICK_D LSTICK_L LSTICK_R RSTICK_U RSTICK_D RSTICK_L RSTICK_R TRIGGER_L TRIGGER_R DPAD_U DPAD_D DPAD_L DPAD_R BTN_A BTN_B BTN_X BTN_Y BTN_L BTN_R BTN_BACK BTN_START BTN_LSTICK BTN_RSTICK
static ushort[] XINPUT_OBJS = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x14, 0x15, 0x16, 0x17, 0x12, 0x13, 0x0f, 0x0e, 0x10, 0x11 };
internal const uint GPID_XINPUT_L2_OBJ = 8;
internal void MapFullXInputPad(uint dev_num)
{
for (int i = 0; i != NUM_INDICES; i++) IDs[i] = GPIDMake(GPIDInterface.XINPUT, dev_num, XINPUT_OBJS[i]);
Refresh(setPad: true);
}
internal void Load(uint[] ids, sbyte[] cals = null, bool clearUndoBuffer = false)
{
for (int i = 0; i != NUM_INDICES; i++) IDs[i] = ids[i];
for (int i = 0; i != NUM_CALS; i++) Cals[i] = (cals == null ? (sbyte)0 : cals[i]);
if (clearUndoBuffer) { UndoBuffer.Clear(); UndoIndex = 0; }
Refresh(setPad: true);
}
internal void LoadAs(uint[] ids, sbyte[] cals, uint switchDevNum, bool removeLastUndo)
{
if (removeLastUndo) UndoIndex -= NUM_INDICES;
for (int i = 0; i != NUM_INDICES; i++) IDs[i] = GPIDMake(GPIDGetInterface(ids[i]), switchDevNum, GPIDGetObjNum(ids[i]));
for (int i = 0; i != NUM_CALS; i++) Cals[i] = (cals == null ? (sbyte)0 : cals[i]);
Refresh(setPad: true);
}
internal static void Swap(GPGamepad[] pads, int a, int b)
{
{ GPGamepad v = pads[a]; pads[a] = pads[b]; pads[b] = v; }
{ int v = pads[a].Index; pads[a].Index = pads[b].Index; pads[b].Index = v; }
pads[a].Refresh(setPad: true);
pads[b].Refresh(setPad: true);
}
internal void WriteID(GPIndices idx, uint id)
{
if (IDs[(int)idx] == id) return;
IDs[(int)idx] = id;
Refresh(setPad: true, dontUpdateUndo:(id == GPID_CAPTURE_NEXT_KEY)); // != 0 is capture or assign cancel
}
internal void WriteCal(GPCals cal, sbyte val)
{
if (Cals[(int)cal] == val) return;
Cals[(int)cal] = val;
Refresh(setPad: true, dontUpdateUndo:true);
}
internal void NavigateUndo(int p)
{
UndoIndex += p * NUM_INDICES;
UndoBuffer.CopyTo(UndoIndex - NUM_INDICES, IDs, 0, NUM_INDICES);
Refresh(setPad: true, dontUpdateUndo: true);
}
internal void AddUndoStep()
{
Refresh(false);
}
internal void Read(GPIDSource captureSources = GPIDSource.NONE)
{
Funcs.UIPad(Index, ptrVals, (uint)captureSources);
if (captureSources != GPIDSource.NONE) Funcs.UIGetPad(Index, ptrIDs, ptrCals);
GPIndices down = GPIndices._MAX;
for (int i = 0; i != NUM_INDICES; i++) { if ((Vals[i] & 0x8000) != 0) { down = (GPIndices)i; if (down != GPIndices.BTN_BACK) break; } }
if (down != GPIndices._MAX && down != Pressed && GPIDGetInterface(IDs[(int)down]) != GPIDInterface.KEYBOARD && GPIDGetInterface(IDs[(int)down]) != GPIDInterface.MOUSE) GUI.OnPadButton(this, down);
Pressed = down;
}
internal bool IsKnownPreset(Dictionary<string, Config.Preset> presets)
{
foreach (Config.Preset p in presets.Values)
{
bool same = true;
for (int i = 0; i != NUM_INDICES; i++)
if (GPIDMake(GPIDGetInterface(IDs[i]), 0, GPIDGetObjNum(IDs[i])) != GPIDMake(GPIDGetInterface(p.IDs[i]), 0, GPIDGetObjNum(p.IDs[i])))
{ same = false; break; }
if (same) return true;
}
return false;
}
internal static void GPIDSetTexts(Button btn, ToolTip toolTip, uint id)
{
string dev, obj;
switch (GPIDGetInterface(id))
{
default:
case GPIDInterface.NONE:
toolTip.SetToolTip(btn, (btn.Text = ""));
return;
case GPIDInterface.CAPTURE_NEXT_KEY:
btn.Text = "...";
toolTip.SetToolTip(btn, "Input a command to assign to this");
return;
case GPIDInterface.KEYBOARD:
obj = Names.GetKeyboard(GPIDGetObjNum(id));
btn.Text = "Key " + obj;
toolTip.SetToolTip(btn, "Keyboard key '" + obj + "'");
return;
case GPIDInterface.MOUSE:
obj = Names.GetMouse(GPIDGetObjNum(id));
btn.Text = "Mouse " + obj;
toolTip.SetToolTip(btn, "Mouse input '" + obj + "'");
return;
case GPIDInterface.DINPUT:
dev = Marshal.PtrToStringUni(Funcs.UIGetDIName(GPIDGetDevNum(id)));
if (dev == null) dev = "Unknown (not connected)";
obj = Names.GetDirectInput(GPIDGetObjNum(id));
btn.Text = "Joy '" + dev.Substring(0, 7) + "...' " + obj;
toolTip.SetToolTip(btn, "DirectInput Joystick '" + dev + "' " + obj);
return;
case GPIDInterface.XINPUT:
dev = (GPIDGetDevNum(id) + 1).ToString();
obj = Names.GetXInput(GPIDGetObjNum(id));
btn.Text = "Pad #" + dev + " " + obj;
toolTip.SetToolTip(btn, "XInput Pad #" + dev + " " + obj);
return;
case GPIDInterface.WII:
dev = (GPIDGetDevNum(id) + 1).ToString();
obj = Names.GetWii(GPIDGetObjNum(id));
btn.Text = "Wii #" + dev + " " + obj;
toolTip.SetToolTip(btn, "Wii Controller #" + dev + " " + obj);
return;
}
}
static class Names
{
static string[] KeyboardKeys = new string[]
{
"", "Esc", "1","2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace", "Tab",
"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "[", "]", "Enter", "Ctrl (Left)", "A", "S",
"D", "F", "G", "H", "J", "K", "L", ";", "'", "`", "Shift (Left)", "Backslash", "Z", "X", "C", "V", "B",
"N", "M", ",", ".", "/", "Shift (Right)", "* (Numpad)", "Alt (Left)", "Space", "Caps Lock", "F1", "F2", "F3", "F4", "F5",
"F6", "F7", "F8", "F9", "F10", "Num Lock", "Scroll Lock", "7 (Numpad)", "8 (Numpad)", "9 (Numpad)", "- (Numpad)", "4 (Numpad)", "5 (Numpad)", "6 (Numpad)", "+ (Numpad)", "1 (Numpad)",
"2 (Numpad)", "3 (Numpad)", "0 (Numpad)", ". (Numpad)", "", "", "", "F11", "F12", "", "", "", "", "", "", "",
"", "", "", "", "F13", "F14", "F15", "", "", "", "", "", "", "", "", "",
"Kana", "", "", "", "", "", "", "", "", "Convert", "", "No Convert", "", "Yen", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "= (Numpad)", "", "",
"^", "@", ":", "_", "Kanji", "Stop", "(Japan AX)", "(J3100)", "", "", "", "", "Enter (Numpad)", "Ctrl (Right)", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", ", (Numpad)", "", "/ (Numpad)", "", "Print Screen", "Alt (Right)", "", "", "", "", "", "", "",
"", "", "", "", "", "Pause", "", "Home", "Arrow Up", "Page Up", "", "Arrow Left", "", "Arrow Right", "", "End",
"Arrow Down", "Page Down", "Insert", "Delete", "", "", "", "", "", "", "", "Windows (Left)", "Windows (Right)", "Menu", "Power", "Sleep",
};
static string[] XInputObj = new string[]
{
"Left Stick Up", "Left Stick Down", "Left Stick Left", "Left Stick Right",
"Right Stick Up", "Right Stick Down", "Right Stick Left", "Right Stick Right",
"Left Trigger", "Right Trigger",
"DPAD Up", "DPAD Down", "DPAD Left", "DPAD Right",
"Start", "Back",
"Left Stick Press", "Right Stick Press",
"Left Shoulder", "Right Shoulder",
"A", "B", "X", "Y",
};
static string[] WiiObj = new string[]
{
"Remote Up", "Remote Down", "Remote Left", "Remote Right",
"Remote A", "Remote B", "Remote One", "Remote Two",
"Remote Plus", "Remote Minus", "Remote Home",
"Left Stick Up", "Left Stick Down", "Left Stick Left", "Left Stick Right",
"Right Stick Up", "Right Stick Down", "Right Stick Left", "Right Stick Right",
"Pad Up", "Pad Down", "Pad Left", "Pad Right", "Pad Plus", "Pad Minus",
"Pad L", "Pad R", "Pad ZL", "Pad ZR",
"Pad B", "Pad A", "Pad Y", "Pad X", "Pad Home",
"Left Trigger", "Right Trigger",
};
static string[] MouseObj = new string[]
{
"Move Right", "Move Left", "Move Down", "Move Up", "Mouse Wheel Up", "Mouse Wheel Down", "Left Click", "Right Click", "Middle Click",
};
internal static string GetKeyboard(uint o) { return KeyboardKeys[o >= KeyboardKeys.Length ? 0 : o]; }
internal static string GetXInput(uint o) { return XInputObj[o >= XInputObj.Length ? 0 : o]; }
enum GPDIJoyState { AXIS_COUNT = 8, POV_COUNT = 4, BUTTON_COUNT = 64 };
internal static string GetDirectInput(uint o)
{
if (o < ((uint)GPDIJoyState.AXIS_COUNT*4))
return ((o & 2) == 2 ? "Inv" : "") + "Axis " + (1+o/4).ToString() + ((o & 1) == 1 ? "+" : "-");
if (o < ((uint)GPDIJoyState.AXIS_COUNT*4+(uint)GPDIJoyState.POV_COUNT*4))
return "POV " + (1+(o-((uint)GPDIJoyState.AXIS_COUNT*4))/4).ToString() + " " + ((o&3)==0 ? "Up" : ((o&3)==1 ? "Down" : ((o&3)==2 ? "Left" : "Right")));
if (o < ((uint)GPDIJoyState.AXIS_COUNT*4+(uint)GPDIJoyState.POV_COUNT*4+(uint)GPDIJoyState.BUTTON_COUNT))
return "Button " + (1+o-((uint)GPDIJoyState.AXIS_COUNT*4+(uint)GPDIJoyState.POV_COUNT*4)).ToString();
return "";
}
internal static string GetWii(uint o) { return WiiObj[o >= WiiObj.Length ? 0 : o]; }
enum GPDIMouseState { AXIS_COUNT = 3, BUTTON_COUNT = 8 };
internal static string GetMouse(uint o)
{
if (o < (uint)MouseObj.Length) return MouseObj[o];
if (o < ((uint)GPDIMouseState.AXIS_COUNT*2+(uint)GPDIMouseState.BUTTON_COUNT))
return "Button " + (1+o-((uint)GPDIMouseState.AXIS_COUNT*2)).ToString();
return "";
}
}
}
static internal class Funcs
{
[UnmanagedFunctionPointer(CallingConvention.Winapi)] internal delegate void D_UIPad(int idx, IntPtr vals, uint captureSources = 0);
[UnmanagedFunctionPointer(CallingConvention.Winapi)] internal delegate void D_UISetPad(int idx, IntPtr ids, IntPtr cals);
[UnmanagedFunctionPointer(CallingConvention.Winapi)] internal delegate bool D_UIGetPad(int idx, IntPtr ids, IntPtr cals);
[UnmanagedFunctionPointer(CallingConvention.Winapi)] internal delegate bool D_UILockLog(bool wantLock, out IntPtr out_log, out int out_length);
[UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet=CharSet.Unicode)] internal delegate void D_UISetup(GPOption options, string excludeList, string preparedDllIni = null);
[UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet=CharSet.Unicode)] internal delegate void D_UILaunch(string commandLine, string startDir);
[UnmanagedFunctionPointer(CallingConvention.Winapi)] internal delegate IntPtr D_UIGetDIName(uint devNum);
[UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet=CharSet.Unicode)] internal delegate int D_UIWii(string hidPath, bool on, int LEDs = 0);
[UnmanagedFunctionPointer(CallingConvention.Winapi)] internal delegate int D_UIViGEm(bool on);
internal static D_UIPad UIPad;
internal static D_UISetPad UISetPad;
internal static D_UIGetPad UIGetPad;
internal static D_UILockLog UILockLog;
internal static D_UISetup UISetup;
internal static D_UILaunch UILaunch;
internal static D_UIGetDIName UIGetDIName;
internal static D_UIWii UIWii;
internal static D_UIViGEm UIViGEm;
internal static string DLL32 = "GamepadPhoenix32.dll", DLL64 = "GamepadPhoenix64.dll";
internal static int SizeDLL32, SizeDLL64;
static internal void Load()
{
IntPtr hModule = LoadLibraryA(IntPtr.Size == 4 ? DLL32 : DLL64);
if (hModule == IntPtr.Zero || !File.Exists(IntPtr.Size != 4 ? DLL32 : DLL64))
{
MessageBox.Show("Missing DLLs " + DLL32 + " and " + DLL64 + ". Unable to continue.", "Gamepad Phoenix", MessageBoxButtons.OK, MessageBoxIcon.Stop);
Environment.Exit(1);
return;
}
SizeDLL32 = (int)new FileInfo(DLL32).Length;
SizeDLL64 = (int)new FileInfo(DLL64).Length;
UIPad = (D_UIPad )Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UIPad" ), typeof(D_UIPad ));
UISetPad = (D_UISetPad )Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UISetPad" ), typeof(D_UISetPad ));
UIGetPad = (D_UIGetPad )Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UIGetPad" ), typeof(D_UIGetPad ));
UILockLog = (D_UILockLog )Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UILockLog" ), typeof(D_UILockLog ));
UISetup = (D_UISetup )Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UISetup" ), typeof(D_UISetup ));
UILaunch = (D_UILaunch )Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UILaunch" ), typeof(D_UILaunch ));
UIGetDIName = (D_UIGetDIName)Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UIGetDIName"), typeof(D_UIGetDIName));
UIWii = (D_UIWii )Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UIWii" ), typeof(D_UIWii ));
UIViGEm = (D_UIViGEm )Marshal.GetDelegateForFunctionPointer(GetProcAddress(hModule, "UIViGEm" ), typeof(D_UIViGEm ));
}
[DllImport("kernel32.dll", ExactSpelling = true, CharSet=CharSet.Ansi)] static extern IntPtr LoadLibraryA(string lpLibFileName);
[DllImport("kernel32.dll", ExactSpelling = true, CharSet=CharSet.Ansi)] static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
}
public class Config
{
internal const string DefaultExcludeList = ""
+ "steam.exe" + "|"
+ "upc.exe" + "|"
+ "Origin.exe" + "|"
+ "EOSOverlayRenderer-Win32-Shipping.exe" + "|"
+ "EOSOverlayRenderer-Win64-Shipping.exe" + "|"
+ "explorer.exe" + "|"
+ "WerFault.exe" + "|"
+ "vsjitdebugger.exe";
public class Preset
{
public Preset() { }
internal Preset(string name, GPGamepad pad)
{
Name = name;
Array.Copy(pad.IDs, IDs, IDs.Length);
foreach (sbyte c in pad.Cals) { if (c != 0) { Cals = new sbyte[(int)GPCals._MAX]; Array.Copy(pad.Cals, Cals, Cals.Length); break; } }
}
[System.Xml.Serialization.XmlAttribute] public string Name = "";
[System.Xml.Serialization.XmlAttribute] public uint[] IDs = new uint[(int)GPIndices._MAX];
[System.Xml.Serialization.XmlAttribute] public sbyte[] Cals;
}
public class GamePad
{
[System.Xml.Serialization.XmlAttribute] public uint[] IDs;
[System.Xml.Serialization.XmlAttribute] public sbyte[] Cals;
}
public class Game
{
[System.Xml.Serialization.XmlAttribute] public string Name = "";
[System.Xml.Serialization.XmlAttribute] [System.ComponentModel.DefaultValue("")] public string Target = "", StartDir = "", Arguments = "";
[System.Xml.Serialization.XmlIgnore] public GPOption Options = GPOption.None;
[System.Xml.Serialization.XmlAttribute("Options")] [System.ComponentModel.DefaultValue("")]
public string _XMLOptions
{
get { return (Options == GPOption.None ? "" : Options.ToString()); }
set { try { Options = (GPOption)Enum.Parse(typeof(GPOption), value, true); } catch { } }
}
public override string ToString() { return Name; }
}
public List<GamePad> Gamepads = new List<GamePad>();
public List<Preset> Presets = new List<Preset>();
public List<Game> Games = new List<Game>();
[System.ComponentModel.DefaultValue(DefaultExcludeList)] public string ExcludeList = DefaultExcludeList;
public bool ShouldSerializeGamepads() { return Gamepads != null && Gamepads.Count > 0; }
public bool ShouldSerializePresets() { return Presets != null && Presets.Count > 0; }
public bool ShouldSerializeGames() { return Games != null && Games.Count > 0; }
static int lastSaveHash = 0;
static string ConfigFileName = new FileInfo(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName).DirectoryName + Path.DirectorySeparatorChar + "GamepadPhoenix.xml";
static internal void Load(out GPGamepad[] pads, out Dictionary<string, Preset> presets, ListBox games, TextBox excludes)
{
Config cfg = null;
if (File.Exists(ConfigFileName)) try
{
string xml = File.ReadAllText(ConfigFileName, System.Text.Encoding.UTF8);
lastSaveHash = xml.GetHashCode();
using (var r = new StringReader(xml))
cfg = (Config)(new System.Xml.Serialization.XmlSerializer(typeof(Config))).Deserialize(r);
}
catch (Exception e) { MessageBox.Show("Error while loading GamepadPhoenix.xml config file:\n" + e.ToString(), "Gamepad Phoenix", MessageBoxButtons.OK, MessageBoxIcon.Stop); }
if (cfg == null) { cfg = new Config(); lastSaveHash = "<Config />".GetHashCode(); }
foreach (Config.GamePad gp in cfg.Gamepads)
if (gp.IDs == null || gp.IDs.Length != (int)GPIndices._MAX)
gp.IDs = new uint[(int)GPIndices._MAX];
bool havePads = false;
pads = new GPGamepad[GPGamepad.NUM_GAMEPADS];
for (int i = 0; i != GPGamepad.NUM_GAMEPADS; i++)
havePads |= (pads[i] = new GPGamepad(i)).Used;
if (!havePads && cfg.Gamepads != null)
for (int i = 0; i < cfg.Gamepads.Count && i < GPGamepad.NUM_GAMEPADS; i++)
pads[i].Load(cfg.Gamepads[i].IDs, cfg.Gamepads[i].Cals, true);
presets = new Dictionary<string,Preset>();
foreach (Config.Preset p in cfg.Presets)
if (p.IDs != null && p.IDs.Length == (int)GPIndices._MAX)
presets.Add(p.Name, p);
games.Items.Clear();
foreach (Config.Game g in cfg.Games)
{
games.Items.Add(g);
if ((g.Options & GPOption.IndirectLoading) != 0)
IndirectLoading.UpgradeDLL(g.Target);
}
excludes.Text = System.Text.RegularExpressions.Regex.Replace(cfg.ExcludeList.Trim(), "[\\0-\\x19|]+", Environment.NewLine);
}
static internal bool Save(GPGamepad[] pads, Dictionary<string, Preset> presets, ListBox games, TextBox excludes)
{
Config cfg = new Config();
int iEnd;
for (int n = GPGamepad.NUM_GAMEPADS - 1;; n--) { if (n < 0 || pads[n].Used) { iEnd = n + 1; break; } }
for (int i = 0; i != iEnd; i++)
{
GamePad gp = new GamePad();
gp.IDs = pads[i].IDs;
foreach (sbyte c in pads[i].Cals) { if (c != 0) { gp.Cals = pads[i].Cals; break; } }
cfg.Gamepads.Add(gp);
}
foreach (Preset p in presets.Values)
cfg.Presets.Add(p);
foreach (object o in games.Items)
cfg.Games.Add((Game)o);
cfg.ExcludeList = System.Text.RegularExpressions.Regex.Replace(excludes.Text.Trim(), "[\\0-\\x19]+", "|");
try { using (StringWriter sw = new StringWriter())
{
(new System.Xml.Serialization.XmlSerializer(typeof(Config))).Serialize(sw, cfg, new System.Xml.Serialization.XmlSerializerNamespaces(new [] { new System.Xml.XmlQualifiedName("", "") }));
string xml = sw.ToString().Substring(sw.ToString().IndexOf("<Config")); // remove xml header
int saveHash = xml.GetHashCode();
if (lastSaveHash != saveHash)
{
File.WriteAllText(ConfigFileName, xml, new System.Text.UTF8Encoding(false));
lastSaveHash = saveHash;
}
}}
catch (Exception e) { MessageBox.Show("Error while saving GamepadPhoenix.xml config file:\n" + e.Message, "Gamepad Phoenix", MessageBoxButtons.OK, MessageBoxIcon.Stop); return false; }
return true;
}
};
static class IndirectLoading
{
static string[] DllOverrides = { "DINPUT8", "XINPUT1_3", "XINPUT1_4", "XINPUT1_2", "XINPUT1_1", "XINPUT9_1_0" };
static byte[] ReadDirectory(FileStream fs, int dir, ref ushort machine, ref long rvaOffset)
{
byte[] buf = new byte[40];
fs.Seek(0x3C, SeekOrigin.Begin);
fs.Read(buf, 0, 4);
uint lfanew = System.BitConverter.ToUInt32(buf, 0);
fs.Seek(lfanew + 4, SeekOrigin.Begin);
fs.Read(buf, 0, 4);
machine = System.BitConverter.ToUInt16(buf, 0);
ushort numberOfSections = System.BitConverter.ToUInt16(buf, 2);
fs.Seek(lfanew + 0x14, SeekOrigin.Begin);
fs.Read(buf, 0, 2);
ushort sizeOfOptionalHeader = System.BitConverter.ToUInt16(buf, 0);
fs.Seek(lfanew + 0x18 + sizeOfOptionalHeader - 0x80 + dir * 8, SeekOrigin.Begin);
fs.Read(buf, 0, 8);
uint dirRVA = System.BitConverter.ToUInt32(buf, 0), dirSize = System.BitConverter.ToUInt32(buf, 4);
if (dirSize == 0) return null;
fs.Seek(lfanew + 0x18 + sizeOfOptionalHeader, SeekOrigin.Begin);
while (numberOfSections-- != 0)
{
fs.Read(buf, 0, 40);
uint virtAddr = System.BitConverter.ToUInt32(buf, 12), rawSize = System.BitConverter.ToUInt32(buf, 16), rawAddr = System.BitConverter.ToUInt32(buf, 20);
if (dirRVA < virtAddr || dirRVA >= virtAddr + rawSize) continue;
byte[] res = new byte[dirSize];
rvaOffset = (long)rawAddr - (long)virtAddr;
fs.Seek(dirRVA + rvaOffset, SeekOrigin.Begin);
fs.Read(res, 0, (int)dirSize);
return res;
}
return null;
}
internal enum Ver { None, Current, Old };
static bool IsGPDLL(string path, ref Ver ver, ref ushort machine)
{
FileInfo fi = new FileInfo(path);
if (!fi.Exists) return false;
int len = (int)fi.Length;
if (len == Funcs.SizeDLL32) { ver = Ver.Current; machine = 0x014c; return true; }
if (len == Funcs.SizeDLL64) { ver = Ver.Current; machine = 0x8664; return true; }
try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
long rvaOffset = 0;
if (System.Text.Encoding.ASCII.GetString(ReadDirectory(fs, 0, ref machine, ref rvaOffset)).IndexOf("\0UIPad\0") == -1) return false; // also contains original linked dll file name
ver = Ver.Old;
return true;
}} catch {}
return false;
}
internal static void ClearIndirectDLLs(string target)
{
try
{
string dir = Path.GetDirectoryName(target); Ver ver = Ver.None; ushort machine = 0;
foreach (string dll in DllOverrides)
{
string path = dir + "\\" + dll + ".DLL";
if (!File.Exists(path) || !IsGPDLL(path, ref ver, ref machine)) continue;
File.Delete(path);
try { File.Delete(path.Substring(0, path.Length - 3) + "INI"); } catch { }
MessageBox.Show("Prepared game has been reverted and " + dll + ".DLL next to the game has been removed.", "Restore Game", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} catch (Exception e) { MessageBox.Show("Error while trying to remove prepared file:\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); }
}
static bool CopyDLL(string dir, string dll, ushort machine)
{
string path = dir + "\\" + dll + ".DLL"; Ver ver = Ver.None; ushort gpmachine = 0;
bool exists = File.Exists(path);
if (exists && !IsGPDLL(path, ref ver, ref gpmachine)) return false;
string gpDll = "GamepadPhoenix" + (machine == 0x8664 ? "64" : "32") + ".dll";
if (!exists || new FileInfo(path).Length != new FileInfo(gpDll).Length)
File.Copy(gpDll, path, true);
MessageBox.Show("Game has been prepared and " + gpDll + " has been copied next to the game as " + dll + ".DLL\n\nNow start the game through its launcher or store. You can also try launching it from here.\n\nBe aware that this tool needs to be running when doing so.", "Prepare Game", MessageBoxButtons.OK, MessageBoxIcon.Information);
return true;
}
internal static void UpgradeDLL(string target)
{
string dir = Path.GetDirectoryName(target); Ver ver = Ver.None; ushort machine = 0;
foreach (string dll in DllOverrides)
{
string path = dir + "\\" + dll + ".DLL";
if (!IsGPDLL(path, ref ver, ref machine)) continue;
if (ver == Ver.Current) return;
string gpDll = "GamepadPhoenix" + (machine == 0x8664 ? "64" : "32") + ".dll";
File.Copy(gpDll, path, true);
}
}
internal static bool PrepareIndirectDLL(string target)
{
try { using (FileStream fs = new FileStream(target, FileMode.Open, FileAccess.Read, FileShare.Read))
{
string dir = Path.GetDirectoryName(target);
ushort machine = 0; long rvaOffset = 0;
byte[] imports = ReadDirectory(fs, 1, ref machine, ref rvaOffset), bufDllName = new byte[16];
for (int offset = 0; offset <= (imports == null ? 0 : imports.Length - 0x14); offset += 0x14)
{
uint dllNameRVA = System.BitConverter.ToUInt32(imports, offset + 0xC);
if (dllNameRVA == 0) continue;
fs.Seek(dllNameRVA + rvaOffset, SeekOrigin.Begin);
fs.Read(bufDllName, 0, 16);
string dllName = System.Text.Encoding.ASCII.GetString(bufDllName);
foreach (string dll in DllOverrides)
if (dllName.StartsWith(dll + ".DLL\0", StringComparison.OrdinalIgnoreCase) && CopyDLL(dir, dll, machine))
return true;
if (dllName.StartsWith("UNITYPLAYER.DLL\0", StringComparison.OrdinalIgnoreCase) && CopyDLL(dir, "XINPUT1_3", machine))
return true;
}
byte[] buf = new byte[8192];
int earliestDLLOverride = DllOverrides.Length;
for (long i = 0; earliestDLLOverride > 0; i += 8192-16)
{
if (fs.Seek(i, SeekOrigin.Begin) != i || fs.Read(buf, 0, 8192) <= 0) break;
string bufstr = System.Text.Encoding.ASCII.GetString(buf);
if (bufstr.IndexOf("INPUT", StringComparison.OrdinalIgnoreCase) == -1) continue;
for (int dll = 0; dll != earliestDLLOverride; dll++)
if (bufstr.IndexOf(DllOverrides[dll] + ".DLL", StringComparison.OrdinalIgnoreCase) != -1)
{ earliestDLLOverride = dll; break; }
}
if (earliestDLLOverride != DllOverrides.Length && CopyDLL(dir, DllOverrides[earliestDLLOverride], machine))
return true;
if (MessageBox.Show("Game might not support indirect loading (no overridable DLLs imported).\n\nDo you want to try to prepare it anyway?", "Prepare", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
foreach (string dll in DllOverrides)
if ((machine != 0x8664 || dll != "DINPUT8") && CopyDLL(dir, dll, machine)) // Assume 64 bit apps to be more likely to use XINPUT and not DINPUT
return true;
}} catch (Exception e) { MessageBox.Show("Game could not be prepared for indirect loading:\n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); }
return false;
}
internal static Ver IsPrepared(string target, ref string path)
{
string dir = Path.GetDirectoryName(target); Ver ver = Ver.None; ushort machine = 0;
foreach (string dll in DllOverrides)
{ string p = dir + "\\" + dll + ".DLL"; if (IsGPDLL(p, ref ver, ref machine)) { path = p; return ver; } }
return Ver.None;
}
}
static class GUI
{
enum EPadPartType { NONE, STICK, TRIGGER, BUTTON, DPAD };
class PadPart
{
internal Image img;
internal int x = -1, y = -1;
internal GPIndices idx = GPIndices._MAX, shareIdx = GPIndices._MAX, stickBtnIdx = GPIndices._MAX;
internal EPadPartType type;
internal Button assignBtn;
internal string name;
internal Rectangle r;
internal uint oldId;
}
static GPGamepad[] Pads;
static Point HoverPos;
static int PadIdx = 0, UpdateCycle = 0;
static PadPart PadPartHover, PadPartAssign;
static List<PadPart> AssignQueue = new List<PadPart>();
static Pen PenBlack = new Pen(Color.Black, 4), PenWhite = new Pen(Color.White, 2);
static Pen PenThin = new Pen(Color.Black, 1);
static Dictionary<string, Config.Preset> Presets;
static bool IsDeviceSwitch, IsAutoLoad, FVisible = true;
static MainForm f;
static Form presetsForm;
static PadPart[] PadParts;
static byte[] LogBuf = new byte[512];
static Config.Game ActiveGame;
static DateTime FormActivateTime = DateTime.MaxValue;
[System.STAThread] static void Main(string[] args)
{
Funcs.Load(); // Connect to native DLL
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
f = new MainForm();
Config.Load(out Pads, out Presets, f.lstLaunchGames, f.txtMoreExcludeList);
SetupPadTab();
SetupLaunchTab();
SetupMoreTab();
// Systray support (could store last f.WindowState before minimizing into f.Tag but our form doesn't maximize)
f.SizeChanged += (object sender, EventArgs e) => { if (f.WindowState == FormWindowState.Minimized) f.Visible = FVisible = false; };
f.systray.Click += ToggleWindowVisibility;
f.systray.DoubleClick += ToggleWindowVisibility;
f.systray.Text = f.Text;
f.systray.Icon = f.Icon;
// Auto launch via command line
bool launch = false;
if (args.Length > 0)
{
foreach (Config.Game g in f.lstLaunchGames.Items) { if (g.Name.Equals(args[0])) { f.lstLaunchGames.SelectedItem = g; launch = SetActiveGame(g); break; } }
if (!launch) launch = SetActiveGame(new Config.Game { Target = args[0], Arguments = (args.Length > 1 ? args[1] : "") }, true);
}
if (launch)
{
LaunchGame();
f.WindowState = FormWindowState.Minimized;
f.tabs.SelectedIndex = f.tabs.TabCount - 2; // set before calling OnSelectTab
f.panelPad.BringToFront(); // otherwise the tab control can end up in front of it...
}
// Finish form setup
f.Activated += (object _s, EventArgs _e) => { FormActivateTime = DateTime.UtcNow; ShowLoading(false); };
f.Deactivate += (object _s, EventArgs _e) => { FormActivateTime = DateTime.MaxValue; ShowLoading(false); };
f.FormClosing += (object _s, FormClosingEventArgs _e) => _e.Cancel = !Config.Save(Pads, Presets, f.lstLaunchGames, f.txtMoreExcludeList);
f.lblLoading.Click += (object _s, EventArgs _e) => { FormActivateTime = DateTime.MaxValue; ShowLoading(false); };
f.timer.Tick += TickTimer;
f.tabs.DrawItem += DrawTab;
f.tabs.Selected += OnSelectTab;
f.tabs.MouseClick += (object _s, MouseEventArgs e) =>
{
if (e.Button != MouseButtons.Right) return;
for (int i = 0, numPadTabs = f.tabs.TabCount - 2; i != numPadTabs; i++)
{
Rectangle r = f.tabs.GetTabRect(i);
if (!r.Contains(e.Location)) continue;
if (!Pads[i].Used) return;
f.tabs.SelectedIndex = i;
ContextMenuStrip cms = new ContextMenuStrip();
cms.Items.Add("Clear All Assignments");
cms.ItemClicked += (object __s, ToolStripItemClickedEventArgs __e) =>
{
if (!Pads[PadIdx].IsKnownPreset(Presets) && MessageBox.Show(f, "Are you sure you want to override and clear the current settings?", "Clear", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return;
Pads[PadIdx].Load(new uint[GPGamepad.NUM_INDICES]);
OnSelectTab();
};
cms.Show(f, new Point(e.X, e.Y));
return;
}
};
OnSelectTab();
Application.Run(f);
Wii.Shutdown();
}
static void ShowLoading(bool on = true)
{
f.lblLoading.Visible = f.lblLoadingShadow.Visible = on;
f.lblLoading.BringToFront();
}
static void ToggleWindowVisibility(object _s = null, EventArgs _e = null)
{
f.Visible = FVisible = !(FVisible && Window.IsOnScreen(f) > 0);
if (FVisible) { f.WindowState = FormWindowState.Normal; f.Activate(); f.BringToFront(); }
}
static void LaunchGame(bool saveConfig = false)
{
string dllPath = null;
if (saveConfig) Config.Save(Pads, Presets, f.lstLaunchGames, f.txtMoreExcludeList);
if ((ActiveGame.Options & GPOption.IndirectLoading) != 0 && IndirectLoading.IsPrepared(ActiveGame.Target, ref dllPath) != IndirectLoading.Ver.Current)
{
if (!IndirectLoading.PrepareIndirectDLL(ActiveGame.Target)) return;
RefreshLaunchTab(true);
}
ShowLoading();
string startDir = (ActiveGame.StartDir.Length > 0 && Directory.Exists(ActiveGame.StartDir) ? ActiveGame.StartDir : Path.GetDirectoryName(ActiveGame.Target));
Funcs.UISetup(ActiveGame.Options, f.txtMoreExcludeList.Text);
Funcs.UILaunch("\"" + ActiveGame.Target + "\" " + ActiveGame.Arguments, startDir);
}
static void RefreshLaunchTab(bool writePreparedDllIni = false)
{
string dllPath = null;
bool indirect = ((ActiveGame.Options & GPOption.IndirectLoading) != 0);
bool valid = (ActiveGame.Target.Length != 0 && File.Exists(ActiveGame.Target));
IndirectLoading.Ver prepared = (indirect && valid ? IndirectLoading.IsPrepared(ActiveGame.Target, ref dllPath) : IndirectLoading.Ver.None);
f.btnLaunchPrepare.Enabled = (indirect && prepared != IndirectLoading.Ver.Current);
f.btnLaunchRestore.Enabled = (indirect && prepared != IndirectLoading.Ver.None);
f.btnLaunchPrepare.Visible = f.btnLaunchRestore.Visible = indirect;
f.btnLaunch.Enabled = valid;
f.btnLaunchOptions.Text = ActiveGame.Options.ToString().Replace("_", ": ");
if (dllPath != null && writePreparedDllIni)
Funcs.UISetup(ActiveGame.Options, f.txtMoreExcludeList.Text, dllPath.Substring(0, dllPath.Length - 3) + "INI");
bool showBigSelectEXE = (ActiveGame.Target.Length == 0);
if (f.btnLaunchSelectGameEXE.Enabled != showBigSelectEXE)
{
f.btnLaunchTargetSelect.Visible = f.btnLaunchTargetSelect.Enabled = !showBigSelectEXE;
f.btnLaunchSelectGameEXE.Visible = f.btnLaunchSelectGameEXE.Enabled = showBigSelectEXE;
f.txtLaunchTarget.Width += (f.btnLaunchSelectGameEXE.Width - f.btnLaunchTargetSelect.Width) * (showBigSelectEXE ? -1 : 1);
}
if (f.btnLaunchNew.Focused && f.btnLaunchSelectGameEXE.Enabled)
f.btnLaunchSelectGameEXE.Focus();
}
static bool SetActiveGame(Config.Game g, bool isNew = false)
{
if (ActiveGame == g) return f.btnLaunch.Enabled;
ActiveGame = g;
f.txtLaunchName.Text = ActiveGame.Name;
f.txtLaunchTarget.Text = ActiveGame.Target;
if (f.txtLaunchStartDir.Text == ActiveGame.StartDir) f.txtLaunchStartDir.Text = "-"; //force update
f.txtLaunchStartDir.Text = ActiveGame.StartDir;
f.txtLaunchArguments.Text = ActiveGame.Arguments;
f.btnLaunchSave.Enabled = isNew;
f.btnLaunchDelete.Enabled = !isNew;
RefreshLaunchTab();
return f.btnLaunch.Enabled;
}
static void OpenPresetList(bool doSave)
{
AssignCancel();
if (!doSave)
{
PadPartAssign = PadParts[2];
PadPartAssign.oldId = Pads[PadIdx].IDs[(int)PadPartAssign.idx];
Pads[PadIdx].WriteID(PadPartAssign.idx, GPGamepad.GPID_CAPTURE_NEXT_KEY);
IsAutoLoad = true;
}
PresetsForm pf = new PresetsForm();
pf.lblAutoLoad.Visible = !doSave;
if (doSave) { pf.lstPresets.Top -= pf.lblAutoLoad.Height; pf.lstPresets.Height += pf.lblAutoLoad.Height; }
foreach (string n in Presets.Keys)
pf.lstPresets.Items.Add(n);
Action refreshPresets = () =>
{
bool known = (Presets.ContainsKey(pf.txtName.Text));
if (pf.txtName.Text != pf.lstPresets.Text)
pf.lstPresets.SelectedItem = (known ? pf.txtName.Text : null);
pf.btnDelete.Enabled = known;
pf.btnOK.Enabled = (pf.txtName.Text.Length != 0 && (doSave || known));
};
pf.btnDelete.Click += (object sender, System.EventArgs e) =>
{
if (MessageBox.Show(pf, "Are you sure you want to delete the preset '" + pf.txtName.Text + "'?", "Delete Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
return;
Presets.Remove(pf.txtName.Text);
pf.lstPresets.Items.Remove(pf.lstPresets.SelectedItem);
refreshPresets();
};
pf.lstPresets.SelectedIndexChanged += (object sender, System.EventArgs e) =>
{
if (pf.lstPresets.Text.Length != 0 && pf.txtName.Text != pf.lstPresets.Text)
pf.txtName.Text = pf.lstPresets.Text;
};
pf.lstPresets.DoubleClick += (object sender, System.EventArgs e) =>
{
if (pf.lstPresets.Text.Length != 0)
pf.DialogResult = DialogResult.OK;
};
pf.txtName.TextChanged += (object sender, System.EventArgs e) => refreshPresets();
refreshPresets();
presetsForm = pf;
bool ok = (pf.ShowDialog() == DialogResult.OK);
presetsForm = null;
AssignCancel(); // reset capture next key
if (ok && doSave)
{
if (!Presets.ContainsKey(pf.txtName.Text) || MessageBox.Show(f, "Save and override preset '" + pf.txtName.Text + "'?", "Save Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
Presets[pf.txtName.Text] = new Config.Preset(pf.txtName.Text, Pads[PadIdx]);
}
else if (ok && !doSave && (!Pads[PadIdx].Used || Pads[PadIdx].IsKnownPreset(Presets) || MessageBox.Show(f, "Are you sure you want to override the current settings with the preset '" + pf.txtName.Text + "'?", "Load Preset", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes))
{
Pads[PadIdx].Load(Presets[pf.txtName.Text].IDs, Presets[pf.txtName.Text].Cals);
OnSelectTab();
}
}
static void SetupPadTab()
{
PadParts = new PadPart[]
{
new PadPart { idx = GPIndices.TRIGGER_L, assignBtn = f.btnL2, name = "L2 (Trigger)", x = 76, y = 0, img = Resources.L2, type = EPadPartType.TRIGGER },
new PadPart { idx = GPIndices.TRIGGER_R, assignBtn = f.btnR2, name = "R2 (Trigger)", x = 310, y = 0, img = Resources.R2, type = EPadPartType.TRIGGER },
new PadPart { idx = GPIndices.BTN_L, assignBtn = f.btnL1, name = "L1 (Bumper)", x = 60, y = 28, img = Resources.L1, type = EPadPartType.BUTTON },
new PadPart { idx = GPIndices.BTN_R, assignBtn = f.btnR1, name = "R1 (Bumper)", x = 325, y = 28, img = Resources.R1, type = EPadPartType.BUTTON },
new PadPart { x = 0, y = 0, img = Resources.BG, },
new PadPart { x = 87, y = 91, img = Resources.Circle, },
new PadPart { idx = GPIndices.LSTICK_U, stickBtnIdx = GPIndices.BTN_LSTICK, x = 100, y = 104, img = Resources.Stick, type = EPadPartType.STICK },
new PadPart { x = 282, y = 189, img = Resources.Circle, },
new PadPart { idx = GPIndices.RSTICK_U, stickBtnIdx = GPIndices.BTN_RSTICK, x = 295, y = 202, img = Resources.Stick, type = EPadPartType.STICK },
new PadPart { x = 149, y = 187, img = Resources.DPADBlack, },
new PadPart { idx = GPIndices.DPAD_U, x = 149, y = 187, img = Resources.DPAD, type = EPadPartType.DPAD },
new PadPart { idx = GPIndices.BTN_Y, assignBtn = f.btnY, name = "Y (Top Button)", x = 371, y = 75, img = Resources.Y, type = EPadPartType.BUTTON },
new PadPart { idx = GPIndices.BTN_X, assignBtn = f.btnX, name = "X (Left Button)", x = 335, y = 110, img = Resources.X, type = EPadPartType.BUTTON },
new PadPart { idx = GPIndices.BTN_A, assignBtn = f.btnA, name = "A (Bottom Button)", x = 371, y = 146, img = Resources.A, type = EPadPartType.BUTTON },
new PadPart { idx = GPIndices.BTN_B, assignBtn = f.btnB, name = "B (Right Button)", x = 408, y = 110, img = Resources.B, type = EPadPartType.BUTTON },
new PadPart { idx = GPIndices.BTN_START, assignBtn = f.btnStart, name = "Start Button", x = 281, y = 115, img = Resources.Start, type = EPadPartType.BUTTON },
new PadPart { idx = GPIndices.BTN_BACK, assignBtn = f.btnSelect, name = "Back/Select Button", x = 206, y = 115, img = Resources.Select, type = EPadPartType.BUTTON },
new PadPart { idx = GPIndices.DPAD_U, assignBtn = f.btnDPadU, name = "D-Pad Up", x = 188, y = 201, shareIdx = GPIndices.DPAD_U },
new PadPart { idx = GPIndices.DPAD_L, assignBtn = f.btnDPadL, name = "D-Pad Left", x = 161, y = 227, shareIdx = GPIndices.DPAD_U },
new PadPart { idx = GPIndices.DPAD_D, assignBtn = f.btnDPadD, name = "D-Pad Down", x = 188, y = 253, shareIdx = GPIndices.DPAD_U },
new PadPart { idx = GPIndices.DPAD_R, assignBtn = f.btnDPadR, name = "D-Pad Right", x = 212, y = 227, shareIdx = GPIndices.DPAD_U },
new PadPart { idx = GPIndices.LSTICK_U, assignBtn = f.btnLStickU, name = "Left-Stick Up", x = 126, y = 100, shareIdx = GPIndices.LSTICK_U },
new PadPart { idx = GPIndices.LSTICK_L, assignBtn = f.btnLStickL, name = "Left-Stick Left", x = 95, y = 129, shareIdx = GPIndices.LSTICK_U },
new PadPart { idx = GPIndices.LSTICK_D, assignBtn = f.btnLStickD, name = "Left-Stick Down", x = 126, y = 158, shareIdx = GPIndices.LSTICK_U },
new PadPart { idx = GPIndices.LSTICK_R, assignBtn = f.btnLStickR, name = "Left-Stick Right", x = 153, y = 129, shareIdx = GPIndices.LSTICK_U },
new PadPart { idx = GPIndices.BTN_LSTICK, assignBtn = f.btnLStick, name = "Left-Stick Button", x = 126, y = 129, shareIdx = GPIndices.LSTICK_U },
new PadPart { idx = GPIndices.RSTICK_U, assignBtn = f.btnRStickU, name = "Right-Stick Up", x = 321, y = 198, shareIdx = GPIndices.RSTICK_U },
new PadPart { idx = GPIndices.RSTICK_L, assignBtn = f.btnRStickL, name = "Right-Stick Left", x = 290, y = 227, shareIdx = GPIndices.RSTICK_U },
new PadPart { idx = GPIndices.RSTICK_D, assignBtn = f.btnRStickD, name = "Right-Stick Down", x = 321, y = 256, shareIdx = GPIndices.RSTICK_U },
new PadPart { idx = GPIndices.RSTICK_R, assignBtn = f.btnRStickR, name = "Right-Stick Right", x = 348, y = 227, shareIdx = GPIndices.RSTICK_U },
new PadPart { idx = GPIndices.BTN_RSTICK, assignBtn = f.btnRStick, name = "Right-Stick Button", x = 321, y = 227, shareIdx = GPIndices.RSTICK_U },
};
foreach (PadPart part in PadParts)
{
if (part.img != null)
part.r = new Rectangle(part.x, part.y, part.img.Width, part.img.Height);
else if (part.idx != GPIndices._MAX && part.x >= 0)
part.r = new Rectangle(part.x - 20, part.y - 20, 40, 40);
if (part.assignBtn != null)
{ part.assignBtn.Tag = part; part.assignBtn.Click += AssignBtnClick; }
}
f.pad.MouseMove += (object sender, MouseEventArgs e) => { HoverPos = e.Location; };
f.pad.MouseLeave += (object sender, System.EventArgs e) => { HoverPos = new Point(-9999, -9999); };
f.pad.Click += OnClickPad;
f.pad.DoubleClick += OnClickPad;
f.btnAssignAll.Click += (object _s, System.EventArgs _e) =>
{
AssignQueue.Clear();
foreach (PadPart part in PadParts)
if (part.assignBtn != null)
AssignQueue.Add(part);
AssignBtnClick();
};
f.btnAssignCancel.Click += AssignCancel;
f.btnAssignClear.Click += (object _s, System.EventArgs _e) =>
{
if (PadPartAssign == null) return;
Pads[PadIdx].WriteID(PadPartAssign.idx, 0);
FinishAssign();
};
f.btnAssignSwitch.Click += (object _s, System.EventArgs _e) =>
{
if (PadPartAssign != null) { AssignCancel(); return; }
PadPartAssign = PadParts[0];
PadPartAssign.oldId = Pads[PadIdx].IDs[(int)PadPartAssign.idx];
Pads[PadIdx].WriteID(PadPartAssign.idx, GPGamepad.GPID_CAPTURE_NEXT_KEY);
IsDeviceSwitch = true;
};
f.btnDeadzones.Click += (object _s, System.EventArgs _e) =>
{
OnDeadzonesButton();
};
f.btnPresetSave.Click += (object _s, System.EventArgs _e) => OpenPresetList(true);
f.btnPresetLoad.Click += (object _s, System.EventArgs _e) => OpenPresetList(false);
f.btnAssignUndo.Click += (object _s, System.EventArgs _e) => { Pads[PadIdx].NavigateUndo(-1); OnSelectTab(); };
f.btnAssignRedo.Click += (object _s, System.EventArgs _e) => { Pads[PadIdx].NavigateUndo( 1); OnSelectTab(); };
f.btnSwapLeft.Click += (object _s, System.EventArgs _e) => { GPGamepad.Swap(Pads, PadIdx, PadIdx - 1); f.tabs.SelectedIndex -= 1; };
f.btnSwapRight.Click += (object _s, System.EventArgs _e) => { GPGamepad.Swap(Pads, PadIdx, PadIdx + 1); f.tabs.SelectedIndex += 1; };
f.cmbAssignSource.SelectedIndex = 0;
}
static void SetupLaunchTab()
{
f.AllowDrop = true;
f.DragEnter += (object sender, DragEventArgs e) =>
{