forked from x360ce/x360ce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainForm.cs
1304 lines (1208 loc) · 42.5 KB
/
MainForm.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
using SharpDX.DirectInput;
using SharpDX.XInput;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.AccessControl;
using System.Windows.Forms;
using x360ce.App.Controls;
using x360ce.Engine;
using x360ce.App.Properties;
using System.ComponentModel;
using JocysCom.ClassLibrary.IO;
using JocysCom.ClassLibrary.Win32;
using JocysCom.ClassLibrary.Controls;
namespace x360ce.App
{
public partial class MainForm : Form
{
public MainForm()
{
ControlsHelper.InitInvokeContext();
InitializeComponent();
}
DeviceDetector detector;
public static MainForm Current { get; set; }
public int oldIndex;
public int ControllerIndex
{
get
{
int newIndex = -1;
if (MainTabControl.SelectedTab == Pad1TabPage) newIndex = 0;
if (MainTabControl.SelectedTab == Pad2TabPage) newIndex = 1;
if (MainTabControl.SelectedTab == Pad3TabPage) newIndex = 2;
if (MainTabControl.SelectedTab == Pad4TabPage) newIndex = 3;
return newIndex;
}
set
{
switch (value)
{
case 0: MainTabControl.SelectedTab = Pad1TabPage; break;
case 1: MainTabControl.SelectedTab = Pad2TabPage; break;
case 2: MainTabControl.SelectedTab = Pad3TabPage; break;
case 3: MainTabControl.SelectedTab = Pad4TabPage; break;
}
}
}
public AboutControl ControlAbout;
public PadControl[] ControlPads;
public TabPage[] ControlPages;
public System.Timers.Timer UpdateTimer;
public System.Timers.Timer SettingsTimer;
public System.Timers.Timer CleanStatusTimer;
public int DefaultPoolingInterval = 50;
public Controller[] GamePads = new Controller[4];
void MainForm_Load(object sender, EventArgs e)
{
if (IsDesignMode) return;
SettingManager.Settings.Load();
SettingManager.Summaries.Load();
SettingManager.Summaries.Items.ListChanged += Summaries_ListChanged;
// Make sure that data will be filtered before loading.
// Note: Make sure to load Programs before Games.
SettingManager.Programs.FilterList = Programs_FilterList;
SettingManager.Programs.Load();
// Make sure that data will be filtered before loading.
SettingManager.Games.FilterList = Games_FilterList;
SettingManager.Games.Load();
SettingManager.Presets.Load();
SettingManager.PadSettings.Load();
for (int i = 0; i < 4; i++)
{
GamePads[i] = new Controller((UserIndex)i);
}
GameToCustomizeComboBox.DataSource = SettingManager.Games.Items;
GameToCustomizeComboBox.DisplayMember = "DisplayName";
UpdateTimer = new System.Timers.Timer();
UpdateTimer.AutoReset = false;
UpdateTimer.SynchronizingObject = this;
UpdateTimer.Interval = DefaultPoolingInterval;
UpdateTimer.Elapsed += new System.Timers.ElapsedEventHandler(UpdateTimer_Elapsed);
SettingsTimer = new System.Timers.Timer();
SettingsTimer.AutoReset = false;
SettingsTimer.SynchronizingObject = this;
SettingsTimer.Interval = 500;
SettingsTimer.Elapsed += new System.Timers.ElapsedEventHandler(SettingsTimer_Elapsed);
CleanStatusTimer = new System.Timers.Timer();
CleanStatusTimer.AutoReset = false;
CleanStatusTimer.SynchronizingObject = this;
CleanStatusTimer.Interval = 3000;
CleanStatusTimer.Elapsed += new System.Timers.ElapsedEventHandler(CleanStatusTimer_Elapsed);
Text = EngineHelper.GetProductFullName();
SetMinimizeToTray(Settings.Default.MinimizeToTray);
// Start Timers.
UpdateTimer.Start();
}
IList<Engine.Data.Program> Programs_FilterList(IList<Engine.Data.Program> items)
{
// Make sure default settings have unique by file name.
var distinctItems = items
.GroupBy(p => p.FileName.ToLower())
.Select(g => g.First())
.ToList();
return distinctItems;
}
IList<Engine.Data.UserGame> Games_FilterList(IList<Engine.Data.UserGame> items)
{
// Make sure default settings have unique by file name.
var distinctItems = items
.GroupBy(p => p.FileName.ToLower())
.Select(g => g.First())
.ToList();
// Check if current app doesn't exist in the list then...
var appFile = new FileInfo(Application.ExecutablePath);
var appItem = distinctItems.FirstOrDefault(x => x.FileName.ToLower() == appFile.Name.ToLower());
if (appItem == null)
{
// Add x360ce.exe
var scanner = new XInputMaskScanner();
var item = scanner.FromDisk(appFile.Name);
var program = SettingManager.Programs.Items.FirstOrDefault(x => x.FileName.ToLower() == appFile.Name.ToLower());
item.LoadDefault(program);
distinctItems.Add(item);
}
else
{
appItem.FullPath = appFile.FullName;
}
return distinctItems;
}
private void Summaries_ListChanged(object sender, ListChangedEventArgs e)
{
// If map to changed then re-detect devices.
var pd = e.PropertyDescriptor;
if (pd != null && pd.Name == "MapTo")
{
forceRecountDevices = true;
}
}
internal bool IsDesignMode { get { return JocysCom.ClassLibrary.Controls.ControlsHelper.IsDesignMode(this); } }
void detector_DeviceChanged(object sender, DeviceDetectorEventArgs e)
{
forceRecountDevices = true;
}
/// <summary>
/// Link control with INI key. Value/Text of control will be automatically tracked and INI file updated.
/// </summary>
void UpdateSettingsMap()
{
// INI setting keys with controls.
SettingManager.Current.ConfigSaved += new EventHandler<SettingEventArgs>(Current_ConfigSaved);
SettingManager.Current.ConfigLoaded += new EventHandler<SettingEventArgs>(Current_ConfigLoaded);
OptionsPanel.InitSettingsManager();
var sm = SettingManager.Current.SettingsMap;
for (int i = 0; i < ControlPads.Length; i++)
{
var map = ControlPads[i].SettingsMap;
foreach (var key in map.Keys) sm.Add(key, map[key]);
}
}
void Current_ConfigSaved(object sender, SettingEventArgs e)
{
StatusSaveLabel.Text = string.Format("S {0}", e.Count);
}
void Current_ConfigLoaded(object sender, SettingEventArgs e)
{
StatusTimerLabel.Text = string.Format("'{0}' loaded.", e.Name);
}
public void CopyElevated(string source, string dest)
{
if (!WinAPI.IsVista)
{
File.Copy(source, dest);
return;
}
var di = new DirectoryInfo(System.IO.Path.GetDirectoryName(dest));
var security = di.GetAccessControl();
var fi = new FileInfo(dest);
var fileSecurity = fi.GetAccessControl();
// Allow Users to Write.
//SecurityIdentifier SID = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
//fileSecurity.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.Write, AccessControlType.Allow));
//fi.SetAccessControl(fileSecurity);
var rules = security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
string message = string.Empty;
foreach (var myacc in rules)
{
var acc = (FileSystemAccessRule)myacc;
message += string.Format("IdentityReference: {0}\r\n", acc.IdentityReference.Value);
message += string.Format("Access Control Type: {0}\r\n", acc.AccessControlType.ToString());
message += string.Format("\t{0}\r\n", acc.FileSystemRights.ToString());
//if ((acc.FileSystemRights & FileSystemRights.FullControl) == FileSystemRights.FullControl)
//{
// Console.Write("FullControl");
//}
//if ((acc.FileSystemRights & FileSystemRights.ReadData) == FileSystemRights.ReadData)
//{
// Console.Write("ReadData");
//}
//if ((acc.FileSystemRights & FileSystemRights.WriteData) == FileSystemRights.WriteData)
//{
// Console.Write("WriteData");
//}
//if ((acc.FileSystemRights & FileSystemRights.ListDirectory) == FileSystemRights.ListDirectory)
//{
// Console.Write("ListDirectory");
//}
//if ((acc.FileSystemRights & FileSystemRights.ExecuteFile) == FileSystemRights.ExecuteFile)
//{
// Console.Write("ExecuteFile");
//}
}
MessageBox.Show(message);
//WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
// FileSystemAccessRule rule = new FileSystemAccessRule(
// self.Name,
// FileSystemRights.FullControl,
// AccessControlType.Allow);
}
void MainForm_KeyDown(object sender, KeyEventArgs e)
{
for (int i = 0; i < ControlPads.Length; i++)
{
// If Escape key was pressed while recording then...
if (e.KeyCode == Keys.Escape)
{
var recordingWasStopped = ControlPads[i].StopRecording();
if (recordingWasStopped)
{
e.Handled = true;
e.SuppressKeyPress = true;
};
}
}
StatusTimerLabel.Text = "";
}
void CleanStatusTimer_Elapsed(object sender, EventArgs e)
{
if (Program.IsClosing) return;
StatusTimerLabel.Text = "";
}
#region Setting Events
public void LoadPreset(string name, int index)
{
// exit if "Presets:" or "Embedded:".
if (name.Contains(":")) return;
var prefix = Path.GetFileNameWithoutExtension(SettingManager.IniFileName);
var ext = Path.GetExtension(SettingManager.IniFileName);
string resourceName = string.Format("{0}.{1}{2}", prefix, name, ext);
var resource = EngineHelper.GetResourceStream("Presets." + resourceName);
// If internal preset was found.
if (resource != null)
{
// Export file.
var sr = new StreamReader(resource);
File.WriteAllText(resourceName, sr.ReadToEnd());
}
SuspendEvents();
// Preset will be stored in inside [PAD1] section;
SettingManager.Current.ReadPadSettings(resourceName, "PAD1", index);
ResumeEvents();
// Save setting and notify if value changed.
if (SettingManager.Current.SaveSettings()) NotifySettingsChange();
// remove file if it was from resource.
if (resource != null) File.Delete(resourceName);
//CleanStatusTimer.Start();
}
int resumed = 0;
int suspended = 0;
object eventsLock = new object();
object eventsEnabled = false;
public void SuspendEvents()
{
lock (eventsLock)
{
StatusEventsLabel.Text = "OFF...";
// Don't allow controls to fire events.
foreach (var control in SettingManager.Current.SettingsMap.Values)
{
if (control is TrackBar) ((TrackBar)control).ValueChanged -= new EventHandler(Control_ValueChanged);
if (control is ListBox) ((ListBox)control).SelectedIndexChanged -= new EventHandler(Control_SelectedIndexChanged);
if (control is NumericUpDown) ((NumericUpDown)control).ValueChanged -= new EventHandler(Control_ValueChanged);
if (control is CheckBox) ((CheckBox)control).CheckedChanged -= new EventHandler(Control_CheckedChanged);
if (control is ComboBox)
{
var cbx = (ComboBox)control;
if (cbx.DropDownStyle == ComboBoxStyle.DropDownList)
{
cbx.SelectedIndexChanged -= new EventHandler(this.Control_TextChanged);
}
else
{
control.TextChanged -= new EventHandler(this.Control_TextChanged);
}
}
// || control is TextBox
}
suspended++;
StatusEventsLabel.Text = string.Format("OFF {0} {1}", suspended, resumed);
}
}
public void ResumeEvents()
{
lock (eventsLock)
{
StatusEventsLabel.Text = "ON...";
// Allow controls to fire events.
foreach (var control in SettingManager.Current.SettingsMap.Values)
{
if (control is TrackBar) ((TrackBar)control).ValueChanged += new EventHandler(Control_ValueChanged);
if (control is ListBox) ((ListBox)control).SelectedIndexChanged += new EventHandler(Control_SelectedIndexChanged);
if (control is NumericUpDown) ((NumericUpDown)control).ValueChanged += new EventHandler(Control_ValueChanged);
if (control is CheckBox) ((CheckBox)control).CheckedChanged += new EventHandler(Control_CheckedChanged);
if (control is ComboBox)
{
var cbx = (ComboBox)control;
if (cbx.DropDownStyle == ComboBoxStyle.DropDownList)
{
cbx.SelectedIndexChanged += new EventHandler(this.Control_TextChanged);
}
else
{
control.TextChanged += new EventHandler(this.Control_TextChanged);
}
}
// || control is TextBox
}
resumed++;
StatusEventsLabel.Text = string.Format("ON {0} {1}", suspended, resumed);
}
}
/// <summary>
/// Delay settings trough timer so interface will be more responsive on TrackBars.
/// Or fast changes. Library will be reloaded as soon as user calms down (no setting changes in 500ms).
/// </summary>
public void NotifySettingsChange()
{
UpdateTimer.Stop();
SettingsTimer.Stop();
// Timer will be started inside Settings timer.
SettingsTimer.Start();
}
void Control_TextChanged(object sender, EventArgs e)
{
// Save setting and notify if value changed.
if (SettingManager.Current.SaveSetting((Control)sender)) NotifySettingsChange();
}
Dictionary<string, int> ListBoxCounts = new Dictionary<string, int>();
/// <summary>Monitor changes remove/add inside ListBoxes.</summary>
void Control_SelectedIndexChanged(object sender, EventArgs e)
{
lock (ListBoxCounts)
{
var lb = (ListBox)sender;
// If list contains count of ListBoxes items.
if (ListBoxCounts.ContainsKey(lb.Name))
{
// If ListBoxe haven't changed then return;
if (ListBoxCounts[lb.Name] == lb.Items.Count) return;
ListBoxCounts[lb.Name] = lb.Items.Count;
}
else
{
ListBoxCounts.Add(lb.Name, lb.Items.Count);
}
}
// Save setting and notify if value changed.
if (SettingManager.Current.SaveSetting((Control)sender)) NotifySettingsChange();
}
void Control_ValueChanged(object sender, EventArgs e)
{
// Save setting and notify if value changed.
if (SettingManager.Current.SaveSetting((Control)sender)) NotifySettingsChange();
}
void Control_CheckedChanged(object sender, EventArgs e)
{
// Save setting and notify if value changed.
if (SettingManager.Current.SaveSetting((Control)sender)) NotifySettingsChange();
}
public void ReloadXinputSettings()
{
SuspendEvents();
SettingManager.Current.ReadSettings();
ResumeEvents();
}
public void SaveSettings()
{
UpdateTimer.Stop();
// Save settings to INI file.
SettingManager.Current.SaveSettings();
// Overwrite Temp file.
var ini = new FileInfo(SettingManager.IniFileName);
ini.CopyTo(SettingManager.TmpFileName, true);
StatusTimerLabel.Text = "Settings saved";
UpdateTimer.Start();
}
#endregion
void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
Program.IsClosing = true;
if (UpdateTimer != null) UpdateTimer.Stop();
// Disable force feedback effect before closing app.
try
{
lock (Controller.XInputLock)
{
for (int i = 0; i < 4; i++)
{
//if (ControlPads[i].LeftMotorTestTrackBar.Value > 0 || ControlPads[i].RightMotorTestTrackBar.Value > 0)
//{
var gamePad = GamePads[i];
if (Controller.IsLoaded && gamePad.IsConnected)
{
// Disable force feedback.
ControlPads[i].TestEnabled = false;
gamePad.SetVibration(new Vibration());
}
//}
}
//BeginInvoke((Action)delegate()
//{
// XInput.FreeLibrary();
//});
}
// Logical delay without blocking the current thread.
System.Threading.Tasks.Task.Delay(100).Wait();
}
catch (Exception) { }
var tmp = new FileInfo(SettingManager.TmpFileName);
var ini = new FileInfo(SettingManager.IniFileName);
if (tmp.Exists)
{
// Before renaming file check for changes.
var changed = false;
if (tmp.Length != ini.Length) { changed = true; }
else
{
var tmpChecksum = EngineHelper.GetFileChecksum(tmp.FullName);
var iniChecksum = EngineHelper.GetFileChecksum(ini.FullName);
changed = !tmpChecksum.Equals(iniChecksum);
}
if (changed)
{
var form = new JocysCom.ClassLibrary.Controls.MessageBoxForm();
form.StartPosition = FormStartPosition.CenterParent;
var result = form.ShowForm(
"Do you want to save changes you made to configuration?",
"Save Changes?",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
if (result == DialogResult.Yes)
{
// Do nothing since INI contains latest updates.
}
else if (result == DialogResult.No)
{
// Rename temp to INI.
tmp.CopyTo(SettingManager.IniFileName, true);
}
else if (result == DialogResult.Cancel)
{
e.Cancel = true;
return;
}
}
// delete temp.
tmp.Delete();
}
Settings.Default.Save();
SettingManager.Settings.Save();
SettingManager.Summaries.Save();
SettingManager.Programs.Save();
SettingManager.Games.Save();
SettingManager.Presets.Save();
SettingManager.PadSettings.Save();
}
#region Timer
DeviceInstance[] diInstancesOld = new DeviceInstance[4];
DeviceInstance[] diInstances = new DeviceInstance[4];
Joystick[] diDevices = new Joystick[4];
DeviceInfo[] diInfos = new DeviceInfo[4];
public bool forceRecountDevices = true;
string deviceInstancesOld = "";
string deviceInstancesNew = "";
public Guid AutoSelectControllerInstance = Guid.Empty;
public DirectInput Manager = new DirectInput();
/// <summary>
/// Get array[4] of direct input devices.
/// </summary>
DeviceInstance[] GetDevices()
{
var devices = Manager.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AllDevices).ToList();
if (SettingManager.Current.ExcludeSuplementalDevices)
{
// Supplemental devices are specialized device with functionality unsuitable for the main control of an application,
// such as pedals used with a wheel.The following subtypes are defined.
var supplementals = devices.Where(x => x.Type == SharpDX.DirectInput.DeviceType.Supplemental).ToArray();
foreach (var supplemental in supplementals)
{
devices.Remove(supplemental);
}
}
if (SettingManager.Current.ExcludeVirtualDevices)
{
// Exclude virtual devices so application could feed them.
var virtualDevices = devices.Where(x => x.InstanceName.Contains("vJoy")).ToArray();
foreach (var virtualDevice in virtualDevices)
{
devices.Remove(virtualDevice);
}
}
// Move gaming wheels to the top index position by default.
// Games like GTA need wheel to be first device to work properly.
var wheels = devices.Where(x => x.Type == SharpDX.DirectInput.DeviceType.Driving || x.Subtype == (int)DeviceSubType.Wheel).ToArray();
foreach (var wheel in wheels)
{
devices.Remove(wheel);
devices.Insert(0, wheel);
}
var orderedDevices = new DeviceInstance[4];
// Assign devices to their positions.
for (int d = 0; d < devices.Count; d++)
{
var ig = devices[d].InstanceGuid;
var section = SettingManager.Current.GetInstanceSection(ig);
var ini2 = new Ini(SettingManager.IniFileName);
string v = ini2.GetValue(section, SettingName.MapToPad);
int mapToPad = 0;
if (int.TryParse(v, out mapToPad) && mapToPad > 0 && mapToPad <= 4)
{
// If position is not occupied then...
if (orderedDevices[mapToPad - 1] == null)
{
orderedDevices[mapToPad - 1] = devices[d];
}
}
}
// Get list of unassigned devices.
var unassignedDevices = devices.Except(orderedDevices).ToArray();
for (int i = 0; i < unassignedDevices.Length; i++)
{
// Assign to first empty slot.
for (int d = 0; d < orderedDevices.Length; d++)
{
// If position is not occupied then...
if (orderedDevices[d] == null)
{
orderedDevices[d] = unassignedDevices[i];
break;
}
}
}
return orderedDevices;
}
/// <summary>
/// Access this only inside Timer_Click!
/// </summary>
bool RefreshCurrentInstances(bool forceReload = false)
{
// If you encounter "LoaderLock was detected" Exception when debugging then:
// Make sure that you have reference to Microsoft.Directx.dll.
bool instancesChanged = false;
DeviceInstance[] devices = null;
//var types = DeviceType.Driving | DeviceType.Flight | DeviceType.Gamepad | DeviceType.Joystick | DeviceType.FirstPerson;
if (forceRecountDevices || forceReload)
{
devices = GetDevices();
// Sore device instances and their order here.
deviceInstancesNew = string.Join(",", devices.Select(x => x == null ? "" : x.InstanceGuid.ToString()));
forceRecountDevices = false;
}
//Populate All devices
if (deviceInstancesNew != deviceInstancesOld)
{
deviceInstancesOld = deviceInstancesNew;
if (devices == null) devices = GetDevices();
var instances = devices;
// Dispose from previous list of devices.
for (int i = 0; i < 4; i++)
{
if (diDevices[i] != null)
{
// Dispose current device.
diDevices[i].Unacquire();
diDevices[i].Dispose();
}
}
// Create new list of devices.
for (int i = 0; i < 4; i++)
{
var inst = instances[i];
if (inst == null)
{
diDevices[i] = null;
diInfos[i] = null;
}
else
{
var j = new Joystick(Manager, inst.InstanceGuid);
diDevices[i] = j;
var classGuid = j.Properties.ClassGuid;
var interfacePath = j.Properties.InterfacePath;
// Must find better way to find Device than by Vendor ID and Product ID.
var devs = DeviceDetector.GetDevices(classGuid, DIGCF.DIGCF_ALLCLASSES, null, j.Properties.VendorId, j.Properties.ProductId, 0);
diInfos[i] = devs.FirstOrDefault();
}
}
SettingsDatabasePanel.BindDevices(instances);
SettingsDatabasePanel.BindFiles();
for (int i = 0; i < 4; i++)
{
// Backup old instance.
diInstancesOld[i] = diInstances[i];
// Assign new instance.
diInstances[i] = instances[i];
}
instancesChanged = true;
}
// Return true if instances changed.
return instancesChanged;
}
void SettingsTimer_Elapsed(object sender, EventArgs e)
{
if (Program.IsClosing) return;
settingsChanged = true;
UpdateTimer.Start();
}
bool settingsChanged = false;
State emptyState = new State();
bool[] cleanPadStatus = new bool[4];
object formLoadLock = new object();
public bool update1Enabled = true;
public bool? update2Enabled;
public bool update3Enabled = false;
void UpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (Program.IsClosing) return;
Program.TimerCount++;
lock (formLoadLock)
{
if (update1Enabled)
{
update1Enabled = false;
UpdateForm1();
// Update 2 part will be enabled after all issues are checked.
}
if (update2Enabled.HasValue && update2Enabled.Value)
{
update2Enabled = false;
UpdateForm2();
update3Enabled = true;
}
if (update3Enabled)
{
UpdateForm3();
}
}
UpdateTimer.Start();
}
void UpdateForm1()
{
detector = new DeviceDetector(false);
detector.DeviceChanged += new DeviceDetector.DeviceDetectorEventHandler(detector_DeviceChanged);
BusyLoadingCircle.Visible = false;
BusyLoadingCircle.Top = HeaderPictureBox.Top;
BusyLoadingCircle.Left = HeaderPictureBox.Left;
defaultBody = HelpBodyLabel.Text;
//if (DesignMode) return;
OptionsPanel.InitOptions();
// Set status.
StatusSaveLabel.Visible = false;
StatusEventsLabel.Visible = false;
// Load Tab pages.
ControlPages = new TabPage[4];
ControlPages[0] = Pad1TabPage;
ControlPages[1] = Pad2TabPage;
ControlPages[2] = Pad3TabPage;
ControlPages[3] = Pad4TabPage;
//BuletImageList.Images.Add("bullet_square_glass_blue.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_blue.png")));
//BuletImageList.Images.Add("bullet_square_glass_green.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_green.png")));
//BuletImageList.Images.Add("bullet_square_glass_grey.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_grey.png")));
//BuletImageList.Images.Add("bullet_square_glass_red.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_red.png")));
//BuletImageList.Images.Add("bullet_square_glass_yellow.png", new Bitmap(Helper.GetResource("Images.bullet_square_glass_yellow.png")));
foreach (var item in ControlPages) item.ImageKey = "bullet_square_glass_grey.png";
// Hide status values.
StatusDllLabel.Text = "";
MainStatusStrip.Visible = false;
// Check if INI and DLL is on disk.
WarningsForm.CheckAndOpen();
}
void UpdateForm2()
{
// Set status labels.
StatusIsAdminLabel.Text = WinAPI.IsVista
? string.Format("Elevated: {0}", WinAPI.IsElevated())
: "";
StatusIniLabel.Text = SettingManager.IniFileName;
CheckEncoding(SettingManager.TmpFileName);
CheckEncoding(SettingManager.IniFileName);
// Show status values.
MainStatusStrip.Visible = true;
// Load PAD controls.
ControlPads = new PadControl[4];
for (int i = 0; i < ControlPads.Length; i++)
{
ControlPads[i] = new Controls.PadControl(i);
ControlPads[i].Name = string.Format("ControlPad{0}", i + 1);
ControlPads[i].Dock = DockStyle.Fill;
ControlPages[i].Controls.Add(ControlPads[i]);
ControlPads[i].InitPadControl();
}
// Initialize pre-sets. Execute only after name of cIniFile is set.
//SettingsDatabasePanel.InitPresets();
// Allow events after PAD control are loaded.
MainTabControl.SelectedIndexChanged += new System.EventHandler(this.MainTabControl_SelectedIndexChanged);
// Load about control.
ControlAbout = new AboutControl();
ControlAbout.Dock = DockStyle.Fill;
AboutTabPage.Controls.Add(ControlAbout);
// Update settings map.
UpdateSettingsMap();
ReloadXinputSettings();
//// start capture events.
if (WinAPI.IsVista && WinAPI.IsElevated() && WinAPI.IsInAdministratorRole) this.Text += " (Administrator)";
}
void UpdateForm3()
{
bool instancesChanged = RefreshCurrentInstances(settingsChanged);
// Load direct input data.
for (int i = 0; i < 4; i++)
{
var currentPadControl = ControlPads[i];
var currentDevice = diDevices[i];
var currentDeviceInfo = diInfos[i];
// If current device is empty then..
if (currentDevice == null)
{
// but form contains data then...
if (!cleanPadStatus[i])
{
// Clear all settings.
SuspendEvents();
SettingManager.Current.ClearPadSettings(i);
ResumeEvents();
cleanPadStatus[i] = true;
}
}
else
{
cleanPadStatus[i] = false;
}
currentPadControl.UpdateFromDirectInput(currentDevice, currentDeviceInfo);
}
// If settings changed or directInput instances changed then...
if (settingsChanged || instancesChanged)
{
if (instancesChanged)
{
var updated = SettingManager.Current.CheckSettings(diInstances, diInstancesOld);
if (updated) SettingManager.Current.SaveSettings();
}
ReloadLibrary();
}
else
{
for (int i = 0; i < 4; i++)
{
// DInput instance is ON.
var diOn = diInstances[i] != null;
// XInput instance is ON.
//XInput.Controllers[i].PollState();
var xiOn = false;
State currentPad = emptyState;
var currentPadControl = ControlPads[i];
lock (Controller.XInputLock)
{
var gamePad = GamePads[i];
if (Controller.IsLoaded)
{
State state;
if (gamePad.GetState(out state))
{
currentPad = state;
xiOn = true;
}
}
}
currentPadControl.UpdateFromXInput(currentPad, xiOn);
// Update LED of GamePad state.
string image = diOn
// DInput ON, XInput ON
? xiOn ? "green"
// DInput ON, XInput OFF
: "red"
// DInput OFF, XInput ON
: xiOn ? "yellow"
// DInput OFF, XInput OFF
: "grey";
string bullet = string.Format("bullet_square_glass_{0}.png", image);
if (ControlPages[i].ImageKey != bullet) ControlPages[i].ImageKey = bullet;
}
UpdateStatus("");
}
}
public void ReloadLibrary()
{
Program.ReloadCount++;
settingsChanged = false;
var dllInfo = EngineHelper.GetDefaultDll();
if (dllInfo != null && dllInfo.Exists)
{
bool byMicrosoft;
var dllVersion = EngineHelper.GetDllVersion(dllInfo.FullName, out byMicrosoft);
StatusDllLabel.Text = dllInfo.Name + " " + dllVersion.ToString() + (byMicrosoft ? " (Microsoft)" : "");
// If fast reload of settings is supported then...
lock (Controller.XInputLock)
{
if (Controller.IsResetSupported)
{
Controller.Reset();
}
// Slow: Reload whole x360ce.dll.
Exception error;
//forceRecountDevices = true;
Controller.ReLoadLibrary(dllInfo.FullName, out error);
if (!Controller.IsLoaded)
{
var caption = string.Format("Failed to load '{0}'", dllInfo.FullName);
var text = string.Format("{0}", error == null ? "Unknown error" : error.Message);
var form = new JocysCom.ClassLibrary.Controls.MessageBoxForm();
form.StartPosition = FormStartPosition.CenterParent;
form.ShowForm(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
for (int i = 0; i < 4; i++)
{
var currentPadControl = ControlPads[i];
currentPadControl.UpdateForceFeedBack();
}
}
}
}
else
{
StatusDllLabel.Text = "";
}
}
public void UpdateStatus(string message)
{
StatusTimerLabel.Text = string.Format("Count: {0}, Reloads: {1}, Errors: {2} {3}",
Program.TimerCount, Program.ReloadCount, Program.ErrorCount, message);
}
#endregion
bool HelpInit = false;
void MainTabControl_SelectedIndexChanged(object sender, EventArgs e)
{
if (MainTabControl.SelectedTab == HelpTabPage && !HelpInit)
{
// Move this here so interface will load one second faster.
HelpInit = true;
var stream = EngineHelper.GetResourceStream("Documents.Help.htm");
var sr = new StreamReader(stream);
NameValueCollection list = new NameValueCollection();
list.Add("font-name-default", "'Microsoft Sans Serif'");
list.Add("font-size-default", "16");
HelpRichTextBox.Rtf = Html2Rtf.Converter.Html2Rtf(sr.ReadToEnd(), list);
HelpRichTextBox.SelectAll();
HelpRichTextBox.SelectionIndent = 8;
HelpRichTextBox.SelectionRightIndent = 8;
HelpRichTextBox.DeselectAll();
}
else if (MainTabControl.SelectedTab == ControllerSettingsTabPage)
{
if (OptionsPanel.InternetCheckBox.Checked && OptionsPanel.InternetAutoloadCheckBox.Checked)
{
SettingsDatabasePanel.RefreshGrid(true);
}
}
UpdateHelpHeader();
}
#region Help Header
string defaultBody;
public void UpdateHelpHeader(string message, MessageBoxIcon icon)
{
HelpSubjectLabel.Text = MainTabControl.SelectedTab.Text;
if (ControllerIndex > -1)
{
var currentPadControl = ControlPads[ControllerIndex];
HelpSubjectLabel.Text += " - " + currentPadControl.PadTabControl.SelectedTab.Text;
}
HelpBodyLabel.Text = string.IsNullOrEmpty(message) ? defaultBody : message;
if (icon == MessageBoxIcon.Error) HelpBodyLabel.ForeColor = System.Drawing.Color.DarkRed;
else if (icon == MessageBoxIcon.Information) HelpBodyLabel.ForeColor = System.Drawing.Color.DarkGreen;
else HelpBodyLabel.ForeColor = System.Drawing.SystemColors.ControlText;
}
public void UpdateHelpHeader(string message)
{
UpdateHelpHeader(message, MessageBoxIcon.None);
}
public void UpdateHelpHeader()
{
UpdateHelpHeader(defaultBody, MessageBoxIcon.None);
}
#endregion
#region Check Files
void CheckEncoding(string path)
{
if (!File.Exists(path)) return;
var sr = new StreamReader(path, true);
var content = sr.ReadToEnd();
sr.Close();
if (sr.CurrentEncoding != System.Text.Encoding.Unicode)
{
File.WriteAllText(path, content, System.Text.Encoding.Unicode);
}
}
bool IsFileSame(string fileName)
{
return false;
//if (!System.IO.File.Exists(fileName)) return false;
//var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
//StreamReader sr;
//// Get MD5 of file on the disk.
//sr = new StreamReader(fileName);
//var dMd5 = new Guid(md5.ComputeHash(sr.BaseStream));
//// Get MD5 of resource file.
//if (fileName == dllFile0) fileName = dllFile;