Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

23.4 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Portions adapted from Beamer (https://github.com/kalkman-code/beamer), Copyright (C) Kalkman Code,
// GPL-3.0. Changed: C# port of the SendInput absolute-move and scan-code key approach.
// SendInput injection of k.* events. Every input carries
// dwExtraInfo = MARK so our own capture/edge code skips it. Held keys/buttons are tracked for
// releaseAll.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;

namespace MacShare
{
    class Injector
    {
        // The emergency return (Crossing.cs) stopped the session: nothing more of it is injected until
        // main has ended it.
        public static volatile bool Blocked;
        readonly HashSet<int> heldScans = new HashSet<int>();
        readonly HashSet<int> heldButtons = new HashSet<int>();
        double fx, fy;              // sub-pixel remainder of relative moves (physical px)
        double wheelRem, hwheelRem; // remainder of wheel units
        // Layout shortcuts from the other computer are done here (NextLayout): Win+Space (Ctrl+Space
        // on a Mac, with the Ctrl/Cmd swap) without its Space, so it can't switch twice, and a tap
        // of a Mac's 🌐/Fn (no Windows key for it). Alt+Shift and Ctrl+Shift go as keys, as typed.
        readonly HashSet<string> tapDown = new HashSet<string>(); // modifiers (and Fn) held now
        readonly HashSet<string> tapMods = new HashSet<string>(); // pressed since none were held
        bool modsOnly, swallowSpace;

        // Called after every injected move with the new position and the requested logical delta
        // (the return edge watches pushes through the edge, armReturn).
        public Action<int, int, double, double> Moved;
        // The armed return sides (Capture.ReturnStops): a move stops at their outer edge.
        public Func<List<string>> Stops;
        // Driven through a cursor portal: its stretch stops a move too (Capture.PortalStop).
        public Screens.PortalStopFn PortalStop;

        static readonly int Size = Marshal.SizeOf(typeof(Native.INPUT));

        // SendInput usually wakes the display, but not always on the lock screen or modern-standby
        // laptops: also reset the idle timers, at most once a second.
        static int lastWake;
        public static void Wake()
        {
            int now = Environment.TickCount;
            if (lastWake != 0 && unchecked(now - lastWake) < 1000) return;
            lastWake = now;
            Native.SetThreadExecutionState(Native.ES_DISPLAY_REQUIRED | Native.ES_SYSTEM_REQUIRED);
        }

        static readonly Native.INPUT[] one = new Native.INPUT[1]; // reused: no array per injected event
        static void Send(Native.INPUT input)
        {
            lock (one)
            {
                one[0] = input;
                Native.SendInput(1, one, Size);
            }
        }

        static Native.INPUT Mouse(int dx, int dy, uint data, uint flags)
        {
            Native.INPUT i = new Native.INPUT();
            i.type = Native.INPUT_MOUSE;
            i.u.mi.dx = dx;
            i.u.mi.dy = dy;
            i.u.mi.mouseData = data;
            i.u.mi.dwFlags = flags;
            i.u.mi.dwExtraInfo = Native.MARK;
            return i;
        }

        // Absolute move on the virtual desktop (avoids Windows applying pointer acceleration twice).
        // SetCursorPos follows SendInput so GetCursorPos on the next call returns the updated position:
        // on the lock screen SendInput alone may not update it, causing the cursor to appear frozen.
        public static void MoveTo(int x, int y)
        {
            int left = Native.GetSystemMetrics(Native.SM_XVIRTUALSCREEN), top = Native.GetSystemMetrics(Native.SM_YVIRTUALSCREEN);
            int w = Math.Max(2, Native.GetSystemMetrics(Native.SM_CXVIRTUALSCREEN)), h = Math.Max(2, Native.GetSystemMetrics(Native.SM_CYVIRTUALSCREEN));
            int ax = (int)Math.Round((x - left) * 65535.0 / (w - 1));
            int ay = (int)Math.Round((y - top) * 65535.0 / (h - 1));
            Send(Mouse(ax, ay, 0, Native.MOUSEEVENTF_MOVE | Native.MOUSEEVENTF_ABSOLUTE | Native.MOUSEEVENTF_VIRTUALDESK));
            Native.SetCursorPos(x, y);
        }

        // Relative move in logical px (main already applied `speed`); scaled by the monitor's DPI.
        public void Move(double dx, double dy)
        {
            if (Blocked) return;
            Native.POINT cur;
            Native.GetCursorPos(out cur);
            double scale = Screens.Scale(cur.x, cur.y);
            double tx = cur.x + fx + dx * scale, ty = cur.y + fy + dy * scale;
            int ix = (int)Math.Round(tx), iy = (int)Math.Round(ty);
            Point p;
            Rectangle pm;
            string ps;
            double pf, pt;
            if (PortalStop != null && PortalStop(out pm, out ps, out pf, out pt)) p = Screens.Walk(ix, iy, cur.x, cur.y, Stops != null ? Stops() : null, pm, ps, pf, pt);
            else p = Screens.Walk(ix, iy, cur.x, cur.y, Stops != null ? Stops() : null);
            if (p.X != ix || p.Y != iy) { fx = 0; fy = 0; } // stopped by an edge: drop the remainder
            else { fx = tx - ix; fy = ty - iy; }
            if (p.X != cur.x || p.Y != cur.y)
            {
                MoveTo(p.X, p.Y);
                WatchStuck(cur);
                CursorShow.Check(); // #329: Windows showing no pointer for the other computer's mouse
            }
            if (Moved != null) Moved(p.X, p.Y, dx, dy);
        }

        // A window run as administrator under the pointer (or in front) takes no injected input
        // (UIPI): the pointer stops there, never reaches the edge that sends it home, and the other
        // computer's mouse seems dead (#278). Moves that don't land for a while over such a window
        // say so once (Stuck); main sends the pointer home. Only for an elevated window, so a game
        // that clips the cursor isn't taken for one.
        public Action Stuck;
        int stuckMoves, stuckSince;
        bool stuckSaid;
        void WatchStuck(Native.POINT before)
        {
            Native.POINT after;
            if (!Native.GetCursorPos(out after)) return;
            if (after.x != before.x || after.y != before.y) { stuckMoves = 0; stuckSaid = false; return; }
            int now = Environment.TickCount;
            if (stuckMoves++ == 0) stuckSince = now;
            if (stuckSaid || stuckMoves < 8 || unchecked(now - stuckSince) < 250) return;
            stuckSaid = true;
            if (Stuck != null && (Elevated(WindowFromPoint(after)) || Elevated(Native.GetForegroundWindow()))) Stuck();
        }

        // Main froze with a button we pressed for the other computer still down (#312): a press on our own
        // app's title bar (a drag, or a caption button OnOwnCaptionButton missed) or borders runs Windows'
        // modal loop on main's thread, the thread that has to bring us the release, so nothing came until
        // this computer's own mouse moved. Main says it's alive with `keepalive {driven}` while it's driven;
        // with no word from it for SilentMs and a button down, the button is let go here and the loop ends.
        // Off until main sends that keepalive: an older one doesn't, and a button held still stays held.
        const int SilentMs = 1500;
        static int heard; // Environment.TickCount of main's last command
        System.Windows.Forms.Timer silence; // on the UI thread: made by Heartbeat (Dispatch)
        public Action<List<int>, int> LetGo; // the buttons let go, how long main was silent

        public static void Heard() { heard = Environment.TickCount; }

        public void Heartbeat()
        {
            if (silence != null) return;
            silence = new System.Windows.Forms.Timer { Interval = 250 };
            silence.Tick += delegate { WatchSilence(); };
            silence.Start();
        }

        void WatchSilence()
        {
            int quiet = unchecked(Environment.TickCount - heard);
            if (quiet < SilentMs) return;
            List<int> down = new List<int>();
            foreach (int b in heldButtons) if (!(b == 0 && captionHeld)) down.Add(b); // a held-back caption click was never pressed
            if (down.Count == 0) return;
            foreach (int b in down) Button(b, false);
            if (LetGo != null) LetGo(down, quiet);
        }

        [DllImport("kernel32.dll")] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
        [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
        [DllImport("advapi32.dll", SetLastError = true)] static extern bool OpenProcessToken(IntPtr process, uint access, out IntPtr token);
        [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation(IntPtr token, int cls, out int info, int len, out int retLen);

        // The window's process runs elevated. A token we may not even read (TOKEN_QUERY refused) is
        // an administrator's; a process we can't open at all (protected) is left alone.
        static bool Elevated(IntPtr w)
        {
            if (w == IntPtr.Zero) return false;
            IntPtr root = GetAncestor(w, 2); // GA_ROOT
            uint pid;
            GetWindowThreadProcessId(root != IntPtr.Zero ? root : w, out pid);
            return ElevatedPid(pid);
        }

        static bool ElevatedPid(uint pid)
        {
            if (pid == 0) return false;
            IntPtr h = OpenProcess(0x1000, false, pid); // PROCESS_QUERY_LIMITED_INFORMATION
            if (h == IntPtr.Zero) return false;
            try
            {
                IntPtr tok;
                if (!OpenProcessToken(h, 0x0008, out tok)) return Marshal.GetLastWin32Error() == 5; // TOKEN_QUERY; ERROR_ACCESS_DENIED
                try
                {
                    int elevated, len;
                    return GetTokenInformation(tok, 20, out elevated, 4, out len) && elevated != 0; // TokenElevation
                }
                finally { CloseHandle(tok); }
            }
            finally { CloseHandle(h); }
        }

        public void Button(int b, bool down)
        {
            uint flags, data = 0;
            switch (b)
            {
                case 0: flags = down ? Native.MOUSEEVENTF_LEFTDOWN : Native.MOUSEEVENTF_LEFTUP; break;
                case 1: flags = down ? Native.MOUSEEVENTF_RIGHTDOWN : Native.MOUSEEVENTF_RIGHTUP; break;
                case 2: flags = down ? Native.MOUSEEVENTF_MIDDLEDOWN : Native.MOUSEEVENTF_MIDDLEUP; break;
                case 3: flags = down ? Native.MOUSEEVENTF_XDOWN : Native.MOUSEEVENTF_XUP; data = Native.XBUTTON1; break;
                case 4: flags = down ? Native.MOUSEEVENTF_XDOWN : Native.MOUSEEVENTF_XUP; data = Native.XBUTTON2; break;
                default: return;
            }
            if (b == 0 && down && OnOwnCaptionButton())
            {
                // Held back until the release (#209): Windows' caption-button loop would stall our app's
                // main thread, which is the one that has to bring us that release.
                Native.GetCursorPos(out heldCaption);
                captionHeld = true;
                heldButtons.Add(b);
                return;
            }
            if (b == 0 && !down && captionHeld)
            {
                captionHeld = false;
                heldButtons.Remove(b);
                Native.POINT now;
                Native.GetCursorPos(out now);
                bool moved = now.x != heldCaption.x || now.y != heldCaption.y;
                if (moved) MoveTo(heldCaption.x, heldCaption.y);
                Send(Mouse(0, 0, 0, Native.MOUSEEVENTF_LEFTDOWN));
                if (moved) MoveTo(now.x, now.y); // released off the button: Windows cancels it, as with a real mouse
                Send(Mouse(0, 0, 0, Native.MOUSEEVENTF_LEFTUP));
                return;
            }
            if (down) heldButtons.Add(b); else heldButtons.Remove(b);
            if (down && b <= 1) WatchClick();
            Send(Mouse(0, 0, data, flags));
        }

        // A click over a window run as administrator goes nowhere, and nothing says so: the moves land
        // (the cursor is the system's), only the press and release are dropped, and SendInput doesn't
        // tell (UIPI's refusal is silent by design). The pointer goes home with the note, as WatchStuck
        // does (#278: cmd, Device Manager, an installer). Not when we're elevated ourselves (or SYSTEM):
        // then the window takes our input.
        static int selfElevated = -1;
        void WatchClick()
        {
            if (Stuck == null) return;
            if (selfElevated < 0) selfElevated = ElevatedPid((uint)System.Diagnostics.Process.GetCurrentProcess().Id) ? 1 : 0;
            if (selfElevated == 1) return;
            Native.POINT p;
            if (Native.GetCursorPos(out p) && Elevated(WindowFromPoint(p))) Stuck();
        }

        bool captionHeld;
        Native.POINT heldCaption;

        [DllImport("user32.dll")] static extern IntPtr WindowFromPoint(Native.POINT p);
        [DllImport("user32.dll")] static extern IntPtr GetAncestor(IntPtr h, uint flags);
        [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
        [DllImport("user32.dll")] static extern IntPtr SendMessageTimeout(IntPtr h, uint msg, IntPtr w, IntPtr l, uint flags, uint timeout, out IntPtr result);

        static uint appPid; // TwinDesk's main process (our parent), 0 until known
        static uint AppPid()
        {
            if (appPid == 0)
            {
                uint ppid;
                if (AppWindows.Parents().TryGetValue((uint)System.Diagnostics.Process.GetCurrentProcess().Id, out ppid)) appPid = ppid;
            }
            return appPid;
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern bool QueryFullProcessImageName(IntPtr h, int flags, System.Text.StringBuilder name, ref int size);

        // TwinDesk's own process: our parent, or (the Full KVM build: the service started this helper, so
        // our parent is the service) any process whose program is TwinDesk.exe.
        static uint twinPid; // the last one found by its name
        static bool IsTwinDesk(uint pid)
        {
            if (pid == 0) return false;
            uint app = AppPid();
            if (app != 0 && pid == app) return true;
            if (pid == twinPid) return true;
            IntPtr h = OpenProcess(0x1000 /* PROCESS_QUERY_LIMITED_INFORMATION */, false, pid);
            if (h == IntPtr.Zero) return false;
            try
            {
                System.Text.StringBuilder name = new System.Text.StringBuilder(1024);
                int size = name.Capacity;
                if (!QueryFullProcessImageName(h, 0, name, ref size)) return false;
                bool twin = string.Equals(System.IO.Path.GetFileName(name.ToString()), "TwinDesk.exe", StringComparison.OrdinalIgnoreCase);
                if (twin) twinPid = pid;
                return twin;
            }
            finally { CloseHandle(h); }
        }

        [StructLayout(LayoutKind.Sequential)] struct RECT { public int left, top, right, bottom; }
        [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int attr, out RECT value, int size);
        [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r);

        // The pointer is on the minimize, maximize, close or help button of one of TwinDesk's own windows.
        // The buttons' bounds come from DWM (DWMWA_CAPTION_BUTTON_BOUNDS), which doesn't ask our app's main
        // thread: WM_NCHITTEST does, and a main busy for its 100 ms missed the button (#209: minimize froze
        // AMXLPDL for 3-5 s, until WatchSilence let go). WM_NCHITTEST stays for a window DWM has no bounds
        // for. Every left press on TwinDesk's own window is logged with what was found, as long as that
        // is still being checked on a real machine.
        static bool OnOwnCaptionButton()
        {
            Native.POINT p;
            if (!Native.GetCursorPos(out p)) return false;
            IntPtr h = WindowFromPoint(p);
            if (h == IntPtr.Zero) return false;
            IntPtr root = GetAncestor(h, 2); // GA_ROOT
            if (root == IntPtr.Zero) root = h;
            uint pid;
            GetWindowThreadProcessId(root, out pid);
            if (!IsTwinDesk(pid)) return false;
            RECT win, btn;
            if (GetWindowRect(root, out win) && DwmGetWindowAttribute(root, 5 /* DWMWA_CAPTION_BUTTON_BOUNDS */, out btn, Marshal.SizeOf(typeof(RECT))) == 0 && btn.right > btn.left)
            {
                bool on = p.x >= win.left + btn.left && p.x < win.left + btn.right && p.y >= win.top + btn.top && p.y < win.top + btn.bottom;
                Console.Error.WriteLine("[caption] left press on TwinDesk's window at " + p.x + "," + p.y + ": buttons " + (win.left + btn.left) + "," + (win.top + btn.top) + "-" + (win.left + btn.right) + "," + (win.top + btn.bottom) + (on ? ", on them: held until the release" : ", not on them"));
                if (on) return true;
            }
            IntPtr hit;
            IntPtr l = new IntPtr(((p.y & 0xFFFF) << 16) | (p.x & 0xFFFF));
            if (SendMessageTimeout(root, 0x84 /* WM_NCHITTEST */, IntPtr.Zero, l, 2 /* SMTO_ABORTIFHUNG */, 100, out hit) == IntPtr.Zero)
            {
                Console.Error.WriteLine("[caption] left press on TwinDesk's window at " + p.x + "," + p.y + ": its hit test didn't answer in 100 ms");
                return false;
            }
            int ht = (int)hit.ToInt64();
            Console.Error.WriteLine("[caption] left press on TwinDesk's window at " + p.x + "," + p.y + ": hit test " + ht);
            return ht == 8 || ht == 9 || ht == 20 || ht == 21; // HTMINBUTTON, HTMAXBUTTON, HTCLOSE, HTHELP
        }

        // DOM sign: positive dy = scroll down (content further down) → negative WHEEL data.
        public void Wheel(double dx, double dy, bool pixel)
        {
            double k = pixel ? 3 : 120;
            wheelRem += -dy * k;
            hwheelRem += dx * k;
            int v = (int)Math.Truncate(wheelRem), h = (int)Math.Truncate(hwheelRem);
            wheelRem -= v;
            hwheelRem -= h;
            if (v != 0) Send(Mouse(0, 0, unchecked((uint)v), Native.MOUSEEVENTF_WHEEL));
            if (h != 0) Send(Mouse(0, 0, unchecked((uint)h), Native.MOUSEEVENTF_HWHEEL));
        }

        public void Key(string code, bool down)
        {
            if (code == "Space")
            {
                if (down && tapDown.Count > 0 && Kinds(tapDown).SetEquals(new[] { "Meta" }))
                {
                    swallowSpace = true;
                    modsOnly = false;
                    NextLayout();
                    SendVk(0xE8, true); // a key between: the Windows key coming up alone would open Start
                    SendVk(0xE8, false);
                    return;
                }
                if (!down && swallowSpace) { swallowSpace = false; return; }
            }
            if (code == "Fn" || Kind(code) != code)
            {
                if (down)
                {
                    if (tapDown.Count == 0) { tapMods.Clear(); modsOnly = true; }
                    tapDown.Add(code);
                    tapMods.Add(code);
                }
                else if (tapDown.Remove(code) && tapDown.Count == 0)
                {
                    if (modsOnly && Kinds(tapMods).SetEquals(new[] { "Fn" })) NextLayout();
                    modsOnly = false;
                }
            }
            else if (down) modsOnly = false;
            int scan = Keys.Scan(code);
            if (scan < 0) return;
            if (down) heldScans.Add(scan); else heldScans.Remove(scan);
            SendScan(scan, down);
        }

        static void SendScan(int scan, bool down)
        {
            Native.INPUT i = new Native.INPUT();
            i.type = Native.INPUT_KEYBOARD;
            i.u.ki.wScan = (ushort)(scan & 0xFF);
            i.u.ki.dwFlags = Native.KEYEVENTF_SCANCODE | ((scan & 0xE000) != 0 ? Native.KEYEVENTF_EXTENDEDKEY : 0) | (down ? 0 : Native.KEYEVENTF_KEYUP);
            i.u.ki.dwExtraInfo = Native.MARK;
            Send(i);
        }

        static string Kind(string code)
        {
            foreach (string k in new[] { "Shift", "Control", "Alt", "Meta" }) if (code.StartsWith(k)) return k;
            return code;
        }

        static HashSet<string> Kinds(IEnumerable<string> codes)
        {
            HashSet<string> out_ = new HashSet<string>();
            foreach (string c in codes) out_.Add(Kind(c));
            return out_;
        }

        // The foreground window's next keyboard layout, as Windows' own shortcut does it.
        static void NextLayout()
        {
            IntPtr w = Native.GetForegroundWindow();
            if (w != IntPtr.Zero) Native.PostMessage(w, Native.WM_INPUTLANGCHANGEREQUEST, new IntPtr(Native.INPUTLANGCHANGE_FORWARD), new IntPtr(Native.HKL_NEXT));
        }

        static void SendVk(ushort vk, bool down)
        {
            Native.INPUT i = new Native.INPUT();
            i.type = Native.INPUT_KEYBOARD;
            i.u.ki.wVk = vk;
            i.u.ki.dwFlags = down ? 0 : Native.KEYEVENTF_KEYUP;
            i.u.ki.dwExtraInfo = Native.MARK;
            Send(i);
        }

        // Text typed as it is, whatever this PC's layout (KEYEVENTF_UNICODE): a letter of another alphabet
        // from the other computer's layout (shared/keylayout.js) or the phone Remote's keyboard.
        public static void Type(string text)
        {
            if (string.IsNullOrEmpty(text)) return;
            if (text.Length > 64) text = text.Substring(0, 64);
            foreach (char ch in text)
                foreach (bool down in new[] { true, false })
                {
                    Native.INPUT i = new Native.INPUT();
                    i.type = Native.INPUT_KEYBOARD;
                    i.u.ki.wScan = ch;
                    i.u.ki.dwFlags = Native.KEYEVENTF_UNICODE | (down ? 0 : Native.KEYEVENTF_KEYUP);
                    i.u.ki.dwExtraInfo = Native.MARK;
                    Send(i);
                }
        }

        // Esc down+up (cancels a local drag-and-drop loop).
        public static void Escape()
        {
            SendScan(0x01, true);
            SendScan(0x01, false);
        }

        public void ReleaseAll()
        {
            CursorShow.Reset(); // the drive ended: the next one checks the pointer again
            foreach (int s in new List<int>(heldScans)) SendScan(s, false);
            heldScans.Clear();
            tapDown.Clear();
            modsOnly = swallowSpace = false;
            if (captionHeld) { captionHeld = false; heldButtons.Remove(0); } // never pressed here: nothing to release
            foreach (int b in new List<int>(heldButtons)) Button(b, false);
            heldButtons.Clear();
            wheelRem = hwheelRem = 0;
        }

        // A k.* event from the owner.
        public void Apply(Dictionary<string, object> ev)
        {
            if (Blocked) return;
            switch (Json.Str(ev, "t", ""))
            {
                case "k.mm": Move(Json.Num(ev, "dx", 0), Json.Num(ev, "dy", 0)); break;
                case "k.md": Button((int)Json.Num(ev, "b", -1), true); break;
                case "k.mu": Button((int)Json.Num(ev, "b", -1), false); break;
                case "k.wh": Wheel(Json.Num(ev, "dx", 0), Json.Num(ev, "dy", 0), Json.Str(ev, "mode", "line") == "pixel"); break;
                case "k.kd": Key(Json.Str(ev, "code", null), true); break;
                case "k.ku": Key(Json.Str(ev, "code", null), false); break;
            }
        }
    }
}