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.

39.8 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 win_app/capture_win.py hooks and raw-mouse edge push.
// Low-level hooks (capture + hotkey), Raw Input (edge push at home, local return-edge motion),
// dead-man timer and the safety rules. Hook callbacks only decide and enqueue.
// The parts inside #if !MULTI are the one side of the one-to-one app; macshare-winhelper-multi.exe
// (built with MULTI, docs/multi-device.md) has CaptureMulti.cs in their place.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MacShare
{
    partial class Capture
    {
        // config (kvmConfig)
#if !MULTI
        public string Side;          // crossing side of this PC (null = unknown)
#endif
        public double ResistancePx = 120;
        // kvmConfig hotkey: one key, or the left and right one ("both")
        public HashSet<uint> HotkeyVks = new HashSet<uint> { 0xA5 }; // Right Alt
        public bool DriveOther;      // edge detection on
        public bool EdgeKeyboard = true; // an edge crossing also captures the keyboard
        public bool DragFiles = true; // file drags at the edge go to the Mac (drag.policy + the Files switches)
        public List<string> DragSides; // …through these sides only (kvmConfig dragSides; null: every watched side)
        public int DeadmanMs = 1500, DoubleTapMs = 400;
        public bool Gestures = true; // Touchpad gestures go over as k.ge (Touchpad.cs)
        Touchpad pad;
        readonly HashSet<uint> padCtrl = new HashSet<uint>(); // Ctrl that Windows made from a pinch, swallowed

        // capture state
        bool capturing, capMouse, capKeys;
        Point saved, parked;
        // When the pointer was parked (Begin). A capture begun outside the mouse hook (a file drag
        // crossing, DropEdge.cs) can still get moves measured from where the pointer was: half a
        // screen at once, which put the drag past the middle of the other screen. Dropped.
        DateTime parkedAt;
        const int StaleMs = 200, StalePx = 150;
        uint mouseCaptureStoppedAt;
        volatile bool mouseArrivalGuard;
        Point arrivedAt; // where Stop put the pointer (the guard's reference)
        public bool HoldReturn; // DropEdge.cs is catching a file drag on the way back: it goes home with it
        readonly HashSet<uint> heldVks = new HashSet<uint>(), swallowVks = new HashSet<uint>();
        readonly Dictionary<uint, uint> swallowSeen = new Dictionary<uint, uint>(); // swallowVks: when each was last seen (#248)
        readonly HashSet<int> heldButtons = new HashSet<int>(), swallowButtons = new HashSet<int>();
        DateTime lastCmd = DateTime.UtcNow;
        // Driven (armReturn on): the first input from this PC's own mouse or touchpad takes the PC back
        // (`local`): main sends the input home, so the driver gets its own pointer again where it left
        // and the two pointers stay apart. A move counts once it went LocalPx (not a resting palm), and
        // nothing counts in the first LocalGraceMs after the watch began.
        bool localWatch;
        DateTime localSince, localAt;
        double localAcc;
        const double LocalPx = 6;
        const int LocalGraceMs = 300;
        // kvmConfig takeBack (off with Sync touchpads): our own input never takes the PC back, the return
        // watch stays on and either mouse crosses.
        bool takeBack = true;
        public bool TakeBack
        {
            get { return takeBack; }
            set { takeBack = value; if (!value) localWatch = false; }
        }

        // edge push (home) and return edge (driven)
#if !MULTI
        double push; DateTime lastPush, pushSince;
        bool retArmed; string retSide; double retResistance, retPush; DateTime retLast, retSince;
#endif
        // No new crossing within CooldownMs of the last one, either way (kvmConfig cooldownMs,
        // KVM_CROSS_COOLDOWN_MS). After arriving, the edge it came through only counts once the pointer
        // moved 8 px inward or GuardMs passed, so the end of a flick doesn't bounce straight back.
        public int CooldownMs = 250;
        // A push crosses once it went the resistance outward and lasted DwellMs (kvmConfig dwellMs,
        // KVM_EDGE_DWELL_MS; none with no resistance): the end of a quick flick that reaches the edge
        // is over by then, a push meant to cross goes on.
        public int DwellMs = 150;
        bool Dwelt(double resistance, DateTime since, DateTime now) { return resistance <= 0 || (now - since).TotalMilliseconds >= DwellMs; }
        // Where along the side the other computer's monitors touch ours (shared/kvm-geom.js zones, 0–1
        // of the bounding box, as Offset): the edge and the way back only cross inside them. null: anywhere.
        public List<double[]> EdgeZones, ReturnZones;

        // kvmConfig / armReturn `zones`: "0.1-0.5,0.7-1" (a little wider, for rounding), "none" (nothing
        // crosses), anything else null (the whole side). An entry may name its side, "top:0.56-0.94" (the
        // Multi-device monitor map, #225): it counts only there. Each zone: { from, to, side } with side
        // the index in ZoneSides, -1 for every side.
        static readonly string[] ZoneSides = { "left", "right", "top", "bottom" };
        public static List<double[]> ParseZones(string text)
        {
            if (text == null) return null;
            List<double[]> list = new List<double[]>();
            if (text == "none") return list;
            foreach (string entry in text.Split(','))
            {
                string part = entry;
                int side = -1;
                int colon = part.IndexOf(':');
                if (colon >= 0)
                {
                    side = Array.IndexOf(ZoneSides, part.Substring(0, colon));
                    if (side < 0) continue;
                    part = part.Substring(colon + 1);
                }
                string[] ab = part.Split('-');
                double a, b;
                if (ab.Length == 2 && double.TryParse(ab[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out a)
                    && double.TryParse(ab[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out b) && a <= b)
                    list.Add(new double[] { a - 0.002, b + 0.002, side });
            }
            return list.Count > 0 ? list : null;
        }

        static bool InZone(List<double[]> zones, int x, int y, string side)
        {
            if (zones == null) return true;
            double o = Screens.Offset(x, y, side);
            int s = Array.IndexOf(ZoneSides, side);
            foreach (double[] z in zones)
            {
                if (z.Length > 2 && z[2] >= 0 && (int)z[2] != s) continue;
                if (o >= z[0] && o <= z[1]) return true;
            }
            return false;
        }
        const int GuardMs = 500;
        DateTime lastCross = DateTime.MinValue, arrivalAt;
        string arrivalSide; double arrivalInward;

        // hotkey double-tap
        bool hkDown; DateTime lastTapUp = DateTime.MinValue;
        // Held back while capturing: a hotkey press is sent only when another
        // key or a click follows (a shortcut); a plain tap never reaches the other computer.
        uint hkPending; string hkPendingCode;
        readonly HashSet<uint> hkLocal = new HashSet<uint>(), hkRemote = new HashSet<uint>(); // pressed at home / sent over

        readonly Action<Dictionary<string, object>> emit;
        Native.HookProc mouseProc, keyProc; // kept in fields so the GC never collects them
        IntPtr mouseHook, keyHook;
        RawWindow raw;
        readonly Timer timer = new Timer();
        public Flash Flash; // crossing animation (set by Program)
        ParkPad parkPad; // our own window under the parked pointer, for the wheel (ParkPad.cs)
        DateTime rawSinceHook = DateTime.MinValue, lastReinstall = DateTime.MinValue; // first raw motion no hook call followed
        bool secure; // a UAC prompt or the lock screen is the input desktop (Native.SecureDesktop)

        public Capture(Action<Dictionary<string, object>> emit)
        {
            this.emit = emit;
        }

        public void Start()
        {
            mouseProc = MouseHook;
            keyProc = KeyHook;
            Hook();
            parkPad = new ParkPad();
            pad = new Touchpad(OnGesture);
            raw = new RawWindow(OnRawMove, (buf, header) =>
            {
                pad.Active = capturing && capMouse && Gestures;
                pad.OnRaw(buf, header);
            });
            timer.Interval = 100;
            timer.Tick += delegate { Tick(); };
            timer.Start();
        }

        // File Shelf (shared/file-shelf.js): with the left button held here, a shake emits shelfShake {x, y}
        // (screen pixels); the shelf opens under the pointer and the drag's drop lands in it.
        public volatile bool ShelfWatch;
        bool shelfDown;
        int shelfX, shelfY;
        void ShelfStep(int msg, Native.MSLLHOOKSTRUCT m)
        {
            if ((m.flags & Native.LLMHF_INJECTED) != 0) return;
            if (msg == Native.WM_LBUTTONDOWN) { shelfDown = true; shelfX = m.pt.x; shelfY = m.pt.y; Shake.Shelf.Reset(); return; }
            if (msg == Native.WM_LBUTTONUP) { shelfDown = false; return; }
            if (msg != Native.WM_MOUSEMOVE || !shelfDown) return;
            int dx = m.pt.x - shelfX, dy = m.pt.y - shelfY;
            shelfX = m.pt.x; shelfY = m.pt.y;
            if (!Shake.Shelf.Step(dx, dy)) return;
            Dictionary<string, object> e = new Dictionary<string, object>();
            e["event"] = "shelfShake"; e["x"] = m.pt.x; e["y"] = m.pt.y;
            emit(e);
        }

        void Hook()
        {
            IntPtr mod = Native.GetModuleHandle(null);
            if (mouseHook != IntPtr.Zero) Native.UnhookWindowsHookEx(mouseHook);
            if (keyHook != IntPtr.Zero) Native.UnhookWindowsHookEx(keyHook);
            mouseHook = Native.SetWindowsHookEx(Native.WH_MOUSE_LL, mouseProc, mod, 0);
            keyHook = Native.SetWindowsHookEx(Native.WH_KEYBOARD_LL, keyProc, mod, 0);
            rawSinceHook = DateTime.MinValue;
        }

        // Windows silently removes a low-level hook whose callback once took longer than
        // LowLevelHooksTimeout. Raw input keeps coming then, but the hook isn't called: put it back,
        // once the mouse has moved for half a second with no hook call (not merely after a pause).
        void Watchdog()
        {
            DateTime now = DateTime.UtcNow;
            if (rawSinceHook == DateTime.MinValue) { rawSinceHook = now; return; }
            if ((now - rawSinceHook).TotalMilliseconds < 500 || (now - lastReinstall).TotalMilliseconds < 1000) return;
            lastReinstall = now;
            Hook();
            emit(Ev("hooksReinstalled"));
        }

        public void Shutdown()
        {
            if (capturing) Stop(null, 0);
            HideCursor.Show();
            timer.Stop();
            if (mouseHook != IntPtr.Zero) Native.UnhookWindowsHookEx(mouseHook);
            if (keyHook != IntPtr.Zero) Native.UnhookWindowsHookEx(keyHook);
            mouseHook = keyHook = IntPtr.Zero;
        }

        public void Touch() { lastCmd = DateTime.UtcNow; }

        static Dictionary<string, object> Ev(string name)
        {
            Dictionary<string, object> d = new Dictionary<string, object>();
            d["event"] = name;
            return d;
        }

        void Forward(Dictionary<string, object> k)
        {
            Lane.Fence(k); // a click, key, wheel or gesture: its event number and fence (Lane.cs)
            Dictionary<string, object> d = Ev("ev");
            d["ev"] = k;
            emit(d);
        }

        static Dictionary<string, object> K(string t)
        {
            Dictionary<string, object> d = new Dictionary<string, object>();
            d["t"] = t;
            return d;
        }

        // A touchpad gesture recognised while capturing: over it goes, by meaning.
        void OnGesture(string g, string phase, double v)
        {
            if (!capturing || !capMouse || !Gestures) return;
            Dictionary<string, object> k = K("k.ge");
            k["g"] = g;
            if (phase != null) k["phase"] = phase;
            if (g == "zoom") k["v"] = v;
            Forward(k);
        }

        // ---- capture on/off ----

#if !MULTI
        public void Begin(bool mouse, bool keys)
        {
            if (capturing) { capMouse = mouse; capKeys = keys; return; }
            mouseArrivalGuard = false;
            capturing = true; capMouse = mouse; capKeys = keys;
            CrossingReset();
            heldVks.Clear(); heldButtons.Clear();
            hkPending = 0; hkRemote.Clear();
            Touch();
            if (mouse)
            {
                Native.POINT p;
                Native.GetCursorPos(out p);
                saved = new Point(p.x, p.y);
                // Leaving: the animation where it goes, then the pointer hides and stays put for
                // the eye (it is parked in the middle only to measure motion).
                if (Flash != null) Flash.Play(saved, Side != null && Screens.OnOuterEdge(p.x, p.y, Side) ? Side : null, true);
                HideCursor.Hide();
                // Park in the middle so outward motion isn't clamped by the screen edge.
                parked = Screens.Center();
                parkedAt = DateTime.UtcNow;
                parkPad.Cover(parked);
                Native.SetCursorPos(parked.X, parked.Y);
            }
            push = 0;
            lastCross = DateTime.UtcNow; arrivalSide = null;
        }

        // side == null: put the pointer back where capture began.
        public void Stop(string side, double offset)
        {
            if (!capturing) return;
            // The guard first: a move the hook sees once capturing is off must already meet it.
            Point p = side != null ? Screens.EdgePoint(side, offset) : saved;
            if (capMouse)
            {
                arrivedAt = p;
                mouseCaptureStoppedAt = unchecked((uint)Environment.TickCount);
                mouseArrivalGuard = true;
            }
            capturing = false;
            CrossingReset();
            // Rule 5: whatever is still held was pressed remotely; its release stays swallowed here.
            uint stopAt = unchecked((uint)Environment.TickCount);
            foreach (uint vk in heldVks) { swallowVks.Add(vk); swallowSeen[vk] = stopAt; }
            foreach (int b in heldButtons) swallowButtons.Add(b);
            heldVks.Clear(); heldButtons.Clear();
            hkPending = 0; hkRemote.Clear(); // a sent hotkey's release is in swallowVks (heldVks) now
            if (capMouse)
            {
                parkPad.Uncover();
                Native.SetCursorPos(p.X, p.Y);
                HideCursor.Show();
                if (Flash != null) Flash.Play(p, side ?? (Side != null && Screens.OnOuterEdge(p.X, p.Y, Side) ? Side : null), false); // arriving
            }
            Arrived(side);
        }
#endif

#if !MULTI
        void DisarmForEmergency() { retArmed = false; localWatch = false; push = 0; }
#endif

        public bool Capturing { get { return capturing; } }
        public DateTime LastCross { get { return lastCross; } } // the last crossing, either way

        // A button pressed while capturing has its release swallowed at home (Stop). A drag that came
        // home with it (dragStart home, dragLocal) is dropped by that release: let it through.
        // True when it was still held (its release now goes through); false: already let go (and swallowed).
        public bool Unswallow(int button) { return swallowButtons.Remove(button); }

        // A file drag caught on the way back (DropEdge.cs, while driven): the input goes home with its
        // files, `return {offset, drag:{paths}}`.
        public void ReturnWithDrag(Point p, string side, string[] paths)
        {
            HoldReturn = false;
            retArmed = false;
#if MULTI
            retPushes.Clear();
#endif
            lastCross = DateTime.UtcNow;
            if (Flash != null) Flash.Play(p, side, true);
            Dictionary<string, object> d = Ev("return");
            AppWindows.AddMoving(d, false); // a window grabbed with the move key goes over with the pointer (pcapps.js)
            d["offset"] = Math.Round(Screens.Offset(p.X, p.Y, side), 4);
#if MULTI
            d["side"] = side;
#endif
            Dictionary<string, object> drag = new Dictionary<string, object>();
            drag["paths"] = paths;
            d["drag"] = drag;
            emit(d);
        }

        // The pointer came to this PC (back home, or placed by the driver) through `side`, or by the
        // hotkey (null): starts the cooldown and the arrival guard, and clears every push.
        public void Arrived(string side)
        {
            lastCross = DateTime.UtcNow;
            arrivalSide = side; arrivalAt = lastCross; arrivalInward = 0;
#if MULTI
            pushes.Clear(); retPushes.Clear();
#else
            push = 0; retPush = 0;
#endif
        }

        // False while a crossing through `side` has to wait (cooldown, arrival guard). `outward`: this
        // move's outward part for that side (negative = inward).
        bool MayCross(string side, double outward)
        {
            DateTime now = DateTime.UtcNow;
            if ((now - lastCross).TotalMilliseconds < CooldownMs) return false;
            if (arrivalSide != null && arrivalSide == side)
            {
                if (outward < 0) arrivalInward -= outward;
                if ((now - arrivalAt).TotalMilliseconds < GuardMs && arrivalInward < 8) return false;
                arrivalSide = null;
            }
            return true;
        }

        // The sides where an injected move stops at the edge rather than jump onto a monitor past it.
        // Called for every injected move (Injector.Stops): the same lists, never a new one.
        static readonly List<string> noStops = new List<string>();
#if !MULTI
        readonly List<string> oneStop = new List<string>(1);
#endif
        public List<string> ReturnStops()
        {
            if (portalReturn != null) return noStops; // the portal's own stop (PortalStop)
#if MULTI
            return retArmed ? retSides : noStops;
#else
            if (!retArmed) return noStops;
            if (oneStop.Count != 1 || oneStop[0] != retSide) { oneStop.Clear(); oneStop.Add(retSide); }
            return oneStop;
#endif
        }

        void WatchLocal(bool on)
        {
            localWatch = on && takeBack;
            localSince = DateTime.UtcNow;
            localAcc = 0;
        }

        // This PC's own mouse or touchpad while driven (our injected input never gets here): true once
        // it takes the PC back. The return watch stops with it, so this same motion can't send a `return`.
        bool NoteLocal(int dx, int dy, bool click)
        {
            if (!localWatch || capturing) return false;
            DateTime now = DateTime.UtcNow;
            if ((now - localSince).TotalMilliseconds < LocalGraceMs) return false;
            if (!click)
            {
                if ((now - localAt).TotalMilliseconds > 300) localAcc = 0;
                localAt = now;
                localAcc += Math.Abs(dx) + Math.Abs(dy);
                if (localAcc < LocalPx) return false;
            }
            localWatch = false;
            retArmed = false;
            emit(Ev("local"));
            return true;
        }

#if !MULTI
        public void ArmReturn(bool on, string side, double resistance)
        {
            WatchLocal(on);
            retArmed = on && side != null;
            retSide = side;
            retResistance = resistance;
            retPush = 0;
        }
#endif

        void Tick()
        {
            HideCursor.Retry();
#if FULLKVM
            // The Full KVM agent (Agent.cs) reaches every desktop, one at a time: another input desktop
            // now, so the service starts the agent there. Out at once: this one's input lands nowhere.
            string want = Agent.MovedTo();
            if (want != null) Agent.Leave(want);
            if (Agent.On) { CheckDeadman(); return; }
#endif
            // A UAC prompt or the lock screen: nothing can be injected or captured there, so the
            // input goes home on both sides (main sends a driven PC's owner home).
            bool now = Native.SecureDesktop();
            if (now != secure)
            {
                secure = now;
                if (secure && capturing)
                {
                    Stop(null, 0);
                    Dictionary<string, object> c = Ev("captureEnded");
                    c["reason"] = "secureDesktop";
                    emit(c);
                }
                // Back from it: a button pressed here for the other computer (the click that opened
                // the prompt) had its release land on the secure desktop, where nothing gets in. Still
                // held, it kept the next crossing from working until this PC's own mouse moved (#210).
                if (!secure && ReleaseInjected != null) ReleaseInjected();
                Dictionary<string, object> e = Ev("secureDesktop");
                e["on"] = secure;
                emit(e);
            }
            CheckDeadman();
        }

        void CheckDeadman()
        {
            if (capturing && (DateTime.UtcNow - lastCmd).TotalMilliseconds > DeadmanMs)
            {
                Stop(null, 0); // Rule 1: a hung main or a dead link never keeps the user's input
                Dictionary<string, object> d = Ev("captureEnded");
                d["reason"] = "deadman";
                emit(d);
            }
        }

        // ---- hooks ----

        IntPtr MouseHook(int nCode, IntPtr wParam, IntPtr lParam)
        {
            rawSinceHook = DateTime.MinValue;
            if (nCode < 0) return Native.CallNextHookEx(mouseHook, nCode, wParam, lParam);
            Native.MSLLHOOKSTRUCT m = Native.ReadMouse(lParam); // no allocation per event
            // Moving a window (AppWindows.TryGrab): the move key and a click grab it, here or injected
            // from the other computer, never while this PC's input goes elsewhere.
            int gmsg = wParam.ToInt32();
            if (gmsg == Native.WM_LBUTTONUP && AppWindows.GrabUpPending) { AppWindows.GrabUp(); return (IntPtr)1; }
            if (!capturing)
            {
                if (gmsg == Native.WM_LBUTTONDOWN && AppWindows.TryGrab(m.pt.x, m.pt.y)) return (IntPtr)1;
                if (gmsg == Native.WM_MOUSEMOVE && AppWindows.Grabbing) AppWindows.GrabMove(m.pt.x, m.pt.y);
            }
            if ((m.flags & Native.LLMHF_INJECTED) != 0 && m.dwExtraInfo == Native.MARK)
            {
                // Our pointer put on a moved window while this PC drives the other one (winMove, the
                // window's copy there is used): this PC's mouse is measured from there on, not as a jump.
                if (capturing && capMouse && gmsg == Native.WM_MOUSEMOVE) parked = new Point(m.pt.x, m.pt.y);
                return Native.CallNextHookEx(mouseHook, nCode, wParam, lParam); // Rule 4: our own
            }
            int msg = wParam.ToInt32();
            if (!capturing && mouseArrivalGuard && msg == Native.WM_MOUSEMOVE && (m.flags & Native.LLMHF_INJECTED) == 0)
            {
                uint now = unchecked((uint)Environment.TickCount);
                if (MouseArrivalGuard.IsStale(m.time, mouseCaptureStoppedAt, now)) return (IntPtr)1;
                if (MouseArrivalGuard.FromPark(m.pt.x, m.pt.y, parked.X, parked.Y, arrivedAt.X, arrivedAt.Y, mouseCaptureStoppedAt, now)) return (IntPtr)1;
                if (unchecked(now - mouseCaptureStoppedAt) > MouseArrivalGuard.ParkMs) mouseArrivalGuard = false;
            }
            int button = ButtonOf(msg, m.mouseData);
            bool down = msg == Native.WM_LBUTTONDOWN || msg == Native.WM_RBUTTONDOWN || msg == Native.WM_MBUTTONDOWN || msg == Native.WM_XBUTTONDOWN;
            bool up = msg == Native.WM_LBUTTONUP || msg == Native.WM_RBUTTONUP || msg == Native.WM_MBUTTONUP || msg == Native.WM_XBUTTONUP;

            if (up && button >= 0 && swallowButtons.Remove(button)) return (IntPtr)1;
            if (down && !capturing && (m.flags & Native.LLMHF_INJECTED) == 0) NoteLocal(0, 0, true); // a click here while driven
            if (ShelfWatch && !capturing) ShelfStep(msg, m); // File Shelf on: a shaken drag here (off: this one check)
            if (!capturing || !capMouse) return Native.CallNextHookEx(mouseHook, nCode, wParam, lParam);

            if (msg == Native.WM_MOUSEMOVE)
            {
                int dx = m.pt.x - parked.X, dy = m.pt.y - parked.Y;
                if ((DateTime.UtcNow - parkedAt).TotalMilliseconds < StaleMs && (Math.Abs(dx) > StalePx || Math.Abs(dy) > StalePx))
                    return (IntPtr)1; // from before the park
                if (dx != 0 || dy != 0)
                {
                    double s = Screens.Scale(parked.X, parked.Y);
                    // The input lane first (Lane.cs): on it, nothing is built or written for this move.
                    uint lr, lmn;
                    double lcx, lcy;
                    int lane = Lane.Move(dx / s, dy / s, out lr, out lmn, out lcx, out lcy);
                    if (lane != 1)
                    {
                        Dictionary<string, object> k = K("k.mm");
                        k["dx"] = Math.Round(dx / s, 2);
                        k["dy"] = Math.Round(dy / s, 2);
                        if (lane == 0) Lane.Totals(k, lr, lmn, lcx, lcy); // the lane is down: its totals go with the move
                        Forward(k);
                    }
                    Shake.Feed(dx / s, dy / s, emit); // after it went: shaken, the pointer comes home (Shake.cs)
                }
            }
            else if (button >= 0 && (down || up))
            {
                if (down) FlushHotkey(); // Ctrl-click with the hotkey key
                if (down) heldButtons.Add(button); else heldButtons.Remove(button);
                Dictionary<string, object> k = K(down ? "k.md" : "k.mu");
                k["b"] = button;
                Forward(k);
            }
            else if ((msg == Native.WM_MOUSEWHEEL || msg == Native.WM_MOUSEHWHEEL) && pad != null && (pad.Pinching || pad.Fingers >= 3))
            {
                // Windows' own wheel from a pinch or a three/four-finger swipe: the gesture goes as k.ge.
            }
            else if (msg == Native.WM_MOUSEWHEEL || msg == Native.WM_MOUSEHWHEEL)
            {
                double notches = (short)((m.mouseData >> 16) & 0xFFFF) / 120.0;
                Dictionary<string, object> k = K("k.wh");
                k["dx"] = msg == Native.WM_MOUSEHWHEEL ? notches : 0.0;
                k["dy"] = msg == Native.WM_MOUSEWHEEL ? -notches : 0.0;
                k["mode"] = "line";
                Forward(k);
            }
            return (IntPtr)1; // swallow: the pointer stays parked
        }

        static int ButtonOf(int msg, uint mouseData)
        {
            switch (msg)
            {
                case Native.WM_LBUTTONDOWN: case Native.WM_LBUTTONUP: return 0;
                case Native.WM_RBUTTONDOWN: case Native.WM_RBUTTONUP: return 1;
                case Native.WM_MBUTTONDOWN: case Native.WM_MBUTTONUP: return 2;
                case Native.WM_XBUTTONDOWN: case Native.WM_XBUTTONUP:
                    return ((mouseData >> 16) & 0xFFFF) == Native.XBUTTON1 ? 3 : 4;
            }
            return -1;
        }

        IntPtr KeyHook(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode < 0) return Native.CallNextHookEx(keyHook, nCode, wParam, lParam);
            Native.KBDLLHOOKSTRUCT k = Native.ReadKey(lParam);
            if ((k.flags & Native.LLKHF_INJECTED) != 0 && k.dwExtraInfo == Native.MARK)
                return Native.CallNextHookEx(keyHook, nCode, wParam, lParam); // Rule 4: our own
            int msg = wParam.ToInt32();
            bool down = msg == Native.WM_KEYDOWN || msg == Native.WM_SYSKEYDOWN;
            string code = Keys.Code(k.vkCode, k.scanCode, (k.flags & Native.LLKHF_EXTENDED) != 0);
            // AltGr (Right Alt on many layouts) sends a fake Left Ctrl first, scan 0x21D. It never goes
            // over: Right Alt does, and the other side's layout makes that AltGr (Option on a Mac); sent,
            // it was a Ctrl there too (Cmd on a Mac: AltGr+E was Cmd+Option+E, not €). With Right Alt as
            // the hotkey it doesn't break the double-tap, and it never counts for a Ctrl hotkey.
            bool fakeCtrl = k.vkCode == 0xA2 && k.scanCode == 0x21D;
            if (!fakeCtrl) NoteModifier(k.vkCode, down); // hold-to-cross and the emergency shortcut (Crossing.cs)
            if (!fakeCtrl) NotePortalKey(code, down); // a portal's key held (Portals.cs)
            if (CheckEmergency(k.vkCode, code, down)) return (IntPtr)1;
            if (emergencyVks.Contains(k.vkCode)) { if (!down) emergencyVks.Remove(k.vkCode); return (IntPtr)1; } // the emergency key's repeats and release
            bool hotkey = !fakeCtrl && DetectHotkey(k.vkCode, down);

            // Still held from over there (#248): its auto-repeat presses stay here too, or Windows would
            // have the key down and never see it come up (its release is swallowed). A press after 1.5 s
            // with nothing in between is a new one (the release got lost): that one goes through.
            if (down && swallowVks.Contains(k.vkCode))
            {
                uint now = unchecked((uint)Environment.TickCount), last;
                if (!swallowSeen.TryGetValue(k.vkCode, out last) || unchecked(now - last) < 1500) { swallowSeen[k.vkCode] = now; return (IntPtr)1; }
                swallowVks.Remove(k.vkCode); swallowSeen.Remove(k.vkCode);
            }
            if (!down && swallowVks.Remove(k.vkCode)) { swallowSeen.Remove(k.vkCode); return (IntPtr)1; }
            // The Ctrl Windows injects for a touchpad pinch (Ctrl+wheel) stays here.
            bool ctrl = k.vkCode == 0xA2 || k.vkCode == 0xA3 || k.vkCode == 0x11;
            if (ctrl && !down && padCtrl.Remove(k.vkCode)) return (IntPtr)1;
            if (ctrl && down && capturing && (k.flags & Native.LLKHF_INJECTED) != 0 && pad != null && pad.Pinching) { padCtrl.Add(k.vkCode); return (IntPtr)1; }

            bool isHk = HotkeyVks.Contains(k.vkCode);
            if (capturing && capKeys)
            {
                if (fakeCtrl) return (IntPtr)1;
                if (isHk)
                {
                    IntPtr r = (IntPtr)1;
                    if (hkLocal.Contains(k.vkCode)) // pressed at home: it is released at home
                    {
                        if (!down) hkLocal.Remove(k.vkCode);
                        r = IntPtr.Zero;
                    }
                    else if (down)
                    {
                        if (!hkRemote.Contains(k.vkCode)) { hkPending = k.vkCode; hkPendingCode = code; } // wait: a shortcut sends it
                    }
                    else if (hkRemote.Remove(k.vkCode))
                    {
                        heldVks.Remove(k.vkCode);
                        if (code != null) { Dictionary<string, object> e = K("k.ku"); e["code"] = code; Forward(e); }
                    }
                    else if (hkPending == k.vkCode) hkPending = 0; // a plain tap: never sent
                    if (hotkey) FireHotkey();
                    return r == IntPtr.Zero ? Native.CallNextHookEx(keyHook, nCode, wParam, lParam) : r;
                }
                if (down) FlushHotkey();
                if (down) heldVks.Add(k.vkCode); else heldVks.Remove(k.vkCode);
                if (code != null) { Dictionary<string, object> e = K(down ? "k.kd" : "k.ku"); e["code"] = code; Forward(e); }
                if (hotkey) FireHotkey();
                return (IntPtr)1;
            }
            if (isHk) { if (down) hkLocal.Add(k.vkCode); else hkLocal.Remove(k.vkCode); }
            if (hotkey) FireHotkey();
            return Native.CallNextHookEx(keyHook, nCode, wParam, lParam);
        }

        // The held hotkey turned out to be part of a shortcut: send its press now, before the key.
        void FlushHotkey()
        {
            uint vk = hkPending;
            hkPending = 0;
            if (vk == 0 || !capturing || !capKeys || hkPendingCode == null) return;
            hkRemote.Add(vk);
            heldVks.Add(vk);
            Dictionary<string, object> e = K("k.kd");
            e["code"] = hkPendingCode;
            Forward(e);
        }

        // Two clean taps (down+up, no other key between) within DoubleTapMs, in every mode.
        bool DetectHotkey(uint vk, bool down)
        {
            DateTime now = DateTime.UtcNow;
            if (!HotkeyVks.Contains(vk))
            {
                if (down) lastTapUp = DateTime.MinValue;
                return false;
            }
            if (down) { hkDown = true; return false; }
            if (!hkDown) return false;
            hkDown = false;
            if (lastTapUp != DateTime.MinValue && (now - lastTapUp).TotalMilliseconds <= DoubleTapMs)
            {
                lastTapUp = DateTime.MinValue;
                return true;
            }
            lastTapUp = now;
            return false;
        }

        // Rule 2: stop capturing in the helper first, then tell main.
        void FireHotkey()
        {
            bool was = capturing;
            if (capturing) Stop(null, 0);
            Dictionary<string, object> d = Ev("hotkey");
            d["wasCapturing"] = was;
            emit(d);
        }

        // ---- raw input: edge push at home, local motion for the return edge ----

        static bool AnyButtonDown()
        {
            return (Native.GetAsyncKeyState(0x01) & 0x8000) != 0 || (Native.GetAsyncKeyState(0x02) & 0x8000) != 0 || (Native.GetAsyncKeyState(0x04) & 0x8000) != 0;
        }

#if !MULTI
        void OnRawMove(int dx, int dy)
        {
            Watchdog();
            if (capturing) return;
            if (NoteLocal(dx, dy, false)) return;
            Native.POINT p;
            Native.GetCursorPos(out p);
            if (retArmed) { FeedReturn(p.x, p.y, dx, dy); return; }
            if (!DriveOther || (AnyButtonDown() && !AppWindows.Grabbing)) { push = 0; return; } // Rule 6: no crossing mid-drag
            if (!EdgeAllowed()) { push = 0; return; } // hold-to-cross: not without the key (Crossing.cs)
            if (PortalStep(new Point(p.x, p.y), dx, dy)) return; // through a cursor portal (Portals.cs)
            if (Side == null || PortalCovers(p.x, p.y, Side)) { push = 0; return; } // a portal owns its stretch
            double outward = Screens.Outward(Side, dx, dy);
            if (!MayCross(Side, outward)) { push = 0; return; }
            if (outward <= 0 || !Screens.OnOuterEdge(p.x, p.y, Side) || !InZone(EdgeZones, p.x, p.y, Side)) { push = 0; return; }
            DateTime now = DateTime.UtcNow;
            if ((now - lastPush).TotalMilliseconds > 300) push = 0;
            lastPush = now;
            if (push == 0) pushSince = now;
            push += outward;
            if (push < ResistancePx || !Dwelt(ResistancePx, pushSince, now)) return;
            double offset = Screens.Offset(p.x, p.y, Side);
            Begin(true, EdgeKeyboard); // start capturing at once so no motion leaks, then tell main
            saved = new Point(p.x, p.y);
            Dictionary<string, object> d = Ev("edge");
            AppWindows.AddMoving(d, true); // a window grabbed with the move key goes over with the pointer (pcapps.js)
            d["offset"] = Math.Round(offset, 4);
            d["crossingFlags"] = LocalCrossingBits();
            emit(d);
        }

        // Injected moves report here too (Injector.Moved): the owner's hand reaches the edge.
        public void FeedReturn(int x, int y, double dx, double dy)
        {
            if (!retArmed || HoldReturn) return;
            if (!ReturnAllowed()) { retPush = 0; return; } // hold-to-cross on the way back (Crossing.cs)
            if (PortalReturnStep(x, y, dx, dy)) return; // came in through a portal: its stretch only (Portals.cs)
            double outward = Screens.Outward(retSide, dx, dy);
            if (!MayCross(retSide, outward)) { retPush = 0; return; }
            if (outward <= 0 || !Screens.OnOuterEdge(x, y, retSide) || !InZone(ReturnZones, x, y, retSide)) { retPush = 0; return; }
            DateTime now = DateTime.UtcNow;
            if ((now - retLast).TotalMilliseconds > 300) retPush = 0;
            retLast = now;
            if (retPush == 0) retSince = now;
            retPush += outward;
            if (retPush < retResistance || !Dwelt(retResistance, retSince, now)) return;
            retArmed = false;
            lastCross = now;
            if (Flash != null) Flash.Play(new Point(x, y), retSide, true); // leaving this PC for the Mac
            Dictionary<string, object> d = Ev("return");
            AppWindows.AddMoving(d, false); // a window grabbed with the move key goes over with the pointer (pcapps.js)
            d["offset"] = Math.Round(Screens.Offset(x, y, retSide), 4);
            emit(d);
        }
#endif

        // Message-only window that receives WM_INPUT for the mouse (usage page 1, usage 2) and, since
        // The precision touchpad (digitizer page 0x0D, usage 5) for Touchpad.cs.
        class RawWindow : NativeWindow
        {
            readonly Action<int, int> onMove;
            readonly Action<IntPtr, int> onTouchpad;

            public RawWindow(Action<int, int> onMove, Action<IntPtr, int> onTouchpad)
            {
                this.onMove = onMove;
                this.onTouchpad = onTouchpad;
                CreateParams cp = new CreateParams();
                cp.Parent = new IntPtr(-3); // HWND_MESSAGE
                CreateHandle(cp);
                Native.RAWINPUTDEVICE[] d = new Native.RAWINPUTDEVICE[2];
                d[0].usUsagePage = 1;
                d[0].usUsage = 2;
                d[0].dwFlags = Native.RIDEV_INPUTSINK;
                d[0].hwndTarget = Handle;
                d[1].usUsagePage = 0x0D;
                d[1].usUsage = 0x05;
                d[1].dwFlags = Native.RIDEV_INPUTSINK;
                d[1].hwndTarget = Handle;
                if (!Native.RegisterRawInputDevices(d, 2, (uint)Marshal.SizeOf(typeof(Native.RAWINPUTDEVICE))))
                    Native.RegisterRawInputDevices(d, 1, (uint)Marshal.SizeOf(typeof(Native.RAWINPUTDEVICE))); // the mouse at least
            }

            protected override void WndProc(ref Message m)
            {
                if (m.Msg == Native.WM_INPUT) Read(m.LParam);
                base.WndProc(ref m);
            }

            void Read(IntPtr hRaw)
            {
                const uint header = 24; // RAWINPUTHEADER on x64
                uint size = 0;
                Native.GetRawInputData(hRaw, Native.RID_INPUT, IntPtr.Zero, ref size, header);
                if (size < header + 8) return; // the smallest HID packet; a mouse one is checked below
                IntPtr buf = Marshal.AllocHGlobal((int)size);
                try
                {
                    if (Native.GetRawInputData(hRaw, Native.RID_INPUT, buf, ref size, header) == uint.MaxValue) return;
                    int type = Marshal.ReadInt32(buf, 0);
                    if (type == 2) { onTouchpad(buf, (int)header); return; } // RIM_TYPEHID: the touchpad
                    if (type != 0 || size < header + 24) return; // RIM_TYPEMOUSE, a whole RAWMOUSE
                    int rm = (int)header;
                    ushort flags = (ushort)Marshal.ReadInt16(buf, rm);
                    int lx = Marshal.ReadInt32(buf, rm + 12), ly = Marshal.ReadInt32(buf, rm + 16);
                    uint extra = (uint)Marshal.ReadInt32(buf, rm + 20);
                    if ((flags & 1) != 0 || extra == 0x4D530000) return; // absolute devices / our own
                    if (lx != 0 || ly != 0) onMove(lx, ly);
                }
                finally { Marshal.FreeHGlobal(buf); }
            }
        }
    }
}