Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
2615 lines (2347 loc) · 112 KB
/
Copy pathProgram.cs
File metadata and controls
2615 lines (2347 loc) · 112 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.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
[assembly: AssemblyTitle("Redgear A20 Control Center")]
[assembly: AssemblyDescription("Open-Source Hardware Control Utility for Redgear A20")]
[assembly: AssemblyProduct("Redgear A20 Control Center")]
[assembly: AssemblyCopyright("Copyright (c) 2026 Redgear A20 Open Driver Project Contributors")]
[assembly: AssemblyVersion("0.2.0.0")]
[assembly: AssemblyFileVersion("0.2.0.0")]
namespace RedgearA20ControlCenter
{
// ═════════════════════════════════════════════════════════════════════════
// Win32 HID Low-Level Communication Layer (Safe P/Invoke)
// ═════════════════════════════════════════════════════════════════════════
public static class HidTransport
{
public const ushort VENDOR_ID = 0x18F8;
public const ushort PRODUCT_ID = 0x0FC0;
public const ushort USAGE_PAGE_PRIMARY = 0xFF01; // Col04
public const ushort USAGE_PAGE_FALLBACK = 0xFF00; // Col03
public const byte REPORT_ID = 0x07;
[StructLayout(LayoutKind.Sequential)]
public struct SP_DEVICE_INTERFACE_DATA
{
public uint cbSize;
public Guid interfaceClassGuid;
public uint flags;
public IntPtr reserved;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct HIDP_CAPS
{
public ushort Usage;
public ushort UsagePage;
public ushort InputReportByteLength;
public ushort OutputReportByteLength;
public ushort FeatureReportByteLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
public ushort[] Reserved;
public ushort NumberLinkCollectionNodes;
public ushort NumberInputButtonCaps;
public ushort NumberInputValueCaps;
public ushort NumberInputDataIndices;
public ushort NumberOutputButtonCaps;
public ushort NumberOutputValueCaps;
public ushort NumberOutputDataIndices;
public ushort NumberFeatureButtonCaps;
public ushort NumberFeatureValueCaps;
public ushort NumberFeatureDataIndices;
}
[StructLayout(LayoutKind.Sequential)]
public struct HIDD_ATTRIBUTES
{
public uint Size;
public ushort VendorID;
public ushort ProductID;
public ushort VersionNumber;
}
[DllImport("hid.dll", SetLastError = true)]
public static extern void HidD_GetHidGuid(out Guid hidGuid);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern IntPtr SetupDiGetClassDevs(ref Guid classGuid, IntPtr enumerator, IntPtr hwndParent, uint flags);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, IntPtr deviceInfoData, ref Guid interfaceClassGuid, uint memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, IntPtr deviceInterfaceDetailData, uint deviceInterfaceDetailDataSize, out uint requiredSize, IntPtr deviceInfoData);
[DllImport("setupapi.dll", SetLastError = true)]
public static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("hid.dll", SetLastError = true)]
public static extern bool HidD_GetAttributes(SafeFileHandle hDevice, ref HIDD_ATTRIBUTES attributes);
[DllImport("hid.dll", SetLastError = true)]
public static extern bool HidD_GetPreparsedData(SafeFileHandle hDevice, out IntPtr preparsedData);
[DllImport("hid.dll", SetLastError = true)]
public static extern bool HidD_FreePreparsedData(IntPtr preparsedData);
[DllImport("hid.dll", SetLastError = true)]
public static extern int HidP_GetCaps(IntPtr preparsedData, ref HIDP_CAPS caps);
[DllImport("hid.dll", SetLastError = true)]
public static extern bool HidD_SetFeature(SafeFileHandle hDevice, byte[] reportBuffer, uint reportBufferLength);
[DllImport("hid.dll", SetLastError = true)]
public static extern bool HidD_GetFeature(SafeFileHandle hDevice, byte[] reportBuffer, uint reportBufferLength);
[DllImport("hid.dll", SetLastError = true)]
public static extern bool HidD_FlushQueue(SafeFileHandle hDevice);
private const uint DIGCF_PRESENT = 0x00000002;
private const uint DIGCF_DEVICEINTERFACE = 0x00000010;
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint OPEN_EXISTING = 3;
public static string FindTargetDevicePath(out ushort detectedUsagePage)
{
detectedUsagePage = 0;
Guid hidGuid;
HidD_GetHidGuid(out hidGuid);
IntPtr hDevInfo = SetupDiGetClassDevs(ref hidGuid, IntPtr.Zero, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
if (hDevInfo == IntPtr.Zero || hDevInfo.ToInt64() == -1) return null;
string primaryPath = null;
string fallbackPath = null;
try
{
SP_DEVICE_INTERFACE_DATA ifData = new SP_DEVICE_INTERFACE_DATA();
ifData.cbSize = (uint)Marshal.SizeOf(typeof(SP_DEVICE_INTERFACE_DATA));
uint index = 0;
while (SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref hidGuid, index++, ref ifData))
{
uint requiredSize = 0;
SetupDiGetDeviceInterfaceDetail(hDevInfo, ref ifData, IntPtr.Zero, 0, out requiredSize, IntPtr.Zero);
if (requiredSize == 0) continue;
IntPtr pDetail = Marshal.AllocHGlobal((int)requiredSize);
try
{
// Set cbSize of SP_DEVICE_INTERFACE_DETAIL_DATA (4 bytes on 32-bit, 8 bytes on 64-bit)
Marshal.WriteInt32(pDetail, IntPtr.Size == 8 ? 8 : 4 + Marshal.SystemDefaultCharSize);
if (SetupDiGetDeviceInterfaceDetail(hDevInfo, ref ifData, pDetail, requiredSize, out requiredSize, IntPtr.Zero))
{
IntPtr pPath = new IntPtr(pDetail.ToInt64() + 4);
string path = Marshal.PtrToStringAuto(pPath);
// Quick filter on VID & PID in string
string pathLower = path.ToLowerInvariant();
if (pathLower.Contains("vid_18f8") && pathLower.Contains("pid_0fc0"))
{
SafeFileHandle hFile = CreateFile(path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (!hFile.IsInvalid)
{
using (hFile)
{
IntPtr pData;
if (HidD_GetPreparsedData(hFile, out pData))
{
try
{
HIDP_CAPS caps = new HIDP_CAPS();
HidP_GetCaps(pData, ref caps);
if (caps.UsagePage == USAGE_PAGE_PRIMARY)
{
primaryPath = path;
detectedUsagePage = USAGE_PAGE_PRIMARY;
break; // Ideal match found
}
else if (caps.UsagePage == USAGE_PAGE_FALLBACK && fallbackPath == null)
{
fallbackPath = path;
}
}
finally
{
HidD_FreePreparsedData(pData);
}
}
}
}
}
}
}
finally
{
Marshal.FreeHGlobal(pDetail);
}
}
}
finally
{
SetupDiDestroyDeviceInfoList(hDevInfo);
}
if (primaryPath != null) return primaryPath;
if (fallbackPath != null)
{
detectedUsagePage = USAGE_PAGE_FALLBACK;
return fallbackPath;
}
return null;
}
public static bool SendSinglePacket(string path, byte[] packet, out int win32Err, out string error)
{
error = null;
win32Err = 0;
if (packet == null || packet.Length != 8)
{
error = "Packet must be exactly 8 bytes.";
return false;
}
SafeFileHandle hFile = CreateFile(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (hFile.IsInvalid)
{
win32Err = Marshal.GetLastWin32Error();
error = string.Format("Failed to open device handle (Win32 Error: {0})", win32Err);
return false;
}
try
{
bool success = HidD_SetFeature(hFile, packet, 8);
if (!success)
{
win32Err = Marshal.GetLastWin32Error();
error = string.Format("HidD_SetFeature failed (Win32 Error: {0})", win32Err);
return false;
}
HidD_FlushQueue(hFile);
return true;
}
finally
{
hFile.Close();
hFile.Dispose();
}
}
public static bool SendSinglePacket(string path, byte[] packet, out string error)
{
int win32Err;
return SendSinglePacket(path, packet, out win32Err, out error);
}
public static bool VerifyDeviceTransportHealth(string path, out int win32Err, out string error)
{
error = null;
win32Err = 0;
SafeFileHandle hFile = CreateFile(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (hFile.IsInvalid)
{
win32Err = Marshal.GetLastWin32Error();
error = string.Format("Device handle unavailable after flash write (Win32 Error: {0})", win32Err);
return false;
}
using (hFile)
{
byte[] buf = new byte[32];
buf[0] = REPORT_ID; // Report ID 0x07 must be byte 0
bool ok = HidD_GetFeature(hFile, buf, (uint)buf.Length);
if (!ok)
{
win32Err = Marshal.GetLastWin32Error();
error = string.Format("Device non-responsive after flash write (Win32 Error: {0})", win32Err);
return false;
}
HidD_FlushQueue(hFile);
return true;
}
}
}
public struct SaveParameters
{
public Color Color;
public int Brightness;
public byte ActiveDpiIndex;
public byte DpiMask;
public bool CommitToFlash;
public bool SendDpi;
}
public class PipelineResult
{
public bool Success;
public string ErrorMessage;
public int FailingPacketIndex;
public int Win32ErrorCode;
}
public enum PersistenceMode
{
StealthWatcher = 0, // Invisible background watcher (No window, No tray icon, ~1.8 MB RAM, 0% CPU, instant hotplug on all ports - Recommended)
TrayAgent = 1, // System tray process (~2.7 MB RAM, quick access tray icon)
Disabled = 2 // RAM only (resets on disconnect or reboot)
}
public class AppProfile
{
public string HexColor = "#BE59FF";
public int Brightness = 100;
public int ActiveDpiStage = 1; // Default 1000 DPI (Stage 1)
public bool EnableDpi = false;
public PersistenceMode Mode = PersistenceMode.StealthWatcher;
public bool AutoStart
{
get { return Mode == PersistenceMode.StealthWatcher || Mode == PersistenceMode.TrayAgent; }
set { Mode = value ? PersistenceMode.StealthWatcher : PersistenceMode.Disabled; }
}
public static string GetProfilePath()
{
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RedgearA20");
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
return Path.Combine(dir, "profile.json");
}
public static AppProfile Load()
{
AppProfile p = new AppProfile();
try
{
string file = GetProfilePath();
if (File.Exists(file))
{
string json = File.ReadAllText(file);
Match mHex = Regex.Match(json, "\"HexColor\"\\s*:\\s*\"([^\"]+)\"");
if (mHex.Success) p.HexColor = mHex.Groups[1].Value;
Match mBri = Regex.Match(json, "\"Brightness\"\\s*:\\s*(\\d+)");
if (mBri.Success) p.Brightness = Math.Max(5, Math.Min(100, int.Parse(mBri.Groups[1].Value)));
Match mDpiStage = Regex.Match(json, "\"ActiveDpiStage\"\\s*:\\s*(\\d+)");
if (mDpiStage.Success) p.ActiveDpiStage = Math.Max(0, Math.Min(5, int.Parse(mDpiStage.Groups[1].Value)));
Match mEnDpi = Regex.Match(json, "\"EnableDpi\"\\s*:\\s*(true|false)", RegexOptions.IgnoreCase);
if (mEnDpi.Success) p.EnableDpi = bool.Parse(mEnDpi.Groups[1].Value);
Match mMode = Regex.Match(json, "\"(?:PersistenceMode|Mode)\"\\s*:\\s*(\\d+)");
if (mMode.Success)
{
int modeVal = int.Parse(mMode.Groups[1].Value);
if (Enum.IsDefined(typeof(PersistenceMode), modeVal))
{
p.Mode = (PersistenceMode)modeVal;
}
}
else
{
Match mModeStr = Regex.Match(json, "\"(?:PersistenceMode|Mode)\"\\s*:\\s*\"([^\"]+)\"");
if (mModeStr.Success)
{
string val = mModeStr.Groups[1].Value;
if (string.Equals(val, "TrayAgent", StringComparison.OrdinalIgnoreCase) || string.Equals(val, "Tray", StringComparison.OrdinalIgnoreCase))
p.Mode = PersistenceMode.TrayAgent;
else if (string.Equals(val, "Disabled", StringComparison.OrdinalIgnoreCase))
p.Mode = PersistenceMode.Disabled;
else
p.Mode = PersistenceMode.StealthWatcher;
}
else
{
// Backwards compatibility with v0.1.0/v0.1.1 legacy profile format: upgrade auto-start to StealthWatcher
Match mAuto = Regex.Match(json, "\"AutoStart\"\\s*:\\s*(true|false)", RegexOptions.IgnoreCase);
if (mAuto.Success)
{
bool auto = bool.Parse(mAuto.Groups[1].Value);
p.Mode = auto ? PersistenceMode.StealthWatcher : PersistenceMode.Disabled;
}
}
}
}
}
catch { }
return p;
}
public bool Save(out string error)
{
error = null;
string tmpFile = null;
try
{
string file = GetProfilePath();
string dir = Path.GetDirectoryName(file);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) Directory.CreateDirectory(dir);
int bri = Math.Max(5, Math.Min(100, Brightness));
int dpi = Math.Max(0, Math.Min(5, ActiveDpiStage));
string json = string.Format("{{\n \"HexColor\": \"{0}\",\n \"Brightness\": {1},\n \"ActiveDpiStage\": {2},\n \"EnableDpi\": {3},\n \"PersistenceMode\": {4}\n}}\n",
HexColor, bri, dpi, EnableDpi.ToString().ToLower(), (int)Mode);
tmpFile = file + ".tmp";
File.WriteAllText(tmpFile, json, Encoding.UTF8);
if (File.Exists(file))
{
try
{
File.Replace(tmpFile, file, null);
}
catch
{
File.Delete(file);
File.Move(tmpFile, file);
}
}
else
{
File.Move(tmpFile, file);
}
return true;
}
catch (Exception ex)
{
error = ex.Message;
if (!string.IsNullOrEmpty(tmpFile))
{
try { if (File.Exists(tmpFile)) File.Delete(tmpFile); } catch { }
}
return false;
}
}
public void Save()
{
string dummy;
Save(out dummy);
}
}
public static class TaskSchedulerHelper
{
public const string TASK_NAME = "RedgearA20_AutoApply";
public const string HARDWARE_MUTEX_NAME = @"Local\RedgearA20_HardwareLock";
public static string GetInstalledExePath()
{
string dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RedgearA20");
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
return Path.Combine(dir, "RedgearA20.exe");
}
public static bool DeployDriverBinary(out string targetPath, out string error)
{
error = null;
targetPath = GetInstalledExePath();
try
{
string currentExe = null;
try
{
currentExe = typeof(TaskSchedulerHelper).Assembly.Location;
}
catch { }
if (string.IsNullOrEmpty(currentExe))
{
currentExe = Application.ExecutablePath;
}
if (string.Equals(currentExe, targetPath, StringComparison.OrdinalIgnoreCase))
{
return true;
}
string dir = Path.GetDirectoryName(targetPath);
try
{
foreach (string f in Directory.GetFiles(dir, "*.old"))
{
try { File.Delete(f); } catch { }
}
}
catch { }
string oldPath = targetPath + ".old";
try { if (File.Exists(oldPath)) File.Delete(oldPath); } catch { }
if (File.Exists(oldPath))
{
oldPath = targetPath + "." + DateTime.UtcNow.Ticks + ".old";
}
if (File.Exists(targetPath))
{
try
{
FileInfo fiSrc = new FileInfo(currentExe);
FileInfo fiDst = new FileInfo(targetPath);
if (fiSrc.Length == fiDst.Length && fiSrc.LastWriteTimeUtc == fiDst.LastWriteTimeUtc)
{
return true;
}
}
catch { }
}
try
{
File.Copy(currentExe, targetPath, true);
return true;
}
catch (IOException)
{
try
{
File.Move(targetPath, oldPath);
try
{
File.Copy(currentExe, targetPath, true);
return true;
}
catch
{
try { File.Move(oldPath, targetPath); } catch { }
throw;
}
}
catch (Exception exMove)
{
if (File.Exists(targetPath)) return true;
throw exMove;
}
}
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
[Obsolete("Task Scheduler mode is deprecated in favor of lightweight Stealth Watcher persistence (--stealth)")]
public static bool InstallTask(out string error)
{
error = "Task Scheduler XML installer is deprecated. Use --stealth to run the lightweight background watcher.";
return false;
}
public static bool RemoveTask(out string error)
{
error = null;
try
{
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "schtasks.exe"),
Arguments = string.Format("/delete /tn \"{0}\" /f", TASK_NAME),
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
using (Process p = Process.Start(psi))
{
p.StandardOutput.ReadToEnd();
p.StandardError.ReadToEnd();
p.WaitForExit(4000);
}
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
}
// ═════════════════════════════════════════════════════════════════════════
// UI Design System Tokens (Zero-Allocation GDI+ Theme)
// ═════════════════════════════════════════════════════════════════════════
public static class Theme
{
// ─── Colors: Base Neutrals ───
public static readonly Color Canvas = Color.FromArgb(18, 19, 22); // #121316
public static readonly Color Surface = Color.FromArgb(26, 28, 34); // #1A1C22
public static readonly Color SurfaceElevated = Color.FromArgb(36, 39, 49); // #242731
public static readonly Color SurfaceHover = Color.FromArgb(45, 49, 62); // #2D313E
public static readonly Color Border = Color.FromArgb(43, 47, 58); // #2B2F3A
public static readonly Color BorderSubtle = Color.FromArgb(32, 35, 42); // #20232A
// ─── Colors: Text Neutrals ───
public static readonly Color TextPrimary = Color.FromArgb(241, 243, 247); // #F1F3F7
public static readonly Color TextSecondary = Color.FromArgb(141, 147, 165);// #8D93A5
public static readonly Color TextMuted = Color.FromArgb(90, 96, 114); // #5A6072
public static readonly Color TextDisabled = Color.FromArgb(82, 88, 102); // #525866
// ─── Colors: Single Primary Accent (Emerald / Hardware Mint) ───
public static readonly Color Accent = Color.FromArgb(16, 185, 129); // #10B981
public static readonly Color AccentHover = Color.FromArgb(5, 150, 105); // #059669
public static readonly Color AccentText = Color.White; // #FFFFFF
public static readonly Color AccentDim = Color.FromArgb(6, 78, 59); // #064E3B
// ─── Colors: Functional Semantic States ───
public static readonly Color Warning = Color.FromArgb(245, 158, 11); // #F59E0B
public static readonly Color WarningSurface = Color.FromArgb(35, 28, 19); // #231C13
public static readonly Color WarningBorder = Color.FromArgb(92, 61, 16); // #5C3D10
public static readonly Color Danger = Color.FromArgb(239, 68, 68); // #EF4444
public static readonly Color DangerSurface = Color.FromArgb(40, 20, 22); // #281416
public static readonly Color DangerBorder = Color.FromArgb(77, 29, 34); // #4D1D22
public static readonly Color TerminalBg = Color.FromArgb(14, 15, 18); // #0E0F12
public static readonly Color TerminalText = Color.FromArgb(16, 185, 129); // #10B981
// ─── Fonts: System Fonts Only (Pre-allocated Static Instances) ───
public static readonly Font FontHeading = new Font("Segoe UI", 9.75f, FontStyle.Bold); // 13px bold
public static readonly Font FontBodyPrimary = new Font("Segoe UI", 9.0f, FontStyle.Regular);// 12px
public static readonly Font FontBodyBold = new Font("Segoe UI", 9.0f, FontStyle.Bold); // 12px bold
public static readonly Font FontBodySecondary = new Font("Segoe UI", 8.25f, FontStyle.Regular); // 11px
public static readonly Font FontBadge = new Font("Segoe UI", 7.5f, FontStyle.Bold); // 10px bold
public static readonly Font FontMono = new Font("Consolas", 8.25f, FontStyle.Regular); // 11px mono
// ─── Cached GDI Brushes & Pens (Never reallocated in Paint) ───
public static readonly SolidBrush BrushCanvas = new SolidBrush(Canvas);
public static readonly SolidBrush BrushSurface = new SolidBrush(Surface);
public static readonly SolidBrush BrushSurfaceElevated = new SolidBrush(SurfaceElevated);
public static readonly SolidBrush BrushAccent = new SolidBrush(Accent);
public static readonly SolidBrush BrushWarning = new SolidBrush(Warning);
public static readonly SolidBrush BrushDanger = new SolidBrush(Danger);
public static readonly SolidBrush BrushTextPrimary = new SolidBrush(TextPrimary);
public static readonly SolidBrush BrushTextSecondary = new SolidBrush(TextSecondary);
public static readonly Pen PenBorder = new Pen(Border, 1);
public static readonly Pen PenBorderSubtle = new Pen(BorderSubtle, 1);
public static readonly Pen PenAccent = new Pen(Accent, 1);
public static readonly Pen PenWarning = new Pen(Warning, 1);
public static readonly Pen PenDanger = new Pen(Danger, 1);
// ─── Spacing Scale (Pixels) ───
public const int Space1 = 4;
public const int Space2 = 8;
public const int Space3 = 12;
public const int Space4 = 16;
public const int Space5 = 20;
// ─── Geometry ───
public const int RadiusDefault = 4;
public const int BorderWidth = 1;
}
// ═════════════════════════════════════════════════════════════════════════
// Main GUI Application Form (Native Windows Forms, Dark Theme)
// ═════════════════════════════════════════════════════════════════════════
public class MainForm : Form
{
// UI Controls
private Panel body;
private Label lblStatus;
private Panel pnlColorPreview;
private TextBox txtHex;
private Button btnPickColor;
private TrackBar tbBrightness;
private Label lblBrightnessVal;
private Button btnApply;
private Button btnSave;
private Button btnReset;
// Persistence & Startup UI (3-Mode Selection)
private Panel gbPersistence;
private RadioButton rbStealth;
private RadioButton rbTrayAgent;
private RadioButton rbDisabled;
// Experimental DPI section
private CheckBox cbEnableDpi;
private Panel gbDpi;
private ComboBox cmbDpiStages;
private Button btnTestDpi;
// Diagnostic Log Panel
private RichTextBox rtbLog;
private Button btnClearLog;
private Button btnCopyLog;
private Button btnRefresh;
private Button btnExit;
private Button[] presetButtons;
// System Tray & Background Watcher
private NotifyIcon trayIcon;
private ContextMenuStrip trayMenu;
private System.Windows.Forms.Timer usbDebounceTimer;
// Internal State
private Color currentColor = Color.FromArgb(190, 89, 255); // Soft Lavender default
private int currentBrightness = 100;
private string cachedDevicePath = null;
private ushort cachedUsagePage = 0;
private volatile bool isSavingInProgress = false;
private AppProfile currentProfile;
private bool startHidden = false;
private bool isStealth = false;
private bool isExplicitlyRestoring = false;
private bool balloonShownOnce = false;
private bool isExiting = false;
private bool isHotplugHandling = false;
private const int EEPROM_WRITE_DELAY_MS = 100;
// Win32 constants & P/Invoke
private const int WM_DEVICECHANGE = 0x0219;
private const int DBT_DEVNODES_CHANGED = 0x0007;
private const int DBT_DEVICEARRIVAL = 0x8000;
private const int DBT_DEVICEREMOVECOMPLETE = 0x8004;
private const string RUN_REG_KEY = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string APP_REG_NAME = "RedgearA20ControlCenter";
[DllImport("kernel32.dll")]
private static extern bool SetProcessWorkingSetSize(IntPtr proc, IntPtr min, IntPtr max);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int RegisterWindowMessage(string lpString);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool ChangeWindowMessageFilter(int message, uint dwFlag);
private const uint MSGFLT_ADD = 1;
[DllImport("dwmapi.dll", PreserveSig = true)]
private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
private const int DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19;
private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
[DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
private static extern int SetWindowTheme(IntPtr hWnd, string pszSubAppName, string pszSubIdList);
private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
private static int wmShowControlCenter = 0;
private static Mutex appMutex = null;
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
try
{
if (Environment.OSVersion.Version.Major >= 10)
{
int useDarkMode = 1;
if (DwmSetWindowAttribute(this.Handle, DWMWA_USE_IMMERSIVE_DARK_MODE, ref useDarkMode, sizeof(int)) != 0)
{
DwmSetWindowAttribute(this.Handle, DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1, ref useDarkMode, sizeof(int));
}
}
}
catch { }
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (isSavingInProgress)
{
MessageBox.Show("Please wait until the operation completes before exiting.", "Busy", MessageBoxButtons.OK, MessageBoxIcon.Warning);
e.Cancel = true;
return;
}
if (!isExiting && currentProfile != null && (currentProfile.Mode == PersistenceMode.StealthWatcher || currentProfile.Mode == PersistenceMode.TrayAgent))
{
e.Cancel = true;
MinimizeToWatcher(showBalloon: currentProfile.Mode == PersistenceMode.TrayAgent);
return;
}
if (trayMenu != null)
{
trayMenu.Dispose();
trayMenu = null;
}
if (trayIcon != null)
{
trayIcon.Visible = false;
trayIcon.Dispose();
trayIcon = null;
}
base.OnFormClosing(e);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (trayMenu != null)
{
trayMenu.Dispose();
trayMenu = null;
}
if (trayIcon != null)
{
trayIcon.Visible = false;
trayIcon.Dispose();
trayIcon = null;
}
if (usbDebounceTimer != null)
{
usbDebounceTimer.Stop();
usbDebounceTimer.Dispose();
usbDebounceTimer = null;
}
}
base.Dispose(disposing);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (this.WindowState == FormWindowState.Minimized && currentProfile != null && currentProfile.Mode == PersistenceMode.TrayAgent)
{
MinimizeToWatcher(false);
}
}
protected override void SetVisibleCore(bool value)
{
if (startHidden && !isExplicitlyRestoring)
{
value = false;
if (!this.IsHandleCreated) CreateHandle();
}
base.SetVisibleCore(value);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_DEVICECHANGE)
{
int wp = m.WParam.ToInt32();
if (wp == DBT_DEVNODES_CHANGED || wp == DBT_DEVICEARRIVAL || wp == DBT_DEVICEREMOVECOMPLETE)
{
if (usbDebounceTimer != null)
{
usbDebounceTimer.Stop();
usbDebounceTimer.Start();
}
}
}
else if (wmShowControlCenter != 0 && m.Msg == wmShowControlCenter)
{
RestoreGui();
}
}
private static void TrimMemory()
{
try
{
GC.Collect();
GC.WaitForPendingFinalizers();
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, new IntPtr(-1), new IntPtr(-1));
}
catch { }
}
private static void SetAutoStart(PersistenceMode mode)
{
try
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_REG_KEY, true))
{
if (key != null)
{
if (mode == PersistenceMode.StealthWatcher)
{
string targetPath;
string deployErr;
if (!TaskSchedulerHelper.DeployDriverBinary(out targetPath, out deployErr))
{
targetPath = Application.ExecutablePath;
}
key.SetValue(APP_REG_NAME, string.Format("\"{0}\" --stealth", targetPath));
}
else if (mode == PersistenceMode.TrayAgent)
{
string targetPath;
string deployErr;
if (!TaskSchedulerHelper.DeployDriverBinary(out targetPath, out deployErr))
{
targetPath = Application.ExecutablePath;
}
key.SetValue(APP_REG_NAME, string.Format("\"{0}\" --tray", targetPath));
}
else
{
key.DeleteValue(APP_REG_NAME, false);
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Registry auto-start error: " + ex.Message);
}
}
private void InitTrayIcon()
{
trayMenu = new ContextMenuStrip();
ToolStripMenuItem miOpen = new ToolStripMenuItem("Open Control Center");
miOpen.Font = new Font(trayMenu.Font, FontStyle.Bold);
miOpen.Click += delegate { RestoreGui(); };
trayMenu.Items.Add(miOpen);
ToolStripMenuItem miApply = new ToolStripMenuItem("Apply Profile Now");
miApply.Click += async delegate { await ApplyCurrentProfileAsync(silent: false); };
trayMenu.Items.Add(miApply);
trayMenu.Items.Add(new ToolStripSeparator());
ToolStripMenuItem miExit = new ToolStripMenuItem("Exit Driver (Stop Persistence)");
miExit.Click += delegate
{
DialogResult dr = MessageBox.Show(
"⚠️ WARNING: This will completely stop the background driver!\n\n" +
"• Your mouse settings will NOT persist across USB unplugs or PC restarts.\n\n" +
"Are you sure you want to exit and stop persistence?",
"Exit Driver Confirmation",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning,
MessageBoxDefaultButton.Button2
);
if (dr == DialogResult.Yes)
{
isExiting = true;
if (trayIcon != null) trayIcon.Visible = false;
Application.Exit();
}
};
trayMenu.Items.Add(miExit);
trayIcon = new NotifyIcon
{
Icon = this.Icon != null ? this.Icon : SystemIcons.Application,
Text = "Redgear A20 Control Center",
ContextMenuStrip = trayMenu,
Visible = (currentProfile != null && currentProfile.Mode == PersistenceMode.TrayAgent)
};
trayIcon.DoubleClick += delegate { RestoreGui(); };
}
private void MinimizeToWatcher(bool showBalloon)
{
this.Hide();
this.ShowInTaskbar = false;
isExplicitlyRestoring = false;
if (trayIcon != null)
{
trayIcon.Visible = (currentProfile != null && currentProfile.Mode == PersistenceMode.TrayAgent);
if (trayIcon.Visible && showBalloon && !balloonShownOnce)
{
trayIcon.ShowBalloonTip(3000, "Redgear A20 Control Center", "Running in tray to auto-apply your RGB settings on reconnect.", ToolTipIcon.Info);
balloonShownOnce = true;
}
}
TrimMemory();
}
private void RestoreGui()
{
isExplicitlyRestoring = true;
startHidden = false;
this.Show();
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = true;
this.BringToFront();
this.Activate();
RefreshDeviceConnection();
UpdateColorPreview();
}
private void InitUsbWatcher()
{
usbDebounceTimer = new System.Windows.Forms.Timer();
usbDebounceTimer.Interval = 400; // 400 ms debounce after USB hotplug
usbDebounceTimer.Tick += OnUsbDebounceTimerTick;
}
private async void OnUsbDebounceTimerTick(object sender, EventArgs e)
{
usbDebounceTimer.Stop();