From 0db7821ff2e794c59d3a4ccf9728b58bb1ca3af3 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 20 Nov 2026 19:03:59 +0100 Subject: [PATCH] feat(panel): welcome screen, better tray placement and installer prompts Welcome - The first start opens a Welcome screen with three steps that check themselves off as they happen: open OpenMouse, a page connects, a mouse is present. - If no page connects within 20 seconds the connection step turns red with the steps to allow it and the button becomes Try again. With all steps checked it goes to Home after 2.5 seconds. - Open OpenMouse opens the site with ?from=bridge. A short notice tells the user to choose Forever when the browser asks, and another says when no page connected. Panel - Each view fits the panel height to its content (see Window below). - On Windows the panel keeps its bottom edge when its height changes, allows for the window frame, stays on screen on every redraw, and sits 24 pixels from the edge of the work area. - It anchors to the corner on the side of the tray instead of to the icon, and an icon in the hidden-icons flyout opens it in the corner and takes focus so the flyout closes. Installer (Windows) - When Bridge is already installed the setup opens on a page offering repair or update, or uninstall. A silent install, which the updater runs, shows no pages. - The uninstaller asks whether to delete the settings, profiles and logs; no is the default and the answer in a silent uninstall. - It checks for a Bridge running from the install folder and asks to close it (a silent uninstall closes it), because a running executable could not be deleted and was left behind with the folder. - It removes the install folder once it is empty. Tray - The battery tooltip separates the device and the level with a hyphen instead of an em dash. Home - A connected mouse shows its polling rate next to the battery and DPI. Chore - Every em dash outside vendored code is now a hyphen. Window - The panel fits its height to its content, so there are no fixed heights per view (never under 200 or over 900). - On Windows it can be dragged by its title and opens where it was last left (saved when it hides, and kept inside the screen). - Settings has an Always on top switch on Windows, macOS (floating window level) and X11 (the window manager's above state). A Wayland layer-shell panel is already on the top layer; a plain Wayland window cannot, so it gets no switch. - On Windows 11 the tray icon is moved out of the hidden-icons flyout onto the taskbar once per executable, so a later choice in Windows settings sticks. - Placing the panel is done outside a GPUI update, because moving it onto a screen with another scale sends messages that re-enter GPUI. - It hides when a click elsewhere takes its focus, except on the Welcome screen or while Always on top is on (from #113). Home - A connected mouse shows its polling rate next to the battery and DPI. Chore - Every em dash outside vendored code is now a hyphen, including the battery tooltip. Co-authored-by: lmaoskript --- .github/workflows/release.yml | 2 +- README.md | 16 +- native-hid/README.md | 26 +- native-hid/bridge-server.mjs | 4 +- native-hid/src/apply.mjs | 20 +- native-hid/src/brands.mjs | 8 +- native-hid/src/button-listener.mjs | 2 +- native-hid/src/hid-device-adapter.mjs | 28 +- native-hid/src/registry.mjs | 4 +- packaging/windows/bridge.iss | 119 +++++ src/config.rs | 4 +- src/drivers/mod.rs | 24 +- src/drivers/native_hid.rs | 14 +- src/drivers/pulsar.rs | 20 +- src/drivers/registry.rs | 8 +- src/gpui_shell/mod.rs | 52 +- src/gpui_shell/panel.rs | 651 ++++++++++++++++++++++---- src/gpui_shell/tray.rs | 505 ++++++++++++++++++-- src/gpui_shell/tray_linux.rs | 49 +- src/hid.rs | 4 +- src/platform/mod.rs | 2 +- src/platform/windows.rs | 112 ++++- src/service.rs | 36 +- src/tray_battery.rs | 14 +- 24 files changed, 1463 insertions(+), 261 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9a423a75..3f813ae8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -71,7 +71,7 @@ jobs: run: | $ErrorActionPreference = "Stop" npm ci --prefix native-hid --omit=dev - # Trim node-hid's other-platform prebuilt bindings — this archive + # Trim node-hid's other-platform prebuilt bindings - this archive # only ever runs on win32-x64. Get-ChildItem native-hid/node_modules/node-hid/prebuilds -Directory | Where-Object { $_.Name -ne "HID-win32-x64" } | diff --git a/README.md b/README.md index 024d0425..d09f028e 100644 --- a/README.md +++ b/README.md @@ -52,24 +52,24 @@ The initial service provides: - a live tray icon that shows the connected mouse's battery, drawn square at the taskbar's real pixel size with either the native Segoe Fluent Icons battery glyph (Segoe MDL2 Assets on Windows 10) or the percentage number in - bold text — a control-panel choice, since the Windows 11 taskbar only - renders square tray icons faithfully — tinted by charge state: green while + bold text - a control-panel choice, since the Windows 11 taskbar only + renders square tray icons faithfully - tinted by charge state: green while charging (the variant with the built-in bolt) or above half, amber through the mid band, alert red at or below the low-battery threshold, gray when - the reading is stale, and a level glyph for every 10% — with a tooltip that - spells everything out — `Device — 87% · Charging · full in 45 m` — + the reading is stale, and a level glyph for every 10% - with a tooltip that + spells everything out - `Device - 87% · Charging · full in 45 m` - including the estimated time remaining from the recent trend; - process-based detection for configured game executables; - startup discovery: Bridge scans the HID bus for mice whose brands it has - drivers for (the same vendor table the native-hid helper drives — Pulsar, + drivers for (the same vendor table the native-hid helper drives - Pulsar, Logitech, Razer, Delux, VGN, and more), so the tray shows the battery from - the first second — no web panel connection and no saved profile required; + the first second - no web panel connection and no saved profile required; - hybrid device mode (toggle in the panel): while the OpenMouse web app is - disconnected, Bridge drives the mouse itself in onboard memory mode — the + disconnected, Bridge drives the mouse itself in onboard memory mode - the active profile's stored DPI, polling rate, and switch mode are pushed natively (switch mode wherever a driver supports it, e.g. Logitech LightForce), and the battery is read directly (including a native Pulsar - battery reader) — and the moment the web app connects, it takes the mouse + battery reader) - and the moment the web app connects, it takes the mouse over live, with Bridge restoring the stored settings and reading the battery again on disconnect; without a saved profile Bridge leaves the mouse's own onboard memory untouched and just monitors it; diff --git a/native-hid/README.md b/native-hid/README.md index d4f1bc65..ea3d1d55 100644 --- a/native-hid/README.md +++ b/native-hid/README.md @@ -7,19 +7,19 @@ battery, without a browser tab open holding a WebHID connection. ## Why Node, in a Rust project Bridge has a dependency-free native Rust driver for the one protocol that's -been hardware-verified in this workspace (Pulsar — see `src/drivers/pulsar.rs` +been hardware-verified in this workspace (Pulsar - see `src/drivers/pulsar.rs` in the parent crate). Every other brand OpenMouse supports is implemented in `@openmouse/protocol` (the sibling `mouse-protocol` repo) as a WebHID driver class, hardware-tested there, not here. Reimplementing all of those in Rust would mean re-deriving and re-verifying ~15,000 lines of vendor-specific wire -protocol with no hardware in hand to test most of it against — real risk of +protocol with no hardware in hand to test most of it against - real risk of silently writing wrong values to someone's mouse. Instead, this package makes those exact same driver classes runnable outside a browser: `hid-device-adapter.mjs` wraps `node-hid` so it satisfies the `HIDDevice` interface the drivers are written against (see `mouse-protocol/src/drivers/webhid.ts`), and `apply.mjs` constructs the -already-verified class for a given brand directly — no protocol code is +already-verified class for a given brand directly - no protocol code is duplicated or reimplemented here. ## How dispatch works @@ -49,8 +49,8 @@ described devices with each request: collection whose descriptor declares it, padded to the declared size as Chrome does (Windows refuses a feature report of any other length), and reads feature reports at their declared size. `client.open()` then - `client.readStatus()` — a cheap, read-only call every `SupportedClient` - implements — probe it before anything is written. When a profile's brand + `client.readStatus()` - a cheap, read-only call every `SupportedClient` + implements - probe it before anything is written. When a profile's brand is not the one the registry files its mouse under (`"Attack Shark"` saved for hardware filed as `"Delux"`), Bridge sends `"matchStatusBrand": true` and every supported device, and the helper keeps the one whose status @@ -89,14 +89,14 @@ on an onboard one, turns the mouse's button events on, and prints stdin stops it: the events go off and the mouse returns to the mode it was in. It needs an `@openmouse/protocol` release that has `startButtonListener`. -## Exit code contract (Bridge depends on this — see `src/drivers/native_hid.rs`) +## Exit code contract (Bridge depends on this - see `src/drivers/native_hid.rs`) -- `0` — a device was found and the requested settings were applied. In +- `0` - a device was found and the requested settings were applied. In status mode (`{"brand": "…", "action": "status"}` on stdin) the device's status was read instead, and its battery is printed on stdout as `{"batteryPercent": 41, "batteryState": "Discharging"}`. -- `3` — no driver is registered for this brand. Not an error. -- `1` — a driver exists for this brand, but no device answered, or applying +- `3` - no driver is registered for this brand. Not an error. +- `1` - a driver exists for this brand, but no device answered, or applying failed. Details on stderr. ## Setup @@ -106,17 +106,17 @@ npm install ``` `@openmouse/protocol` is a normal git dependency pinned to a specific commit -(`package.json`), matching how `openmouse` itself depends on it — not a +(`package.json`), matching how `openmouse` itself depends on it - not a local `file:`/symlink reference to the sibling `../../mouse-protocol` checkout, deliberately: that checkout can have local work in progress (it -did when this package was created — untracked G-Wolves driver files that +did when this package was created - untracked G-Wolves driver files that briefly broke its own build), and a `file:` dependency would rebuild it as a side effect of `npm install` here. Bump the pinned commit by hand when you want a newer `mouse-protocol`. Both dependencies have install scripts (`node-hid` needs to select its prebuilt native binding; `@openmouse/protocol` needs to compile its -TypeScript) — this environment's npm requires approving those explicitly: +TypeScript) - this environment's npm requires approving those explicitly: ```sh npm approve-scripts node-hid "@openmouse/protocol" @@ -127,7 +127,7 @@ npm install # re-run once scripts are approved, so they actually execute Bridge's release packaging (`.github/workflows/release.yml`) bundles this whole directory next to the `openmouse-bridge` executable, plus a -standalone Node.js runtime under `native-hid/node/` — end users don't need +standalone Node.js runtime under `native-hid/node/` - end users don't need Node.js installed. `src/drivers/native_hid.rs` looks for that bundled runtime first and falls back to `node` on `PATH`, so local development (this README's setup above) works without it. diff --git a/native-hid/bridge-server.mjs b/native-hid/bridge-server.mjs index 2b5b669d..90cf40ef 100644 --- a/native-hid/bridge-server.mjs +++ b/native-hid/bridge-server.mjs @@ -146,7 +146,7 @@ class ManagedDevice { this.batteryAt = Date.now(); console.log(`[Bridge] 🔋 Battery update for ${this.productName}: ${pct}%`); // Forward the raw battery input report to all connected WebSocket clients - // using type:'report' — the format bridge-hid.ts's #receive handler + // using type:'report' - the format bridge-hid.ts's #receive handler // already understands and routes to device.deliver() → AttackShark // driver's onInputReport → x11RuntimeStates cache update. // Payload mirrors the real HID packet: [0x55, 0x40, 0x01, pct] @@ -426,7 +426,7 @@ wss.on('connection', (ws) => { dev.adapter.removeEventListener('inputreport', dev._bridgeListener); delete dev._bridgeListener; } - // Do NOT stop the battery monitor — keep it running so the passive + // Do NOT stop the battery monitor - keep it running so the passive // push updates continue for all connected clients. ws.send(JSON.stringify({ id, ok: true })); return; diff --git a/native-hid/src/apply.mjs b/native-hid/src/apply.mjs index d3b2c35c..7050433c 100644 --- a/native-hid/src/apply.mjs +++ b/native-hid/src/apply.mjs @@ -5,7 +5,7 @@ // // Usage: node apply.mjs < request.json // stdin: {"brand": "Razer", "dpi": 800, "pollingRateHz": 1000} -// (dpi / pollingRateHz are each optional — omit to leave that setting alone) +// (dpi / pollingRateHz are each optional - omit to leave that setting alone) // stdin: {"brand": "Razer", "dpi": 800, "settings": {"lightforceSwitchMode": "Optical"}} // (settings carries the panel's stored MouseStatus fields; ones the driver // supports are applied, the rest are reported and skipped) @@ -16,21 +16,21 @@ // "switchMode": "Optical"} (settings fields null when unreadable) // // Exit codes (Bridge's src/drivers/native_hid.rs depends on this contract): -// 0 — a device was found and the requested settings were applied (or, in +// 0 - a device was found and the requested settings were applied (or, in // status mode, its status was read and printed). -// 3 — no native driver is registered for this brand (not an error: most +// 3 - no native driver is registered for this brand (not an error: most // devices are still driven by the OpenMouse web app over WebHID). -// 1 — a driver is registered for this brand, but no matching device +// 1 - a driver is registered for this brand, but no matching device // answered, or applying the settings failed. Details on stderr. // mouse-protocol's driver classes were written for a browser and several of // them (17 of ~18 brands as of this writing) time their HID++/vendor // request-response waits with `window.setTimeout`/`window.clearTimeout`. // `window` doesn't exist in Node, so that throws a ReferenceError inside the -// Promise executor — which JS silently turns into an instant rejection, not +// Promise executor - which JS silently turns into an instant rejection, not // a timeout, before any real reply can arrive. Concretely, this made // LogitechHidppClient misread that instant non-timeout rejection as "the // receiver answered but this slot has no sensor" on every pairing slot, so -// it reported a connected mouse as "not a mouse" — nothing to do with HID +// it reported a connected mouse as "not a mouse" - nothing to do with HID // permissions or the mouse being asleep. `window` aliased to `globalThis` // fixes every driver relying on this pattern at once. Must run before any // `@openmouse/protocol` driver module is imported, including the dynamic @@ -76,7 +76,7 @@ async function probe(device, candidate) { try { await withTimeout(client.open(), PROBE_TIMEOUT_MS, `${candidate.exportName}.open()`); // Every SupportedClient implements readStatus() (mouse-protocol's - // shared client contract) — a cheap, read-only way to confirm this is + // shared client contract) - a cheap, read-only way to confirm this is // really the right class for this interface before writing anything. const status = await withTimeout(client.readStatus(), PROBE_TIMEOUT_MS, `${candidate.exportName}.readStatus()`); if (candidate.requireBrand !== undefined && brandKey(status?.brand ?? "") !== candidate.requireBrand) { @@ -164,7 +164,7 @@ async function main() { JSON.stringify({ batteryPercent: status?.batteryPercent ?? null, batteryState: status?.batteryState ?? null, - // The driver's own model name (MouseStatus.name) — better than the + // The driver's own model name (MouseStatus.name) - better than the // receiver-level name Bridge's discovery gets from the HID // descriptor (a LIGHTSPEED receiver reports "USB Receiver"). deviceName: status?.name ?? null, @@ -182,7 +182,7 @@ async function main() { // ── Wooting 60HE+ ─────────────────────────────────────────────────── // RAM-only switch needs no confirm; flash saves require confirmed: true - // in stdin (headless gate — no modal possible), else exit 1 unsent. + // in stdin (headless gate - no modal possible), else exit 1 unsent. if (input.action === "switch-profile") { if (!Number.isInteger(input.slot)) { console.error("[native-hid] switch-profile needs an integer slot."); @@ -274,7 +274,7 @@ async function main() { } } if (skipped.length > 0) { - console.error(`[native-hid] no native support for: ${skipped.join(", ")} — skipped.`); + console.error(`[native-hid] no native support for: ${skipped.join(", ")} - skipped.`); } } diff --git a/native-hid/src/brands.mjs b/native-hid/src/brands.mjs index 2537980b..ffc03462 100644 --- a/native-hid/src/brands.mjs +++ b/native-hid/src/brands.mjs @@ -1,6 +1,6 @@ // The fallback dispatch table. Bridge normally sends the devices it described // and the protocol package's own registry picks the driver (registry.mjs); this -// table is used only for a request without them — when the registry could not +// table is used only for a request without them - when the registry could not // be loaded, and for Zaunkoenig's acknowledged automation (automation.mjs). // // Maps a MouseStatus `brand` string (mouse-protocol/src/drivers/mouse-types.ts) @@ -8,11 +8,11 @@ // try constructing against each interface found, in the same order // mouse-protocol/src/drivers/registry.ts's DEVICE_DRIVERS lists them for // that brand (first-match-wins there; here, first class whose open() + -// readStatus() probe succeeds wins — see apply.mjs). +// readStatus() probe succeeds wins - see apply.mjs). // // "Pulsar" is left out: Bridge has a dependency-free native Rust driver for it // (src/drivers/pulsar.rs) that claims the brand before this helper is ever -// invoked — see src/drivers/mod.rs. +// invoked - see src/drivers/mod.rs. // // Vendor ids are copied from mouse-protocol/src/drivers/vendors.ts and each // driver's own `isSupported()`; class import paths use the package's @@ -91,7 +91,7 @@ export const BRAND_DRIVERS = { }, ninjutso: { // NINJUTSO_VENDOR_ID (current) and NINJUTSO_LEGACY_VENDOR_ID (shared - // with Orbital) — see mouse-protocol/src/ninjutso/index.ts. + // with Orbital) - see mouse-protocol/src/ninjutso/index.ts. vendorIds: [0x093a, 0x1915], classes: [client("@openmouse/protocol/drivers/ninjutso/hid", "NinjutsoHidClient")], }, diff --git a/native-hid/src/button-listener.mjs b/native-hid/src/button-listener.mjs index c5e763c0..2440774b 100644 --- a/native-hid/src/button-listener.mjs +++ b/native-hid/src/button-listener.mjs @@ -9,7 +9,7 @@ // to the mode it was in, if this helper changed it. // stdout: one JSON object per line. // {"event": "ready", "priorMode": "Onboard", "buttons": [1, 2, 3, 4, 5]} -// {"event": "buttons", "mask": 16} — the buttons held right now +// {"event": "buttons", "mask": 16} - the buttons held right now // {"event": "error", "message": "..."} // {"event": "stopped"} // diff --git a/native-hid/src/hid-device-adapter.mjs b/native-hid/src/hid-device-adapter.mjs index 2d822538..70041170 100644 --- a/native-hid/src/hid-device-adapter.mjs +++ b/native-hid/src/hid-device-adapter.mjs @@ -1,7 +1,7 @@ // Wraps one or more node-hid devices so together they satisfy the WebHID // `HIDDevice` interface mouse-protocol's driver classes are written against // (see mouse-protocol/src/drivers/webhid.ts, an ambient-type declaration -// only — this file is the runtime implementation of that same shape for +// only - this file is the runtime implementation of that same shape for // Node). // // This lets Bridge reuse OpenMouse's actual, hardware-verified driver @@ -10,9 +10,9 @@ // // One WebHID `HIDDevice` == one USB/BT *interface*, which can carry several // top-level HID collections (e.g. a short and a long report variant on the -// same vendor interface — this is exactly Logitech's HID++ receiver shape: +// same vendor interface - this is exactly Logitech's HID++ receiver shape: // report 0x10 in one collection, report 0x11 in another, same interface). -// node-hid enumerates one entry *per collection*, not per interface — on +// node-hid enumerates one entry *per collection*, not per interface - on // macOS in particular, IOHIDManager opens a separate IOHIDDevice service per // top-level collection it finds, each capable of receiving input reports // only for the report ids declared in *its own* collection. Opening only @@ -43,7 +43,7 @@ export class HidDeviceAdapter { this.vendorId = primary.vendorId; this.productId = primary.productId; this.productName = primary.product ?? ""; - // Real report-descriptor parsing isn't implemented here — callers must + // Real report-descriptor parsing isn't implemented here - callers must // not rely on collections-based `isSupported()` gating (see // native-hid/README.md); construct the known-correct driver class // directly instead. @@ -115,7 +115,7 @@ export class HidDeviceAdapter { async sendReport(reportId, data) { this._requireOpen(); const frame = this._frame(reportId, data); - // Any split for this interface can carry the write on real hardware — + // Any split for this interface can carry the write on real hardware - // the split is a macOS/IOHIDManager enumeration artifact per top-level // collection, not a hardware restriction on which handle can transmit // which report id. Writing through all of them costs little (these are @@ -158,16 +158,16 @@ export class HidDeviceAdapter { * from the parsed report descriptor. Drivers here call this with the * length they themselves expect back baked into their own retry/parsing * logic, so a generous fixed buffer (the largest report any known driver - * here uses) is safe — short replies are simply the leading bytes of it. + * here uses) is safe - short replies are simply the leading bytes of it. * * Classic Razer's control protocol is the largest: 90-byte feature reports * on report id 0 (mouse-protocol/src/razer/codec.ts, RAZER_PACKET_LENGTH = - * 90; the Rust transport's per-vendor budget is 91 for it — see + * 90; the Rust transport's per-vendor budget is 91 for it - see * RAZER_FEATURE_BUFFER_LEN in src/hid.rs). Requesting the whole report one * byte at a time would be wrong; request the id byte plus the largest * payload up front: `getFeatureReport` fills its first byte with the * requested report id and returns that id prefix as part of the buffer - * (node-hid's HID.cc passes buf[0] on to hidapi, which counts it — the + * (node-hid's HID.cc passes buf[0] on to hidapi, which counts it - the * exact same shape the Rust transport's receive_feature_report() accounts * for with `data[1..size]`). Strip that id byte so the drivers see the * payload they get from WebHID. Some backends omit the id byte entirely; @@ -224,7 +224,7 @@ export class HidDeviceAdapter { _onData(data) { // Some backends prefix numbered reports with the report id on read, // some don't (mirrors the same ambiguity the Rust Pulsar driver - // handles) — there is no fully reliable way to tell from the bytes + // handles) - there is no fully reliable way to tell from the bytes // alone, so report id 0 is assumed when in doubt; drivers here match // responses by their own payload content, not strictly by report id. const reportId = data.length > 0 ? data[0] : 0; @@ -237,7 +237,7 @@ export class HidDeviceAdapter { /** @param {Error} error */ _onError(error) { // Surfaced to whoever is waiting on a pending exchange via their own - // timeout, matching how a real device disconnect looks over WebHID — + // timeout, matching how a real device disconnect looks over WebHID - // there is no dedicated "error" WebHID event drivers here listen for. // Logged so it's not silently swallowed. console.error(`[native-hid] device error: ${error.message}`); @@ -245,7 +245,7 @@ export class HidDeviceAdapter { } /** - * Lists every HID *interface* for a vendor id, ready to be opened — one + * Lists every HID *interface* for a vendor id, ready to be opened - one * HidDeviceAdapter per interface, merging any node-hid entries that split * off the same interface into separate top-level collections (see module * docs above). @@ -284,7 +284,7 @@ export function candidateDevices(vendorId, hints = {}, list = devices) { const infos = onPage.length > 0 ? onPage : group; // Several node-hid entries for one interface commonly share the same // underlying `path` (one physical device, listed once per top-level - // collection its descriptor declares) — open each distinct path once. + // collection its descriptor declares) - open each distinct path once. const seen = new Set(); const unique = infos.filter((info) => (seen.has(info.path) ? false : seen.add(info.path))); return new HidDeviceAdapter(unique); @@ -307,8 +307,8 @@ function isStandardOnly(path) { /** * One device as Bridge described it (src/hid.rs, `DescribedDevice`): the - * WebHID view the control panel would get — the same grouping and the - * collections parsed from the report descriptors — plus each collection's + * WebHID view the control panel would get - the same grouping and the + * collections parsed from the report descriptors - plus each collection's * path and the payload size of every report it declares. * * Unlike HidDeviceAdapter it sends a report down only the path whose diff --git a/native-hid/src/registry.mjs b/native-hid/src/registry.mjs index 48ef47ca..8aa3381a 100644 --- a/native-hid/src/registry.mjs +++ b/native-hid/src/registry.mjs @@ -4,8 +4,8 @@ // // Bridge only describes devices matching the registry's SUPPORTED_HID_FILTERS // (the filters the panel requests devices with), and a driver is only used on -// a device its own `supports()` accepts — the same product-id and descriptor -// checks as in the browser — so nothing outside what OpenMouse itself would +// a device its own `supports()` accepts - the same product-id and descriptor +// checks as in the browser - so nothing outside what OpenMouse itself would // open is ever written to. // // The modules are imported lazily: loading the registry pulls in every driver, diff --git a/packaging/windows/bridge.iss b/packaging/windows/bridge.iss index 5dbdbdbf..3f0bd963 100644 --- a/packaging/windows/bridge.iss +++ b/packaging/windows/bridge.iss @@ -40,3 +40,122 @@ Name: "{autodesktop}\OpenMouse Bridge"; Filename: "{app}\openmouse-bridge.exe"; [Run] Filename: "{app}\openmouse-bridge.exe"; Description: "Launch OpenMouse Bridge"; Flags: nowait postinstall skipifsilent + +[Code] +var + DeleteUserData: Boolean; + ExistingPage: TInputOptionWizardPage; + UninstallCommand: String; + InstalledVersion: String; + LeaveSetup: Boolean; + +function FindInstalled(): Boolean; +var + Key: String; +begin + Key := 'Software\Microsoft\Windows\CurrentVersion\Uninstall\io.openmouse.bridge_is1'; + Result := RegQueryStringValue(HKCU, Key, 'UninstallString', UninstallCommand); + if Result then + begin + if not RegQueryStringValue(HKCU, Key, 'DisplayVersion', InstalledVersion) then + InstalledVersion := ''; + end; +end; + +procedure InitializeWizard(); +var + Choice: String; +begin + if FindInstalled() then + begin + if InstalledVersion = '{#AppVersion}' then + Choice := 'Repair Bridge (install the current version again)' + else + Choice := 'Update Bridge to {#AppVersion}'; + ExistingPage := CreateInputOptionPage(wpWelcome, + 'OpenMouse Bridge is already installed', + 'Installed version: ' + InstalledVersion, + 'What would you like to do?', True, False); + ExistingPage.Add(Choice); + ExistingPage.Add('Uninstall Bridge'); + ExistingPage.Values[0] := True; + end; +end; + +function NextButtonClick(CurPageID: Integer): Boolean; +var + ResultCode: Integer; +begin + Result := True; + if (ExistingPage <> nil) and (CurPageID = ExistingPage.ID) and ExistingPage.Values[1] then + begin + Exec(RemoveQuotes(UninstallCommand), '', '', SW_SHOWNORMAL, ewNoWait, ResultCode); + LeaveSetup := True; + WizardForm.Close; + Result := False; + end; +end; + +procedure CancelButtonClick(CurPageID: Integer; var Cancel, Confirm: Boolean); +begin + if LeaveSetup then + Confirm := False; +end; + +function BridgeProcesses(StopThem: Boolean): Integer; +var + Script, Flag: String; + ResultCode: Integer; +begin + Result := 0; + Script := + 'param([string]$Dir, [string]$Stop)' + #13#10 + + '$found = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -eq "openmouse-bridge.exe" -and $_.ExecutablePath -and $_.ExecutablePath.StartsWith($Dir, [StringComparison]::OrdinalIgnoreCase) })' + #13#10 + + 'if ($Stop -eq "1") { $found | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }; Start-Sleep -Seconds 1 }' + #13#10 + + 'exit $found.Count'; + if StopThem then + Flag := '1' + else + Flag := '0'; + if SaveStringToFile(ExpandConstant('{tmp}\check-bridge.ps1'), Script, False) then + if Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), + '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{tmp}\check-bridge.ps1') + '" -Dir "' + ExpandConstant('{app}') + '" -Stop ' + Flag, + '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then + Result := ResultCode; +end; + +function InitializeUninstall(): Boolean; +begin + Result := True; + if BridgeProcesses(False) > 0 then + begin + if SuppressibleMsgBox('OpenMouse Bridge is running.' + #13#10 + #13#10 + 'Close it so it can be uninstalled?', mbConfirmation, MB_YESNO, IDYES) = IDYES then + BridgeProcesses(True) + else + Result := False; + end; + if Result then + DeleteUserData := SuppressibleMsgBox( + 'Also delete your Bridge settings, profiles and logs?' + #13#10 + #13#10 + + 'Choose No to keep them for a later reinstall.', + mbConfirmation, MB_YESNO, IDNO) = IDYES; +end; + +procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep); +var + ResultCode: Integer; +begin + if CurUninstallStep = usUninstall then + begin + BridgeProcesses(True); + Exit; + end; + if CurUninstallStep <> usPostUninstall then + Exit; + if DeleteUserData then + begin + DelTree(ExpandConstant('{userappdata}\OpenMouse\OpenMouse Bridge'), True, True, True); + RemoveDir(ExpandConstant('{userappdata}\OpenMouse')); + end; + Exec(ExpandConstant('{cmd}'), '/C ping -n 8 127.0.0.1 >nul & rmdir "' + ExpandConstant('{app}') + '"', '', SW_HIDE, ewNoWait, ResultCode); +end; diff --git a/src/config.rs b/src/config.rs index a20715e6..3e0609bf 100644 --- a/src/config.rs +++ b/src/config.rs @@ -34,9 +34,9 @@ pub struct BridgeConfig { #[serde(default = "default_tray_battery_style")] pub tray_battery_style: String, /// Hybrid device mode: while the OpenMouse web panel is disconnected, - /// Bridge drives the mouse itself — the active profile's stored settings + /// Bridge drives the mouse itself - the active profile's stored settings /// (DPI, polling rate, switch mode) go to the onboard memory and the - /// battery is read natively — and hands the mouse over to the panel the + /// battery is read natively - and hands the mouse over to the panel the /// moment it connects, applying the stored settings again on disconnect. #[serde(default = "enabled_by_default")] pub hybrid_mode: bool, diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs index 83bc2b77..9146d505 100644 --- a/src/drivers/mod.rs +++ b/src/drivers/mod.rs @@ -4,7 +4,7 @@ //! //! Each driver is a Rust port of the matching hardware-verified WebHID //! driver in the sibling `mouse-protocol` repo (`@openmouse/protocol`), -//! scoped to DPI/polling-rate only — the only settings Bridge profiles +//! scoped to DPI/polling-rate only - the only settings Bridge profiles //! store. Dispatch matches `ApplicationProfile.device.id`'s `":"` //! prefix, the same convention the OpenMouse web app writes when it saves a //! profile (see `openmouse/src/app/InterfaceSettings.tsx`); brand strings @@ -34,10 +34,10 @@ mod registry; pub use native_hid::{NativeBattery, NativeStatus, spawn_button_listener}; /// A mouse Bridge discovered by itself, by scanning the HID bus for vendor -/// ids its drivers recognize — no saved profile required. +/// ids its drivers recognize - no saved profile required. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct DetectedMouse { - /// Stable profile-style id, `":"` — the same + /// Stable profile-style id, `":"` - the same /// `":"` prefix convention the OpenMouse web app writes. pub device_id: String, /// Human-readable product name from the HID descriptor. @@ -53,8 +53,8 @@ pub struct DetectedMouse { /// (the same drivers the web panel drives, and the same normalization /// `apply.mjs` gives `device.id` prefixes: trim + lowercase). When several /// brands share a vendor id, the entry names the brand whose driver class -/// list covers the most sibling hardware — Delux's list includes the Attack -/// Shark and Lamzu clients — or `mouse-protocol`'s registry.ts first match; +/// list covers the most sibling hardware - Delux's list includes the Attack +/// Shark and Lamzu clients - or `mouse-protocol`'s registry.ts first match; /// the loser's devices merely fail their silent battery probe later. const KNOWN_BRANDS: &[(&str, &[u16])] = &[ ("Delux", &[0x1d57, 0x248a, 0x373e]), @@ -92,10 +92,10 @@ pub fn brand_in_name(name: &str) -> Option<&'static str> { /// Logitech is special: every Logitech-branded device (keyboards, headsets) /// shares vendor id 0x046d and the HID++ transport (`mouse-protocol`'s -/// `drivers/logitech/hidpp.ts` has the same limitation — "whether it is a +/// `drivers/logitech/hidpp.ts` has the same limitation - "whether it is a /// *mouse* cannot be told from descriptors"), so discovery keeps the HID++ -/// collections — short/long reports on usage page 0xFF00, Bluetooth on -/// 0xFF43 — and a keyboard merely fails its battery probe silently later. +/// collections - short/long reports on usage page 0xFF00, Bluetooth on +/// 0xFF43 - and a keyboard merely fails its battery probe silently later. const LOGITECH_VENDOR_ID: u16 = 0x046d; const HIDPP_USAGE_PAGE: u16 = 0xff00; const HIDPP_BLUETOOTH_USAGE_PAGE: u16 = 0xff43; @@ -414,7 +414,7 @@ fn write_settings_held( } /// Reads the onboard-memory state of the mouse `device_id` names -/// (`":"`) over native HID — battery, and the current DPI / +/// (`":"`) over native HID - battery, and the current DPI / /// polling rate / switch mode wherever the driver can read them. /// `Ok(None)` means Bridge has no reader for the brand or the mouse reports /// no battery; `Err` means a driver exists but the mouse did not answer @@ -833,7 +833,7 @@ mod tests { } /// Exercises the real Rust -> Node.js round trip, so it needs Node.js on - /// PATH and the native-hid/ checkout present next to Cargo.toml — not + /// PATH and the native-hid/ checkout present next to Cargo.toml - not /// guaranteed in every CI environment, so it's opt-in rather than part /// of the default `cargo test` run. Run explicitly with /// `cargo test -- --ignored native_hid`. @@ -856,7 +856,7 @@ mod tests { /// Discovery must see every vendor id the helper can drive, and every /// brand discovery writes into `device.id` must normalize to a helper - /// brand key — otherwise a mouse is discovered but its battery or + /// brand key - otherwise a mouse is discovered but its battery or /// settings can never be read. Parses `native-hid/src/brands.mjs` (the /// helper's own table) so the two cannot drift apart silently. #[test] @@ -896,7 +896,7 @@ mod tests { } assert!( !helper_vendor_ids.is_empty(), - "parsed no vendor ids — did brands.mjs's format change?" + "parsed no vendor ids - did brands.mjs's format change?" ); let discoverable = |id: u16| { // The special-cased vendor ids in `discovered_brand`: CompX's diff --git a/src/drivers/native_hid.rs b/src/drivers/native_hid.rs index 466d26b0..7148d7fa 100644 --- a/src/drivers/native_hid.rs +++ b/src/drivers/native_hid.rs @@ -2,7 +2,7 @@ //! that doesn't have a dependency-free native Rust driver. The helper reuses //! OpenMouse's own hardware-verified `@openmouse/protocol` WebHID driver //! classes through a small adapter, instead of Bridge reimplementing every -//! vendor's wire protocol from scratch — see `native-hid/README.md`. +//! vendor's wire protocol from scratch - see `native-hid/README.md`. #[cfg(target_os = "windows")] use std::os::windows::process::CommandExt; @@ -93,7 +93,7 @@ struct StatusReply { battery_percent: Option, battery_state: Option, /// The driver's own model name (`MouseStatus.name`), when the driver - /// reports one — better than the receiver-level name discovery gets from + /// reports one - better than the receiver-level name discovery gets from /// the HID descriptor. device_name: Option, /// The settings currently in the device's onboard memory, when the @@ -126,7 +126,7 @@ pub struct NativeStatus { /// `MouseStatus.dpi` is either one number or a per-stage list; the stages /// have no reliable "active" marker, so a list collapses to its first -/// stage — the one most drivers treat as the default. +/// stage - the one most drivers treat as the default. fn coerce_dpi(value: Option<&serde_json::Value>) -> Option { match value? { serde_json::Value::Number(number) => number.as_u64().map(|dpi| dpi as u32), @@ -316,7 +316,7 @@ pub(super) fn run_helper(request: &impl Serialize) -> Result>> { bundled.display() ), None => format!( - "could not start Node.js to run {} — is Node.js installed and on PATH?", + "could not start Node.js to run {} - is Node.js installed and on PATH?", script.display() ), })?; @@ -352,8 +352,8 @@ pub fn spawn_button_listener(brand: &str) -> Result { }) } -/// Finds `native-hid/src/apply.mjs` next to the running executable — how a -/// packaged Bridge release is expected to ship it — falling back to the +/// Finds `native-hid/src/apply.mjs` next to the running executable - how a +/// packaged Bridge release is expected to ship it - falling back to the /// checkout's own source tree so `cargo run`/`cargo test` work without a /// packaging step. fn locate_apply_script() -> Result { @@ -395,7 +395,7 @@ fn runs_inside(checkout: &Path) -> bool { /// Finds the Node.js runtime a packaged Bridge release bundles at /// `native-hid/node/` next to the executable (see `.github/workflows/release.yml`). /// `None` means no bundled runtime was found, so the caller should fall back -/// to `node` on `PATH` — the normal case for `cargo run`/`cargo test`, which +/// to `node` on `PATH` - the normal case for `cargo run`/`cargo test`, which /// don't produce a packaged layout. fn locate_node_binary() -> Option { let dir = installed_native_hid_dir()?.join("node"); diff --git a/src/drivers/pulsar.rs b/src/drivers/pulsar.rs index cae0d37f..cdb826b2 100644 --- a/src/drivers/pulsar.rs +++ b/src/drivers/pulsar.rs @@ -1,5 +1,5 @@ //! Native HID driver for real Pulsar-vendor (0x3710) mice, so Bridge can push -//! DPI and polling-rate changes to the mouse on its own — without a browser +//! DPI and polling-rate changes to the mouse on its own - without a browser //! tab open and holding a WebHID connection. //! //! The wire protocol here is ported byte-for-byte from @@ -19,7 +19,7 @@ use anyhow::{Context, Result, anyhow, bail}; use super::{NativeBattery, NativeStatus}; use crate::config::ApplicationProfile; -/// This driver's slot in `crate::drivers`' brand registry — matches the +/// This driver's slot in `crate::drivers`' brand registry - matches the /// `"Pulsar:"` prefix the OpenMouse web app writes into `device.id`. pub const BRAND: &str = "pulsar"; @@ -60,7 +60,7 @@ fn read_flash_settings(device: &PulsarDevice) -> Result<(Option, Option Result> { /// Real Pulsar-branded mice and dongles. The Pulsar 4K Wireless Receiver /// shares a report-8 16-byte protocol but enumerates under a different, -/// shared vendor id (0x3554) that other brands also use — out of scope here. +/// shared vendor id (0x3554) that other brands also use - out of scope here. pub const VENDOR_ID: u16 = 0x3710; const CONFIG_REPORT_ID: u8 = 0x08; @@ -155,7 +155,7 @@ fn encode_polling_rate(rate_hz: u32) -> Result { /// The 10-step low range plus a dpiEx-flagged high range real Pulsar-vendor /// flash mice (including the X2 CrazyLight, CID 0x57) use. Do not apply this -/// to the Pulsar 4K Wireless Receiver (vendor 0x3554) — it uses a flat +/// to the Pulsar 4K Wireless Receiver (vendor 0x3554) - it uses a flat /// 50-step encoding with no dpiEx branching (`pulsarVgn*` in the TS source). fn decode_dpi(data: &[u8]) -> Option { if data.len() < 4 { @@ -225,7 +225,7 @@ pub struct PulsarDevice { impl PulsarDevice { /// Scans every HID interface reporting Pulsar's vendor id and opens the - /// first one that answers the identification query on report 8 — a mouse + /// first one that answers the identification query on report 8 - a mouse /// exposes several HID interfaces (boot mouse, consumer control, ...) /// sharing the same vendor id, and only one of them is this config /// channel, so wrong interfaces are expected to fail here and are @@ -330,7 +330,7 @@ impl PulsarDevice { } /// Wraps a flash read/write in the receiver's host-control handshake: - /// entered before the operation, always exited afterward (best-effort — + /// entered before the operation, always exited afterward (best-effort - /// leaving the receiver stuck in host-control mode would also break its /// normal button/movement reporting). fn with_device_control(&self, operation: impl FnOnce() -> Result) -> Result { @@ -354,7 +354,7 @@ impl PulsarDevice { assert_accepted(&response, label)?; if response[9] != 1 { if enabled && response[5] != 1 { - bail!("the Pulsar mouse is offline — move it or click a button, then retry"); + bail!("the Pulsar mouse is offline - move it or click a button, then retry"); } return Ok(()); } @@ -444,7 +444,7 @@ impl PulsarDevice { if read == 0 { continue; } - // Some backends prefix the report id, some don't — accept both. + // Some backends prefix the report id, some don't - accept both. let body = if read == buffer.len() && buffer[0] == CONFIG_REPORT_ID { &buffer[1..read] } else { @@ -516,7 +516,7 @@ mod tests { #[test] fn packet_checksum_matches_the_hardware_verified_pulsar_formula() { // 0x55 - (CONFIG_REPORT_ID + sum(bytes[0..14])) & 0xff, over a - // deviceOnline(true) packet — mirrors pulsarPacketChecksum in + // deviceOnline(true) packet - mirrors pulsarPacketChecksum in // mouse-protocol/src/pulsar/index.ts. let mut packet = [0u8; PACKET_LENGTH]; packet[0] = command::DEVICE_ONLINE; diff --git a/src/drivers/registry.rs b/src/drivers/registry.rs index d1df1a87..ce673f78 100644 --- a/src/drivers/registry.rs +++ b/src/drivers/registry.rs @@ -1,6 +1,6 @@ //! Which devices on the bus are mice Bridge can drive, and which brand each -//! is, decided by `@openmouse/protocol`'s own driver registry — the same -//! `supports()` checks the control panel runs in the browser — rather than a +//! is, decided by `@openmouse/protocol`'s own driver registry - the same +//! `supports()` checks the control panel runs in the browser - rather than a //! vendor-id table of Bridge's own. //! //! Bridge describes the bus (`hid::describe_devices`: grouped devices with @@ -168,9 +168,9 @@ fn brands_by_key(reply: IdentifyReply) -> HashMap { } /// The devices a `brand` request may use: those the registry gives that -/// brand. When none has it — a profile saved under the brand the driver +/// brand. When none has it - a profile saved under the brand the driver /// reports (`Attack Shark`) for hardware the registry files under another -/// (`Delux`) — every supported device is offered and the helper keeps the one +/// (`Delux`) - every supported device is offered and the helper keeps the one /// whose own status reports `brand`. `None` when the registry is unavailable. pub(super) fn devices_for(brand: &str) -> Option { let devices = devices()?; diff --git a/src/gpui_shell/mod.rs b/src/gpui_shell/mod.rs index f5fd7e7d..f3202058 100644 --- a/src/gpui_shell/mod.rs +++ b/src/gpui_shell/mod.rs @@ -153,6 +153,7 @@ pub fn run() -> Result<()> { // environment. let show_panel = show_panel || std::env::var_os("OPENMOUSE_BRIDGE_SHOW_WINDOW").is_some(); + hide_when_unfocused(cx, handle, &view); let (tray_commands, mut tray_handle) = match tray::install(cx, handle) { Some((commands, tray)) => (Some(commands), Some(tray)), None => (None, None), @@ -202,7 +203,23 @@ pub fn run() -> Result<()> { } else { // Shown at launch (the first run): beside the tray, not mid-screen. if tray_commands.is_some() { - let _ = cx.update_window(handle, |_, window, _| tray::place(window, None)); + // Moving the window sends it messages that re-enter GPUI, so it + // is done from a task once this startup callback has returned. + cx.spawn(async move |cx| { + #[cfg(windows)] + { + let plan = cx + .update_window(handle, |_, window, _| { + tray::plan_place(window, None) + }) + .ok() + .flatten(); + tray::apply_move(plan); + } + #[cfg(not(windows))] + let _ = cx.update_window(handle, |_, window, _| tray::place(window, None)); + }) + .detach(); } cx.activate(true); } @@ -312,6 +329,16 @@ pub fn run() -> Result<()> { cx.background_executor().timer(LAYER_MAP_DELAY).await; } } + #[cfg(windows)] + { + let plan = cx + .update_window(handle, |_, window, _| { + tray::plan_place(window, anchor) + }) + .ok() + .flatten(); + tray::apply_move(plan); + } let _ = cx.update_window(handle, |_, window, _| tray::show(window, anchor)); } for command in tray_requests { @@ -376,6 +403,26 @@ fn panel_wanted_after(shown: bool, api_request: bool, commands: &[tray::Command] wanted } +/// Hides the panel to the tray when a click elsewhere takes its focus, where it +/// is a popup by the tray (see [`tray::hides_on_blur`]). +fn hide_when_unfocused(cx: &mut App, handle: AnyWindowHandle, view: &Entity) { + let _ = cx.update_window(handle, |_, window, cx| { + view.update(cx, |_, cx| { + cx.observe_window_activation(window, |panel, window, _| { + if !window.is_window_active() + && tray::hides_on_blur() + && !panel.stays_open() + && !tray::always_on_top() + { + tracing::debug!("hiding the panel after it lost focus"); + tray::hide_on_blur(window); + } + }) + .detach(); + }); + }); +} + /// Makes the window's close button hide the panel to the tray, or quit when /// there is no tray to bring it back from. #[cfg(target_os = "linux")] @@ -431,8 +478,9 @@ fn open_layer_panel( }; let view = view.clone(); match open_window(options, cx, move |_, _| view) { - Ok((handle, _)) => { + Ok((handle, view)) => { close_hides_or_quits(cx, handle, exit); + hide_when_unfocused(cx, handle, &view); Some(handle) } Err(error) => { diff --git a/src/gpui_shell/panel.rs b/src/gpui_shell/panel.rs index 2ac49539..f80ef852 100644 --- a/src/gpui_shell/panel.rs +++ b/src/gpui_shell/panel.rs @@ -1,6 +1,11 @@ //! The tray panel's views: Home, Settings and the Bridge info page. -use std::{sync::mpsc, time::Duration}; +use std::cell::Cell; +use std::rc::Rc; +use std::{ + sync::mpsc, + time::{Duration, Instant}, +}; use gpui_kit::assets::IconName; use gpui_kit::component::{ @@ -21,11 +26,107 @@ use tokio::sync::mpsc as tokio_mpsc; use super::{ExitFlags, ascii}; use crate::overlay::Overlay; use crate::runtime::{ - BridgeCommand, UpdateEvent, WINDOW_HEIGHT, WINDOW_WIDTH, notify_natively, open_logs, - service_label, + BridgeCommand, UpdateEvent, WINDOW_WIDTH, notify_natively, open_logs, service_label, }; -const OPENMOUSE_URL: &str = "https://control.openmouse.app"; +const OPENMOUSE_URL: &str = "https://control.openmouse.app/?from=bridge"; + +const SITE_CONNECT_GRACE: Duration = Duration::from_secs(20); + +const WELCOME_STEPS: [(&str, &str); 3] = [ + ( + "Open OpenMouse", + "Click the button below. It opens in your browser.", + ), + ( + "Allow the connection", + "When your browser asks to connect to Bridge on this computer, choose Forever so it only asks once.", + ), + ( + "Plug in your mouse", + "It shows up in OpenMouse. Bridge keeps running in the tray, so you can close this window.", + ), +]; + +const WELCOME_DONE: [&str; 3] = [ + "Opened in your browser.", + "Your browser is connected to Bridge.", + "Mouse detected.", +]; + +const WELCOME_AUTO_CLOSE: Duration = Duration::from_millis(2500); + +const WELCOME_FAILED: &str = "Not connected. In your browser: lock icon, Site settings, Local network access, Allow. Then try again."; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum StepStatus { + Done, + Current, + Failed, + Pending, +} + +fn welcome_progress( + opened: bool, + page_connected: bool, + mouse_present: bool, + failed: bool, +) -> [StepStatus; 3] { + let finished = [ + opened || page_connected, + page_connected, + page_connected && mouse_present, + ]; + let mut current_found = false; + let mut index = 0; + finished.map(|done| { + let status = if done { + StepStatus::Done + } else if !current_found { + current_found = true; + if failed && index == 1 { + StepStatus::Failed + } else { + StepStatus::Current + } + } else { + StepStatus::Pending + }; + index += 1; + status + }) +} + +#[derive(Debug, PartialEq, Eq)] +enum SiteWait { + Idle, + Waiting, + Connected, + TimedOut, +} + +fn opening_notice(connected: bool) -> Option { + if connected { + return None; + } + Some(Notice { + title: "Allow the connection".into(), + detail: "Choose Forever when your browser asks.".into(), + }) +} + +fn site_wait(opened_at: Option, connected: bool, now: Instant) -> SiteWait { + let Some(opened_at) = opened_at else { + return SiteWait::Idle; + }; + if connected { + SiteWait::Connected + } else if now.duration_since(opened_at) >= SITE_CONNECT_GRACE { + SiteWait::TimedOut + } else { + SiteWait::Waiting + } +} /// The low-battery alert levels on offer. const BATTERY_THRESHOLDS: [u8; 7] = [10, 15, 20, 25, 30, 40, 50]; @@ -55,6 +156,9 @@ fn step_volume(current: u8, up: bool) -> u8 { /// How many remembered mice Home lists before summarising the rest. const HOME_DEVICE_ROWS: usize = 3; +/// The window never gets smaller or taller than this, in logical points. +const MIN_HEIGHT: f32 = 200.0; +const MAX_HEIGHT: f32 = 900.0; /// Installing the udev rule that lets Bridge open plugged-in mice (Linux). enum UdevFix { @@ -81,30 +185,9 @@ enum View { Settings, Info, WhatsNew, + Welcome, } -impl View { - /// The panel's base height in logical points. - fn base_height(self) -> f32 { - match self { - View::Home => WINDOW_HEIGHT, - View::Settings => 600.0, - View::Info => 420.0, - View::WhatsNew => 480.0, - } - } -} - -/// Extra height for one more line of content, in logical points. -const ROW_HEIGHT: f32 = 24.0; -const NOTE_HEIGHT: f32 = 22.0; -/// The update card on Home. -const NOTICE_HEIGHT: f32 = 58.0; -/// The progress bar under the update card's headline, with its gap. -const BAR_HEIGHT: f32 = 14.0; -/// Home's "Updated to …" line after an update. -const WHATS_NEW_HEIGHT: f32 = 34.0; - pub struct PanelView { snapshots: mpsc::Receiver, commands: tokio_mpsc::UnboundedSender, @@ -113,8 +196,16 @@ pub struct PanelView { panel_requests: mpsc::Receiver<()>, exit: ExitFlags, snapshot: Option, + site_opened_at: Option, + resize_bottom: Option, + content_height: Rc>>, + welcome_opened: bool, + welcome_failed: bool, + welcome_done_at: Option, view: View, autostart: bool, + always_on_top: bool, + always_on_top_supported: bool, automatic_updates: bool, hybrid_mode: bool, tray_style: TrayBatteryStyle, @@ -195,18 +286,6 @@ impl UpdateState { ) } - /// Worth a card on Home, not only a line in Settings. - fn is_notice(&self) -> bool { - matches!( - self, - Self::Available(_) - | Self::Downloading(_) - | Self::Ready(_) - | Self::Restarting(_) - | Self::Failed(_) - ) - } - /// A progress bar goes under the headline. fn shows_bar(&self) -> bool { matches!(self, Self::Downloading(_) | Self::Restarting(_)) @@ -346,15 +425,25 @@ impl PanelView { panel_requests, exit, snapshot: None, + site_opened_at: None, + resize_bottom: None, + content_height: Rc::new(Cell::new(None)), + welcome_opened: false, + welcome_failed: false, + welcome_done_at: None, // A development aid: OPENMOUSE_BRIDGE_START_VIEW=settings|info opens // straight onto that view. view: match std::env::var("OPENMOUSE_BRIDGE_START_VIEW").as_deref() { Ok("settings") => View::Settings, Ok("info") => View::Info, Ok("whats-new") => View::WhatsNew, + Ok("welcome") => View::Welcome, + _ if first_run => View::Welcome, _ => View::Home, }, autostart: platform::autostart_enabled(), + always_on_top: super::tray::load_always_on_top(), + always_on_top_supported: false, automatic_updates: false, hybrid_mode: true, tray_style: TrayBatteryStyle::Glyph, @@ -443,6 +532,46 @@ impl PanelView { } else if self.progress.take().is_some() { changed = true; } + let connected = self + .snapshot + .as_ref() + .is_some_and(|snapshot| snapshot.client_connected); + match site_wait(self.site_opened_at, connected, Instant::now()) { + SiteWait::Idle | SiteWait::Waiting => {} + SiteWait::Connected => { + self.site_opened_at = None; + self.welcome_failed = false; + } + SiteWait::TimedOut => { + self.site_opened_at = None; + if self.view == View::Welcome { + self.welcome_failed = true; + changed = true; + } else { + self.present(&Notice { + title: "OpenMouse did not connect".into(), + detail: "Allow local network access in your browser's site settings, then reload.".into(), + }); + } + } + } + if self.view == View::Welcome { + let all_done = self + .welcome_statuses() + .iter() + .all(|status| *status == StepStatus::Done); + if !all_done { + self.welcome_done_at = None; + } else { + let since = *self.welcome_done_at.get_or_insert_with(Instant::now); + changed = true; + if since.elapsed() >= WELCOME_AUTO_CLOSE { + self.view = View::Home; + self.error = None; + self.welcome_done_at = None; + } + } + } while let Ok(notice) = self.notices.try_recv() { self.present(¬ice); } @@ -485,12 +614,51 @@ impl PanelView { } } + /// The Welcome screen sends the user to the browser and watches for the + /// connection, so it stays up when the panel loses focus. + pub fn stays_open(&self) -> bool { + self.view == View::Welcome + } + fn show_view(&mut self, view: View, cx: &mut Context) { self.view = view; + self.content_height.set(None); self.error = None; cx.notify(); } + fn welcome_statuses(&self) -> [StepStatus; 3] { + let snapshot = self.snapshot.as_ref(); + let connected = snapshot.is_some_and(|snapshot| snapshot.client_connected); + let mouse_present = snapshot.is_some_and(|snapshot| { + snapshot.known_devices.iter().any(|device| { + matches!( + device.state, + KnownDeviceState::Connected | KnownDeviceState::Asleep + ) + }) + }); + welcome_progress( + self.welcome_opened, + connected, + mouse_present, + self.welcome_failed, + ) + } + + fn open_site(&mut self, announce: bool, cx: &mut Context) { + cx.open_url(OPENMOUSE_URL); + self.welcome_failed = false; + self.site_opened_at = Some(Instant::now()); + let connected = self + .snapshot + .as_ref() + .is_some_and(|snapshot| snapshot.client_connected); + if announce && let Some(notice) = opening_notice(connected) { + self.present(¬ice); + } + } + /// Home offers this version's notes: Bridge was updated and they have not /// been seen or dismissed yet. fn offers_whats_new(&self) -> bool { @@ -518,50 +686,6 @@ impl PanelView { self.show_view(View::WhatsNew, cx); } - /// The height the current view needs: the base height plus a line for each - /// extra remembered mouse, the "more" note, and the update status text. - fn desired_height(&self) -> f32 { - let mut height = self.view.base_height(); - match self.view { - View::Home => { - let known = self - .snapshot - .as_ref() - .map_or(0, |snapshot| snapshot.known_devices.len()); - height += ROW_HEIGHT * known.min(HOME_DEVICE_ROWS).saturating_sub(1) as f32; - if known > HOME_DEVICE_ROWS { - height += NOTE_HEIGHT; - } - if self.update.is_notice() { - height += NOTICE_HEIGHT; - if self.update.shows_bar() { - height += BAR_HEIGHT; - } - if matches!(self.update, UpdateState::Failed(_)) { - height += NOTE_HEIGHT * 2.0; - } - } - if native_problem(self.snapshot.as_ref()).is_some() { - height += NOTE_HEIGHT * 2.0; - } - if hid_blocked(self.snapshot.as_ref()) { - height += NOTICE_HEIGHT + NOTE_HEIGHT * 2.0; - if matches!(self.udev_fix, UdevFix::Failed { .. }) { - height += NOTE_HEIGHT * 2.0; - } - } - if self.first_run_hint { - height += NOTE_HEIGHT * 2.0; - } - if self.offers_whats_new() { - height += WHATS_NEW_HEIGHT; - } - } - View::Settings | View::Info | View::WhatsNew => {} - } - height - } - /// Installs the udev rule through `pkexec` on a thread of its own: the /// password prompt blocks until the user answers it. fn fix_hid_permissions(&mut self, cx: &mut Context) { @@ -584,6 +708,12 @@ impl PanelView { cx.notify(); } + fn set_always_on_top(&mut self, enabled: bool, window: &Window, cx: &mut Context) { + self.always_on_top = enabled; + super::tray::set_always_on_top(window, enabled); + cx.notify(); + } + fn set_automatic_updates(&mut self, enabled: bool, cx: &mut Context) { self.automatic_updates = enabled; let _ = self @@ -823,6 +953,9 @@ fn known_device_text(device: &KnownDeviceStatus) -> String { if let Some(dpi) = device.dpi { parts.push(format!("{dpi} DPI")); } + if let Some(rate) = device.polling_rate_hz { + parts.push(format!("{rate} Hz")); + } } else { parts.push(format!( "Last seen {}", @@ -873,6 +1006,7 @@ impl PanelView { .items_center() .gap_2() .py_1() + .window_control_area(WindowControlArea::Drag) .on_mouse_down(MouseButton::Left, |_, window, _| window.start_window_move()) .child(div().size(px(8.)).flex_none().rounded_full().bg(accent)) .child( @@ -1141,9 +1275,7 @@ impl PanelView { .primary() .compact() .label("Open OpenMouse") - .on_click(cx.listener(|_, _, _, cx| { - cx.open_url(OPENMOUSE_URL); - })), + .on_click(cx.listener(|this, _, _, cx| this.open_site(true, cx))), ) .child( Button::new("restart") @@ -1264,6 +1396,16 @@ impl PanelView { this.set_autostart(*enabled, cx); })), )) + .children(self.always_on_top_supported.then(|| { + switch_row( + "Always on top", + Switch::new("always-on-top") + .checked(self.always_on_top) + .on_change(cx.listener(|this, enabled: &bool, window, cx| { + this.set_always_on_top(*enabled, window, cx); + })), + ) + })) .child(switch_row( "Hybrid mode", Switch::new("hybrid-mode") @@ -1567,6 +1709,183 @@ impl PanelView { .child(self.title_bar("What's new", true, false, accent, muted, cx)) .child(notes) } + + fn welcome(&self, muted: Hsla, accent: Hsla, cx: &mut Context) -> Div { + let on_accent = cx.theme().primary_foreground; + let danger = cx.theme().danger; + let foreground = cx.theme().foreground; + let line = Hsla { a: 0.35, ..muted }; + let statuses = self.welcome_statuses(); + let all_done = statuses.iter().all(|status| *status == StepStatus::Done); + let failed = statuses.contains(&StepStatus::Failed); + let mut steps = div().flex().flex_col(); + for (index, ((heading, detail), status)) in WELCOME_STEPS.iter().zip(statuses).enumerate() { + let last = index + 1 == WELCOME_STEPS.len(); + let badge = div() + .flex() + .items_center() + .justify_center() + .rounded_full() + .text_sm() + .font_weight(FontWeight::SEMIBOLD); + let marker = div() + .size_6() + .flex() + .flex_none() + .items_center() + .justify_center(); + let marker = match status { + StepStatus::Done => marker.child( + badge + .bg(accent) + .text_color(on_accent) + .child("\u{2713}") + .with_animation( + SharedString::from(format!("welcome-done-{index}")), + Animation::new(Duration::from_millis(420)), + |badge, delta| { + let size = if delta < 0.6 { + 14.0 + delta / 0.6 * 13.0 + } else { + 27.0 - (delta - 0.6) / 0.4 * 3.0 + }; + badge.size(px(size)).opacity((0.4 + delta).min(1.0)) + }, + ), + ), + StepStatus::Current => marker.child( + badge + .size_6() + .bg(accent) + .text_color(on_accent) + .child(format!("{}", index + 1)) + .with_animation( + SharedString::from(format!("welcome-current-{index}")), + Animation::new(Duration::from_millis(1400)).repeat(), + |badge, delta| { + let wave = if delta < 0.5 { + delta * 2.0 + } else { + 2.0 - delta * 2.0 + }; + badge.opacity(0.55 + 0.45 * wave) + }, + ), + ), + StepStatus::Failed => { + marker.child(badge.size_6().bg(danger).text_color(on_accent).child("!")) + } + StepStatus::Pending => marker.child( + badge + .size_6() + .border_1() + .border_color(muted) + .text_color(muted) + .child(format!("{}", index + 1)), + ), + }; + let mut rail = div() + .flex() + .flex_col() + .items_center() + .w_6() + .flex_none() + .child(marker); + if !last { + rail = rail.child( + div() + .w(px(2.0)) + .flex_1() + .min_h(px(10.0)) + .mt_1() + .rounded_full() + .bg(if status == StepStatus::Done { + accent + } else { + line + }), + ); + } + let (heading_color, text_color, text) = match status { + StepStatus::Done => (foreground, muted, WELCOME_DONE[index]), + StepStatus::Current => (accent, muted, *detail), + StepStatus::Failed => (danger, danger, WELCOME_FAILED), + StepStatus::Pending => (muted, muted, *detail), + }; + let mut row = div() + .flex() + .flex_row() + .items_stretch() + .gap_3() + .child(rail) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap_1() + .child( + div() + .text_sm() + .font_weight(FontWeight::SEMIBOLD) + .text_color(heading_color) + .child(*heading), + ) + .child(div().text_xs().text_color(text_color).child(text)), + ); + if !last { + row = row.pb_4(); + } + steps = steps.child(row); + } + let intro = if all_done { + "All set. Bridge is connected and sees your mouse." + } else { + "Bridge lets OpenMouse in your browser talk to your mouse. Three quick steps:" + }; + let mut buttons = div().flex().flex_row().gap_2(); + buttons = if all_done { + buttons.child( + Button::new("welcome-done") + .primary() + .label("Done") + .on_click(cx.listener(|this, _, _, cx| this.show_view(View::Home, cx))), + ) + } else { + buttons + .child( + Button::new("welcome-open") + .primary() + .label(if failed { + "Try again" + } else { + "Open OpenMouse" + }) + .on_click(cx.listener(|this, _, _, cx| { + this.welcome_opened = true; + this.open_site(false, cx); + cx.notify(); + })), + ) + .child( + Button::new("welcome-skip") + .label("Skip") + .on_click(cx.listener(|this, _, _, cx| this.show_view(View::Home, cx))), + ) + }; + div() + .flex() + .flex_col() + .size_full() + .p_4() + .gap_4() + .child(self.title_bar("Welcome to Bridge", false, false, accent, muted, cx)) + .child(div().text_sm().text_color(muted).child(intro)) + .child(steps) + .child(div().flex_1()) + .child(buttons) + } } impl Render for PanelView { @@ -1586,18 +1905,33 @@ impl Render for PanelView { a: 0.35, ..theme.sidebar }; - // Keep the window as tall as its content so nothing is clipped. - let desired = self.desired_height(); + // Fit the window to its content: the height measured while drawing the + // last frame, so nothing is clipped and nothing is left empty. + self.always_on_top_supported = super::tray::always_on_top_supported(window); + let current = window.viewport_size().height.as_f32(); + let desired = self.content_height.get().map_or(current, |height| { + height.ceil().clamp(MIN_HEIGHT, MAX_HEIGHT) + }); if (window.viewport_size().height.as_f32() - desired).abs() > 1.0 { + if self.resize_bottom.is_none() { + self.resize_bottom = super::tray::bottom_edge(window); + } window.resize(size(px(WINDOW_WIDTH), px(desired))); + if let Some(bottom) = self.resize_bottom { + super::tray::set_bottom_edge(window, bottom, desired); + } super::tray::keep_on_screen(window, desired); + } else { + self.resize_bottom = None; } let field = self.field.element(window, cx); + let measured = self.content_height.clone(); let content = match self.view { View::Home => self.home(muted, accent, line, fill, cx), View::Settings => self.settings(muted, accent, line, fill, danger, cx), View::Info => self.info(muted, accent, line, fill, cx), View::WhatsNew => self.whats_new(muted, accent, cx), + View::Welcome => self.welcome(muted, accent, cx), }; // The ASCII field sits behind the content; the window's own Root paints // the background, so this shell stays clear. @@ -1617,7 +1951,25 @@ impl Render for PanelView { } })) .child(field) - .child(content) + .child( + div().relative().w_full().child(content).child( + canvas( + move |bounds, window, _| { + let height = bounds.size.height.as_f32(); + measured.set(Some(height)); + if (window.viewport_size().height.as_f32() - height.ceil()).abs() > 1.0 + { + window.request_animation_frame(); + } + }, + |_, _, _, _| {}, + ) + .absolute() + .top_0() + .left_0() + .size_full(), + ), + ) } } @@ -1625,8 +1977,100 @@ impl Render for PanelView { mod tests { // Not `use super::*`: that pulls in GPUI's own `test` macro, which shadows // `#[test]`. - use super::{UpdateState, offered_notes, step_threshold, step_volume}; + use super::{ + SITE_CONNECT_GRACE, SiteWait, StepStatus, UpdateState, known_device_text, offered_notes, + opening_notice, site_wait, step_threshold, step_volume, welcome_progress, + }; use crate::runtime::UpdateEvent; + use openmouse_bridge::service::{KnownDeviceState, KnownDeviceStatus}; + use std::time::{Duration, Instant}; + + #[test] + fn a_page_that_never_connects_is_reported_after_the_grace_period() { + let opened = Instant::now(); + assert_eq!(site_wait(None, false, opened), SiteWait::Idle); + assert_eq!(site_wait(Some(opened), false, opened), SiteWait::Waiting); + let almost = opened + SITE_CONNECT_GRACE - Duration::from_secs(1); + assert_eq!(site_wait(Some(opened), false, almost), SiteWait::Waiting); + let late = opened + SITE_CONNECT_GRACE; + assert_eq!(site_wait(Some(opened), false, late), SiteWait::TimedOut); + } + + #[test] + fn the_welcome_checklist_advances_one_step_at_a_time() { + use StepStatus::{Current, Done, Pending}; + assert_eq!( + welcome_progress(false, false, true, false), + [Current, Pending, Pending] + ); + assert_eq!( + welcome_progress(true, false, true, false), + [Done, Current, Pending] + ); + assert_eq!( + welcome_progress(true, true, false, false), + [Done, Done, Current] + ); + assert_eq!( + welcome_progress(true, true, true, false), + [Done, Done, Done] + ); + } + + #[test] + fn a_page_that_connects_completes_the_first_two_steps_even_if_the_button_was_not_used() { + use StepStatus::{Current, Done}; + assert_eq!( + welcome_progress(false, true, false, false), + [Done, Done, Current] + ); + } + + #[test] + fn a_timeout_fails_the_connection_step_only_while_it_is_the_current_one() { + use StepStatus::{Current, Done, Failed, Pending}; + assert_eq!( + welcome_progress(true, false, false, true), + [Done, Failed, Pending] + ); + assert_eq!( + welcome_progress(false, false, false, true), + [Current, Pending, Pending] + ); + assert_eq!( + welcome_progress(true, true, false, true), + [Done, Done, Current] + ); + } + + #[test] + fn the_welcome_steps_cover_opening_the_site_and_the_permission() { + let text: String = super::WELCOME_STEPS + .iter() + .map(|(heading, detail)| format!("{heading} {detail}")) + .collect::>() + .join(" "); + assert!(text.contains("Open OpenMouse")); + assert!(text.contains("Forever")); + } + + #[test] + fn opening_the_site_for_the_first_time_says_to_choose_forever() { + let notice = opening_notice(false).expect("a notice before any page has connected"); + assert!(notice.detail.contains("Forever")); + assert!( + opening_notice(true).is_none(), + "nothing to say once a page is connected" + ); + } + + #[test] + fn a_page_that_connects_in_time_cancels_the_wait() { + let opened = Instant::now(); + assert_eq!(site_wait(Some(opened), true, opened), SiteWait::Connected); + let late = opened + SITE_CONNECT_GRACE * 2; + assert_eq!(site_wait(Some(opened), true, late), SiteWait::Connected); + } #[test] fn the_alert_level_steps_along_the_offered_list() { @@ -1673,6 +2117,25 @@ mod tests { assert_eq!(offered_notes(&UpdateEvent::Checking), None); } + #[test] + fn a_connected_mouse_shows_battery_dpi_and_polling_rate() { + let mut device = KnownDeviceStatus { + id: "Logitech:PRO X3 SUPERSTRIKE".into(), + name: "PRO X3 SUPERSTRIKE".into(), + connected: true, + state: KnownDeviceState::Connected, + last_seen_seconds_ago: 0, + percent: Some(73), + charging: Some(false), + dpi: Some(1600), + polling_rate_hz: Some(4000), + switch_mode: None, + }; + assert_eq!(known_device_text(&device), "73% · 1600 DPI · 4000 Hz"); + device.polling_rate_hz = None; + assert_eq!(known_device_text(&device), "73% · 1600 DPI"); + } + #[test] fn only_work_in_progress_is_busy() { assert!(state(UpdateEvent::Checking).busy()); @@ -1684,15 +2147,9 @@ mod tests { } #[test] - fn home_gets_a_card_for_updates_that_need_attention_only() { - assert!(!UpdateState::Idle.is_notice()); - assert!(!state(UpdateEvent::Checking).is_notice()); - assert!(!state(UpdateEvent::UpToDate).is_notice()); - assert!(state(UpdateEvent::Downloading("2.0.0".into())).is_notice()); - assert!(state(UpdateEvent::Restarting("2.0.0".into())).is_notice()); - assert!(state(UpdateEvent::Failed("no network".into())).is_notice()); + fn a_ready_update_is_not_busy_and_has_no_bar() { let ready = state(UpdateEvent::Ready("2.0.0".into())); - assert!(ready.is_notice() && !ready.busy() && !ready.shows_bar()); + assert!(!ready.busy() && !ready.shows_bar()); assert_eq!( ready.headline(None).as_deref(), Some("Update 2.0.0 is ready") diff --git a/src/gpui_shell/tray.rs b/src/gpui_shell/tray.rs index 13196a5a..2792fa84 100644 --- a/src/gpui_shell/tray.rs +++ b/src/gpui_shell/tray.rs @@ -4,9 +4,13 @@ //! //! Linux uses StatusNotifierItem over D-Bus, without a GTK event loop. -use std::sync::{ - atomic::{AtomicBool, Ordering}, - mpsc, +use std::{ + sync::{ + Mutex, + atomic::{AtomicBool, Ordering}, + mpsc, + }, + time::{Duration, Instant}, }; #[cfg(any(target_os = "macos", windows))] @@ -29,6 +33,57 @@ pub struct Anchor { pub bottom: f64, } +#[cfg(any(windows, test))] +fn corner_x(icon_left: f64, icon_right: f64, work_left: f64, work_right: f64, width: f64) -> f64 { + if (icon_left + icon_right) / 2.0 >= (work_left + work_right) / 2.0 { + work_right - width + } else { + work_left + } +} + +#[cfg(any(windows, test))] +fn inside_area(anchor: &Anchor, left: f64, top: f64, right: f64, bottom: f64) -> bool { + anchor.left >= left && anchor.right <= right && anchor.top >= top && anchor.bottom <= bottom +} + +#[cfg(test)] +mod placement_tests { + use super::{Anchor, corner_x, inside_area}; + + #[test] + fn the_panel_sits_in_the_corner_on_the_side_of_the_tray() { + assert_eq!(corner_x(1560.0, 1584.0, 0.0, 1920.0, 360.0), 1560.0); + assert_eq!(corner_x(30.0, 54.0, 0.0, 1920.0, 360.0), 0.0); + } + + fn icon(left: f64, top: f64) -> Anchor { + Anchor { + left, + top, + right: left + 24.0, + bottom: top + 24.0, + } + } + + #[test] + fn an_icon_in_the_hidden_icons_flyout_is_inside_the_work_area() { + assert!(inside_area(&icon(1100.0, 590.0), 0.0, 0.0, 1920.0, 1032.0)); + } + + #[test] + fn an_icon_on_the_taskbar_is_outside_the_work_area() { + assert!(!inside_area( + &icon(1700.0, 1040.0), + 0.0, + 0.0, + 1920.0, + 1032.0 + )); + assert!(!inside_area(&icon(1900.0, 600.0), 0.0, 0.0, 1920.0, 1032.0)); + } +} + /// The tray icon, kept by the poll loop so it can show the battery on it. pub struct TrayHandle { #[cfg(target_os = "linux")] @@ -135,6 +190,18 @@ mod platform { } } + /// NSFloatingWindowLevel (3) keeps the panel above normal windows; + /// NSNormalWindowLevel is 0. + pub fn set_topmost(window: &Window, on: bool) { + if let Some(window) = ns_window(window) { + window.setLevel(if on { 3 } else { 0 }); + } + } + + pub fn supports_topmost(_window: &Window) -> bool { + true + } + pub fn show_window(window: &mut Window) -> bool { if let Some(window) = ns_window(window) { window.makeKeyAndOrderFront(None); @@ -201,15 +268,74 @@ mod platform { use windows_sys::Win32::{ Foundation::{POINT, RECT}, Graphics::Gdi::{ - GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTOPRIMARY, MONITORINFO, - MonitorFromPoint, MonitorFromRect, + GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITOR_DEFAULTTONULL, + MONITOR_DEFAULTTOPRIMARY, MONITORINFO, MonitorFromPoint, MonitorFromRect, }, + System::Threading::{AttachThreadInput, GetCurrentThreadId}, UI::WindowsAndMessaging::{ - GetWindowRect, SW_HIDE, SW_RESTORE, SWP_NOACTIVATE, SWP_NOSIZE, SWP_NOZORDER, - SetForegroundWindow, SetWindowPos, ShowWindow, + BringWindowToTop, GetForegroundWindow, GetWindowRect, GetWindowThreadProcessId, + HWND_NOTOPMOST, HWND_TOPMOST, SW_HIDE, SW_RESTORE, SWP_NOACTIVATE, SWP_NOMOVE, + SWP_NOSIZE, SWP_NOZORDER, SetForegroundWindow, SetWindowPos, ShowWindow, }, }; + use super::{corner_x, inside_area}; + + pub fn bottom_edge(window: &Window) -> Option { + let hwnd = hwnd_of(window)?; + let mut rect = RECT { + left: 0, + top: 0, + right: 0, + bottom: 0, + }; + if unsafe { GetWindowRect(hwnd, &mut rect) } == 0 { + return None; + } + let scale = f64::from(window.scale_factor()); + let client = (f64::from(window.viewport_size().height.as_f32()) * scale).round() as i32; + let frame = (rect.bottom - rect.top - client).max(0); + Some(rect.bottom - frame) + } + + pub fn set_bottom_edge(window: &Window, bottom: i32, height: f32) { + let Some(hwnd) = hwnd_of(window) else { + return; + }; + let height = (f64::from(height) * f64::from(window.scale_factor())).ceil() as i32; + let mut rect = RECT { + left: 0, + top: 0, + right: 0, + bottom: 0, + }; + if unsafe { GetWindowRect(hwnd, &mut rect) } == 0 { + return; + } + let mut info = MONITORINFO { + cbSize: std::mem::size_of::() as u32, + ..Default::default() + }; + let monitor = unsafe { MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST) }; + if unsafe { GetMonitorInfoW(monitor, &mut info) } == 0 { + return; + } + let y = (bottom - height).max(info.rcWork.top + MARGIN as i32); + if y != rect.top { + unsafe { + SetWindowPos( + hwnd, + std::ptr::null_mut(), + rect.left, + y, + 0, + 0, + SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, + ); + } + } + } + /// Slides the panel up when a window of `height` logical points, growing /// down from where it is now, would run past the work area's bottom edge. pub fn keep_on_screen(window: &Window, height: f32) { @@ -253,7 +379,7 @@ mod platform { } /// Distance kept from the work area's edges and from the icon, in pixels. - const MARGIN: f64 = 8.0; + const MARGIN: f64 = 24.0; fn hwnd_of(window: &Window) -> Option { match HasWindowHandle::window_handle(window).map(|handle| handle.as_raw()) { @@ -275,7 +401,17 @@ mod platform { if let Some(hwnd) = hwnd_of(window) { unsafe { ShowWindow(hwnd, SW_RESTORE); + let foreground = + GetWindowThreadProcessId(GetForegroundWindow(), std::ptr::null_mut()); + let current = GetCurrentThreadId(); + let attached = foreground != 0 + && foreground != current + && AttachThreadInput(current, foreground, 1) != 0; + BringWindowToTop(hwnd); SetForegroundWindow(hwnd); + if attached { + AttachThreadInput(current, foreground, 0); + } } } false @@ -290,14 +426,104 @@ mod platform { } } + pub fn supports_topmost(_window: &Window) -> bool { + true + } + + pub fn set_topmost(window: &Window, on: bool) { + if let Some(hwnd) = hwnd_of(window) { + unsafe { + SetWindowPos( + hwnd, + if on { HWND_TOPMOST } else { HWND_NOTOPMOST }, + 0, + 0, + 0, + 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE, + ); + } + } + } + + pub fn position(window: &Window) -> Option<(i32, i32)> { + let hwnd = hwnd_of(window)?; + let mut rect = RECT { + left: 0, + top: 0, + right: 0, + bottom: 0, + }; + (unsafe { GetWindowRect(hwnd, &mut rect) } != 0).then_some((rect.left, rect.top)) + } + + /// Where to put the panel. Moving a window onto a screen with another scale + /// sends it messages that re-enter GPUI, so the move is made by [`apply`] + /// outside any GPUI update, not while the panel is being placed. + pub struct Move { + pub hwnd: isize, + pub x: i32, + pub y: i32, + } + + pub fn apply(target: &Move) { + unsafe { + SetWindowPos( + target.hwnd as _, + std::ptr::null_mut(), + target.x, + target.y, + 0, + 0, + SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, + ); + } + } + + /// Where the panel goes when that spot is still on a screen, pulling it + /// inside the work area. False when no screen has that spot any more. + pub fn plan_restore(window: &Window, x: i32, y: i32) -> Option { + let hwnd = hwnd_of(window)?; + let mut rect = RECT { + left: 0, + top: 0, + right: 0, + bottom: 0, + }; + if unsafe { GetWindowRect(hwnd, &mut rect) } == 0 { + return None; + } + let (width, height) = (rect.right - rect.left, rect.bottom - rect.top); + let target = RECT { + left: x, + top: y, + right: x + width, + bottom: y + height, + }; + let monitor = unsafe { MonitorFromRect(&target, MONITOR_DEFAULTTONULL) }; + let mut info = MONITORINFO { + cbSize: std::mem::size_of::() as u32, + ..Default::default() + }; + if monitor.is_null() || unsafe { GetMonitorInfoW(monitor, &mut info) } == 0 { + return None; + } + let work = info.rcWork; + let x = x.min(work.right - width).max(work.left); + let y = y.min(work.bottom - height).max(work.top); + Some(Move { + hwnd: hwnd as isize, + x, + y, + }) + } + /// Puts the panel's right edge on the icon's, above it when the icon is in /// the lower half of its screen (a bottom taskbar) and below it otherwise, /// kept inside the work area. With no click to go by it goes to the primary /// screen's bottom-right corner. - pub fn place_near_tray(window: &Window, anchor: Option) { - let Some(hwnd) = hwnd_of(window) else { - return; - }; + pub fn plan_near_tray(window: &Window, anchor: Option) -> Option { + let hwnd = hwnd_of(window)?; let scale = f64::from(window.scale_factor()); let size = window.bounds().size; let (width, height) = ( @@ -323,18 +549,21 @@ mod platform { } }; if unsafe { GetMonitorInfoW(monitor, &mut info) } == 0 { - return; + return None; } let work = info.rcWork; let (work_left, work_top) = (f64::from(work.left), f64::from(work.top)); let (work_right, work_bottom) = (f64::from(work.right), f64::from(work.bottom)); - let icon = anchor.unwrap_or(Anchor { + let in_flyout = anchor + .as_ref() + .is_some_and(|icon| inside_area(icon, work_left, work_top, work_right, work_bottom)); + let icon = anchor.filter(|_| !in_flyout).unwrap_or(Anchor { left: work_right, top: work_bottom, right: work_right, bottom: work_bottom, }); - let x = icon.right - width; + let x = corner_x(icon.left, icon.right, work_left, work_right, width); let y = if (icon.top + icon.bottom) / 2.0 > (work_top + work_bottom) / 2.0 { icon.top - height - MARGIN } else { @@ -343,17 +572,11 @@ mod platform { let clamp = |value: f64, low: f64, high: f64| value.clamp(low, high.max(low)); let x = clamp(x, work_left + MARGIN, work_right - width - MARGIN); let y = clamp(y, work_top + MARGIN, work_bottom - height - MARGIN); - unsafe { - SetWindowPos( - hwnd, - std::ptr::null_mut(), - x as i32, - y as i32, - 0, - 0, - SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE, - ); - } + Some(Move { + hwnd: hwnd as isize, + x: x as i32, + y: y as i32, + }) } } @@ -408,6 +631,29 @@ mod platform { } } } + /// A layer-shell panel is already on the compositor's top layer; an X11 + /// window asks its window manager. A plain Wayland window cannot. + pub fn supports_topmost(window: &Window) -> bool { + super::layer_panel() + || matches!( + HasWindowHandle::window_handle(window).map(|handle| handle.as_raw()), + Ok(raw_window_handle::RawWindowHandle::Xcb(_)) + ) + } + + pub fn set_topmost(window: &Window, on: bool) { + if super::layer_panel() { + return; + } + let Ok(handle) = HasWindowHandle::window_handle(window).map(|handle| handle.as_raw()) + else { + return; + }; + if let Err(error) = super::linux::set_x11_above(handle, on) { + tracing::warn!(%error, "Could not change whether the panel stays on top"); + } + } + // Wayland compositors control top-level placement; do not interpret the // host's coordinate hints as portable window positions. pub fn place_near_tray(_window: &Window, _anchor: Option) {} @@ -424,12 +670,21 @@ mod platform { false } pub fn place_near_tray(_window: &Window, _anchor: Option) {} + pub fn set_topmost(_window: &Window, _on: bool) {} + pub fn supports_topmost(_window: &Window) -> bool { + false + } } /// Whether the panel is on screen. While it is hidden in the tray nothing /// repaints it. Stays true where there is no tray to hide it to. static VISIBLE: AtomicBool = AtomicBool::new(true); +/// Set once the panel has been put somewhere on purpose, so the spot it first +/// opened at (hidden at start, centred by the system) is never remembered. +#[cfg(windows)] +static PLACED: AtomicBool = AtomicBool::new(false); + /// Whether the panel was last shown rather than hidden through [`show`] and /// [`hide`], which is what a click on the icon toggles. Unlike [`is_visible`] /// this does not assume a Linux window is on screen. @@ -572,7 +827,57 @@ pub fn can_hide() -> bool { cfg!(any(target_os = "macos", windows)) } +/// When the panel last hid itself because it lost focus. +static HIDDEN_ON_BLUR_AT: Mutex> = Mutex::new(None); + +/// How soon after the panel hides on losing focus a click on the icon counts +/// as the click that took the focus: pressing the icon takes focus from the +/// panel before the click arrives, and that click should leave it closed. +const BLUR_CLICK_WINDOW: Duration = Duration::from_millis(500); + +/// Whether the panel hides when it loses focus, like a popup: where it sits by +/// the tray and the icon brings it back. Not for a normal Linux window (no +/// layer-shell), which has a taskbar entry and stays where it was put. +pub fn hides_on_blur() -> bool { + #[cfg(target_os = "linux")] + { + layer_panel() && can_hide() + } + #[cfg(not(target_os = "linux"))] + can_hide() +} + +/// Hides the panel because a click elsewhere took its focus. +pub fn hide_on_blur(window: &mut Window) { + if !shown() { + return; + } + hide(window); + if let Ok(mut at) = HIDDEN_ON_BLUR_AT.lock() { + *at = Some(Instant::now()); + } +} + +/// What a click on the icon sends: a toggle, or nothing when the panel has +/// just hidden because pressing the icon took its focus. +pub fn click_command(anchor: Option) -> Option { + let just_hidden = HIDDEN_ON_BLUR_AT + .lock() + .ok() + .and_then(|mut at| at.take()) + .is_some_and(|at| at.elapsed() < BLUR_CLICK_WINDOW); + (!just_hidden).then_some(Command::Toggle(anchor)) +} + pub fn hide(window: &mut Window) { + #[cfg(windows)] + if let Some((x, y)) = PLACED + .load(Ordering::Relaxed) + .then(|| platform::position(window)) + .flatten() + { + save_position(x, y); + } platform::hide_window(window); #[cfg(any(target_os = "macos", windows, target_os = "linux"))] VISIBLE.store(false, Ordering::Relaxed); @@ -581,10 +886,28 @@ pub fn hide(window: &mut Window) { /// Moves the panel beside the tray icon (see [`Anchor`]); without an anchor, /// to the tray's usual corner of the main screen. #[cfg_attr(target_os = "linux", allow(dead_code))] +#[cfg(not(windows))] pub fn place(window: &Window, anchor: Option) { platform::place_near_tray(window, anchor); } +/// Where the panel goes on Windows: where it was left, else beside the tray. +/// The move itself is made by [`apply_move`], called outside any GPUI update. +#[cfg(windows)] +pub fn plan_place(window: &Window, anchor: Option) -> Option { + PLACED.store(true, Ordering::Relaxed); + saved_position() + .and_then(|(x, y)| platform::plan_restore(window, x, y)) + .or_else(|| platform::plan_near_tray(window, anchor)) +} + +#[cfg(windows)] +pub fn apply_move(target: Option) { + if let Some(target) = target { + platform::apply(&target); + } +} + /// After the panel grows (opening Settings), keeps its bottom edge on screen. /// Only Windows needs this: it grows down from a fixed top-left corner. pub fn keep_on_screen(window: &Window, height: f32) { @@ -594,8 +917,97 @@ pub fn keep_on_screen(window: &Window, height: f32) { let _ = (window, height); } +pub fn bottom_edge(window: &Window) -> Option { + #[cfg(windows)] + { + platform::bottom_edge(window) + } + #[cfg(not(windows))] + { + let _ = window; + None + } +} + +pub fn set_bottom_edge(window: &Window, bottom: i32, height: f32) { + #[cfg(windows)] + platform::set_bottom_edge(window, bottom, height); + #[cfg(not(windows))] + let _ = (window, bottom, height); +} + +static ALWAYS_ON_TOP: AtomicBool = AtomicBool::new(false); + +fn always_on_top_file() -> Option { + Some( + crate::config::config_path() + .ok()? + .parent()? + .join("always-on-top.txt"), + ) +} + +/// Reads the saved "always on top" choice; the panel does this once at start. +pub fn load_always_on_top() -> bool { + let on = always_on_top_file() + .and_then(|file| std::fs::read_to_string(file).ok()) + .is_some_and(|text| text.trim() == "1"); + ALWAYS_ON_TOP.store(on, Ordering::Relaxed); + on +} + +/// Whether the panel stays above other windows; it then also stays open when +/// it loses focus. +pub fn always_on_top() -> bool { + ALWAYS_ON_TOP.load(Ordering::Relaxed) +} + +pub fn set_always_on_top(window: &Window, on: bool) { + ALWAYS_ON_TOP.store(on, Ordering::Relaxed); + if let Some(file) = always_on_top_file() { + let _ = std::fs::write(file, if on { "1" } else { "0" }); + } + platform::set_topmost(window, on); +} + +/// Whether the panel can stay above other windows here, which decides if +/// Settings offers the switch. +pub fn always_on_top_supported(window: &Window) -> bool { + platform::supports_topmost(window) +} + +#[cfg(windows)] +fn position_file() -> Option { + Some( + crate::config::config_path() + .ok()? + .parent()? + .join("window-position.txt"), + ) +} + +#[cfg(windows)] +fn save_position(x: i32, y: i32) { + if let Some(file) = position_file() { + let _ = std::fs::write(file, format!("{x} {y}")); + } +} + +#[cfg(windows)] +fn saved_position() -> Option<(i32, i32)> { + let text = std::fs::read_to_string(position_file()?).ok()?; + let (x, y) = text.trim().split_once(' ')?; + Some((x.parse().ok()?, y.parse().ok()?)) +} + pub fn show(window: &mut Window, anchor: Option) { - platform::place_near_tray(window, anchor); + #[cfg(not(windows))] + place(window, anchor); + #[cfg(windows)] + let _ = anchor; + if cfg!(windows) || always_on_top() { + platform::set_topmost(window, always_on_top()); + } if !platform::show_window(window) { window.activate_window(); } @@ -631,6 +1043,32 @@ fn build_icon() -> Option { builder.build().ok() } +/// Moves the icon out of the hidden-icons flyout once per executable, so putting +/// it back there in Windows settings is not undone at the next start. +#[cfg(windows)] +fn promote_icon_once() { + let Ok(executable) = std::env::current_exe() else { + return; + }; + let executable = executable.to_string_lossy().to_lowercase(); + let Some(marker) = crate::config::config_path() + .ok() + .and_then(|path| Some(path.parent()?.join("tray-icon-promoted.txt"))) + else { + return; + }; + if std::fs::read_to_string(&marker).is_ok_and(|done| done.trim() == executable) { + return; + } + for _ in 0..20 { + if openmouse_bridge::platform::promote_tray_icon() { + let _ = std::fs::write(&marker, &executable); + return; + } + std::thread::sleep(std::time::Duration::from_secs(1)); + } +} + /// Creates the tray icon and makes closing `window` hide it. Returns the /// channel its clicks and menu items arrive on and the icon itself, or `None` /// when there is no tray (then closing the window still quits). @@ -644,6 +1082,8 @@ pub fn install( use tray_icon::{MouseButton, MouseButtonState, TrayIconEvent}; let tray = build_icon()?; + #[cfg(windows)] + std::thread::spawn(promote_icon_once); // The handlers run on the main thread inside the platform's event // dispatch; they only queue a command for the poll loop in `run`. @@ -721,11 +1161,14 @@ pub fn install( _ => return, }; let anchor = Some(anchor); - let _ = sender.send(if double_click { - Command::Show(anchor) + let command = if double_click { + Some(Command::Show(anchor)) } else { - Command::Toggle(anchor) - }); + click_command(anchor) + }; + if let Some(command) = command { + let _ = sender.send(command); + } } })); diff --git a/src/gpui_shell/tray_linux.rs b/src/gpui_shell/tray_linux.rs index 4d086f98..b4791947 100644 --- a/src/gpui_shell/tray_linux.rs +++ b/src/gpui_shell/tray_linux.rs @@ -44,6 +44,51 @@ pub(super) fn restore_x11_window(handle: raw_window_handle::RawWindowHandle) -> Ok(()) } +/// Asks the window manager to keep the X11 panel above other windows, or to +/// stop, with a `_NET_WM_STATE` request for `_NET_WM_STATE_ABOVE`. +pub(super) fn set_x11_above(handle: raw_window_handle::RawWindowHandle, on: bool) -> Result<()> { + use raw_window_handle::RawWindowHandle; + use x11rb::{ + connection::Connection as _, + protocol::xproto::{ClientMessageEvent, ConnectionExt as _, EventMask}, + }; + + let RawWindowHandle::Xcb(handle) = handle else { + return Ok(()); + }; + let (connection, screen) = x11rb::connect(None).context("could not open the X display")?; + let root = connection + .setup() + .roots + .get(screen) + .context("the X display has no screen")? + .root; + let state = connection + .intern_atom(false, b"_NET_WM_STATE")? + .reply()? + .atom; + let above = connection + .intern_atom(false, b"_NET_WM_STATE_ABOVE")? + .reply()? + .atom; + let event = ClientMessageEvent::new( + 32, + handle.window.get(), + state, + [u32::from(on), above, 0, 1, 0], + ); + connection + .send_event( + false, + root, + EventMask::SUBSTRUCTURE_REDIRECT | EventMask::SUBSTRUCTURE_NOTIFY, + event, + )? + .check() + .context("could not ask the window manager to change the stacking")?; + Ok(()) +} + /// The XDG activation token the tray host sent with the last click, kept until /// the panel is shown. On Wayland only a token from the user's click lets the /// compositor raise (and un-minimize) the panel. @@ -290,7 +335,9 @@ impl Tray for LinuxTray { right: f64::from(x), bottom: f64::from(y), }); - let _ = self.sender.send(Command::Toggle(anchor)); + if let Some(command) = super::click_command(anchor) { + let _ = self.sender.send(command); + } } fn menu(&self) -> Vec> { use ksni::menu::StandardItem; diff --git a/src/hid.rs b/src/hid.rs index 73762a8a..23839ef6 100644 --- a/src/hid.rs +++ b/src/hid.rs @@ -109,7 +109,7 @@ fn note_session_ended(session_id: u64) { } /// The devices the control panel currently holds open over native HID, most -/// recently opened first. Empty when no HID session has a device open — e.g. +/// recently opened first. Empty when no HID session has a device open - e.g. /// a wired mouse that was never opened still leaves no trace here, which is /// why callers fall back to the battery list and the active profile. pub fn active_devices() -> Vec { @@ -382,7 +382,7 @@ impl ReaderHandle { // The handle is shared with send_report, and std's Mutex is not // fair: a reader that blocks in read_timeout while holding the // lock, then immediately re-locks, can starve a writer for many - // seconds — and the writer holds the session lock meanwhile, so + // seconds - and the writer holds the session lock meanwhile, so // every other command (even `list`) stalls behind it. Read without // blocking under the lock and idle with it released instead. #[cfg(not(target_os = "windows"))] diff --git a/src/platform/mod.rs b/src/platform/mod.rs index 04477d4e..87525a12 100644 --- a/src/platform/mod.rs +++ b/src/platform/mod.rs @@ -17,7 +17,7 @@ mod portable; #[cfg(target_os = "windows")] pub use windows::{ autostart_enabled, battery_icon_rgba, light_tray_theme, linux_distribution, platform_name, - set_autostart, tray_icon_size, + promote_tray_icon, set_autostart, tray_icon_size, }; #[cfg(target_os = "macos")] diff --git a/src/platform/windows.rs b/src/platform/windows.rs index 3b4270ce..4733b29f 100644 --- a/src/platform/windows.rs +++ b/src/platform/windows.rs @@ -10,8 +10,9 @@ use windows_sys::Win32::{ OUT_TT_PRECIS, SelectObject, }, System::Registry::{ - HKEY_CURRENT_USER, REG_SZ, RRF_RT_REG_DWORD, RRF_RT_REG_SZ, RegDeleteKeyValueW, - RegGetValueW, RegSetKeyValueW, + HKEY_CURRENT_USER, KEY_READ, REG_DWORD, REG_SZ, RRF_RT_REG_DWORD, RRF_RT_REG_SZ, + RegCloseKey, RegDeleteKeyValueW, RegEnumKeyExW, RegGetValueW, RegOpenKeyExW, + RegSetKeyValueW, }, UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSMICON}, }; @@ -84,11 +85,11 @@ pub fn battery_glyph(percent: u8, charging: bool) -> u32 { } /// Renders the tray battery display as a square `size` × `size` RGBA -/// buffer, tinted with `ink` — the Windows 11 taskbar only renders square +/// buffer, tinted with `ink` - the Windows 11 taskbar only renders square /// tray icons faithfully. The `style` picks what fills the square: the /// Segoe Fluent battery glyph for the level (the charging variant with the /// bolt when `charging`), or the percentage number in bold UI text (the -/// `%` is left off — at tray sizes it would shrink the digits to a +/// `%` is left off - at tray sizes it would shrink the digits to a /// squint; the tooltip spells the full `NN%` out). Returns the buffer with /// its width and height. `Segoe Fluent Icons` ships with Windows 11; /// `Segoe MDL2 Assets` carries the same glyphs on Windows 10. @@ -206,7 +207,7 @@ fn compose_battery_display( // Otherwise the digits fill it. if label.is_empty() { // A landscape glyph in a square icon: fitting its width to all but - // 1px of the canvas — the footprint the old square renderer used — + // 1px of the canvas - the footprint the old square renderer used - // is the largest it can be, and the height lands near half. let battery = fit_and_rasterize( dc, @@ -231,7 +232,7 @@ fn compose_battery_display( return Ok((canvas.rgba, height, height)); } - // The digits are drawn as tall as the square allows — a 2px margin — + // The digits are drawn as tall as the square allows - a 2px margin - // and squeezed proportionally when the string is wider than tall // ("100" is, at every size that matters). let mut target = height.saturating_sub(4).max(8); @@ -267,7 +268,7 @@ struct LabelRaster { /// Rasterizes the label into one tight coverage bitmap in a bold UI face, /// sized so a digit stands `target` pixels tall. Characters are placed by -/// the font's own advances and side bearings, top-aligned — digits and +/// the font's own advances and side bearings, top-aligned - digits and /// `%` share the cap height, so the row lines up. fn rasterize_label(dc: HDC, label: &[u16], family: &[u16], target: u32) -> Option { if label.is_empty() { @@ -399,8 +400,8 @@ impl Canvas { } /// Fits the font so the battery glyph's visible bounds span `target` -/// pixels wide — the right fit for a landscape glyph in a square icon (the -/// fit loop accepts within a pixel) — then rasterizes the glyph as an +/// pixels wide - the right fit for a landscape glyph in a square icon (the +/// fit loop accepts within a pixel) - then rasterizes the glyph as an /// 8-bit coverage bitmap. `None` when the font or glyph is missing. fn fit_and_rasterize( dc: HDC, @@ -461,13 +462,13 @@ fn fit_and_rasterize( /// Rasterizes the glyph as an 8-bit grayscale coverage bitmap /// (`GGO_GRAY8_BITMAP`): GDI's own anti-aliased glyph raster, no drawing /// surface involved. GDI writes the bitmap's *actual* bounds back into -/// `metrics` — which can come back a pixel wider than `GGO_METRICS` +/// `metrics` - which can come back a pixel wider than `GGO_METRICS` /// reported (the anti-aliased edge column), so the caller must lay the /// buffer out by the written-back values or every row skews. fn glyph_bitmap(dc: HDC, codepoint: u32, metrics: &mut GLYPHMETRICS) -> Option> { // SAFETY: `dc` is a live DC with a font selected; the metrics and // matrix structs are valid for the call and the buffer is sized to hold - // the reported black box (rows are DWORD-aligned) plus slack — GDI + // the reported black box (rows are DWORD-aligned) plus slack - GDI // rejects an exact-size buffer for some glyphs, asking for a few bytes // more than stride × rows. unsafe { @@ -585,6 +586,93 @@ pub fn set_autostart(enabled: bool) -> Result<()> { Err(registry_error(result)).context("Windows rejected the autostart change") } +const NOTIFY_ICONS_SUBKEY: &str = r"Control Panel\NotifyIconSettings"; + +/// Asks Windows 11 to show Bridge's tray icon on the taskbar instead of in the +/// hidden-icons flyout. True once the icon's entry has been found, false while +/// Windows has not listed it yet. The caller does this once per executable so a +/// later choice in Settings sticks. +pub fn promote_tray_icon() -> bool { + let Ok(executable) = env::current_exe() else { + return true; + }; + let executable = executable.to_string_lossy().to_lowercase(); + let root = wide(NOTIFY_ICONS_SUBKEY); + let mut key = null_mut(); + if unsafe { RegOpenKeyExW(HKEY_CURRENT_USER, root.as_ptr(), 0, KEY_READ, &mut key) } + != ERROR_SUCCESS + { + return true; + } + let mut found = false; + let mut index = 0; + loop { + let mut name = [0u16; 256]; + let mut length = name.len() as u32; + let status = unsafe { + RegEnumKeyExW( + key, + index, + name.as_mut_ptr(), + &mut length, + null_mut(), + null_mut(), + null_mut(), + null_mut(), + ) + }; + if status != ERROR_SUCCESS { + break; + } + index += 1; + let entry = format!( + "{NOTIFY_ICONS_SUBKEY}\\{}", + String::from_utf16_lossy(&name[..length as usize]) + ); + if notify_icon_path(&entry).is_some_and(|path| path.to_lowercase() == executable) { + found = true; + let subkey = wide(&entry); + let value_name = wide("IsPromoted"); + let promoted = 1u32; + unsafe { + RegSetKeyValueW( + HKEY_CURRENT_USER, + subkey.as_ptr(), + value_name.as_ptr(), + REG_DWORD, + (&promoted as *const u32).cast(), + size_of::() as u32, + ); + } + } + } + unsafe { RegCloseKey(key) }; + found +} + +fn notify_icon_path(entry: &str) -> Option { + let subkey = wide(entry); + let value_name = wide("ExecutablePath"); + let mut buffer = [0u16; 1024]; + let mut byte_count = std::mem::size_of_val(&buffer) as u32; + let status = unsafe { + RegGetValueW( + HKEY_CURRENT_USER, + subkey.as_ptr(), + value_name.as_ptr(), + RRF_RT_REG_SZ, + null_mut(), + buffer.as_mut_ptr().cast(), + &mut byte_count, + ) + }; + if status != ERROR_SUCCESS { + return None; + } + let length = (byte_count as usize / size_of::()).saturating_sub(1); + Some(String::from_utf16_lossy(&buffer[..length])) +} + fn wide(value: impl AsRef) -> Vec { value.as_ref().encode_wide().chain(Some(0)).collect() } @@ -627,7 +715,7 @@ mod tests { assert_eq!(rgba.len(), (size * size * 4) as usize); let coverage = |x: u32, y: u32| rgba[((y * size + x) * 4 + 3) as usize]; // The glyph's visible bounds fill the canvas: across the - // middle row, the covered span (first to last covered pixel — + // middle row, the covered span (first to last covered pixel - // the battery's body-to-nub gap doesn't count against it) is // at most two blank columns short of the full width. let row = size / 2; diff --git a/src/service.rs b/src/service.rs index 7696300e..0b0716b1 100644 --- a/src/service.rs +++ b/src/service.rs @@ -142,7 +142,7 @@ const BATTERY_TREND_WINDOW: Duration = Duration::from_secs(6 * 60 * 60); const BATTERY_MIN_TREND_SPAN: Duration = Duration::from_secs(30 * 60); /// The smallest drift (percent per minute) that counts as a trend, about 1% -/// per 3 hours — the pace a mouse battery actually moves at. +/// per 3 hours - the pace a mouse battery actually moves at. const BATTERY_TREND_EPSILON: f64 = 0.005; /// Estimates beyond this are noise for a mouse battery, not a plan. @@ -455,13 +455,13 @@ fn switch_message( match outcome { Some(ApplyOutcome::Failed) => { switch.detail = if current.is_none() { - "Couldn't restore original mouse settings — check Bridge status".into() + "Couldn't restore original mouse settings - check Bridge status".into() } else { - "Couldn't reach the mouse — open OpenMouse to apply".into() + "Couldn't reach the mouse - open OpenMouse to apply".into() }; } Some(ApplyOutcome::NoDriver) => { - switch.detail = "Bridge can't drive this mouse — open OpenMouse to apply".into(); + switch.detail = "Bridge can't drive this mouse - open OpenMouse to apply".into(); } _ => {} } @@ -519,7 +519,7 @@ struct BridgeState { active_games: Vec, processes: Vec, applications: Vec, - // Every visible application, registered game or not — what a control + // Every visible application, registered game or not - what a control // panel offers when someone requests a new game or app be added. running_applications: Vec, application_icons: HashMap>>, @@ -573,7 +573,7 @@ pub struct BatteryReading { #[serde(default)] pub charging: bool, /// The settings currently in the mouse's onboard memory, when the - /// reader could see them — native reads report them; a control panel's + /// reader could see them - native reads report them; a control panel's /// `PUT /v1/battery` may not. #[serde(default)] pub dpi: Option, @@ -607,7 +607,7 @@ struct BatteryState { /// Estimates the minutes left until the battery is empty (discharging) or /// full (charging) from the percent history: the level's drift across the /// samples inside the trend window. `None` while there is no confident -/// trend yet — too little history, or the level is holding still. +/// trend yet - too little history, or the level is holding still. fn estimate_minutes_remaining( history: &VecDeque<(Instant, u8)>, percent: u8, @@ -660,8 +660,8 @@ pub struct DeviceBattery { } /// A mouse the control panel currently holds open over native HID, most -/// recently opened first. Unlike the battery list — which accumulates every -/// device that ever reported a charge level — this reflects the live HID +/// recently opened first. Unlike the battery list - which accumulates every +/// device that ever reported a charge level - this reflects the live HID /// session, so the status view can follow device switches (including wired /// mice that never report battery). #[derive(Clone, Debug, Serialize)] @@ -1635,10 +1635,10 @@ impl BridgeService { } match mode { DeviceMode::Live => { - tracing::info!("the web panel connected — it drives the mouse live now"); + tracing::info!("the web panel connected - it drives the mouse live now"); } DeviceMode::Onboard => { - tracing::info!("the web panel disconnected — resuming onboard memory mode"); + tracing::info!("the web panel disconnected - resuming onboard memory mode"); let hybrid = service.inner.read().await.config.hybrid_mode; if !hybrid { continue; @@ -1800,7 +1800,7 @@ impl BridgeService { )> = None; if !state.profile_seeded { // Adopt the initial profile silently so startup is quiet, - // but still push it to the mouse — Bridge should reflect + // but still push it to the mouse - Bridge should reflect // the right settings from a cold start, not only switches. state.active_profile_key = current_key; state.applied_profile = current.clone(); @@ -1862,7 +1862,7 @@ impl BridgeService { /// One battery-polling pass: covers every device named by the saved profiles /// plus every mouse Bridge discovered on the HID bus whose brand no profile /// already names, reads each mouse's battery natively (skipped while the web -/// panel holds the session — it reports the battery itself over +/// panel holds the session - it reports the battery itself over /// `PUT /v1/battery`) and records it. Used by the five-minute monitor and by /// onboard-mode handovers. /// Writes devices.json; a failure is logged and never stops Bridge. @@ -2140,7 +2140,7 @@ fn canonical_battery_identity(device_id: &str, reported_name: &str) -> String { } /// The devices battery polling should cover: the saved profiles' devices plus -/// discovered mice whose brand no profile already names — discovery fills the +/// discovered mice whose brand no profile already names - discovery fills the /// gap before the panel has ever saved a profile, without double-reporting a /// mouse a profile already covers (profile and discovery ids for the same /// physical mouse differ, so brand-level dedup keeps one battery entry). @@ -2163,7 +2163,7 @@ fn merge_detected_mice( } /// Enters onboard memory mode: pushes the stored settings to the mouse's -/// onboard memory (when a default profile exists — without one, the device +/// onboard memory (when a default profile exists - without one, the device /// simply keeps the memory it already has) and reads the battery right away. /// Shared by the startup seed and the panel-disconnect handover. async fn resume_onboard(service: &BridgeService) { @@ -2953,13 +2953,13 @@ mod tests { switch_message(Some(&game), None, None, Some(ApplyOutcome::Failed), false).unwrap(); assert_eq!( notice.detail, - "Couldn't restore original mouse settings — check Bridge status" + "Couldn't restore original mouse settings - check Bridge status" ); let unsupported = switch_message(None, Some(&game), None, Some(ApplyOutcome::NoDriver), false).unwrap(); assert_eq!( unsupported.detail, - "Bridge can't drive this mouse — open OpenMouse to apply" + "Bridge can't drive this mouse - open OpenMouse to apply" ); } @@ -3010,7 +3010,7 @@ mod tests { switch_message(None, Some(&game), None, failed, false) .unwrap() .detail, - "Couldn't reach the mouse — open OpenMouse to apply" + "Couldn't reach the mouse - open OpenMouse to apply" ); assert_eq!( switch_message(None, Some(&game), None, failed, true) diff --git a/src/tray_battery.rs b/src/tray_battery.rs index b477fade..a775cc63 100644 --- a/src/tray_battery.rs +++ b/src/tray_battery.rs @@ -107,7 +107,7 @@ pub fn remaining_text(minutes: u32) -> String { } } -/// `Device — 87% · Charging · full in 45 m`. +/// `Device - 87% · Charging · full in 45 m`. pub fn tooltip(battery: &TrayBattery) -> String { let status = match (battery.charging, battery.stale) { (true, _) => " · Charging", @@ -123,10 +123,10 @@ pub fn tooltip(battery: &TrayBattery) -> String { }); let text = match estimate { Some(estimate) => format!( - "{} — {}%{status} · {estimate}", + "{} - {}%{status} · {estimate}", battery.device_name, battery.percent ), - None => format!("{} — {}%{status}", battery.device_name, battery.percent), + None => format!("{} - {}%{status}", battery.device_name, battery.percent), }; text.chars().take(TOOLTIP_CHARS).collect() } @@ -201,18 +201,18 @@ mod tests { #[test] fn the_tooltip_spells_out_the_state() { - assert_eq!(tooltip(&tray(87, false, false, None)), "Mouse — 87%"); + assert_eq!(tooltip(&tray(87, false, false, None)), "Mouse - 87%"); assert_eq!( tooltip(&tray(87, true, false, Some(45))), - "Mouse — 87% · Charging · full in 45 m" + "Mouse - 87% · Charging · full in 45 m" ); assert_eq!( tooltip(&tray(40, false, false, Some(150))), - "Mouse — 40% · 2 h 30 m left" + "Mouse - 40% · 2 h 30 m left" ); assert_eq!( tooltip(&tray(40, false, true, None)), - "Mouse — 40% · Not updating" + "Mouse - 40% · Not updating" ); }