-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGpdGui.cs
More file actions
1964 lines (1756 loc) · 73.7 KB
/
GpdGui.cs
File metadata and controls
1964 lines (1756 loc) · 73.7 KB
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 System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using GpdControl;
namespace GpdGui
{
public class MainForm : Form
{
// private ListBox keyList;
// private ComboBox valueCombo;
private Button applyButton;
private Button reloadButton;
private Button checkUpdatesButton;
private Button accessibilityButton;
private CheckBox safeApplyCheckBox;
private Label statusLabel;
private TabControl mainTabControl;
private Config currentConfig;
private GpdDevice device;
private const string CurrentAppVersion = "2.0.1";
private const string ReleasesApiUrl = "https://api.github.com/repos/VIPPotato/Better-GPD-WinControls/releases/latest";
private const string ReleasesPageUrl = "https://github.com/VIPPotato/Better-GPD-WinControls/releases";
public MainForm()
{
this.Text = "Better GPD WinControl";
this.Size = new Size(600, 500);
this.StartPosition = FormStartPosition.CenterScreen;
// Layout
TableLayoutPanel mainLayout = new TableLayoutPanel();
mainLayout.Dock = DockStyle.Fill;
mainLayout.RowCount = 4;
mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 40)); // Top buttons
mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); // Content
mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 40)); // Footer buttons
mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 30)); // Status
this.Controls.Add(mainLayout);
// Top Buttons
FlowLayoutPanel buttonPanel = new FlowLayoutPanel();
buttonPanel.Dock = DockStyle.Fill;
reloadButton = new Button();
reloadButton.Text = "Reload from Device";
reloadButton.AutoSize = true;
reloadButton.Click += new EventHandler(ReloadButton_Click);
applyButton = new Button();
applyButton.Text = "Apply Changes";
applyButton.AutoSize = true;
applyButton.Click += new EventHandler(ApplyButton_Click);
Button resetButton = new Button();
resetButton.Text = "Reset to Defaults";
resetButton.AutoSize = true;
resetButton.Click += new EventHandler(ResetButton_Click);
safeApplyCheckBox = new CheckBox();
safeApplyCheckBox.Text = "Safe Apply Verify";
safeApplyCheckBox.AutoSize = true;
safeApplyCheckBox.Checked = true;
buttonPanel.Controls.Add(reloadButton);
buttonPanel.Controls.Add(applyButton);
buttonPanel.Controls.Add(resetButton);
buttonPanel.Controls.Add(safeApplyCheckBox);
mainLayout.Controls.Add(buttonPanel, 0, 0);
// Content Tabs
mainTabControl = new TabControl();
mainTabControl.Dock = DockStyle.Fill;
mainLayout.Controls.Add(mainTabControl, 0, 1);
// 1. Buttons Tab
TabPage buttonsTab = new TabPage("Buttons");
mainTabControl.TabPages.Add(buttonsTab);
CreateListTab(buttonsTab, "Key");
// 2. Macros Tab
TabPage macrosTab = new TabPage("Macros");
mainTabControl.TabPages.Add(macrosTab);
CreateListTab(macrosTab, "Macro");
// 3. Settings Tab
TabPage settingsTab = new TabPage("Settings");
mainTabControl.TabPages.Add(settingsTab);
CreateSettingsTab(settingsTab);
// 4. Profiles Tab
TabPage profilesTab = new TabPage("Profiles");
mainTabControl.TabPages.Add(profilesTab);
CreateProfilesTab(profilesTab);
// Status
statusLabel = new Label();
statusLabel.Dock = DockStyle.Fill;
statusLabel.TextAlign = ContentAlignment.MiddleLeft;
statusLabel.Text = "Ready.";
mainLayout.Controls.Add(statusLabel, 0, 3);
// Footer Buttons (visible across all tabs)
FlowLayoutPanel footerPanel = new FlowLayoutPanel();
footerPanel.Dock = DockStyle.Fill;
footerPanel.FlowDirection = FlowDirection.LeftToRight;
footerPanel.WrapContents = false;
checkUpdatesButton = new Button();
checkUpdatesButton.Text = "Check for Updates";
checkUpdatesButton.AutoSize = true;
checkUpdatesButton.Click += CheckUpdatesButton_Click;
Button backupButton = new Button();
backupButton.Text = "Backup Config";
backupButton.AutoSize = true;
backupButton.Click += BackupButton_Click;
Button restoreButton = new Button();
restoreButton.Text = "Restore Config";
restoreButton.AutoSize = true;
restoreButton.Click += RestoreButton_Click;
Button dataFolderButton = new Button();
dataFolderButton.Text = "Data Folder...";
dataFolderButton.AutoSize = true;
dataFolderButton.Click += DataFolderButton_Click;
accessibilityButton = new Button();
accessibilityButton.Text = "Accessibility: Off";
accessibilityButton.AutoSize = true;
accessibilityButton.Click += AccessibilityButton_Click;
Button aboutButton = new Button();
aboutButton.Text = "About";
aboutButton.AutoSize = true;
aboutButton.Click += AboutButton_Click;
Button exitButton = new Button();
exitButton.Text = "Exit";
exitButton.AutoSize = true;
exitButton.Click += ExitButton_Click;
footerPanel.Controls.Add(checkUpdatesButton);
footerPanel.Controls.Add(backupButton);
footerPanel.Controls.Add(restoreButton);
footerPanel.Controls.Add(dataFolderButton);
footerPanel.Controls.Add(accessibilityButton);
footerPanel.Controls.Add(aboutButton);
footerPanel.Controls.Add(exitButton);
mainLayout.Controls.Add(footerPanel, 0, 2);
this.Shown += (s, e) =>
{
Application.DoEvents();
GpdDevice openedDevice = null;
Config loadedConfig = null;
RunBackgroundAction("Connecting to device...", delegate
{
openedDevice = new GpdDevice();
openedDevice.Open();
byte[] data = openedDevice.ReadConfig();
loadedConfig = new Config(data);
},
delegate
{
device = openedDevice;
currentConfig = loadedConfig;
RefreshList();
statusLabel.Text = string.Format("Configuration loaded. Firmware: {0}", device.FirmwareVersion);
SetConnectedState(true);
CheckForUpdates(false);
},
delegate(Exception ex)
{
if (openedDevice != null) openedDevice.Dispose();
MessageBox.Show("Could not connect to device: " + ex.Message);
statusLabel.Text = "Disconnected.";
currentConfig = null;
device = null;
SetConnectedState(false);
GuiLogger.LogException("Initial device connection failed", ex);
CheckForUpdates(false);
});
};
SetConnectedState(false);
GuiLogger.Log("MainForm initialized.");
}
private Dictionary<string, ListBox> tabLists = new Dictionary<string, ListBox>();
private Dictionary<string, ComboBox> tabCombos = new Dictionary<string, ComboBox>();
private Dictionary<string, Button> tabCaptureButtons = new Dictionary<string, Button>();
// For settings tab controls
private Dictionary<string, Control> settingControls = new Dictionary<string, Control>();
private bool _suppressComboEvents;
private bool _accessibilityMode;
private bool _isBusy;
private void SetConnectedState(bool connected)
{
applyButton.Enabled = connected && !_isBusy;
}
private bool TryBeginBusy(string statusText)
{
if (_isBusy)
{
statusLabel.Text = "Please wait for the current operation to finish.";
return false;
}
_isBusy = true;
UseWaitCursor = true;
if (!string.IsNullOrWhiteSpace(statusText))
{
statusLabel.Text = statusText;
}
if (mainTabControl != null) mainTabControl.Enabled = false;
if (reloadButton != null) reloadButton.Enabled = false;
if (safeApplyCheckBox != null) safeApplyCheckBox.Enabled = false;
if (checkUpdatesButton != null) checkUpdatesButton.Enabled = false;
applyButton.Enabled = false;
return true;
}
private void EndBusy(string statusText)
{
_isBusy = false;
UseWaitCursor = false;
if (!string.IsNullOrWhiteSpace(statusText))
{
statusLabel.Text = statusText;
}
if (mainTabControl != null) mainTabControl.Enabled = true;
if (reloadButton != null) reloadButton.Enabled = true;
if (safeApplyCheckBox != null) safeApplyCheckBox.Enabled = true;
if (checkUpdatesButton != null) checkUpdatesButton.Enabled = true;
SetConnectedState(device != null && currentConfig != null);
}
private void RunBackgroundAction(string startStatus, Action worker, Action onSuccess, Action<Exception> onError)
{
if (!TryBeginBusy(startStatus)) return;
ThreadPool.QueueUserWorkItem(delegate
{
Exception workerError = null;
try
{
worker();
}
catch (Exception ex)
{
workerError = ex;
}
Action complete = delegate
{
try
{
if (workerError == null)
{
if (onSuccess != null) onSuccess();
}
else
{
if (onError != null) onError(workerError);
}
}
finally
{
EndBusy(null);
}
};
try
{
if (IsHandleCreated && !IsDisposed)
{
BeginInvoke(complete);
}
else
{
_isBusy = false;
}
}
catch
{
_isBusy = false;
}
});
}
private bool EnsureConnectedAndLoaded()
{
if (_isBusy)
{
statusLabel.Text = "Please wait for the current operation to finish.";
return false;
}
if (device == null)
{
try
{
device = new GpdDevice();
device.Open();
}
catch (Exception ex)
{
MessageBox.Show("Could not connect to device: " + ex.Message);
statusLabel.Text = "Disconnected.";
SetConnectedState(false);
GuiLogger.LogException("EnsureConnectedAndLoaded connection failed", ex);
return false;
}
}
if (currentConfig == null)
{
LoadConfig();
if (currentConfig == null) return false;
}
return true;
}
private bool TryResolveProfilePath(string profileName, out string fullPath, out string error)
{
fullPath = null;
error = null;
if (string.IsNullOrWhiteSpace(profileName))
{
error = "Profile name cannot be empty.";
return false;
}
if (profileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0 || profileName.Contains("\\") || profileName.Contains("/"))
{
error = "Profile name contains invalid characters.";
return false;
}
string profilesDir = AppPaths.ProfilesDir;
string baseDir = System.IO.Path.GetFullPath(profilesDir).TrimEnd(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar)
+ System.IO.Path.DirectorySeparatorChar;
string candidate = System.IO.Path.GetFullPath(System.IO.Path.Combine(profilesDir, profileName + ".txt"));
if (!candidate.StartsWith(baseDir, StringComparison.OrdinalIgnoreCase))
{
error = "Profile path escapes the profiles directory.";
return false;
}
fullPath = candidate;
return true;
}
private void PopulateKeyCombo(ComboBox combo)
{
combo.Items.Clear();
foreach (string key in KeyCodes.Map.Keys) combo.Items.Add(key);
combo.AutoCompleteSource = AutoCompleteSource.ListItems;
combo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
}
private void SetCaptureButtonState(string type, bool enabled)
{
Button captureButton;
if (tabCaptureButtons.TryGetValue(type, out captureButton))
{
captureButton.Enabled = enabled;
captureButton.Visible = enabled;
}
}
private void CheckUpdatesButton_Click(object sender, EventArgs e)
{
if (_isBusy) return;
CheckForUpdates(true);
}
private void AccessibilityButton_Click(object sender, EventArgs e)
{
SetAccessibilityMode(!_accessibilityMode);
}
private void SetAccessibilityMode(bool enabled)
{
_accessibilityMode = enabled;
if (accessibilityButton != null)
{
accessibilityButton.Text = enabled ? "Accessibility: On" : "Accessibility: Off";
}
float size = enabled ? 11.0f : 8.25f;
ApplyFontRecursive(this, size);
if (enabled)
{
this.Size = new Size(820, 620);
statusLabel.Text = "Accessibility mode enabled.";
}
else
{
this.Size = new Size(600, 500);
statusLabel.Text = "Accessibility mode disabled.";
}
GuiLogger.Log("Accessibility mode set to " + enabled);
}
private void ApplyFontRecursive(Control root, float size)
{
if (root == null) return;
try
{
root.Font = new Font(root.Font.FontFamily, size, root.Font.Style);
}
catch
{
}
foreach (Control child in root.Controls)
{
ApplyFontRecursive(child, size);
}
}
private void ShowInfo(string message, string statusText)
{
if (!string.IsNullOrWhiteSpace(statusText))
{
statusLabel.Text = statusText;
}
if (_accessibilityMode)
{
GuiLogger.Log("Info: " + message);
return;
}
MessageBox.Show(message);
}
private void BackupButton_Click(object sender, EventArgs e)
{
if (!EnsureConnectedAndLoaded()) return;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*";
sfd.FileName = "gpd-config-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + ".bin";
if (sfd.ShowDialog() != DialogResult.OK) return;
string backupPath = sfd.FileName;
RunBackgroundAction("Backing up config...", delegate
{
byte[] data = device.ReadConfig();
File.WriteAllBytes(backupPath, data);
},
delegate
{
statusLabel.Text = "Backup saved: " + Path.GetFileName(backupPath);
GuiLogger.Log("Backup saved to " + backupPath);
ShowInfo("Backup saved.", "Backup saved: " + Path.GetFileName(backupPath));
},
delegate(Exception ex)
{
MessageBox.Show("Backup failed: " + ex.Message);
statusLabel.Text = "Backup failed.";
GuiLogger.LogException("Backup failed", ex);
});
}
private void RestoreButton_Click(object sender, EventArgs e)
{
if (!EnsureConnectedAndLoaded()) return;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Binary Files (*.bin)|*.bin|All Files (*.*)|*.*";
if (ofd.ShowDialog() != DialogResult.OK) return;
string restorePath = ofd.FileName;
byte[] raw;
try
{
raw = File.ReadAllBytes(restorePath);
}
catch (Exception ex)
{
MessageBox.Show("Restore failed: " + ex.Message);
statusLabel.Text = "Restore failed.";
GuiLogger.LogException("Restore read failed", ex);
return;
}
if (raw.Length != 256)
{
MessageBox.Show("Invalid backup size. Expected 256 bytes.");
statusLabel.Text = "Restore failed.";
return;
}
if (MessageBox.Show("Restore this backup to device firmware?", "Confirm Restore", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
{
return;
}
Config restoredConfig = null;
RunBackgroundAction("Restoring backup...", delegate
{
device.WriteConfig(raw);
restoredConfig = new Config((byte[])raw.Clone());
},
delegate
{
currentConfig = restoredConfig;
RefreshList();
statusLabel.Text = "Restore completed.";
GuiLogger.Log("Restore completed from " + restorePath);
ShowInfo("Restore completed.", "Restore completed.");
},
delegate(Exception ex)
{
MessageBox.Show("Restore failed: " + ex.Message);
statusLabel.Text = "Restore failed.";
GuiLogger.LogException("Restore failed", ex);
});
}
private void DataFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Select data folder for profiles and logs";
fbd.SelectedPath = AppPaths.DataRoot;
if (fbd.ShowDialog() != DialogResult.OK) return;
string error;
if (!AppPaths.TrySetDataRoot(fbd.SelectedPath, out error))
{
MessageBox.Show("Could not set data folder: " + error);
GuiLogger.Log("Data folder change failed: " + error);
return;
}
RefreshProfilesList();
ShowInfo("Data folder updated.", "Data folder: " + AppPaths.DataRoot);
GuiLogger.Log("Data folder updated to " + AppPaths.DataRoot);
}
private void AboutButton_Click(object sender, EventArgs e)
{
string aboutText =
"Better GPD WinControl is a lightweight tool for configuring GPD Win controller mappings." + Environment.NewLine + Environment.NewLine +
"Author: VIPPotato" + Environment.NewLine +
"Version: " + CurrentAppVersion + Environment.NewLine + Environment.NewLine +
"Thanks to everyone who reverse engineered the protocol and shared their findings.";
MessageBox.Show(aboutText, "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ExitButton_Click(object sender, EventArgs e)
{
Close();
}
private void CheckForUpdates(bool manual)
{
if (checkUpdatesButton != null) checkUpdatesButton.Enabled = false;
if (manual) statusLabel.Text = "Checking for updates...";
ThreadPool.QueueUserWorkItem(delegate
{
string latestTag;
string releaseUrl;
string error;
bool success = TryFetchLatestRelease(out latestTag, out releaseUrl, out error);
Action complete = delegate
{
if (checkUpdatesButton != null) checkUpdatesButton.Enabled = !_isBusy;
if (!success)
{
if (manual) MessageBox.Show("Update check failed: " + error);
statusLabel.Text = "Update check failed.";
GuiLogger.Log("Update check failed: " + error);
return;
}
Version currentVersion;
if (!TryParseVersion(CurrentAppVersion, out currentVersion))
{
currentVersion = new Version(0, 0, 0, 0);
}
Version latestVersion;
if (!TryParseVersion(latestTag, out latestVersion))
{
if (manual) MessageBox.Show("Could not parse latest release version: " + latestTag);
statusLabel.Text = "Update check finished.";
GuiLogger.Log("Could not parse latest release version: " + latestTag);
return;
}
if (latestVersion > currentVersion)
{
statusLabel.Text = "Update available: " + latestTag;
GuiLogger.Log("Update available. Current=" + CurrentAppVersion + " Latest=" + latestTag);
DialogResult result = MessageBox.Show(
"A newer version is available (" + latestTag + "). Open the releases page?",
"Update Available",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
OpenUrl(releaseUrl);
}
}
else
{
statusLabel.Text = "You are up to date.";
GuiLogger.Log("No update found. Current=" + CurrentAppVersion + " Latest=" + latestTag);
if (manual)
{
ShowInfo("You are up to date (" + CurrentAppVersion + ").", "You are up to date.");
}
}
};
try
{
if (IsHandleCreated && !IsDisposed)
{
BeginInvoke(complete);
}
}
catch (Exception ex)
{
GuiLogger.LogException("Failed to finish update-check UI flow", ex);
}
});
}
private bool TryFetchLatestRelease(out string latestTag, out string releaseUrl, out string error)
{
latestTag = null;
releaseUrl = ReleasesPageUrl;
error = null;
try
{
// Ensure GitHub HTTPS handshake works on older .NET defaults.
ServicePointManager.SecurityProtocol =
ServicePointManager.SecurityProtocol |
(SecurityProtocolType)192 | // TLS 1.0
(SecurityProtocolType)768 | // TLS 1.1
(SecurityProtocolType)3072; // TLS 1.2
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.UserAgent] = "Better-GPD-WinControls/" + CurrentAppVersion;
client.Headers[HttpRequestHeader.Accept] = "application/vnd.github+json";
string json = client.DownloadString(ReleasesApiUrl);
Match tagMatch = Regex.Match(json, "\"tag_name\"\\s*:\\s*\"([^\"]+)\"");
if (!tagMatch.Success)
{
error = "GitHub response did not include tag_name.";
return false;
}
Match urlMatch = Regex.Match(json, "\"html_url\"\\s*:\\s*\"([^\"]+)\"");
if (urlMatch.Success)
{
releaseUrl = Regex.Unescape(urlMatch.Groups[1].Value);
}
latestTag = Regex.Unescape(tagMatch.Groups[1].Value);
return true;
}
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
private bool TryParseVersion(string rawVersion, out Version version)
{
version = null;
if (string.IsNullOrWhiteSpace(rawVersion)) return false;
string cleaned = rawVersion.Trim();
if (cleaned.StartsWith("v", StringComparison.OrdinalIgnoreCase))
{
cleaned = cleaned.Substring(1);
}
Match match = Regex.Match(cleaned, @"^(\d+(?:\.\d+){0,3})");
if (!match.Success) return false;
return Version.TryParse(match.Groups[1].Value, out version);
}
private void OpenUrl(string url)
{
try
{
ProcessStartInfo psi = new ProcessStartInfo(url);
psi.UseShellExecute = true;
Process.Start(psi);
GuiLogger.Log("Opened URL: " + url);
}
catch (Exception ex)
{
MessageBox.Show("Could not open browser: " + ex.Message);
GuiLogger.LogException("Failed to open URL: " + url, ex);
}
}
private bool TryApplyComboValue(ComboBox combo, bool showMessage)
{
if (combo == null) return true;
ListBox list = combo.Tag as ListBox;
if (list == null) return true;
string valWithoutTarget = combo.Text == null ? string.Empty : combo.Text.Trim();
if (!(list.SelectedItem is ConfigItem))
{
if (!string.IsNullOrWhiteSpace(valWithoutTarget))
{
string msgNoTarget = "Select a mapping row before applying a value.";
statusLabel.Text = msgNoTarget;
GuiLogger.Log(msgNoTarget + " RawInput='" + valWithoutTarget + "'");
if (showMessage) MessageBox.Show(msgNoTarget);
return false;
}
return true;
}
ConfigItem item = (ConfigItem)list.SelectedItem;
string val = combo.Text == null ? string.Empty : combo.Text.Trim();
if (string.IsNullOrWhiteSpace(val)) return true;
try
{
if (item.Def.Type == "Millis")
{
ushort parsedMs;
if (!ushort.TryParse(val, out parsedMs))
{
throw new Exception("Delay must be an integer between 0 and 65535.");
}
}
item.Config.Set(item.Def.Name, val);
list.Refresh();
return true;
}
catch (Exception ex)
{
string msg = "Invalid value for '" + item.Def.Name + "': " + ex.Message;
statusLabel.Text = msg;
GuiLogger.Log(msg);
if (showMessage) MessageBox.Show(msg);
return false;
}
}
private bool CommitAllEditorValues(bool showMessageForFirstError)
{
bool ok = true;
bool shown = false;
foreach (var kvp in tabCombos)
{
bool show = showMessageForFirstError && !shown;
bool thisOk = TryApplyComboValue(kvp.Value, show);
if (!thisOk)
{
ok = false;
shown = true;
}
}
return ok;
}
private void CreateListTab(TabPage tab, string filterType)
{
SplitContainer contentSplit = new SplitContainer();
contentSplit.Dock = DockStyle.Fill;
tab.Controls.Add(contentSplit);
ListBox list = new ListBox();
list.Dock = DockStyle.Fill;
list.Tag = filterType; // Store filter
list.SelectedIndexChanged += new EventHandler(KeyList_SelectedIndexChanged);
contentSplit.Panel1.Controls.Add(list);
tabLists[filterType] = list;
FlowLayoutPanel editPanel = new FlowLayoutPanel();
editPanel.Dock = DockStyle.Fill;
editPanel.FlowDirection = FlowDirection.TopDown;
Label lbl = new Label();
lbl.Text = "New Value:";
lbl.AutoSize = true;
editPanel.Controls.Add(lbl);
ComboBox combo = new ComboBox();
combo.Width = 200;
combo.DropDownStyle = (filterType == "Key" || filterType == "Macro") ? ComboBoxStyle.DropDown : ComboBoxStyle.DropDownList;
combo.Enabled = false;
combo.Tag = list; // Link back to list
if (filterType == "Key" || filterType == "Macro") PopulateKeyCombo(combo);
// For Macros, we might want delays (Millis) too?
// Handled by filter logic later.
combo.SelectedIndexChanged += new EventHandler(ValueCombo_SelectedIndexChanged);
combo.LostFocus += new EventHandler(ValueCombo_LostFocus);
editPanel.Controls.Add(combo);
if (filterType == "Key" || filterType == "Macro")
{
Label hint = new Label();
hint.AutoSize = true;
hint.Text = "Type key name or hex keycode (e.g. 0xEA).";
editPanel.Controls.Add(hint);
}
if (filterType == "Key" || filterType == "Macro")
{
Button capBtn = new Button();
capBtn.Text = "Capture Key";
capBtn.AutoSize = true;
capBtn.Tag = combo; // Link to combo
capBtn.Click += CaptureKey_Click;
capBtn.Enabled = (filterType == "Key");
capBtn.Visible = (filterType == "Key");
editPanel.Controls.Add(capBtn);
tabCaptureButtons[filterType] = capBtn;
}
contentSplit.Panel2.Controls.Add(editPanel);
tabCombos[filterType] = combo;
}
private void CreateSettingsTab(TabPage tab)
{
FlowLayoutPanel panel = new FlowLayoutPanel();
panel.Dock = DockStyle.Fill;
panel.FlowDirection = FlowDirection.TopDown;
panel.AutoScroll = true;
panel.Padding = new Padding(10);
tab.Controls.Add(panel);
// We will populate this dynamically in RefreshList or statically here?
// Statically is better for layout, but we need the FieldDefs.
// Since FieldDefs are static in Config, we can access them.
foreach (Config.FieldDef def in Config.Fields)
{
if (def.Type == "Key" || def.Type == "Millis") continue; // Skip keys/macros here
// This catches Rumble, LedMode, Colour, Signed (Deadzone)
Panel row = new Panel();
row.Width = 550;
row.Height = 40;
Label lbl = new Label();
lbl.Text = def.Desc + ":";
lbl.Width = 200;
lbl.Location = new Point(0, 8);
row.Controls.Add(lbl);
Control inputCtrl = null;
if (def.Type == "Rumble")
{
ComboBox cb = new ComboBox();
cb.DropDownStyle = ComboBoxStyle.DropDownList;
cb.Items.Add("Off (0)");
cb.Items.Add("Low (1)");
cb.Items.Add("High (2)");
inputCtrl = cb;
}
else if (def.Type == "LedMode")
{
ComboBox cb = new ComboBox();
cb.DropDownStyle = ComboBoxStyle.DropDownList;
cb.Items.Add("Off (0)");
cb.Items.Add("Solid (1)");
cb.Items.Add("Breathe (0x11)");
cb.Items.Add("Rotate (0x21)");
inputCtrl = cb;
}
else if (def.Type == "Colour")
{
Button btn = new Button();
btn.Text = "Pick Color";
btn.Click += (s, e) => {
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
{
btn.BackColor = cd.Color;
// Store value?
currentConfig.Set(def.Name, string.Format("{0:X2}{1:X2}{2:X2}", cd.Color.R, cd.Color.G, cd.Color.B));
}
};
inputCtrl = btn;
}
else if (def.Type == "Signed")
{
NumericUpDown nud = new NumericUpDown();
nud.Minimum = -128;
nud.Maximum = 127;
inputCtrl = nud;
}
if (inputCtrl != null)
{
inputCtrl.Location = new Point(210, 5);
inputCtrl.Width = 150;
inputCtrl.Tag = def; // Store field def
// Add change handler
if (inputCtrl is ComboBox) ((ComboBox)inputCtrl).SelectedIndexChanged += Setting_Changed;
if (inputCtrl is NumericUpDown) ((NumericUpDown)inputCtrl).ValueChanged += Setting_Changed;
row.Controls.Add(inputCtrl);
settingControls[def.Name] = inputCtrl;
}
panel.Controls.Add(row);
}
}
private ListBox profilesList;
private void CreateProfilesTab(TabPage tab)
{
SplitContainer split = new SplitContainer();
split.Dock = DockStyle.Fill;
tab.Controls.Add(split);
profilesList = new ListBox();
profilesList.Dock = DockStyle.Fill;
split.Panel1.Controls.Add(profilesList);
FlowLayoutPanel buttonPanel = new FlowLayoutPanel();
buttonPanel.Dock = DockStyle.Fill;
buttonPanel.FlowDirection = FlowDirection.TopDown;
split.Panel2.Controls.Add(buttonPanel);
Button newBtn = new Button(); newBtn.Text = "New Profile"; newBtn.Width = 150; newBtn.AutoSize = true;
newBtn.Click += NewProfile_Click;
buttonPanel.Controls.Add(newBtn);
Button delBtn = new Button(); delBtn.Text = "Delete Profile"; delBtn.Width = 150; delBtn.AutoSize = true;
delBtn.Click += DeleteProfile_Click;
buttonPanel.Controls.Add(delBtn);
Button editBtn = new Button(); editBtn.Text = "Edit (Load to GUI)"; editBtn.Width = 150; editBtn.AutoSize = true;
editBtn.Click += EditProfile_Click;
buttonPanel.Controls.Add(editBtn);
Button diffBtn = new Button(); diffBtn.Text = "View Diff"; diffBtn.Width = 150; diffBtn.AutoSize = true;
diffBtn.Click += ViewProfileDiff_Click;
buttonPanel.Controls.Add(diffBtn);
Button saveBtn = new Button(); saveBtn.Text = "Save GUI to Profile"; saveBtn.Width = 150; saveBtn.AutoSize = true;
saveBtn.Click += SaveProfileChanges_Click;
buttonPanel.Controls.Add(saveBtn);
Button loadBtn = new Button(); loadBtn.Text = "Load (Write to Device)"; loadBtn.Width = 150; loadBtn.AutoSize = true;
loadBtn.Click += LoadProfile_Click;
buttonPanel.Controls.Add(loadBtn);
RefreshProfilesList();
}
private void RefreshProfilesList()
{
if (profilesList == null) return;
profilesList.BeginUpdate();
try
{
profilesList.Items.Clear();
string profilesDir = AppPaths.ProfilesDir;