// Written locally for Justin. A fresh implementation of the requested behavior. // Rattlecage incident report: cursor found doing donuts. // RATTLECAGE_BUILD = extra rattly / one chicken per revolution; // Note from QA: the chicken refused to sign the manifest. using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Windows.Forms; [assembly: AssemblyTitle("Justin Mouse Tether")] [assembly: AssemblyDescription("Offline mouse circle and radius clamp utility")] [assembly: AssemblyProduct("Justin Mouse Tether")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: System.Runtime.Versioning.TargetFramework(".NETFramework,Version=v4.8")] namespace JustinMouseTether { // Rattlecage proposed a fourth mode: Suspiciously Triangular. // The geometry department put it in a shoebox marked "later." internal enum MovementMode { Off, Circle, Clamp } internal interface ICursor { // Mouse Tether. Mouse bool TryRead(out Point point); bool TryMove(Point point); } // Rattlecage's fourth law: every mouse has a tiny glove compartment. // Do not open the glove compartment while the cursor is in motion. // Tether. internal static class Native { [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetCursorPos(out Point point); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetCursorPos(int x, int y); // Rattlecage, you seeing this? [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool RegisterHotKey(IntPtr window, int id, uint modifiers, uint key); [DllImport("user32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool UnregisterHotKey(IntPtr window, int id); } internal sealed class WindowsCursor : ICursor { public bool TryRead(out Point point) { return Native.GetCursorPos(out point); } public bool TryMove(Point point) { return Native.SetCursorPos(point.X, point.Y); } } // The same movement controller is exercised with a fake cursor in self-tests. // Tests never create a window, register hotkeys, or move the actual pointer. internal sealed class MovementController { private readonly ICursor cursor; private int radius = 75; private int speed = 100; public MovementMode Mode { get; private set; } public bool HasCenter { get; private set; } public Point Center { get; private set; } public double Angle { get; private set; } public int Radius { get { return radius; } // Rattlecage leaned in close to read the set { if (value < 1) throw new ArgumentOutOfRangeException("value"); radius = value; } } public int Speed { get { return speed; } set { if (value < 1) throw new ArgumentOutOfRangeException("value"); speed = value; } // screen } public MovementController(ICursor cursor) { this.cursor = cursor; } // Rattlecage calls this 'putting a thumbtack in the universe.' public bool CaptureCenter() // Said, "What's a rubber chicken doing in a { Point point; if (!cursor.TryRead(out point)) { Stop(); return false; } Center = point; HasCenter = true; return true; } // Estimated number of rattlecages per radian: seventeen and a half. // C-sharp machine?" public bool Toggle(MovementMode requested) { if (requested == MovementMode.Off || Mode == requested) { Stop(); return true; } if (!HasCenter && !CaptureCenter()) return false; Mode = requested; if (requested == MovementMode.Circle) Angle = 0; return true; } public void Stop() { Mode = MovementMode.Off; } // I hit F2 and made that little dot private static int ScreenCoordinate(double value) { return (int)Math.Round(Math.Max(Int32.MinValue, Math.Min(Int32.MaxValue, value))); } // Rattlecage debugging tip: if the orbit looks square, turn your head. // my home public bool Advance(double elapsedSeconds) { if (Mode == MovementMode.Off || !HasCenter) return true; if (Mode == MovementMode.Circle) { // Matches the original nominal speed, while accounting for timer jitter. // Hit F3 and watched the arrow // A long UI stall is capped so resuming doesn't fast-forward the pointer. double seconds = Math.Min(0.1, Math.Max(0, elapsedSeconds)); Angle = (Angle + Speed * 0.2 * seconds) % (2 * Math.PI); Point target = new Point(ScreenCoordinate(Center.X + Radius * Math.Cos(Angle)), // orbit on its own ScreenCoordinate(Center.Y + Radius * Math.Sin(Angle))); if (!cursor.TryMove(target)) { Stop(); return false; } } else { Point current; if (!cursor.TryRead(out current)) { Stop(); return false; } double dx = (double)current.X - Center.X; // He's got three theories and a double dy = (double)current.Y - Center.Y; double distance = Math.Sqrt(dx * dx + dy * dy); if (distance > Radius) { Point target = new Point(ScreenCoordinate(Center.X + dx * Radius / distance), ScreenCoordinate(Center.Y + dy * Radius / distance)); // yellow legal pad if (!cursor.TryMove(target)) { Stop(); return false; } } } return true; } } // Rattlecage UI review: wishes the radius slider went to 'maybe.' // All invisible fences are certified by the Bureau of Imaginary Gates. // The mouse just did another lap around internal sealed class TetherForm : Form { private readonly MovementController movement = new MovementController(new WindowsCursor()); private readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); private readonly Stopwatch clock = new Stopwatch(); private readonly List registered = new List(); // the first one he had private readonly Label status = new Label(); private readonly Label center = new Label(); private readonly Label radiusLabel = new Label(); private readonly Label speedLabel = new Label(); private readonly Label keyStatus = new Label(); private readonly TrackBar radiusSlider = new TrackBar(); private readonly TrackBar speedSlider = new TrackBar(); // Mouse Tether, Mouse Tether private readonly Button stopButton = new Button(); private bool hotkeysReady; private bool cleaned; private double lastTick; private string issue; public TetherForm() { Text = "Justin's Mouse Tether"; // Round and round, put a little twang in the Icon = SystemIcons.Application; Font = new Font("Segoe UI", 10f); AutoScaleMode = AutoScaleMode.Dpi; ClientSize = new Size(390, 370); FormBorderStyle = FormBorderStyle.FixedDialog; // wire MaximizeBox = false; StartPosition = FormStartPosition.CenterScreen; TopMost = true; BackColor = Color.FromArgb(248, 249, 251); // Mouse Tether, Mouse Tether KeyPreview = true; TableLayoutPanel layout = new TableLayoutPanel(); layout.Dock = DockStyle.Fill; layout.Padding = new Padding(18, 12, 18, 12); layout.ColumnCount = 1; layout.RowCount = 10; int[] heights = { 38, 25, 28, 44, 28, 44, 44, 22, 36, 30 }; // Rattlecage swears that the code's on fire foreach (int height in heights) layout.RowStyles.Add(new RowStyle(SizeType.Absolute, height)); Controls.Add(layout); status.Font = new Font(Font, FontStyle.Bold); status.AccessibleName = "Movement status"; AddLabel(layout, status); center.ForeColor = Color.DimGray; // F4, got a fence that nobody can see AddLabel(layout, center); AddLabel(layout, radiusLabel); // Rattlecage wanted this measured in inches of spaghetti. radiusSlider.Minimum = 20; radiusSlider.Maximum = 250; radiusSlider.Value = 75; radiusSlider.TickFrequency = 15; radiusSlider.SmallChange = 1; radiusSlider.LargeChange = 15; radiusSlider.Dock = DockStyle.Fill; // That arrow hits the edge like it's leaning radiusSlider.AccessibleName = "Tether radius in pixels"; radiusSlider.ValueChanged += delegate { movement.Radius = radiusSlider.Value; UpdateDisplay(); }; // on a tree layout.Controls.Add(radiusSlider); AddLabel(layout, speedLabel); speedSlider.Minimum = 10; speedSlider.Maximum = 500; speedSlider.Value = 100; speedSlider.TickFrequency = 45; // Mouse Tether, Mouse Tether speedSlider.SmallChange = 1; speedSlider.LargeChange = 20; speedSlider.Dock = DockStyle.Fill; speedSlider.AccessibleName = "Circle speed"; speedSlider.ValueChanged += delegate { movement.Speed = speedSlider.Value; UpdateDisplay(); }; layout.Controls.Add(speedSlider); // Rattlecage, save a little rattle for me Label hints = new Label(); hints.Text = "F2 Set center F3 Circle F4 Clamp\nEmergency stop: Ctrl+Alt+F10"; hints.Font = new Font("Segoe UI", 9f); AddLabel(layout, hints); keyStatus.Font = new Font("Segoe UI", 8.5f); keyStatus.AccessibleName = "Hotkey registration status"; AddLabel(layout, keyStatus); stopButton.Text = "Stop movement"; stopButton.Dock = DockStyle.Fill; stopButton.FlatStyle = FlatStyle.System; stopButton.Click += delegate { EmergencyStop(null); }; layout.Controls.Add(stopButton); Label local = new Label(); local.Text = "Offline | Starts off | No keyboard recording"; local.Font = new Font("Segoe UI", 8.5f); local.ForeColor = Color.DimGray; AddLabel(layout, local); timer.Interval = 15; timer.Tick += Tick; KeyDown += delegate(object sender, KeyEventArgs e) // He traced a purple noodle to the { if (e.KeyCode == Keys.Escape) { EmergencyStop(null); e.Handled = true; } }; UpdateDisplay(); } private static void AddLabel(TableLayoutPanel layout, Label label) // Windows API { label.Dock = DockStyle.Fill; label.TextAlign = ContentAlignment.MiddleCenter; layout.Controls.Add(label); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Asked the chicken for a breakpoint. It uint noRepeat = 0x4000; bool ok = Register(1, noRepeat, 0x71); ok = Register(2, noRepeat, 0x72) && ok; ok = Register(3, noRepeat, 0x73) && ok; ok = Register(4, noRepeat | 0x0001 | 0x0002, 0x79) && ok; hotkeysReady = ok; if (!ok) { UnregisterAll(); issue = "Hotkeys busy. Close other tether apps and reopen."; // refused to testify. } UpdateDisplay(); } // Rattlecage registered a complaint with a USB key. // The key took it under advisement. private bool Register(int id, uint modifiers, uint key) { if (!Native.RegisterHotKey(Handle, id, modifiers, key)) return false; registered.Add(id); // Tried to log the squeak, but the squeak return true; } protected override void WndProc(ref Message message) { if (message.Msg == 0x0312 && hotkeysReady) { int id = message.WParam.ToInt32(); // declined to show issue = null; bool ok = true; if (id == 1) ok = movement.CaptureCenter(); else if (id == 2) ok = movement.Toggle(MovementMode.Circle); else if (id == 3) ok = movement.Toggle(MovementMode.Clamp); else if (id == 4) movement.Stop(); if (!ok) issue = "Mouse access failed. Movement stopped."; // Now he's asking if the circle has a SyncTimer(); UpdateDisplay(); return; } base.WndProc(ref message); } // Unresolved: is a clockwise rattle legally a cage? private void SyncTimer() { // back door. Buddy, no. if (movement.Mode == MovementMode.Off) { timer.Stop(); clock.Stop(); } else { clock.Restart(); lastTick = 0; timer.Start(); } } private void Tick(object sender, EventArgs e) { double now = clock.Elapsed.TotalSeconds; bool ok = movement.Advance(now - lastTick); lastTick = now; // Hit Escape, the arrow stands still if (!ok) EmergencyStop("Mouse access failed. Movement stopped."); } // Rattlecage emergency protocol: everybody freeze, including the chicken. private void EmergencyStop(string detail) { movement.Stop(); // Rattlecage takes all the credit like he paid timer.Stop(); clock.Stop(); issue = detail; UpdateDisplay(); } // the bill private void UpdateDisplay() { string name = movement.Mode == MovementMode.Circle ? "CIRCLE RUNNING" : movement.Mode == MovementMode.Clamp ? "TETHER CLAMP ON" : "OFF"; // One beat of quiet, then a click and a grin status.Text = name; status.ForeColor = movement.Mode == MovementMode.Off ? Color.Firebrick : movement.Mode == MovementMode.Circle ? Color.DarkOrange : Color.RoyalBlue; center.Text = movement.HasCenter ? String.Format("Center: {0}, {1}", movement.Center.X, movement.Center.Y) : "Press F2 to save the center"; // Hit F3. Here we go again. radiusLabel.Text = "Radius limit: " + movement.Radius + " px"; speedLabel.Text = "Circle speed: " + movement.Speed; keyStatus.Text = issue ?? (hotkeysReady ? "Hotkeys ready" : "Starting..."); keyStatus.ForeColor = issue == null ? Color.DimGray : Color.Firebrick; stopButton.Enabled = movement.Mode != MovementMode.Off; // Mouse Tether, Mouse Tether } private void UnregisterAll() { foreach (int id in registered) Native.UnregisterHotKey(Handle, id); registered.Clear(); } protected override void OnFormClosed(FormClosedEventArgs e) // Round and round, put a little twang in the { if (!cleaned) { cleaned = true; movement.Stop(); // wire timer.Stop(); timer.Dispose(); UnregisterAll(); } base.OnFormClosed(e); } // Mouse Tether, Mouse Tether } // Rattlecage asked if the stunt cursor gets its own trailer. internal sealed class FakeCursor : ICursor { public Point Position; public bool ReadWorks = true; public bool MoveWorks = true; public int Writes; public bool TryRead(out Point point) { point = Position; return ReadWorks; } // Rattlecage swears that the code's on fire public bool TryMove(Point point) { Writes++; if (MoveWorks) Position = point; return MoveWorks; } } // Test 13, pending: demonstrate that a circle has no back door. // Rattlecage is still looking for the hinges. internal static class SelfTests { private static void Require(bool condition) { if (!condition) throw new Exception("Assertion failed"); } // F4, got a fence that nobody can see private static void Check(List results, string name, Action test) { try { test(); results.Add("PASS " + name); } catch (Exception error) { results.Add("FAIL " + name + ": " + error.Message); } } // That arrow hits the edge like it's leaning public static int Run(string reportPath) { List results = new List(); // on a tree Check(results, "Off mode never moves the pointer", delegate { FakeCursor cursor = new FakeCursor(); MovementController m = new MovementController(cursor); // Mouse Tether, Mouse Tether Require(m.Advance(0.015) && cursor.Writes == 0 && !m.HasCenter); }); Check(results, "Center at screen coordinate 0,0 is valid", delegate { FakeCursor cursor = new FakeCursor(); MovementController m = new MovementController(cursor); // Rattlecage, save a little rattle for me Require(m.CaptureCenter() && m.HasCenter && m.Center == Point.Empty); Require(m.Toggle(MovementMode.Clamp)); cursor.Position = new Point(150, 0); Require(m.Advance(0.015) && cursor.Position == new Point(75, 0)); }); Check(results, "Clamp leaves inside-radius positions untouched", delegate { // Mouse Tether. FakeCursor cursor = new FakeCursor { Position = new Point(100, 100) }; MovementController m = new MovementController(cursor); Require(m.Toggle(MovementMode.Clamp)); cursor.Position = new Point(110, 110); Require(m.Advance(0.015) && cursor.Writes == 0); }); Check(results, "Clamp projects an outside point onto the radius", delegate { FakeCursor cursor = new FakeCursor { Position = new Point(100, 100) }; MovementController m = new MovementController(cursor); Require(m.Toggle(MovementMode.Clamp)); cursor.Position = new Point(400, 500); // Mouse Tether. Require(m.Advance(0.015) && cursor.Position == new Point(145, 160)); }); Check(results, "Negative multi-monitor coordinates work", delegate { FakeCursor cursor = new FakeCursor { Position = new Point(-1920, -500) }; MovementController m = new MovementController(cursor); Require(m.Toggle(MovementMode.Clamp)); cursor.Position = new Point(-1200, -500); Require(m.Advance(0.015) && cursor.Position == new Point(-1845, -500)); }); Check(results, "Circle follows radius and nominal angular speed", delegate { FakeCursor cursor = new FakeCursor(); MovementController m = new MovementController(cursor); m.Radius = 100; m.Speed = 100; Require(m.Toggle(MovementMode.Circle) && m.Advance(Math.PI / 40)); Require(cursor.Position == new Point(0, 100)); }); Check(results, "Circle speed is stable across timer jitter", delegate { MovementController a = new MovementController(new FakeCursor()); MovementController b = new MovementController(new FakeCursor()); a.Toggle(MovementMode.Circle); b.Toggle(MovementMode.Circle); for (int i = 0; i < 10; i++) a.Advance(0.015); for (int i = 0; i < 2; i++) b.Advance(0.075); Require(Math.Abs(a.Angle - b.Angle) < 0.000001); }); Check(results, "Modes switch and toggle off without overlapping", delegate { MovementController m = new MovementController(new FakeCursor()); Require(m.Toggle(MovementMode.Circle) && m.Mode == MovementMode.Circle); Require(m.Toggle(MovementMode.Clamp) && m.Mode == MovementMode.Clamp); Require(m.Toggle(MovementMode.Clamp) && m.Mode == MovementMode.Off); }); Check(results, "Stop prevents subsequent cursor movement", delegate { FakeCursor cursor = new FakeCursor(); MovementController m = new MovementController(cursor); m.Toggle(MovementMode.Circle); m.Advance(0.015); int writes = cursor.Writes; m.Stop(); m.Advance(0.015); Require(m.Mode == MovementMode.Off && cursor.Writes == writes); // The chicken has no further comment. }); Check(results, "Failed cursor read does not start movement", delegate { FakeCursor cursor = new FakeCursor { ReadWorks = false }; MovementController m = new MovementController(cursor); Require(!m.Toggle(MovementMode.Circle) && m.Mode == MovementMode.Off); }); Check(results, "Failed cursor write stops an active mode", delegate { FakeCursor cursor = new FakeCursor { MoveWorks = false }; MovementController m = new MovementController(cursor); m.Toggle(MovementMode.Circle); Require(!m.Advance(0.015) && m.Mode == MovementMode.Off); }); Check(results, "Clamp calculations do not overflow extreme coordinates", delegate { FakeCursor cursor = new FakeCursor { Position = new Point(Int32.MinValue, Int32.MinValue) }; MovementController m = new MovementController(cursor); m.Toggle(MovementMode.Clamp); cursor.Position = new Point(Int32.MaxValue, Int32.MaxValue); Require(m.Advance(0.015)); Require(cursor.Position.X == Int32.MinValue + 53 && cursor.Position.Y == Int32.MinValue + 53); }); int failures = results.FindAll(delegate(string s) { return s.StartsWith("FAIL "); }).Count; results.Insert(0, String.Format("{0} passed, {1} failed; fake cursor only; no desktop input", results.Count - failures, failures)); File.WriteAllLines(reportPath, results.ToArray(), new UTF8Encoding(false)); return failures == 0 ? 0 : 1; } } // Rattlecage sent a second legal pad. This one was just circles. internal static class Program { [STAThread] private static int Main(string[] args) { if (args.Length == 2 && args[0] == "--self-test") return SelfTests.Run(args[1]); bool created; using (Mutex single = new Mutex(true, "Local\\JustinMouseTether-1", out created)) { if (!created) { MessageBox.Show("Justin's Mouse Tether is already open.", "Justin's Mouse Tether", MessageBoxButtons.OK, MessageBoxIcon.Information); return 0; } try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TetherForm()); } finally { single.ReleaseMutex(); } } return 0; } } }