From 4225aeda33cf7215fca32937d1fb5eb76c981085 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Sat, 17 Jan 2026 00:32:58 -0500 Subject: [PATCH] refactor: implement InputLibrary Interface; make libraries support interface --- Spectrum/Detection/DetectionManager.cs | 1 - .../InputLibraries/Arduino/ArduinoMain.cs | 37 +++- Spectrum/Input/InputLibraries/HID/HIDMain.cs | 190 +++++++++--------- .../Input/InputLibraries/IInputLibrary.cs | 13 ++ .../InputLibraries/MouseEvent/MouseMain.cs | 33 ++- Spectrum/Input/InputManager.cs | 44 ++-- Spectrum/Program.cs | 4 + Spectrum/Renderer/Renderer.cs | 19 +- 8 files changed, 188 insertions(+), 153 deletions(-) create mode 100644 Spectrum/Input/InputLibraries/IInputLibrary.cs diff --git a/Spectrum/Detection/DetectionManager.cs b/Spectrum/Detection/DetectionManager.cs index 71fb889..c14765a 100644 --- a/Spectrum/Detection/DetectionManager.cs +++ b/Spectrum/Detection/DetectionManager.cs @@ -50,7 +50,6 @@ namespace Spectrum.Detection var t0 = Stopwatch.GetTimestamp(); renderer?.ClearDetectionDrawCommands(); - AddTiming("Clear Draw Commands", Stopwatch.GetTimestamp() - t0); if (!config.ClosestToMouse) { diff --git a/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs b/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs index 68328f1..c9a15f4 100644 --- a/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs +++ b/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs @@ -5,17 +5,19 @@ using LogLevel = Spectrum.Utilities.LogManager.LogLevel; namespace Spectrum.Input.InputLibraries.Arduino { - class ArduinoMain + internal class ArduinoMain : IInputLibrary, IDisposable { private static readonly byte PingCommand = 0x02; private static readonly byte PingResponse = 0xAA; private const int BaudRate = 115200; private const int HandshakeTimeoutMs = 1500; private const int OpenResetDelayMs = 1200; - private static SerialPort? serial; - private static readonly object sync = new(); + private SerialPort? serial; + private readonly object sync = new(); - public static bool Load() + public bool RequiresInitialization => true; + public bool IsConnected => serial != null && serial.IsOpen; + public bool Initialize() { lock (sync) { @@ -106,7 +108,7 @@ namespace Spectrum.Input.InputLibraries.Arduino return false; } - public static void Close() + public void Dispose() { lock (sync) { @@ -130,7 +132,7 @@ namespace Spectrum.Input.InputLibraries.Arduino } } - public static void Move(int x, int y) + public void Move(int x, int y) { SerialPort? sp; lock (sync) sp = serial; @@ -158,17 +160,17 @@ namespace Spectrum.Input.InputLibraries.Arduino y -= stepY; } } - public static void ClickDown(int button = 0x03) + public void Press(int button) { - SendClick(button, true); + SendMappedClick(button, true); } - public static void ClickUp(int button = 0x03) + public void Release(int button) { - SendClick(button, false); + SendMappedClick(button, false); } - private static void SendClick(int buttonBase, bool expectDown) + private void SendClick(int buttonBase, bool expectDown) { SerialPort? sp; lock (sync) sp = serial; @@ -188,5 +190,18 @@ namespace Spectrum.Input.InputLibraries.Arduino LogManager.Log($"ArduinoMain: Click {(expectDown ? "down" : "up")} failed: {ex.Message}", LogLevel.Debug); } } + + private void SendMappedClick(int button, bool isDown) + { + int mapped = button switch + { + 0x01 => 0x03, + 0x02 => 0x05, + _ => 0 + }; + + if (mapped == 0) return; + SendClick(mapped, isDown); + } } } \ No newline at end of file diff --git a/Spectrum/Input/InputLibraries/HID/HIDMain.cs b/Spectrum/Input/InputLibraries/HID/HIDMain.cs index 22963a6..5f8f865 100644 --- a/Spectrum/Input/InputLibraries/HID/HIDMain.cs +++ b/Spectrum/Input/InputLibraries/HID/HIDMain.cs @@ -4,7 +4,7 @@ using LogLevel = Spectrum.Utilities.LogManager.LogLevel; namespace Spectrum.Input.InputLibraries.HID { - internal class HIDMain(int? vid = null, int? pid = null) + internal class HIDMain(int? vid = null, int? pid = null) : IInputLibrary, IDisposable { readonly int[] ExpectedVIDs = [ @@ -40,6 +40,89 @@ namespace Spectrum.Input.InputLibraries.HID HidStream? stream; private readonly object _syncLock = new(); + public bool RequiresInitialization => true; + public bool IsConnected => stream != null && device != null; + public bool Initialize() + { + lock (_syncLock) + { + if (stream != null && device != null) + { + LogManager.Log("HIDMain: Device already initialized.", LogLevel.Debug); + return true; + } + + LogManager.Log("HIDMain: Scanning for devices", LogLevel.Debug); + var candidates = FindDevice().ToList(); + + if (candidates.Count == 0) + { + LogManager.Log("HIDMain: No gaming mouse emulator vendor interface found.", LogLevel.Warning); + return false; + } + + foreach (var dev in candidates) + { + try + { + LogManager.Log($"HIDMain: Testing device: {dev.GetProductName()} (VID:PID {dev.VendorID:X4}:{dev.ProductID:X4})", LogLevel.Debug); + + if (dev.TryOpen(out stream)) + { + if (TestDeviceWithPing(dev, stream)) + { + device = dev; + vid = dev.VendorID; + pid = dev.ProductID; + LogManager.Log($"HIDMain: Connected successfully to {dev.GetProductName()}", LogLevel.Info); + return true; + } + LogManager.Log($"HIDMain: Device {dev.GetProductName()} did not respond to ping", LogLevel.Debug); + stream.Close(); + stream.Dispose(); + stream = null; + } + else + { + LogManager.Log($"HIDMain: Could not open device {dev.GetProductName()}", LogLevel.Debug); + } + } + catch (Exception ex) + { + LogManager.Log($"HIDMain: Error testing device: {ex.Message}", LogLevel.Debug); + stream?.Close(); + stream?.Dispose(); + stream = null; + } + } + + LogManager.Log("HIDMain: Failed to connect to any gaming mouse emulator.", LogLevel.Warning); + return false; + } + } + + public void Dispose() + { + lock (_syncLock) + { + try + { + stream?.Close(); + stream?.Dispose(); + LogManager.Log("HIDMain: Connection closed.", LogLevel.Debug); + } + catch (Exception ex) + { + LogManager.Log($"HIDMain: Error closing connection: {ex.Message}", LogLevel.Debug); + } + finally + { + stream = null; + device = null; + } + } + } + IEnumerable FindDevice() { var devices = DeviceList.Local.GetHidDevices(); @@ -153,67 +236,6 @@ namespace Spectrum.Input.InputLibraries.HID return false; } - public bool Init() - { - lock (_syncLock) - { - if (stream != null && device != null) - { - LogManager.Log("HIDMain: Device already initialized.", LogLevel.Debug); - return true; - } - - LogManager.Log("HIDMain: Scanning for devices", LogLevel.Debug); - var candidates = FindDevice().ToList(); - - if (candidates.Count == 0) - { - LogManager.Log("HIDMain: No gaming mouse emulator vendor interface found.", LogLevel.Warning); - return false; - } - - foreach (var dev in candidates) - { - try - { - LogManager.Log($"HIDMain: Testing device: {dev.GetProductName()} (VID:PID {dev.VendorID:X4}:{dev.ProductID:X4})", LogLevel.Debug); - - if (dev.TryOpen(out stream)) - { - if (TestDeviceWithPing(dev, stream)) - { - device = dev; - vid = dev.VendorID; - pid = dev.ProductID; - LogManager.Log($"HIDMain: Connected successfully to {dev.GetProductName()}", LogLevel.Info); - return true; - } - else - { - LogManager.Log($"HIDMain: Device {dev.GetProductName()} did not respond to ping", LogLevel.Debug); - stream.Close(); - stream.Dispose(); - stream = null; - } - } - else - { - LogManager.Log($"HIDMain: Could not open device {dev.GetProductName()}", LogLevel.Debug); - } - } - catch (Exception ex) - { - LogManager.Log($"HIDMain: Error testing device: {ex.Message}", LogLevel.Debug); - stream?.Close(); - stream?.Dispose(); - stream = null; - } - } - - LogManager.Log("HIDMain: Failed to connect to any gaming mouse emulator.", LogLevel.Warning); - return false; - } - } private bool SendFeatureReport(byte[] data) { @@ -245,7 +267,7 @@ namespace Spectrum.Input.InputLibraries.HID } } - public bool Move(int x, int y) + public void Move(int x, int y) { x = Math.Clamp(x, -127, 127); y = Math.Clamp(y, -127, 127); @@ -254,9 +276,7 @@ namespace Spectrum.Input.InputLibraries.HID byte yByte = unchecked((byte)y); byte[] data = [CMD_MOVE, xByte, yByte]; - bool success = SendFeatureReport(data); - - return success; + SendFeatureReport(data); } public bool Click(byte button) @@ -267,20 +287,16 @@ namespace Spectrum.Input.InputLibraries.HID return success; } - public bool Press(byte button) + public void Press(int button) { - byte[] data = [CMD_PRESS, button]; - bool success = SendFeatureReport(data); - - return success; + byte[] data = [CMD_PRESS, (byte)button]; + SendFeatureReport(data); } - public bool Release(byte button) + public void Release(int button) { - byte[] data = [CMD_RELEASE, button]; - bool success = SendFeatureReport(data); - - return success; + byte[] data = [CMD_RELEASE, (byte)button]; + SendFeatureReport(data); } public bool Scroll(int amount) @@ -294,28 +310,6 @@ namespace Spectrum.Input.InputLibraries.HID return success; } - public void Close() - { - lock (_syncLock) - { - try - { - stream?.Close(); - stream?.Dispose(); - LogManager.Log("HIDMain: Connection closed.", LogLevel.Debug); - } - catch (Exception ex) - { - LogManager.Log($"HIDMain: Error closing connection: {ex.Message}", LogLevel.Debug); - } - finally - { - stream = null; - device = null; - } - } - } - public bool IsConnected => stream != null && device != null; } } diff --git a/Spectrum/Input/InputLibraries/IInputLibrary.cs b/Spectrum/Input/InputLibraries/IInputLibrary.cs new file mode 100644 index 0000000..ba7390a --- /dev/null +++ b/Spectrum/Input/InputLibraries/IInputLibrary.cs @@ -0,0 +1,13 @@ +namespace Spectrum.Input.InputLibraries +{ + public interface IInputLibrary + { + bool RequiresInitialization { get; } + bool IsConnected { get; } + bool Initialize(); + void Dispose(); + void Move(int x, int y); + void Press(int button); + void Release(int button); + } +} diff --git a/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs b/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs index 34499bf..8221ba6 100644 --- a/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs +++ b/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs @@ -2,23 +2,44 @@ namespace Spectrum.Input.InputLibraries.MouseEvent { - public class MouseMain + public class MouseMain : IInputLibrary { [DllImport("user32.dll")] private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo); + public bool RequiresInitialization => false; + public bool IsConnected => true; + public bool Initialize() { return true; } + public void Dispose() { } - public static void Move(int x, int y) + public void Move(int x, int y) { mouse_event(0x0001, (uint)x, (uint)y, 0, 0); } - public static void ClickDown() + public void Press(int button) { - mouse_event(0x0002, 0, 0, 0, 0); + uint downFlag = button switch + { + 0x01 => 0x0002, // left: down + 0x02 => 0x0008, // right: down + 0x03 => 0x0020, // middle: down + _ => 0 + }; + if (downFlag != 0) + mouse_event(downFlag, 0, 0, 0, 0); } - public static void ClickUp() + + public void Release(int button) { - mouse_event(0x0004, 0, 0, 0, 0); + uint upFlag = button switch + { + 0x01 => 0x0004, // left: up + 0x02 => 0x0010, // right: up + 0x03 => 0x0040, // middle: up + _ => 0 + }; + if (upFlag != 0) + mouse_event(upFlag, 0, 0, 0, 0); } } } diff --git a/Spectrum/Input/InputManager.cs b/Spectrum/Input/InputManager.cs index 3840a86..5b14ff2 100644 --- a/Spectrum/Input/InputManager.cs +++ b/Spectrum/Input/InputManager.cs @@ -1,9 +1,7 @@ -using Spectrum.Input.InputLibraries.Arduino; -using Spectrum.Input.InputLibraries.HID; +using Spectrum.Input.InputLibraries.HID; using Spectrum.Utilities; using System.Diagnostics; using System.Runtime.InteropServices; -using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain; namespace Spectrum.Input { @@ -107,10 +105,10 @@ namespace Spectrum.Input switch (config.MovementMethod) { case MovementMethod.MouseEvent: - MouseEvent.Move(deltaX, deltaY); + Program.MouseMain.Move(deltaX, deltaY); break; case MovementMethod.Arduino: - ArduinoMain.Move(deltaX, deltaY); + Program.ArduinoMain.Move(deltaX, deltaY); break; case MovementMethod.HID: if (hid != null && hid.IsConnected) @@ -119,7 +117,7 @@ namespace Spectrum.Input LogManager.Log($"Hid is null: {hid == null} | hid is connected: {hid?.IsConnected}"); break; default: - MouseEvent.Move(deltaX, deltaY); + Program.MouseMain.Move(deltaX, deltaY); break; } } @@ -132,25 +130,17 @@ namespace Spectrum.Input MovementType.Linear => MovementPaths.LinearInterpolation(start, end, sensitivity), MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, sensitivity), MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, sensitivity), - MovementType.WindMouse => TrackWindMouse(start, end, sensitivity, insideBoundingBox), + MovementType.WindMouse => MovementPaths.WindMouse(start, end, + mainConfig.Data.WindMouseGravity, + mainConfig.Data.WindMouseWind, + mainConfig.Data.WindMouseMaxStep, + sensitivity, + mainConfig.Data.WindMouseOvershoot, + insideBoundingBox), _ => MovementPaths.LinearInterpolation(start, end, sensitivity), }; } - private static Point TrackWindMouse(Point start, Point end, double sensitivity, bool insideBoundingBox) - { - var t0 = Stopwatch.GetTimestamp(); - var result = MovementPaths.WindMouse(start, end, - mainConfig.Data.WindMouseGravity, - mainConfig.Data.WindMouseWind, - mainConfig.Data.WindMouseMaxStep, - sensitivity, - mainConfig.Data.WindMouseOvershoot, - insideBoundingBox); - Program.Timings.Add("WindMouse", Stopwatch.GetTimestamp() - t0); - return result; - } - public static async Task ClickMouse() { var config = mainConfig.Data; @@ -219,17 +209,17 @@ namespace Spectrum.Input switch (movementMethod) { case MovementMethod.MouseEvent: - MouseEvent.ClickDown(); + Program.MouseMain.Press(0x01); break; case MovementMethod.Arduino: - ArduinoMain.ClickDown(); + Program.ArduinoMain.Press(0x01); break; case MovementMethod.HID: if (hid != null && hid.IsConnected) hid.Press(HIDMain.BUTTON_LEFT); break; default: - MouseEvent.ClickDown(); + Program.MouseMain.Press(0x01); break; } } @@ -238,17 +228,17 @@ namespace Spectrum.Input switch (movementMethod) { case MovementMethod.MouseEvent: - MouseEvent.ClickUp(); + Program.MouseMain.Release(0x01); break; case MovementMethod.Arduino: - ArduinoMain.ClickUp(); + Program.ArduinoMain.Release(0x01); break; case MovementMethod.HID: if (hid != null && hid.IsConnected) hid.Release(HIDMain.BUTTON_LEFT); break; default: - MouseEvent.ClickUp(); + Program.MouseMain.Release(0x01); break; } } diff --git a/Spectrum/Program.cs b/Spectrum/Program.cs index 74c32d5..021135d 100644 --- a/Spectrum/Program.cs +++ b/Spectrum/Program.cs @@ -1,6 +1,8 @@ using OpenCvSharp; using Spectrum.Detection; +using Spectrum.Input.InputLibraries.Arduino; using Spectrum.Input.InputLibraries.HID; +using Spectrum.Input.InputLibraries.MouseEvent; using Spectrum.Utilities; using System.CommandLine; @@ -11,6 +13,8 @@ namespace Spectrum static Renderer? renderer = null; public static ConfigManager mainConfig = new("bin\\configs\\default.json", "bin\\configs"); public static ColorConfigManager colorConfig = new("bin\\configs\\colors"); + public static MouseMain MouseMain = new(); + public static ArduinoMain ArduinoMain = new(); public static HIDMain HIDMain = new(); private static DetectionManager? detectionManager; public static CaptureManager SharedCaptureManager { get; } = new CaptureManager(); diff --git a/Spectrum/Renderer/Renderer.cs b/Spectrum/Renderer/Renderer.cs index 45c59ac..4fc38af 100644 --- a/Spectrum/Renderer/Renderer.cs +++ b/Spectrum/Renderer/Renderer.cs @@ -1,12 +1,11 @@ using ClickableTransparentOverlay; using ImGuiNET; using OpenCvSharp; -using Spectrum.Detection; -using Spectrum.Input; -using Spectrum.Input.InputLibraries.Arduino; -using Spectrum.Utilities; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; +using Spectrum.Detection; +using Spectrum.Input; +using Spectrum.Utilities; using System.Collections.Concurrent; using System.Diagnostics; using System.Numerics; @@ -691,13 +690,13 @@ namespace Spectrum case MovementMethod.Arduino: { if (Program.HIDMain != null && Program.HIDMain.IsConnected == true) - Program.HIDMain.Close(); - var ok = ArduinoMain.Load(); + Program.HIDMain.Dispose(); + var ok = Program.ArduinoMain.Initialize(); if (!ok) { LogManager.Log("Arduino failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning); config.MovementMethod = MovementMethod.MouseEvent; - ArduinoMain.Close(); + Program.ArduinoMain.Dispose(); } break; } @@ -706,7 +705,7 @@ namespace Spectrum try { if (Program.HIDMain?.IsConnected == false) - Program.HIDMain.Init(); + Program.HIDMain.Initialize(); } catch (Exception ex) { @@ -716,9 +715,9 @@ namespace Spectrum break; } default: - ArduinoMain.Close(); + Program.ArduinoMain.Dispose(); if (Program.HIDMain != null && Program.HIDMain.IsConnected == true) - Program.HIDMain.Close(); + Program.HIDMain.Dispose(); break; } }