From 0ad72faeee64199f257eea693ea73e3032300f35 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 14:00:59 +0100 Subject: [PATCH 1/6] feat: VIA keyboards, Logitech onboard profiles and tools, tray pin - VIA keyboards: keymap, layers and knobs, Lighting tab, keyboard macros, full-size picture - Logitech: DPI, polling rate and lift-off in onboard mode are written into the running profile instead of switching the mouse to host mode; gaming surface no longer shows a false switch to host - Logitech: website-style DPI stage editor on Performance (5 slots, starting stage, separate X/Y with link toggle, typed values, autosave) - Logitech: DPI writes and stage saves snap to values the mouse accepts - Logitech profiles: rename with the pencil on each card, turn profiles on or off, restore the factory profiles (or set up a mouse with none) - Logitech: live press depth for hall-effect buttons, Easy-Switch, haptics test, give back buttons another app diverted - A queued left-click rescue runs on the mouse it was meant for after switching mice instead of being dropped - Read back after profile writes retries while the device is busy - TextDecoder shim decodes UTF-16LE, so profile names read back in full - Tray: option to keep the icon on the taskbar (Windows) - Credits: add onyxhq-dev --- .gitattributes | 2 +- README.md | 14 +- crates/openmouse-hid/src/hid_descriptor.rs | 10 +- crates/openmouse-hid/src/lib.rs | 172 +++---- crates/openmouse-presence/src/lib.rs | 2 +- gpui/examples/chime_demo.rs | 2 +- gpui/examples/hid_button.rs | 2 +- gpui/examples/hid_onboard.rs | 2 +- gpui/examples/hid_probe.rs | 2 +- gpui/examples/hid_profile.rs | 2 +- gpui/examples/hid_rescan.rs | 2 +- gpui/examples/hid_tabs.rs | 2 +- gpui/examples/hid_write.rs | 2 +- gpui/examples/overlay_demo.rs | 4 +- gpui/examples/usb_topology.rs | 2 +- gpui/installer/Cargo.toml | 6 +- gpui/installer/build.rs | 4 +- gpui/installer/src/colors.rs | 6 +- gpui/installer/src/main.rs | 12 +- gpui/installer/src/paths.rs | 2 +- gpui/installer/src/registry.rs | 2 +- gpui/installer/src/shortcuts.rs | 2 +- gpui/js/controls.ts | 28 +- gpui/js/depth-stream.ts | 13 +- gpui/js/entry.ts | 94 +++- gpui/js/extra-controls.ts | 4 +- gpui/js/globals.ts | 8 + gpui/js/keyboard-via.ts | 379 +++++++++++++++ gpui/js/keyboards.ts | 31 +- gpui/js/lib/changelog.ts | 2 +- gpui/js/lib/game-profiles.ts | 18 +- gpui/js/lib/logitech-controls.ts | 6 +- gpui/js/macros.ts | 6 +- gpui/js/more-controls.ts | 39 +- gpui/js/nape-controls.ts | 4 +- gpui/js/native-hid/brands.ts | 22 +- gpui/js/native-hid/device-images.ts | 34 +- gpui/js/native-hid/device-store.ts | 16 +- gpui/js/native-hid/hid-open-lock.ts | 18 +- gpui/js/native-hid/logitech-actions.ts | 24 +- gpui/js/native-hid/scan.ts | 32 +- gpui/js/native-hid/tauri-hid-device.ts | 12 +- gpui/js/native-hid/write.ts | 36 +- gpui/js/steelseries-controls.ts | 4 +- gpui/src/active_mouse.rs | 2 +- gpui/src/app.rs | 25 + gpui/src/app/about_page.rs | 4 +- gpui/src/app/appearance.rs | 4 +- gpui/src/app/ascii.rs | 2 +- gpui/src/app/controls.rs | 126 ++++- gpui/src/app/device_io.rs | 74 ++- gpui/src/app/device_overview.rs | 2 +- gpui/src/app/device_page.rs | 61 ++- gpui/src/app/device_state.rs | 10 +- gpui/src/app/keyboard_panel.rs | 32 +- gpui/src/app/logitech_stages.rs | 459 ++++++++++++------ gpui/src/app/macro_panel.rs | 7 +- gpui/src/app/magnetic_panel.rs | 4 +- gpui/src/app/overview.rs | 6 +- gpui/src/app/plugins_page.rs | 4 +- gpui/src/app/profile_ui.rs | 8 +- gpui/src/app/safety.rs | 49 +- gpui/src/app/settings_page.rs | 13 + gpui/src/app/text_controls.rs | 94 +++- gpui/src/app/theme_studio.rs | 2 +- gpui/src/app/travel_panel.rs | 19 +- gpui/src/app/updates.rs | 12 +- gpui/src/audio.rs | 4 +- gpui/src/bin/main.rs | 2 +- gpui/src/games.rs | 6 +- gpui/src/hid.rs | 59 ++- gpui/src/marketplace.rs | 4 +- gpui/src/native_window.rs | 4 +- gpui/src/profiles.rs | 2 +- gpui/src/settings.rs | 8 +- gpui/src/theme.rs | 30 +- gpui/src/tray.rs | 74 ++- gpui/src/update_check.rs | 10 +- gpui/src/usb_topology.rs | 4 +- gpui/src/write_safety.rs | 7 + gpui/tests/fixtures/generic.json | 2 +- gpui/tests/fixtures/performance.json | 2 +- gpui/vendor/gpui-pre-apple/src/metal_atlas.rs | 2 +- .../vendor/gpui/src/platform.rs | 4 +- .../gpui-pre-apple/vendor/gpui/src/window.rs | 12 +- install-linux.sh | 6 +- marketplace-worker/src/index.js | 20 +- public/credits.json | 1 + 88 files changed, 1778 insertions(+), 590 deletions(-) create mode 100644 gpui/js/keyboard-via.ts diff --git a/.gitattributes b/.gitattributes index 1a2fd968..5f9d2892 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,4 @@ -# Shell scripts must stay LF even on Windows checkouts — a CRLF line ending +# Shell scripts must stay LF even on Windows checkouts - a CRLF line ending # breaks the `#!/bin/sh` shebang and the deb/rpm maintainer scripts (bundled # by tauri-bundler) fail to run on the Linux CI / install hosts. *.sh text eol=lf diff --git a/README.md b/README.md index 5a375707..876b7959 100644 --- a/README.md +++ b/README.md @@ -22,12 +22,12 @@ Built with [GPUI](https://www.gpui.rs/) and Rust on top of [`@openmouse/protocol ## Features -- **100+ Gaming Mice & Keyboards** — Powered by [`@openmouse/protocol`](https://github.com/OpenMouse-Project/mouse-protocol) (109+ mouse drivers) and [`@openmouse/keyboard-protocol`](https://github.com/OpenMouse-Project/keyboard-protocol), covering DPI stages, polling rate, lift-off distance, motion sync, macros, button remapping, onboard profiles, HE actuation / rapid trigger, and lighting. -- **Native Performance** — GPU-accelerated Rust UI via GPUI with direct native HID access and an embedded QuickJS driver runtime. No Electron, no background bloat. -- **Automatic Game Profiles** — Detects installed Steam, Epic, and Proton/Wine games and automatically switches mouse settings when you launch a game. -- **Marketplace & Theme Studio** — Browse and install community CSS themes or design your own in the built-in visual **Theme Studio** with live app preview, color pickers, and synced CSS editing. -- **Cross-Platform Tray & Updates** — System tray with live battery status on Windows, macOS, and Linux (`StatusNotifierItem`), plus SHA-256 verified automatic in-app updates across Windows, macOS, and Linux. -- **Safe & Transparent** — Re-reads device state after writes, asks before destructive resets, and keeps serial numbers and personal paths out of local logs. +- **100+ Gaming Mice & Keyboards** - Powered by [`@openmouse/protocol`](https://github.com/OpenMouse-Project/mouse-protocol) (109+ mouse drivers) and [`@openmouse/keyboard-protocol`](https://github.com/OpenMouse-Project/keyboard-protocol), covering DPI stages, polling rate, lift-off distance, motion sync, macros, button remapping, onboard profiles, HE actuation / rapid trigger, and lighting. +- **Native Performance** - GPU-accelerated Rust UI via GPUI with direct native HID access and an embedded QuickJS driver runtime. No Electron, no background bloat. +- **Automatic Game Profiles** - Detects installed Steam, Epic, and Proton/Wine games and automatically switches mouse settings when you launch a game. +- **Marketplace & Theme Studio** - Browse and install community CSS themes or design your own in the built-in visual **Theme Studio** with live app preview, color pickers, and synced CSS editing. +- **Cross-Platform Tray & Updates** - System tray with live battery status on Windows, macOS, and Linux (`StatusNotifierItem`), plus SHA-256 verified automatic in-app updates across Windows, macOS, and Linux. +- **Safe & Transparent** - Re-reads device state after writes, asks before destructive resets, and keeps serial numbers and personal paths out of local logs. ## Screenshots @@ -52,7 +52,7 @@ Download the disk image and drag **OpenMouse.app** to Applications: ### Linux `x86_64` portable build (compiled on Ubuntu 22.04 / `glibc 2.35`, compatible with Ubuntu 22.04+, Debian 12+, Fedora, Arch/CachyOS, and openSUSE). -Run the interactive CLI installer — it detects your distro (`pacman`, `apt`, `dnf`, `zypper`), installs missing runtime libraries, verifies the SHA-256 checksum, sets up the mouse-only `udev` rule so no root is needed at runtime, and adds an app-menu launcher: +Run the interactive CLI installer - it detects your distro (`pacman`, `apt`, `dnf`, `zypper`), installs missing runtime libraries, verifies the SHA-256 checksum, sets up the mouse-only `udev` rule so no root is needed at runtime, and adds an app-menu launcher: ```bash curl -fsSL https://raw.githubusercontent.com/OpenMouse-Project/Desktop/main/install-linux.sh | bash diff --git a/crates/openmouse-hid/src/hid_descriptor.rs b/crates/openmouse-hid/src/hid_descriptor.rs index 6eb07509..4a557beb 100644 --- a/crates/openmouse-hid/src/hid_descriptor.rs +++ b/crates/openmouse-hid/src/hid_descriptor.rs @@ -3,7 +3,7 @@ //! //! Why this exists: `@openmouse/protocol`'s driver registry matches devices //! with `Client.isSupported(device)`, and every one of those predicates reads -//! `device.collections` — the WebHID view of a device's collections and the +//! `device.collections` - the WebHID view of a device's collections and the //! report ids each declares. A browser populates it; hidapi does not. Without //! it the app cannot use the protocol library's own registry, which is why //! `src/native-hid/brands.ts` grew a hand-maintained copy of the registry @@ -60,7 +60,7 @@ pub struct ReportLayout { impl ReportLayout { /// Buffer size for reading `report_id` on this interface, including the - /// report-id byte, or `None` when the interface does not declare it — the + /// report-id byte, or `None` when the interface does not declare it - the /// distinction a caller needs to skip an interface that cannot answer. pub fn feature_buffer_len(&self, report_id: u8) -> Option { self.feature_bits.get(&report_id).map(|bits| { @@ -71,7 +71,7 @@ impl ReportLayout { } /// True when this interface declares `report_id` as an output or feature - /// report — i.e. a command for it could be sent here. + /// report - i.e. a command for it could be sent here. pub fn declares(&self, report_id: u8, feature: bool) -> bool { if feature { self.feature_bits.contains_key(&report_id) @@ -86,7 +86,7 @@ impl ReportLayout { self.input_bits.contains_key(&0) } - /// True when this interface declares `report_id` as an input report — i.e. + /// True when this interface declares `report_id` as an input report - i.e. /// an answer to it could arrive here. The direction a *response* uses is /// not always the direction the request used, so reads consult this /// separately from `declares`. @@ -205,7 +205,7 @@ pub fn parse_report_descriptor(bytes: &[u8]) -> Result<(Vec, Rep (0, 10) => { // Collection start. // If the descriptor set Usage Minimum/Maximum instead of Usage - // before Collection, `usages` is empty — keep the active global + // before Collection, `usages` is empty - keep the active global // usage page rather than zeroing it out. let (usage_page, usage) = match usages.first().copied() { Some(full) => ((full >> 16) as u16, full as u16), diff --git a/crates/openmouse-hid/src/lib.rs b/crates/openmouse-hid/src/lib.rs index 425d55c4..1ea5ae75 100644 --- a/crates/openmouse-hid/src/lib.rs +++ b/crates/openmouse-hid/src/lib.rs @@ -2,7 +2,7 @@ //! commands + an `"hid-input-report"` event. //! //! This exists so the frontend can drive `@openmouse/protocol`'s driver -//! classes — written against the browser WebHID API — from inside Tauri's +//! classes - written against the browser WebHID API - from inside Tauri's //! webview, which does not implement WebHID. The frontend's //! `TauriHidDevice` (see `src/native-hid/tauri-hid-device.ts`) wraps these //! commands into the same `HIDDevice`-shaped interface the driver classes @@ -15,8 +15,8 @@ //! per interface, so every collection sharing a (vendor id, product id) pair //! is grouped and opened together as one logical device. //! -//! This used to group by (vendor id, product id, interface number) instead — -//! mirroring the Node adapter's `candidateDevices()` — but `interface_number` +//! This used to group by (vendor id, product id, interface number) instead - +//! mirroring the Node adapter's `candidateDevices()` - but `interface_number` //! turned out to not be stable across separate `device_list()` calls on //! macOS for several real devices (a Logitech receiver, a Wooting keyboard), //! producing a different number per enumeration for what was the same @@ -24,19 +24,19 @@ //! (the same physical device appearing under several different keys) and, on //! connect, an "exclusive access, device already open" hidapi error (list //! time and open time disagreeing on which path a given key meant). Vendor + -//! product id alone is coarser — two genuinely different physical devices -//! that happen to share both ids would incorrectly merge into one entry — +//! product id alone is coarser - two genuinely different physical devices +//! that happen to share both ids would incorrectly merge into one entry - //! but that's a rare edge case, and it's stable, which interface_number is //! not on this platform. //! //! ## The actual cause of the input-freeze bug (found via the hidapi crate's //! own doc comment on `HidApi::set_open_exclusive`, after several wrong -//! guesses — see git history on this file for the discarded theories): +//! guesses - see git history on this file for the discarded theories): //! **on macOS, hidapi opens every device in *exclusive* mode by default.** //! That seizes the device from the OS's own HID client, which is exactly //! why any real mouse/keyboard went unresponsive the moment this code //! opened it, regardless of which collection, how long it stayed open, or -//! whether the `HidApi` instance was shared or freshly created each call — +//! whether the `HidApi` instance was shared or freshly created each call - //! none of those things actually mattered; every one of them still opened //! in exclusive mode. `with_hid_api()` below calls //! `api.set_open_exclusive(false)` once, immediately after creating the @@ -45,19 +45,19 @@ //! //! **Known gap, confirmed on real hardware, not yet solved:** at least one //! device (Endgame Gear's OP1-8K) answers `GetFeatureReport` with an I/O -//! timeout when opened non-exclusively — its control-transfer protocol +//! timeout when opened non-exclusively - its control-transfer protocol //! appears to require exclusive HID access to work at all. Exclusive access //! was tried again with the shortest possible open/one-read/close window //! and still froze the device's own input immediately, so duration is not //! a mitigating factor. Non-exclusive stays the default because freezing a //! user's real mouse/keyboard is a worse failure than a device's config -//! protocol not answering — a device that needs exclusive access to +//! protocol not answering - a device that needs exclusive access to //! function is presently unreachable through this bridge, not a bug to //! "fix" by bringing exclusive mode back. //! //! A single `HidApi` instance is kept alive for the app's whole lifetime //! (`HidApiHandle` below) and refreshed rather than recreated on every -//! call — simpler and cheaper than a fresh instance per call, and (now that +//! call - simpler and cheaper than a fresh instance per call, and (now that //! exclusive mode is off) has no bearing on the freeze either way. use std::collections::{HashMap, HashSet}; use std::ffi::CString; @@ -106,7 +106,7 @@ pub type ReportSink = std::sync::Arc Vec { /// This is also the floor on how long a *write* waits, which is why it is /// short. `hidapi::HidDevice` is `Send` but not `Sync`, so the reader thread /// and the request path (`try_each`) have to share one mutex, and the reader -/// holds it for the whole blocking read — a request can only be written once +/// holds it for the whole blocking read - a request can only be written once /// that read returns. /// /// MEASURED on real hardware (a Lightspeed receiver, with `try_each`'s own /// lock wait instrumented): at the 200 ms this used to be, the 27-request /// stretch of a `readStatus()` walk that was captured showed 24 separate /// acquisitions at `wait_ms≈203` before their request could even be written -/// — only the 3 that happened to land in the idle gap below went out +/// - only the 3 that happened to land in the idle gap below went out /// immediately. A full 37-request Logitech walk is therefore seconds of pure /// mutex wait before any protocol time at all. At 10 ms the same walk's worst /// case is 37 * 10 ms, and polling this often costs nothing while idle: @@ -334,21 +334,21 @@ const READ_POLL_TIMEOUT_MS: i32 = 10; /// Gap between read iterations, held *outside* the device lock so a writer /// parked on `try_each`'s blocking `lock()` can take it. Without this the /// reader re-acquires via `try_lock()` the instant the previous guard drops -/// and the parked writer has no fairness guarantee against it — macOS's +/// and the parked writer has no fairness guarantee against it - macOS's /// pthread mutex (which parking_lot wraps here) does not queue a parked /// waiter ahead of a thread that keeps re-acquiring, so the reader could win /// every re-lock race indefinitely. That is a livelock, not a slow poll, and /// it was seen live: a write for deviceIndex=0xff sat on "waiting for /// lock…" forever while the reader looped. The gap is what actually hands the -/// lock over, so it stays on every iteration — not only after a failed -/// `try_lock()` — but it now runs *after* an incoming report has been +/// lock over, so it stays on every iteration - not only after a failed +/// `try_lock()` - but it now runs *after* an incoming report has been /// emitted, so it no longer delays report delivery by 5 ms. const READ_IDLE_GAP_MS: u64 = 5; /// Backoff after a failed read, doubling per consecutive failure. /// -/// A split the process may not read — Windows denies `ReadFile` on keyboard -/// collections — fails forever with `ERROR_ACCESS_DENIED`. Retrying it at the +/// A split the process may not read - Windows denies `ReadFile` on keyboard +/// collections - fails forever with `ERROR_ACCESS_DENIED`. Retrying it at the /// normal 15 ms cadence burned CPU and printed tens of error lines a second /// for the life of the session; the reader now backs off to one attempt every /// couple of seconds and logs the first failure only. @@ -428,7 +428,7 @@ pub struct HidInterface { pub manufacturer_string: String, /// This interface's HID collections and the report ids they declare, in /// WebHID's own shape. `@openmouse/protocol`'s drivers match devices with - /// `isSupported(device)`, every one of which reads `device.collections` — + /// `isSupported(device)`, every one of which reads `device.collections` - /// a browser populates that for free, hidapi does not, which is why /// `src/native-hid/brands.ts` had to hand-copy the library's registry. /// Supplying it is what lets the app read the protocols from the library. @@ -462,16 +462,16 @@ struct OpenGroup { /// splits' readers are still backing off on unrelated errors. disconnected: Arc, /// Which split answered a given report id last time. WebHID never has to - /// guess this — the browser already knows which collection declares a + /// guess this - the browser already knows which collection declares a /// report id from `device.collections` and routes straight to it. /// hidapi's flat device list gives us no such map, so `try_each` used to - /// re-probe from split 0 on every single call — for a device where the + /// re-probe from split 0 on every single call - for a device where the /// answering split isn't first, that's a guaranteed-fail write before /// the one that actually works, paid again on every one of the dozens of /// requests a full `readStatus()` walk makes. Once a split answers for a /// report id, remember it and try that one first next time. routes: Mutex>, - /// Splits that accepted a request and answered with an empty packet — + /// Splits that accepted a request and answered with an empty packet - /// an interface that is up but not carrying the device's traffic (the /// usual cause: a composite wireless receiver, where the first split by /// rank is not the one the mouse answers on). They are skipped by @@ -480,11 +480,11 @@ struct OpenGroup { /// device is replugged, handled in `try_each`. silent: Mutex>, /// The payload last written per report id, so a read that comes back as - /// our own bytes can be told from an answer — see `is_unprocessed_echo`. + /// our own bytes can be told from an answer - see `is_unprocessed_echo`. last_sent: Mutex>>, } -/// One `HidApi` for the app's lifetime — see the module docs above for why +/// One `HidApi` for the app's lifetime - see the module docs above for why /// this matters, not just for efficiency. pub struct HidApiHandle(Mutex>); @@ -510,7 +510,7 @@ fn interface_key(vendor_id: u16, product_id: u16) -> String { } /// The one message the frontend reads as "someone else is using this device, -/// try again" — byte-identical to BUSY_MESSAGE in +/// try again" - byte-identical to BUSY_MESSAGE in /// src/native-hid/hid-open-lock.ts, which is what makes a refusal here benign /// (the auto-refresh and transport ticks retry on their own) instead of an /// error the user is shown. @@ -561,7 +561,7 @@ fn read_descriptor_for_path( } // A brief open, closed by the drop below: it is the only way to ask an // interface what it declares. This is safe to do during a scan now that - // `with_hid_api` refuses a re-entrant call instead of blocking on it — + // `with_hid_api` refuses a re-entrant call instead of blocking on it - // the open pumps the main thread's run loop (hidapi's macOS enumerator // does), which is what used to re-enter and deadlock the UI. // @@ -613,7 +613,7 @@ fn read_descriptor_for_path( Some(collections) } -/// The collections of one interface group, merged across its paths — the app +/// The collections of one interface group, merged across its paths - the app /// presents a device's interfaces as one synthetic device (see /// `tauri-hid-device.ts`), so this is that device's `collections`. /// @@ -683,8 +683,8 @@ fn interface_collections( } /// Runs `f` against the shared `HidApi`, initializing it on first use and -/// refreshing its device list (cheap — no manager teardown/recreation) on -/// every later call. Non-exclusive open is set once, right after creation — +/// refreshing its device list (cheap - no manager teardown/recreation) on +/// every later call. Non-exclusive open is set once, right after creation - /// see the module docs above for why this is the actual freeze fix. /// /// `try_lock`, never `lock`: hidapi's macOS enumerator pumps the *calling @@ -692,7 +692,7 @@ fn interface_collections( /// `CFRunLoopRunInMode`, hid.c:492), and both callers here run on the main /// thread. That pumped run loop services the webview's next `invoke`, which /// lands back in this function on the same thread while the outer call still -/// holds the guard — so a blocking `lock()` can never succeed on that path. +/// holds the guard - so a blocking `lock()` can never succeed on that path. /// It deadlocked exactly that way: `sample` of the frozen app showed the main /// thread parked in `__psynch_cvwait` under `hid_list_interfaces` → /// `with_hid_api` → `lock_slow`, nested inside `hid_open` → @@ -716,12 +716,12 @@ fn with_hid_api( let api = HidApi::new().map_err(|error| error.to_string())?; // CONFIRMED on real hardware: exclusive open freezes the // device's own input (mouse cursor/keyboard keys) the moment - // it's opened — reproduced even with the shortest possible + // it's opened - reproduced even with the shortest possible // open/one-read/close window, so duration was never the // mitigating factor. Non-exclusive avoids that entirely. The // real cost: at least one device's (Endgame Gear OP1-8K) // GetFeatureReport-based protocol needs exclusive access to - // answer at all and fails outright non-exclusively — a genuine + // answer at all and fails outright non-exclusively - a genuine // conflict between "don't freeze the user's hardware" and // "every protocol variant works." Freezing real input is the // worse failure mode, so non-exclusive wins here. A device @@ -730,7 +730,7 @@ fn with_hid_api( // freeze. // // `set_open_exclusive` only exists on Darwin (hidapi-rs gates it - // behind `#[cfg(target_os = "macos")]` — CONFIRMED by reading + // behind `#[cfg(target_os = "macos")]` - CONFIRMED by reading // its own doc comment: "By default on Darwin platform all // devices ... are opened in exclusive mode"). Windows/Linux // don't share that exclusive-by-default behavior in the first @@ -761,17 +761,17 @@ pub fn hid_vendors_with_usage(api_handle: &HidApiHandle, usage_page: u16, usage: // hid_list_interfaces and hid_open stay synchronous (blocking the main // thread) deliberately, unlike every other command below: they're the two -// that touch `HidApi` itself — `HidApi::new()`/`refresh_devices()`/ +// that touch `HidApi` itself - `HidApi::new()`/`refresh_devices()`/ // `open_path()`, the calls that actually open a device handle through // macOS's IOHIDManager, as opposed to reading/writing an already-open one. // Making them `async fn` (moving that off the main thread, onto Tokio's -// runtime) reproduced a real hang requiring a force-quit — every prior +// runtime) reproduced a real hang requiring a force-quit - every prior // successful connect this session happened with these on the main thread, // and there is no equivalent evidence they're safe off it the way the // reader threads' plain read()/write() on an open handle demonstrably are // (those have run on a spawned thread since the very start of this file's // history without incident). Left blocking here; the high-frequency calls -// during a `readStatus()` walk — the ones that actually caused the original +// during a `readStatus()` walk - the ones that actually caused the original const LOGITECH_VENDOR_ID: u16 = 0x046d; /// On Linux, `hid-logitech-dj` exposes every mouse paired to a Lightspeed/Unifying @@ -806,7 +806,7 @@ fn is_non_mouse_logitech_audio(vendor_id: u16, product_id: u16, product_string: .any(|kw| lower.contains(kw)) } -// UI freeze — are the ones below that stayed async. +// UI freeze - are the ones below that stayed async. pub fn hid_list_interfaces( api_handle: &HidApiHandle, vendor_ids: Vec, @@ -937,7 +937,7 @@ pub fn hid_list_interfaces( }) } -// See the comment on hid_list_interfaces above — kept synchronous for the +// See the comment on hid_list_interfaces above - kept synchronous for the // same reason. pub fn hid_open( sink: ReportSink, @@ -961,7 +961,7 @@ pub fn hid_open( // `any`, not `all`: on a composite device some interfaces never // deliver input at all, so their readers end immediately and // legitimately. Only every reader being finished means the device - // itself is gone — treating partial death as staleness reopened the + // itself is gone - treating partial death as staleness reopened the // device on nearly every request, which is the churn holding the // link is meant to remove. if !existing.disconnected.load(Ordering::Relaxed) @@ -984,7 +984,7 @@ pub fn hid_open( } let devices = with_hid_api(api_handle, |api| { - // `mut` looks unnecessary from a macOS build's perspective — + // `mut` looks unnecessary from a macOS build's perspective - // pushed into only in the #[cfg(target_os = "windows")] block // below, so Windows genuinely needs it mutable even though macOS // can't see why. @@ -998,13 +998,13 @@ pub fn hid_open( .collect(); // Split order decides where `try_each` sends a request first, and a // split that accepts a write but never answers pins the route cache to - // itself — every request then reads back an all-zero packet. + // itself - every request then reads back an all-zero packet. // // A brand whose control channel is a *standard* collection names it // outright and it goes first: Razer is the case in point, whose driver // documents the channel as "the interface whose only collection is // Generic Desktop Mouse" (usage page 0x0001, usage 0x0002). The - // heuristics below are the opposite of what it needs — 0x000C is + // heuristics below are the opposite of what it needs - 0x000C is // ranked early for the vendor case, and on the attached DeathAdder V3 // HyperSpeed the consumer collection is the *first* split, which is // exactly the all-zero reply the app was reporting ("Class 0x00 @@ -1015,7 +1015,7 @@ pub fn hid_open( // (>= 0xFF00), then Consumer Control (0x000C). On Linux, hidapi can // open the standard mouse pointer collection (0x0001), which often // acts as a black hole: it successfully accepts feature reports but - // drops them or returns zeroes — which is why vendor collections are + // drops them or returns zeroes - which is why vendor collections are // tried first for the brands that don't declare one. let ranked = |page: u16, usage: u16| match (preferred_usage_page, preferred_usage) { (Some(preferred_page), Some(preferred)) if page == preferred_page && usage == preferred => 0, @@ -1030,8 +1030,8 @@ pub fn hid_open( // of a split is a different interface to try a request on. hidapi // lists one entry per usage on an interface, so one physical interface // shows up several times, and opening every entry gave this app - // several IOHIDDevice handles — each with its own reader thread - // hammering `hid_read` — onto the same device. CONFIRMED in the + // several IOHIDDevice handles - each with its own reader thread + // hammering `hid_read` - onto the same device. CONFIRMED in the // on-disk log for the attached Razer: six opens of // DevSrvsID:4295095113 across usage pages 0001/000c/0001/0080, out of // nine splits in total, where the device really has three interfaces. @@ -1109,7 +1109,7 @@ pub fn hid_open( })?; let key = interface_key(vendor_id, product_id); - // Shared across every split's reader thread for this group — see + // Shared across every split's reader thread for this group - see // `spawn_reader`'s own docs for why this exists. let last_reply = Arc::new(Mutex::new(None)); let disconnected = Arc::new(AtomicBool::new(false)); @@ -1149,7 +1149,7 @@ pub fn hid_open( Ok(()) } -/// Standard HID++ short/long report ids (0x10/0x11) — see `brands.ts`'s own +/// Standard HID++ short/long report ids (0x10/0x11) - see `brands.ts`'s own /// list: nearly every driver in this app that answers a request/response /// exchange through an input report (not a plain feature report) uses these /// two, Logitech's HID++ included. @@ -1169,15 +1169,15 @@ const DUPLICATE_DELIVERY_WINDOW: Duration = Duration::from_millis(50); /// to all nine handles" from "the device sent the same bytes twice, in reply /// to two different requests". `IRoot.getFeature()` replies carry no trace of /// what was asked, so a mouse that lacks two features in a row (a PRO X -/// Superlight's 0x1000 and 0x1001 battery features, both absent — it reports +/// Superlight's 0x1000 and 0x1001 battery features, both absent - it reports /// through 0x1004) answers both with the same all-zero "not found" payload. /// MEASURED on real hardware: those two replies land ~9 ms apart, well inside /// the window, so the second was swallowed as a duplicate delivery and -/// `readStatus()` sat waiting out its 6 s request timeout — "The mouse did not +/// `readStatus()` sat waiting out its 6 s request timeout - "The mouse did not /// answer. Move it or click a button." on every single connect, reproduced 3/3 /// times, with the walk dying at request 8 of 37 every time. The same walk /// completed before the reader/writer mutex fix above only because requests -/// were ~200 ms apart then, i.e. outside this window — the slow path was +/// were ~200 ms apart then, i.e. outside this window - the slow path was /// hiding it. /// /// A report's own handle always delivers it exactly once, so an identical @@ -1190,7 +1190,7 @@ struct LastReply { split: usize, } -/// HID++ 2.0 error codes (byte 4 of a 0xFF error reply) — mirrors +/// HID++ 2.0 error codes (byte 4 of a 0xFF error reply) - mirrors /// `HIDPP20_ERRORS` in mouse-protocol's `logitech/index.ts`, purely so a /// rejection is legible in these logs without needing the webview's own /// devtools console open. @@ -1209,7 +1209,7 @@ fn hidpp20_error_name(code: u8) -> Option<&'static str> { }) } -/// HID++ 1.0 error codes (byte 4 of a 0x8F error reply) — mirrors +/// HID++ 1.0 error codes (byte 4 of a 0x8F error reply) - mirrors /// `HIDPP10_ERRORS` in the same file. fn hidpp10_error_name(code: u8) -> Option<&'static str> { Some(match code { @@ -1229,9 +1229,9 @@ fn hidpp10_error_name(code: u8) -> Option<&'static str> { }) } -/// Decodes an outgoing HID++ short/long request's own header — deviceIndex, +/// Decodes an outgoing HID++ short/long request's own header - deviceIndex, /// featureIndex, function id (the software id in the low nibble stripped -/// off), and parameter bytes — so a request can be matched by eye against +/// off), and parameter bytes - so a request can be matched by eye against /// the reply (or rejection) it produced a few lines later in the log. fn describe_hidpp_request(data: &[u8]) -> String { if data.len() < 3 { @@ -1247,7 +1247,7 @@ fn describe_hidpp_request(data: &[u8]) -> String { ) } -/// Decodes an incoming report as a HID++ error notification, if it is one — +/// Decodes an incoming report as a HID++ error notification, if it is one - /// `[deviceIndex, 0xFF|0x8F, featureIndex, function+softwareId, errorCode]`, /// mirroring `hidppErrorForRequest` in mouse-protocol's own driver. Returns /// `None` for anything else (a normal reply, or a raw input/status report). @@ -1313,7 +1313,7 @@ fn spawn_reader( // try_lock, not lock: a query/response exchange (hid_send_report // / hid_get_feature_report, called from the JS driver's own // readStatus()) needs this same device's lock and must never - // wait behind this loop's read — reads are continuous and + // wait behind this loop's read - reads are continuous and // best-effort (missing one poll cycle is fine), but a stuck // query is what "Connecting…" hanging looked like. If a writer // currently holds the lock, skip this cycle instead of blocking @@ -1328,11 +1328,11 @@ fn spawn_reader( // guarantee against that: macOS's pthread mutex doesn't queue a // parked waiter ahead of a thread that keeps re-acquiring via // try_lock, so this loop could win every single re-lock race - // indefinitely — a real livelock, not a slow poll. Seen live: + // indefinitely - a real livelock, not a slow poll. Seen live: // resolveDeviceIndex walking receiver pairing slots got every // reply promptly right up until the write for deviceIndex=0xff, // whose try_each sat on "waiting for lock…" and never - // progressed — this loop had just finished draining a backlog + // progressed - this loop had just finished draining a backlog // and immediately re-entered another 200ms held read_timeout, // over and over, never leaving a gap for the scheduler to hand // the lock to the parked writer. The gap sleep below (outside @@ -1341,7 +1341,7 @@ fn spawn_reader( // Second, the other half of the same coin: because the writer // could only ever win the lock during that gap, the *length* of // READ_POLL_TIMEOUT_MS was the latency of every single request - // in a walk. That is why it is 10ms now, not 200ms — see its own + // in a walk. That is why it is 10ms now, not 200ms - see its own // docs for the measurements. let read = match split.device.try_lock() { Some(device) => device.read_timeout(&mut buffer, READ_POLL_TIMEOUT_MS), @@ -1358,12 +1358,12 @@ fn spawn_reader( let (report_id, data) = split_report(&split.layout, &buffer[..length]); // CONFIRMED on real hardware: macOS delivers the same // physical report to every open split's handle, not just - // the one collection that actually declares it — every + // the one collection that actually declares it - every // request/reply exchange gets emitted here once per // split, not once. A driver's own reply matching keys on // (deviceIndex, featureIndex, functionId), not report // content, and several unrelated requests can share that - // key (every HID++ getFeature() call does) — so a + // key (every HID++ getFeature() call does) - so a // duplicate arriving late enough to land after the next // request went out gets consumed as that request's // answer instead, silently corrupting whichever field @@ -1373,7 +1373,7 @@ fn spawn_reader( // collection that actually declared it. Collapsing an // exact repeat of the immediately preceding // request/reply-shaped report is the equivalent fix - // here. Left unrestricted to every report id — a raw + // here. Left unrestricted to every report id - a raw // input stream (movement, clicks) can legitimately // repeat the same idle payload many times in a row, and // collapsing those would silently drop real reports. @@ -1382,7 +1382,7 @@ fn spawn_reader( // not a bare content match: an IRoot.getFeature() "not // found" reply carries no trace of which feature id was // asked (deviceIndex, echoed featureIndex=0, echoed - // functionId, all-zero payload) — so two DIFFERENT, + // functionId, all-zero payload) - so two DIFFERENT, // genuinely sequential getFeature() calls that both come // back "not found" are byte-for-byte identical. A bare // content-match dedup silently ate the second one @@ -1395,7 +1395,7 @@ fn spawn_reader( // answers a short HID++ request in ~9 ms (measured, see // LastReply), so two identical replies to two consecutive // requests land *inside* any window wide enough to catch - // macOS's duplicate deliveries — and swallowing the + // macOS's duplicate deliveries - and swallowing the // second one fails the whole walk. `LastReply`'s split is // what actually separates the two cases: one physical // report is delivered to every split's handle exactly @@ -1425,7 +1425,7 @@ fn spawn_reader( } drop(last); // Only log HID++ protocol traffic (report ids 0x10/0x11), - // and only once it's cleared the dedup check above — not + // and only once it's cleared the dedup check above - not // every raw report a split hands us. The continuous // stream of movement/click/battery-poll reports on other // report ids is real and gets emitted below same as @@ -1471,7 +1471,7 @@ fn spawn_reader( } } // Deliberately after the report above has been emitted and with - // no lock held — see READ_IDLE_GAP_MS. + // no lock held - see READ_IDLE_GAP_MS. thread::sleep(Duration::from_millis(READ_IDLE_GAP_MS)); // Quiet for a while: wait longer, still with no lock held. A request // unparks this (see `wake_readers`); see `IDLE_BACKOFF`. @@ -1490,7 +1490,7 @@ pub fn hid_close( // Deliberately does NOT release anything. Every protocol driver calls // `close()` at the end of a walk, and honouring it meant the app closed // and reopened the device on every status read: a full enumeration plus - // one open per split, and — worse — a fresh `OpenGroup`, throwing away + // one open per split, and - worse - a fresh `OpenGroup`, throwing away // what the app had learned about which split actually answers (see // `OpenGroup::silent` and `last_sent`). The handles, the reader threads and // that knowledge now live until the process exits. `hid_open` still @@ -1539,7 +1539,7 @@ pub fn hid_send_feature_report( frame.push(report_id); frame.extend_from_slice(&data); // Remembered so a read that echoes these bytes back is recognised as - // silence rather than an answer — see `is_unprocessed_echo`. + // silence rather than an answer - see `is_unprocessed_echo`. group.last_sent.lock().insert(report_id, data.clone()); // Fan out for Razer only: see `send_each`. Except the Viper 8KHz, // which a feature report on any interface but its control one knocks @@ -1581,8 +1581,8 @@ pub fn hid_get_input_report( return Err("input report read returned 0 bytes".to_string()); } result = Some(buffer[1..data_end].to_vec()); - // Input reports are noise-prone by nature — a mouse's idle report - // really is zeros — so an empty one is not treated as silence. + // Input reports are noise-prone by nature - a mouse's idle report + // really is zeros - so an empty one is not treated as silence. Ok(SplitAnswer::Answered) }); outcome.and(result.ok_or_else(|| "no split returned data".to_string())) @@ -1614,7 +1614,7 @@ pub fn hid_get_feature_report( // `length` is the caller's idea of how much to ask for and is often // far too small: the adapter in this app passes a flat 90 for every // feature read, while a device can declare a much longer report - // under the same id family — Endgame Gear's OP1 8K declares its + // under the same id family - Endgame Gear's OP1 8K declares its // config report 0xa0 as 1040 payload bytes, and asking Windows for // 90 of them fails outright (ERROR_INVALID_PARAMETER) instead of // truncating. The descriptor knows the real length, so use it: the @@ -1637,7 +1637,7 @@ pub fn hid_get_feature_report( // with two mouse-collection splits on the receiver, the first by // rank replies to every command with our own bytes and status 0x00 // ("Class 0x04 command 0x05 returned status 0x00") while the mouse - // is working fine — the desktop's cursor proves it, because the + // is working fine - the desktop's cursor proves it, because the // desktop is served by the other interface. Counting that as an // answer is what pinned `routes` to the dead interface and made the // device look asleep. Report it as silence so `try_each` moves on @@ -1672,8 +1672,8 @@ pub fn hid_get_feature_report( } /// Runs `operation` against the open splits for a group (plus its -/// report-id→split route cache — see `OpenGroup::routes`), trying every -/// split in turn on a cache miss — the report id in question may only be +/// report-id→split route cache - see `OpenGroup::routes`), trying every +/// split in turn on a cache miss - the report id in question may only be /// declared on one of them, same reasoning as the Node adapter's /// `sendReport`/`receiveFeatureReport`. fn with_open_group( @@ -1708,13 +1708,13 @@ fn declaring_first(declares: &[bool]) -> Vec { /// Sends one report to the group's interfaces. /// -/// With `fan_out` — which is Razer only, mirroring OpenMouse-Bridge: its +/// With `fan_out` - which is Razer only, mirroring OpenMouse-Bridge: its /// `send_report` routes by *declared report ids* wherever a report descriptor /// parses, and only inspects nothing for Razer, fanning the command out to /// every interface instead. Which of a composite receiver's interfaces reaches /// the mouse is not knowable from the outside, so the command is written to all /// of them and whichever one is live processes it. Writing only to the first -/// interface that merely *accepts* the write — which is what this app did — +/// interface that merely *accepts* the write - which is what this app did - /// leaves the command on an interface that never forwards it, and the read that /// follows finds no answer at all. /// @@ -1726,7 +1726,7 @@ fn declaring_first(declares: &[bool]) -> Vec { /// Ordering comes from the descriptors (see `declaring_first`), so the /// interface a report id belongs to is tried before ones that cannot carry it. /// The error returned when everything fails is the one from an interface that -/// *does* declare the report — the sibling collections' "Incorrect function" +/// *does* declare the report - the sibling collections' "Incorrect function" /// says only that they have no such report, which is why the message the user /// saw named a mouse collection while the vendor collection's real failure went /// unreported. @@ -1794,7 +1794,7 @@ fn send_each( /// Drops a group whose handles no longer work, so the next call reopens the /// device from a fresh enumeration. /// -/// `try_each` only gives up when *every* split has failed at the HID level — +/// `try_each` only gives up when *every* split has failed at the HID level - /// "hidapi error: Device is disconnected" after a receiver is unplugged, which /// is exactly what the app hit once it started holding handles for the session /// (see `hid_close`): the readers stay blocked in `hid_read` on a vanished @@ -1830,7 +1830,7 @@ fn drop_group(registry: &HidRegistry, vendor_id: u16, product_id: u16) { } /// What one split did with a request. `Silent` is this app's own term for an -/// interface that accepted it and answered with an empty packet — a receiver +/// interface that accepted it and answered with an empty packet - a receiver /// interface that is up but not carrying the mouse's traffic. See /// `hid_get_feature_report`. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -1841,7 +1841,7 @@ enum SplitAnswer { /// True when a reply is byte-for-byte the request that preceded it: the /// interface echoed it back instead of answering. CONFIRMED for this app's own -/// Razer — with two mouse-collection splits on one receiver, the first by rank +/// Razer - with two mouse-collection splits on one receiver, the first by rank /// replies to every command with our own bytes and status 0x00 /// ("Class 0x04 command 0x05 returned status 0x00") while the mouse works fine /// on the desktop, because the desktop is served by the other interface. @@ -1876,7 +1876,7 @@ fn feature_payload(buffer: &[u8], read: usize) -> Result, String> { /// /// The descriptor is authoritative: Windows rejects a read *shorter* than the /// declared report (ERROR_INVALID_PARAMETER), and some receivers reject a read -/// *longer* than it too — the WLMouse 8K receiver answers +/// *longer* than it too - the WLMouse 8K receiver answers /// `ERROR_GEN_FAILURE` when asked for 90 bytes of its declared 64-byte config /// report. Only when the interface declares no such report (Razer's /// undocumented 90-byte reports, say) does the caller's request decide the size. @@ -1895,7 +1895,7 @@ fn try_each( declaring_only: bool, mut operation: impl FnMut(&hidapi::HidDevice, &ReportLayout) -> Result, ) -> Result<(), String> { - // Try whichever split answered this exact report id last time first — + // Try whichever split answered this exact report id last time first - // see `OpenGroup::routes`. Falls through to the rest in order on a miss // (first call for this report id, or the routed split stopped working), // so this is a pure optimization, never a correctness change. @@ -2043,7 +2043,7 @@ mod tests { // A longer request does not inflate a declared report either. assert_eq!(feature_read_len(&layout, 0xa0, 4096), 1041); // An interface that does not declare the report keeps the caller's - // request — the platform may still answer something. + // request - the platform may still answer something. assert_eq!(feature_read_len(&layout, 0x99, 90), 91); assert!(layout.declares(0xa1, true)); assert!(!layout.declares(0xa1, false)); @@ -2074,7 +2074,7 @@ mod tests { /// holds the handle, never wait for it. Waiting is what froze the app: /// hidapi's macOS enumerator pumps the calling thread's run loop /// (`process_pending_events`), so an `invoke` serviced by that pump - /// re-enters here on the same thread that already holds the guard — a + /// re-enters here on the same thread that already holds the guard - a /// `lock()` there parks forever (`__psynch_cvwait` under /// `hid_list_interfaces`, nested inside `hid_open`'s `hid_enumerate`, /// observed with `sample`) and the window stops responding while the @@ -2195,7 +2195,7 @@ mod tests { assert!(!feature_reports_declaring_only(0x046d, RAZER_VIPER_8K_PRODUCT_ID), "same pid, other vendor"); } - /// A device dropping off the bus can answer a feature read with 0 bytes — + /// A device dropping off the bus can answer a feature read with 0 bytes - /// not even the report id. That used to panic the I/O thread on /// `buffer[1..0]`; it must be an ordinary error instead. #[test] diff --git a/crates/openmouse-presence/src/lib.rs b/crates/openmouse-presence/src/lib.rs index f443d719..1befa4fc 100644 --- a/crates/openmouse-presence/src/lib.rs +++ b/crates/openmouse-presence/src/lib.rs @@ -112,7 +112,7 @@ impl Presence { /// Connects to the running Discord client and shows the initial activity. /// Blocking; fails if Discord is not running. If a client already exists its /// socket may be dead (Discord was quit), so it is reconnected rather than - /// trusted — otherwise the switch would look on while nothing is connected. + /// trusted - otherwise the switch would look on while nothing is connected. pub fn enable(&self) -> Result<(), String> { applog!("[discord] enable requested"); let mut guard = self.connection.lock(); diff --git a/gpui/examples/chime_demo.rs b/gpui/examples/chime_demo.rs index 195aa3ad..43e7eb95 100644 --- a/gpui/examples/chime_demo.rs +++ b/gpui/examples/chime_demo.rs @@ -1,4 +1,4 @@ -//! `cargo run --example chime_demo` — plays the success chime, then the error chime. +//! `cargo run --example chime_demo` - plays the success chime, then the error chime. use openmouse_gpui::audio::{play, Chime}; fn main() { diff --git a/gpui/examples/hid_button.rs b/gpui/examples/hid_button.rs index 7642b5df..4dea5f10 100644 --- a/gpui/examples/hid_button.rs +++ b/gpui/examples/hid_button.rs @@ -1,4 +1,4 @@ -//! `cargo run --example hid_button` — button-remap path check. Assigns button 0 +//! `cargo run --example hid_button` - button-remap path check. Assigns button 0 //! the action it ALREADY has, which the protocol library detects as "no change" //! and skips the flash write for, so it proves the call chain without altering //! anything. diff --git a/gpui/examples/hid_onboard.rs b/gpui/examples/hid_onboard.rs index 2773514c..19558854 100644 --- a/gpui/examples/hid_onboard.rs +++ b/gpui/examples/hid_onboard.rs @@ -1,4 +1,4 @@ -//! `cargo run --example hid_onboard` — read-only: the Logitech mouse's stored profiles. +//! `cargo run --example hid_onboard` - read-only: the Logitech mouse's stored profiles. use openmouse_gpui::hid::HidService; fn main() { diff --git a/gpui/examples/hid_probe.rs b/gpui/examples/hid_probe.rs index dea69ad7..d0dbbe90 100644 --- a/gpui/examples/hid_probe.rs +++ b/gpui/examples/hid_probe.rs @@ -1,4 +1,4 @@ -//! `cargo run --example hid_probe` — lists supported HID interfaces and reads +//! `cargo run --example hid_probe` - lists supported HID interfaces and reads //! the status of the first (or `--key vvvv:pppp`) through the embedded //! protocol runtime. Handy for checking device support without the UI. diff --git a/gpui/examples/hid_profile.rs b/gpui/examples/hid_profile.rs index 1f7cbed7..dd22c8a8 100644 --- a/gpui/examples/hid_profile.rs +++ b/gpui/examples/hid_profile.rs @@ -1,4 +1,4 @@ -//! `cargo run --example hid_profile` — applies a game profile through the shared +//! `cargo run --example hid_profile` - applies a game profile through the shared //! `applyGameProfile` (one device session) and prints what the mouse applied. use openmouse_gpui::{hid::HidService, profiles::GameProfile}; diff --git a/gpui/examples/hid_rescan.rs b/gpui/examples/hid_rescan.rs index 714c8d2d..a0fecd66 100644 --- a/gpui/examples/hid_rescan.rs +++ b/gpui/examples/hid_rescan.rs @@ -1,4 +1,4 @@ -//! `cargo run --example hid_rescan` — list/connect repeatedly in one process, +//! `cargo run --example hid_rescan` - list/connect repeatedly in one process, //! the path the Overview's Rescan button takes. Regression check for HidApi //! being touched from more than one thread (aborts inside IOHID on macOS). diff --git a/gpui/examples/hid_tabs.rs b/gpui/examples/hid_tabs.rs index 3ec4ffa0..52ddd9a7 100644 --- a/gpui/examples/hid_tabs.rs +++ b/gpui/examples/hid_tabs.rs @@ -1,4 +1,4 @@ -//! `cargo run --example hid_tabs -- ` — what the Buttons / Lighting / +//! `cargo run --example hid_tabs -- ` - what the Buttons / Lighting / //! Advanced tabs would show for one device. use openmouse_gpui::hid::HidService; diff --git a/gpui/examples/hid_write.rs b/gpui/examples/hid_write.rs index 992d989e..1b3eca8e 100644 --- a/gpui/examples/hid_write.rs +++ b/gpui/examples/hid_write.rs @@ -1,4 +1,4 @@ -//! `cargo run --example hid_write -- ` — one live write +//! `cargo run --example hid_write -- ` - one live write //! through the embedded runtime, printing exactly what comes back. Actions: //! dpi, pollingRate, liftOff, surface. Targets the first listed device. diff --git a/gpui/examples/overlay_demo.rs b/gpui/examples/overlay_demo.rs index ac8b5e2f..eaf89656 100644 --- a/gpui/examples/overlay_demo.rs +++ b/gpui/examples/overlay_demo.rs @@ -1,4 +1,4 @@ -//! `cargo run --example overlay_demo -- [corner] [error]` — shows only the game +//! `cargo run --example overlay_demo -- [corner] [error]` - shows only the game //! overlay toast for a few seconds, so its placement can be checked on its own. use gpui_kit::*; use openmouse_gpui::{native_window::OverlayCorner, overlay, theme::{self, ThemeChoice}}; @@ -18,7 +18,7 @@ fn main() { if error { "Couldn't apply \"Counter-Strike 2\" profile: the mouse is asleep".to_string() } else { - "Applied \"Counter-Strike 2\" profile — 800 DPI, 1000 Hz.".to_string() + "Applied \"Counter-Strike 2\" profile - 800 DPI, 1000 Hz.".to_string() }, error, corner, diff --git a/gpui/examples/usb_topology.rs b/gpui/examples/usb_topology.rs index 5a5e48af..337aaefa 100644 --- a/gpui/examples/usb_topology.rs +++ b/gpui/examples/usb_topology.rs @@ -1,4 +1,4 @@ -//! `cargo run --example usb_topology` — scans the machine's USB host +//! `cargo run --example usb_topology` - scans the machine's USB host //! controllers, hubs, ports, and PCIe parent bridges, and prints a logical //! CPU vs. Chipset routing map with mouse placement grading, recommended open //! ports, and per-device USB endpoint/power stats. diff --git a/gpui/installer/Cargo.toml b/gpui/installer/Cargo.toml index 6e627faa..3206edac 100644 --- a/gpui/installer/Cargo.toml +++ b/gpui/installer/Cargo.toml @@ -4,12 +4,12 @@ version = "1.2.0" edition = "2021" license = "AGPL-3.0-or-later" -# Standalone crate, not a workspace member of `gpui/` — its build.rs needs +# Standalone crate, not a workspace member of `gpui/` - its build.rs needs # only the already-built `openmouse-gpui.exe` bytes, not the node/esbuild # toolchain `gpui/build.rs` runs for the JS driver bundle. # # One binary serves as both installer and uninstaller (mode picked at -# runtime — see `src/main.rs`), not two `[[bin]]` targets: the installer +# runtime - see `src/main.rs`), not two `[[bin]]` targets: the installer # copies ITS OWN running .exe into the install dir as the uninstaller, so # there's no circular "uninstaller bytes embedded in the installer" build # step to sequence. @@ -27,7 +27,7 @@ serde_json = "1" [target.'cfg(windows)'.dependencies] winreg = "0.52" -# Pure-Rust .lnk writer — no COM/windows-rs, matching the repo's existing +# Pure-Rust .lnk writer - no COM/windows-rs, matching the repo's existing # "no windows crate" stance (see gpui/src/native_window/win.rs). mslnk = "0.1" diff --git a/gpui/installer/build.rs b/gpui/installer/build.rs index b099d689..7b279afc 100644 --- a/gpui/installer/build.rs +++ b/gpui/installer/build.rs @@ -37,7 +37,7 @@ fn main() { let exe_bytes = compress_file(&app_exe, &out_dir.join("openmouse-gpui.exe.deflate")).unwrap_or_else(|error| { panic!( - "could not read/compress the built app at {} ({error}) — run `cargo build --release` \ + "could not read/compress the built app at {} ({error}) - run `cargo build --release` \ in gpui/ first, or set OPENMOUSE_GPUI_EXE to its path", app_exe.display() ) @@ -52,7 +52,7 @@ fn main() { let pdb_bytes = compress_file(&app_pdb, &out_dir.join("openmouse_gpui.pdb.deflate")).unwrap_or_else(|error| { panic!( - "could not read/compress the built app symbols at {} ({error}) — run \ + "could not read/compress the built app symbols at {} ({error}) - run \ `cargo build --release` in gpui/ first, or set OPENMOUSE_GPUI_PDB to its path", app_pdb.display() ) diff --git a/gpui/installer/src/colors.rs b/gpui/installer/src/colors.rs index 5d8277fd..14faa572 100644 --- a/gpui/installer/src/colors.rs +++ b/gpui/installer/src/colors.rs @@ -1,10 +1,10 @@ //! The app's brand green (the `logo.png` pill, `[data-theme="emerald"]` in -//! `src/App.css`) rather than the default Matt dark theme's orange — this is +//! `src/App.css`) rather than the default Matt dark theme's orange - this is //! a standalone installer, not a copy of the main app's current theme choice, //! so it paints the one color scheme that's unambiguously "OpenMouse" no //! matter what theme the user picked inside the app. //! -//! Duplicated here rather than depending on the `openmouse-gpui` crate — +//! Duplicated here rather than depending on the `openmouse-gpui` crate - //! its `build.rs` needs node/esbuild for the JS driver bundle, which this //! installer has no use for. @@ -39,7 +39,7 @@ pub fn accent_ink() -> Hsla { /// Paints the live [`Theme`] with the palette above, so every `gpui-kit` /// component (`Button::primary()`, `Checkbox`, `Spinner`) picks it up -/// automatically instead of needing per-element color overrides — same +/// automatically instead of needing per-element color overrides - same /// mechanism `gpui/src/theme.rs`'s `paint_shared` uses for the main app. /// Call once, after the window exists (`Theme::change` mid-construction /// poisons first render). diff --git a/gpui/installer/src/main.rs b/gpui/installer/src/main.rs index 57a32774..ecd04a05 100644 --- a/gpui/installer/src/main.rs +++ b/gpui/installer/src/main.rs @@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; /// Fade + slight rise, same feel as the main app's title-badge reveal -/// (`gpui/src/app.rs`'s `BADGE_FADE`) — just slower, since this is a whole +/// (`gpui/src/app.rs`'s `BADGE_FADE`) - just slower, since this is a whole /// screen swapping rather than a small hover detail. const STEP_TRANSITION: Duration = Duration::from_millis(260); /// Breathing pulse on the in-progress step dot. @@ -26,7 +26,7 @@ const LOGO_PNG: &[u8] = include_bytes!("../../assets/logo.png"); /// Same binary, two roles: run normally it's the installer; copied into the /// install directory and invoked with `--uninstall` (how the Add/Remove -/// Programs entry's `UninstallString` calls it — see `registry.rs`) it's the +/// Programs entry's `UninstallString` calls it - see `registry.rs`) it's the /// uninstaller. Falling back to a filename sniff covers someone just /// double-clicking the copy left behind in the install folder. fn uninstall_mode() -> bool { @@ -41,9 +41,9 @@ fn uninstall_mode() -> bool { #[derive(Clone, Copy, PartialEq)] enum Screen { - /// Welcome (install) or confirm-removal (uninstall) — step 1. + /// Welcome (install) or confirm-removal (uninstall) - step 1. Start, - /// Copying files / removing them — step 2. + /// Copying files / removing them - step 2. Working, /// Step 3. Carries whether it ended in an error. Done, @@ -242,7 +242,7 @@ impl InstallerView { } /// Three dots tracking progress through Start → Working → Done, filled - /// green up to the current step — the "step by step" wizard framing. The + /// green up to the current step - the "step by step" wizard framing. The /// in-progress dot breathes while `Working` is running; the rest are static. fn step_dots(&self, cx: &mut Context) -> impl IntoElement { let current = self.step_index(); @@ -499,7 +499,7 @@ fn main() { }) .detach(); // No explicit `window_bounds` otherwise defaults to filling the - // display — this is a small dialog, not a resizable app window. + // display - this is a small dialog, not a resizable app window. let window_size = size(px(480.), px(440.)); let options = WindowOptions { window_bounds: Some(WindowBounds::Windowed(Bounds::centered(None, window_size, cx))), diff --git a/gpui/installer/src/paths.rs b/gpui/installer/src/paths.rs index 71ed9cfe..4979be70 100644 --- a/gpui/installer/src/paths.rs +++ b/gpui/installer/src/paths.rs @@ -1,4 +1,4 @@ -//! Per-user install location and shortcut paths — no admin rights needed +//! Per-user install location and shortcut paths - no admin rights needed //! anywhere in this crate. use std::path::{Path, PathBuf}; diff --git a/gpui/installer/src/registry.rs b/gpui/installer/src/registry.rs index e476df5c..159a5e98 100644 --- a/gpui/installer/src/registry.rs +++ b/gpui/installer/src/registry.rs @@ -1,4 +1,4 @@ -//! Add/Remove Programs entry (`HKCU\...\Uninstall\OpenMouseDesktop`) — same +//! Add/Remove Programs entry (`HKCU\...\Uninstall\OpenMouseDesktop`) - same //! `winreg` crate and per-user `HKEY_CURRENT_USER` pattern already used by //! `gpui/src/autostart.rs` for the Run-key entry. diff --git a/gpui/installer/src/shortcuts.rs b/gpui/installer/src/shortcuts.rs index c54ed629..cccc6993 100644 --- a/gpui/installer/src/shortcuts.rs +++ b/gpui/installer/src/shortcuts.rs @@ -1,4 +1,4 @@ -//! Start Menu + optional Desktop `.lnk` creation via `mslnk` — a pure-Rust +//! Start Menu + optional Desktop `.lnk` creation via `mslnk` - a pure-Rust //! `.lnk` writer, deliberately chosen over `windows-rs`'s `IShellLink` COM //! API to match the repo's existing "no windows crate" stance (see //! `gpui/src/native_window/win.rs`). diff --git a/gpui/js/controls.ts b/gpui/js/controls.ts index c1728a3d..2aea5f00 100644 --- a/gpui/js/controls.ts +++ b/gpui/js/controls.ts @@ -1,7 +1,7 @@ // What the device page's Buttons, Lighting and Advanced tabs offer for a // connected device, and how each control writes. A transliteration of // src/components/Device{Buttons,Lighting,Advanced}Tab.tsx: the same brand -// gating on the same MouseStatus fields, the same write functions — but as +// gating on the same MouseStatus fields, the same write functions - but as // plain data, so the Rust side can draw any brand without knowing it. import { gatherButtons } from "./buttons-tab"; @@ -44,7 +44,7 @@ function razerAndEgg(brand: string, s: any): Section[] { if (isRazer) { out.push({ - title: "Razer — Buttons", + title: "Razer - Buttons", controls: RAZER_BUTTON_CONTROLS.filter((c: string) => c !== RAZER_LOCKED_BUTTON_CONTROL).map((c: string) => ({ id: `razer.button.${c}`, label: (RAZER_BUTTON_CONTROL_LABEL as any)[c], @@ -57,7 +57,7 @@ function razerAndEgg(brand: string, s: any): Section[] { } if (isEgg) { out.push({ - title: "Endgame Gear — Buttons", + title: "Endgame Gear - Buttons", controls: (EGG_BUTTON_NAMES as readonly string[]).map((name, i) => ({ id: `egg.button.${i}`, label: name, @@ -68,7 +68,7 @@ function razerAndEgg(brand: string, s: any): Section[] { }); if (Array.isArray(s.eggMulticlickFilters) && s.eggMulticlickFilters.length > 0) { out.push({ - title: "Endgame Gear — Debounce", + title: "Endgame Gear - Debounce", controls: (EGG_BUTTON_NAMES as readonly string[]).slice(0, s.eggMulticlickFilters.length).map((name, i) => ({ id: `egg.debounce.${i}`, label: name, @@ -94,7 +94,7 @@ function genericButtons(s: any): Section[] { const fixed: string[] = Array.isArray(s.fixedButtons) ? s.fixedButtons : []; const controls: Control[] = Object.entries(s.buttonMappings as Record).map(([button, action]) => fixed.includes(button) - ? { id: `gen.fixed/${button}`, label: button, description: "Set up with a macro or custom binding — not editable here.", kind: "info" as const, current: String(action) } + ? { id: `gen.fixed/${button}`, label: button, description: "Set up with a macro or custom binding - not editable here.", kind: "info" as const, current: String(action) } : { id: `gen.button/${button}`, label: button, kind: "choice" as const, options: opts(s.buttonOptions), current: action }, ); return controls.length ? [{ title: "Buttons", controls }] : []; @@ -127,8 +127,8 @@ function advanced(s: any, brand: string): Section[] { if (typeof s.motionJitterFilter === "boolean") c.push({ id: "egg.jitter", label: "Motion-jitter filter", kind: "toggle", current: s.motionJitterFilter }); const gx = ["Off", "GX Safe", "GX Speed"]; if (s.leftSpdtMode != null || s.rightSpdtMode != null) { - c.push({ id: "egg.spdt.left", label: "GX switch — left button", kind: "choice", options: opts(gx), current: s.leftSpdtMode ?? "Off" }); - if (s.rightSpdtMode != null) c.push({ id: "egg.spdt.right", label: "GX switch — right button", kind: "choice", options: opts(gx), current: s.rightSpdtMode }); + c.push({ id: "egg.spdt.left", label: "GX switch - left button", kind: "choice", options: opts(gx), current: s.leftSpdtMode ?? "Off" }); + if (s.rightSpdtMode != null) c.push({ id: "egg.spdt.right", label: "GX switch - right button", kind: "choice", options: opts(gx), current: s.rightSpdtMode }); } if (Array.isArray(s.eggCpiStages) && s.eggCpiStages.length > 0) { c.push({ id: "egg.cpiLevels", label: "CPI levels", kind: "choice", options: opts([1, 2, 3, 4]), current: s.eggCpiLevels ?? 1 }); @@ -138,7 +138,7 @@ function advanced(s: any, brand: string): Section[] { c.push({ id: "egg.pollingDivider", label: "8K polling divider", - description: `Result: ${Number.isInteger(d) && d > 0 ? `${(8000 / d).toLocaleString(undefined, { maximumFractionDigits: 2 })} Hz` : "—"}`, + description: `Result: ${Number.isInteger(d) && d > 0 ? `${(8000 / d).toLocaleString(undefined, { maximumFractionDigits: 2 })} Hz` : "-"}`, kind: "number", min: 1, max: 255, @@ -477,8 +477,8 @@ function withCurrent(steps: readonly number[], current: number | null | undefine * The Performance tab's controls beyond DPI / polling / lift-off / surface (those * have dedicated UI): sleep, the sensor-processing switches, on-device DPI stages, * debounce, low-power threshold, USB speed and primary button. Every control is - * gated exactly as src/components/DevicePerformanceTab.tsx gates it — a status - * field the driver reports, minus whatever the driver's own `ui` hints hide — and + * gated exactly as src/components/DevicePerformanceTab.tsx gates it - a status + * field the driver reports, minus whatever the driver's own `ui` hints hide - and * all of them apply immediately, as they do there. */ /** Brands whose drivers implement `setAngleTuning` (the others only report the angle). */ @@ -542,7 +542,7 @@ function performanceExtras(brand: string, status: any, caps: DeviceCapabilities) c.push({ id: "perf.debounce", label: "Debounce", - description: `Filters out physical switch bounce (0–${values[values.length - 1]} ms). Higher is steadier, slightly more click lag.`, + description: `Filters out physical switch bounce (0-${values[values.length - 1]} ms). Higher is steadier, slightly more click lag.`, kind: "stepped", options: values.map((ms) => ({ value: ms, label: `${ms} ms` })), current: status.debounceMs, @@ -626,7 +626,11 @@ export function describeControls(brand: string, status: any, caps: DeviceCapabil ...keychron.advanced, ...more.advanced, ...deviceInfo(status)], performance: [...stageSections(status), ...performanceExtras(brand, status, caps), ...keychron.performance, ...more.performance], }); - return { ...tabs, lighting: status.lighting ?? null, receiver: keychron.receiver, magnetic: magneticPanel(status), macros: macroPanel(status) }; + const t = status.analogButtonTuning; + const hitsTravel = brand === "Logitech" && t?.buttons?.length && t.maxActuation > 0 + ? { triggers: [0, 1].map((i) => (t.buttons[i] ? (t.buttons[i].actuation / t.maxActuation) * 100 : null)) } + : null; + return { ...tabs, lighting: status.lighting ?? null, receiver: keychron.receiver, magnetic: magneticPanel(status), macros: macroPanel(status), hitsTravel }; } /** Writes HITS tuning live for the affected buttons, then saves both into the running profile. */ diff --git a/gpui/js/depth-stream.ts b/gpui/js/depth-stream.ts index 92f88c3b..ea1d690d 100644 --- a/gpui/js/depth-stream.ts +++ b/gpui/js/depth-stream.ts @@ -93,9 +93,20 @@ export function openTravel(info: HidInterfaceInfo): (sample: (left: number, righ return async (sample) => { for (const candidate of candidatesForDevice(info)) { const client = candidate.create(new TauriHidDevice(info, candidate.preferredCollection)) as any; - if (typeof client?.onButtonDepth !== "function") continue; + const analog = typeof client?.onAnalogPress === "function" && typeof client?.startAnalogPressStream === "function"; + if (typeof client?.onButtonDepth !== "function" && !analog) continue; try { await client.open(); + if (analog) { + if (typeof client.resolveDeviceIndex === "function") await client.resolveDeviceIndex(); + const unsubscribe = client.onAnalogPress((left: number, right: number) => sample(left * 10, right * 10)); + await client.startAnalogPressStream(); + return async () => { + unsubscribe(); + await client.stopAnalogPressStream().catch(() => undefined); + await client.close().catch(() => undefined); + }; + } const unsubscribe = client.onButtonDepth(sample); return async () => { unsubscribe(); diff --git a/gpui/js/entry.ts b/gpui/js/entry.ts index 0e3bf3c8..39e43904 100644 --- a/gpui/js/entry.ts +++ b/gpui/js/entry.ts @@ -6,7 +6,7 @@ import "./globals"; import "./wlmouse-apply"; import { macroOp } from "./macros"; import { callClientMethod as genericCall } from "./generic-write"; -import { connectKeyboard, describeKeyboard, listKeyboards, keyboardOp, writeKeyboard } from "./keyboards"; +import { connectKeyboard, describeKeyboard, listKeyboards, keyboardMacroOp, keyboardOp, writeKeyboard } from "./keyboards"; import { DepthStream, openTravel } from "./depth-stream"; import { napeEditedLayer, readNapeLayer } from "./nape-controls"; import { ALL_STAGE_SUPPORT, driverSetters, stageSupport } from "./dpi-stages"; @@ -17,7 +17,7 @@ import * as genericWrite from "./native-hid/write"; import { deviceCapabilities, dpiBounds } from "./native-hid/write"; import { DPI_MAX, DPI_MIN, DPI_PRESETS, DPI_STEP, GAMING_SURFACE_MODES } from "./lib/logitech-controls"; import { withLogitechClient } from "./native-hid/logitech-actions"; -import { LOGITECH_BUTTON_ACTIONS } from "@openmouse/protocol/drivers/logitech/onboard-profiles"; +import { LOGITECH_BUTTON_ACTIONS, factoryDirectoryForFormat } from "@openmouse/protocol/drivers/logitech/onboard-profiles"; import { LOGITECH_COMMANDS, commandFor } from "./lib/logitech-commands"; import { applyGameProfile } from "./lib/game-profiles"; import { describeControls, setPrefs, writeControl, writeLighting } from "./controls"; @@ -92,7 +92,8 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); /** Magnetic button travel since the last call; keeps the stream alive. */ async buttonDepth(key: string): Promise { if (isMockKey(key)) return JSON.stringify(mockDepths()); - if (!lastStatus.get(key)?.magneticButtons?.liveDepth) return "[]"; + const s = lastStatus.get(key); + if (!s?.magneticButtons?.liveDepth && !s?.analogButtonTuning?.buttons?.length) return "[]"; return JSON.stringify(await travel.drain(key)); }, async stopButtonDepth(): Promise { @@ -105,6 +106,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); await travel.stop(key); + if (candidate.kind === "keyboard") return JSON.stringify(await keyboardMacroOp(candidate.info, action, args)); return JSON.stringify(await macroOp(candidate.info, lastStatus.get(key) ?? {}, action, args)); }, /** Keys, actuation and lighting of a keyboard. */ @@ -135,6 +137,17 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); max: attackShark ? 22000 : razer ? 8500 : DPI_MAX, step: attackShark ? 50 : razer ? 100 : DPI_STEP, }); + if (!mock && device.brand === "Logitech") { + const status = device.status as any; + const options: number[] | null = await withLogitechClient(candidate.info, "getDpiOptions", (client: any) => client.getDpiOptions()).catch(() => null); + if (options && options.length > 1) { + const sorted = [...options].sort((a, b) => a - b); + status.dpiOptions = sorted; + const gaps = sorted.slice(1).map((v, i) => v - sorted[i]).filter((gap) => gap > 0); + Object.assign(bounds, { min: sorted[0], max: sorted[sorted.length - 1], step: Math.min(...gaps) }); + } + if (status.onboardProfileFormat) status.onboardProfileFormat.factory = factoryDirectoryForFormat(status.onboardProfileFormat.id, 255) !== null; + } const presets = attackShark ? [400, 800, 1600, 3200, 6400, 12800, 22000] : razer ? [400, 800, 1600, 3200, 6400, 8000] : DPI_PRESETS; // What the stage editor needs to know about this device (see dpi-stages.ts). Object.assign(device.status, { @@ -189,25 +202,52 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); }, /** Switch the running onboard profile (volatile, no flash write) or Onboard/Host mode. */ async onboardAction(argsJson: string): Promise { - const { key, action, value } = JSON.parse(argsJson) as { key: string; action: "useProfile" | "mode" | "stages"; value: any }; + const { key, action, value } = JSON.parse(argsJson) as { key: string; action: "useProfile" | "mode" | "stages" | "rename" | "factory" | "enable"; value: any }; await travel.stop(key); if (isMockKey(key)) return JSON.stringify(mockOnboardAction(action, value)); const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); return JSON.stringify( await withLogitechClient(candidate.info, `onboard ${action}`, async (client: any) => { + client.profileFormatId ??= lastStatus.get(key)?.onboardProfileFormat?.id ?? null; try { if (action === "useProfile") { // A stored profile only runs while the mouse is in Onboard mode. await client.setOnboardMode("Onboard"); await client.setCurrentProfile(Number(value)); + if (lastStatus.get(key)) lastStatus.get(key).deviceMode = "Onboard"; return value; } + if (action === "enable") { + await client.setProfileEnabled(Number(value.sector), Boolean(value.enabled)); + return value.enabled; + } + if (action === "rename") { + const name = String(value.name ?? "").trim(); + if (!name) throw new Error("A profile name can't be empty."); + await client.writeActiveProfile({ sector: Number(value.sector), name }); + return name; + } + if (action === "factory") { + const profiles = await client.readOnboardProfiles(); + if (profiles.length === 0) await client.initializeBlankOnboardProfiles(); + else await client.resetAllOnboardProfiles(); + if (lastStatus.get(key)) lastStatus.get(key).deviceMode = "Onboard"; + return "Onboard"; + } if (action === "stages") { - await client.setProfileDpiStages(value); + const { sector, ...plan } = value; + const options: number[] | null = lastStatus.get(key)?.dpiOptions ?? await client.getDpiOptions().catch(() => null); + if (options?.length) { + const snap = (v: number) => options.reduce((best, o) => (Math.abs(o - v) < Math.abs(best - v) ? o : best)); + plan.stages = plan.stages.map((stage: any) => ({ ...stage, x: snap(stage.x), y: snap(stage.y) })); + } + await client.writeActiveProfile({ sector, dpiStages: plan }); return value; } - return await client.setOnboardMode(value === "Onboard" ? "Onboard" : "Host"); + const mode = await client.setOnboardMode(value === "Onboard" ? "Onboard" : "Host"); + if (lastStatus.get(key)) lastStatus.get(key).deviceMode = mode; + return mode; } catch (error) { // Log sector/mode + HID++ feature versions so field rejections (e.g. #53) // are diagnosable from a single user log without a custom build. @@ -265,11 +305,11 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); }, /** * One live setting. Logitech goes through its receiver-aware module, every - * other brand through the generic one — the same split DevicePerformanceTab + * other brand through the generic one - the same split DevicePerformanceTab * makes. Resolves to the value the device actually applied. */ async write(argsJson: string): Promise { - const { key, brand, action, value } = JSON.parse(argsJson) as { + let { key, brand, action, value } = JSON.parse(argsJson) as { key: string; brand: string; action: string; @@ -292,12 +332,48 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); // A few controls decide which others are shown (a Starlight X switch in // TMR mode gains its analog settings, a magnetic button's rapid trigger its // sensitivity); their write returns the new layout. - if (id.startsWith("slx.mode") || id === "slx.link" || id === "hits.link" || id === "perf.stageCount" || id.startsWith("logi.remap.") || id.startsWith("mag.") || id.startsWith("x.nape.") || id.startsWith("x.xm.") || id.startsWith("x.fmp.name.") || id === "x.lg.name" || id.endsWith(".curve") || id.endsWith("/mode")) return JSON.stringify({ tabs: describeControls(brand, status, lastCaps.get(key)) }); + if (id.startsWith("slx.mode") || id === "slx.link" || id === "hits.link" || id === "perf.stageCount" || id.startsWith("logi.remap.") || id.startsWith("mag.") || id.startsWith("x.nape.") || id.startsWith("x.xm.") || id.startsWith("x.fmp.name.") || id === "x.lg.name" || id === "x.lg.restoreButtons" || id.endsWith(".curve") || id.endsWith("/mode")) return JSON.stringify({ tabs: describeControls(brand, status, lastCaps.get(key)) }); return JSON.stringify(value); } if (action === "lighting") { return JSON.stringify(await writeLighting(info, lastStatus.get(key) ?? {}, value)); } + const onboard = lastStatus.get(key); + const options: number[] | undefined = onboard?.dpiOptions; + if (brand === "Logitech" && action === "dpi" && options?.length) { + const snap = (v: number) => options.reduce((best, o) => (Math.abs(o - v) < Math.abs(best - v) ? o : best)); + value = typeof value === "number" ? snap(value) : { ...value, x: snap(value.x), y: snap(value.y) }; + } + if (brand === "Logitech" && (action === "dpi" || action === "pollingRate" || action === "liftOff") && onboard?.deviceMode === "Onboard" && onboard?.onboardProfileFormat?.writable) { + return JSON.stringify(await withLogitechClient(info, `profile ${action}`, async (client: any) => { + client.profileFormatId ??= onboard.onboardProfileFormat.id ?? null; + const profile = (await client.readOnboardProfiles()).find((p: any) => p.isCurrent); + if (!profile) throw new Error("Couldn't find the profile the mouse is running."); + if (action === "liftOff") { + const lod = ({ Low: 1, Medium: 2, High: 3 } as Record)[value]; + if (!lod || !profile.dpiStages.some((stage: any) => stage.lod > 0)) throw new Error("This profile doesn't store a lift-off distance. Switch the mouse to host mode to change it."); + const stages = profile.dpiStages.map((stage: any) => ({ ...stage, lod })); + await client.writeActiveProfile({ sector: profile.sector, dpiStages: { stages, defaultIndex: Math.min(profile.defaultDpiIndex ?? 0, stages.length - 1) } }); + return value; + } + if (action === "pollingRate") { + const wired = onboard.connectionType === "Wired"; + if (client.usbTransportId == null) { + const firmware = await client.getFeature(0x0003); + if (firmware.index) client.usbTransportId = (await client.readIdentity(firmware.index)).transportIds.USB ?? null; + } + await client.writeActiveProfile({ sector: profile.sector, [wired ? "reportRateWiredHz" : "reportRateWirelessHz"]: value }); + } else { + const [x, y] = typeof value === "number" ? [value, value] : [value.x, value.y]; + const index = Math.min(profile.defaultDpiIndex ?? 0, profile.dpiStages.length - 1); + if (index < 0) throw new Error("This profile has no DPI stages."); + const stages = profile.dpiStages.map((stage: any, i: number) => (i === index ? { ...stage, x: Math.round(x), y: Math.round(y) } : stage)); + await client.writeActiveProfile({ sector: profile.sector, dpiStages: { stages, defaultIndex: index } }); + } + await client.setCurrentProfile(profile.sector); + return typeof value === "number" ? value : Math.round(value.x ?? value); + })); + } switch (action) { case "dpi": { const has = (method: string) => (lastStatus.get(key)?.methods ?? []).includes(method); diff --git a/gpui/js/extra-controls.ts b/gpui/js/extra-controls.ts index 199c0c66..8f1341c6 100644 --- a/gpui/js/extra-controls.ts +++ b/gpui/js/extra-controls.ts @@ -302,7 +302,7 @@ function razerToggles(s: any, has: (m: string) => boolean): Section[] { options: choices([...new Set([info.enabledLabel, "Disabled"])]), current: s.razerButtonMappings[control], })); - return controls.length ? [{ title: "Razer — Scroll & toggles", controls }] : []; + return controls.length ? [{ title: "Razer - Scroll & toggles", controls }] : []; } /** ATK R1 button remapping. */ @@ -313,7 +313,7 @@ function atkButtons(s: any, has: (m: string) => boolean): Section[] { id: `x.atkButton.${b.id}`, label: `${b.name} button`, kind: "choice", options, current: options.find((o) => o.label === b.action)?.value ?? null, })); - return [{ title: "ATK — Buttons", controls }]; + return [{ title: "ATK - Buttons", controls }]; } /** Every extra control this device has. `status.methods` lists its driver's setters. */ diff --git a/gpui/js/globals.ts b/gpui/js/globals.ts index f5bb687a..020c3152 100644 --- a/gpui/js/globals.ts +++ b/gpui/js/globals.ts @@ -88,10 +88,18 @@ g.TextEncoder ??= class TextEncoder { } }; g.TextDecoder ??= class TextDecoder { + private utf16: boolean; + constructor(label = "utf-8") { + this.utf16 = /^utf-?16(le)?$/i.test(label); + } decode(input?: ArrayBufferView | ArrayBuffer): string { if (!input) return ""; const b = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength); let out = ""; + if (this.utf16) { + for (let i = 0; i + 1 < b.length; i += 2) out += String.fromCharCode(b[i] | (b[i + 1] << 8)); + return out; + } for (let i = 0; i < b.length; ) { const c = b[i++]; let cp: number; diff --git a/gpui/js/keyboard-via.ts b/gpui/js/keyboard-via.ts new file mode 100644 index 00000000..a92adbd1 --- /dev/null +++ b/gpui/js/keyboard-via.ts @@ -0,0 +1,379 @@ +import { invoke } from "@tauri-apps/api/core"; +import { + decodeViaMacro, describeViaKeycode, encodeViaMacro, evaluateViaCondition, joinViaMacros, parseViaDefinition, parseViaMacroExpression, + parseViaMenus, viaActiveKeys, viaKeycodeFromLayoutName, viaKeycodePicker, viaKeycodeToLayoutName, viaLayoutChoices, viaMacroToExpression, + viaNumberToBytes, viaPackLayoutChoices, viaValueToNumber, VIA_MACRO_DELAY_PROTOCOL, type ViaDefinition, type ViaKeycodeGroupId, + type ViaMacroAction, type ViaMenuItem, +} from "@openmouse/keyboard-protocol/via"; +import { hidUsage } from "./keys"; +import { MODIFIERS, nameOf, numbered, type MacroStep } from "./macros"; +import type { HidInterfaceInfo } from "./native-hid/tauri-hid-device"; + +export const VIA_FEATURES = { remap: true, noSave: true }; + +const ENCODER_ROW = 200; + +const GROUP_NAMES: Record = { + letters: "Letters", numbers: "Numbers", symbols: "Symbols", function: "Function keys", + navigation: "Navigation", keypad: "Keypad", modifiers: "Modifiers", media: "Media", + special: "Special", layers: "Layers", macros: "Macros", lighting: "Lighting", custom: "Custom", +}; + +const definitions = new Map(); + +export async function viaDefinition(info: HidInterfaceInfo): Promise { + const id = `${info.vendorId}:${info.productId}`; + if (definitions.has(id)) return definitions.get(id)!; + const text = await invoke("via_definition", { vendorId: info.vendorId, productId: info.productId }); + let definition: ViaDefinition | null = null; + try { + definition = text ? parseViaDefinition(JSON.parse(text)) : null; + } catch { + definition = null; + } + definitions.set(id, definition); + return definition; +} + +async function context(client: any, info: HidInterfaceInfo) { + const via = (await client.readStatus()).via; + if (!via?.layerCount) throw new Error("The keyboard did not report its VIA layers."); + const definition = await viaDefinition(info); + if (!definition) throw new Error("VIA has no layout for this keyboard, so its keys can't be shown."); + const label = (code: number) => describeViaKeycode(code, via.protocolVersion, definition.customKeycodes).label; + const choices = via.layoutOptions == null ? [] : viaLayoutChoices(definition.labels, via.layoutOptions); + return { via, definition, label, choices }; +} + +async function readKeys(client: any, info: HidInterfaceInfo, wanted: number) { + const { via, definition, label, choices } = await context(client, info); + const layer = Math.min(via.layerCount - 1, Math.max(0, wanted)); + const keymap: number[][] = await client.readKeymap(definition.matrix, layer + 1); + const codes = keymap[layer] ?? []; + const active = viaActiveKeys(definition, choices); + const keys = active + .filter((key) => key.row >= 0) + .map((key) => { + const code = codes[key.row * definition.matrix.cols + key.col] ?? 0; + return { row: key.row, col: key.col, x: key.x, y: key.y, w: key.w, h: key.h, code, label: label(code), standard: code, standardLabel: "" }; + }); + const encoders = [...new Set(active.filter((key) => key.encoder !== undefined).map((key) => key.encoder!))].sort((a, b) => a - b); + const bottom = Math.max(0, ...keys.map((key) => key.y + key.h)); + for (const [index, id] of encoders.entries()) { + for (const clockwise of [false, true]) { + const code = await client.readEncoder(layer, id, clockwise); + keys.push({ + row: ENCODER_ROW + id, col: clockwise ? 1 : 0, x: index * 2.25 + (clockwise ? 1 : 0), y: bottom + 0.25, w: 1, h: 1, + code, label: `${clockwise ? "↻" : "↺"} ${label(code)}`, standard: code, standardLabel: "", + }); + } + } + const groups = viaKeycodePicker(via.protocolVersion, via.layerCount, via.macroCount ?? 0, { + modules: definition.keycodeModules, custom: definition.customKeycodes, + }); + return { + layer, + layers: via.layerCount, + width: Math.max(definition.width, encoders.length * 2.25), + keys, + categories: groups + .filter((group) => group.keycodes.length > 0) + .map((group) => ({ name: GROUP_NAMES[group.id], keys: group.keycodes.map((code) => ({ code, label: label(code) })) })), + }; +} + +async function setKey(client: any, info: HidInterfaceInfo, args: any) { + const { layer, row, col, code } = args; + const { via, definition, label } = await context(client, info); + if (![layer, row, col, code].every(Number.isInteger) || layer < 0 || layer >= via.layerCount || code < 0 || code > 0xffff) { + throw new RangeError("That key can't be assigned."); + } + if (row >= ENCODER_ROW) { + const confirmed = await client.setEncoder(layer, row - ENCODER_ROW, col === 1, code); + return { row, col, code: confirmed, label: `${col === 1 ? "↻" : "↺"} ${label(confirmed)}` }; + } + if (row >= definition.matrix.rows || col >= definition.matrix.cols) throw new RangeError("That key is outside the keyboard's matrix."); + const confirmed = await client.setKeycode(layer, row, col, code); + return { row, col, code: confirmed, label: label(confirmed) }; +} + +export async function viaOp(client: any, info: HidInterfaceInfo, op: string, args: any): Promise { + switch (op) { + case "keys": + return readKeys(client, info, Number(args.layer) || 0); + case "setKey": + return setKey(client, info, args); + case "save": + return true; + default: + throw new Error(`Unknown keyboard operation ${op}`); + } +} + +const valueKey = (ids: readonly number[]) => ids.join(":"); +const itemLength = (item: ViaMenuItem) => (item.control.type === "color" ? 2 : item.bytes); +const wire = (item: ViaMenuItem, protocol: number) => + protocol < 11 && item.legacyId !== undefined ? [item.legacyId, ...item.ids.slice(2)] : item.ids; + +function hsvToHex(hue: number, saturation: number): string { + const h = (hue / 255) * 6; + const s = saturation / 255; + const f = (n: number) => { + const k = (n + h) % 6; + return Math.round(255 * (1 - s * Math.max(0, Math.min(k, 4 - k, 1)))); + }; + return `#${[f(5), f(3), f(1)].map((v) => v.toString(16).padStart(2, "0")).join("")}`; +} + +function hexToHsv(hex: string): [number, number] { + const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); + if (!m) throw new RangeError("That is not a colour."); + const [r, g, b] = [0, 2, 4].map((i) => parseInt(m[1]!.slice(i, i + 2), 16) / 255) as [number, number, number]; + const max = Math.max(r, g, b); + const delta = max - Math.min(r, g, b); + let hue = 0; + if (delta > 0) hue = max === r ? ((g - b) / delta + 6) % 6 : max === g ? (b - r) / delta + 2 : (r - g) / delta + 4; + return [Math.round((hue / 6) * 255) % 256, Math.round((max === 0 ? 0 : delta / max) * 255)]; +} + +async function menuState(client: any, info: HidInterfaceInfo) { + const { via, definition, label, choices } = await context(client, info); + const items = parseViaMenus(definition.menus).flatMap((menu) => menu.sections.flatMap((section) => section.items)); + const values = new Map(); + for (const item of items) { + const key = valueKey(item.ids); + if (values.has(key) || item.control.type === "button") continue; + values.set(key, await client.readCustomValue(wire(item, via.protocolVersion), itemLength(item)).catch(() => null)); + } + return { via, definition, label, choices, items, values }; +} + +function itemControl(item: ViaMenuItem, value: number[] | null) { + const id = `via.v.${valueKey(item.ids)}`; + const control = item.control; + const number = value ? viaValueToNumber(value) : null; + if (control.type === "range") return { id, label: item.label, kind: "number", min: control.min, max: control.max, step: 1, unit: control.unit, current: number ?? control.min }; + if (control.type === "toggle") return { id, label: item.label, kind: "toggle", current: number === null ? false : control.anyOn ? number !== control.off : number === control.on }; + if (control.type === "dropdown") return { id, label: item.label, kind: "choice", options: control.options, current: number }; + if (control.type === "color") return { id, label: item.label, kind: "color", current: value && value.length >= 2 ? hsvToHex(value[0]!, value[1]!) : "#ffffff" }; + return { id, label: item.label, kind: "button", options: [{ label: item.label, value: control.value }], current: control.value }; +} + +const labelTitle = (label: unknown) => (Array.isArray(label) ? String(label[0]) : String(label)); + +export async function viaSections(client: any, info: HidInterfaceInfo) { + const { via, definition, choices, values } = await menuState(client, info); + const known = new Map(); + for (const item of parseViaMenus(definition.menus).flatMap((menu) => menu.sections.flatMap((section) => section.items))) { + const value = values.get(valueKey(item.ids)); + if (value) known.set(item.token, viaValueToNumber(value)); + } + const shown = (expression?: string) => !expression || evaluateViaCondition(expression, (token) => known.get(token)); + const lighting: { title: string; controls: unknown[] }[] = []; + const sections: { title: string; controls: unknown[] }[] = []; + for (const menu of parseViaMenus(definition.menus).filter((m) => shown(m.showIf))) { + for (const section of menu.sections) { + const controls = section.items.filter((item) => shown(item.showIf)).map((item) => itemControl(item, values.get(valueKey(item.ids)) ?? null)); + if (controls.length) lighting.push({ title: section.label && section.label !== menu.label ? `${menu.label}: ${section.label}` : menu.label, controls }); + } + } + if (definition.labels.length) { + sections.push({ + title: "Layout", + controls: definition.labels.map((label, index) => Array.isArray(label) + ? { id: `via.layout.${index}`, label: labelTitle(label), kind: "choice", options: label.slice(1).map((name, value) => ({ label: String(name), value })), current: choices[index] ?? 0 } + : { id: `via.layout.${index}`, label: labelTitle(label), kind: "toggle", current: (choices[index] ?? 0) === 1 }), + }); + } + sections.push({ + title: "Backup", + controls: [ + { id: "via.file.save", label: "Save layout file", description: "The keymap, macros and knobs as a VIA .layout.json file.", kind: "saveFile", options: [{ label: "Save…", value: `${definition.name.replace(/[^a-zA-Z0-9]/g, "_").toLowerCase() || "keyboard"}.layout.json` }], current: null }, + { id: "via.file.load", label: "Load layout file", description: "Replaces the keymap, macros and knobs with a VIA .layout.json file.", kind: "openFile", options: [{ label: "Load…", value: "json" }], current: null }, + ], + }); + return { lighting, advanced: sections }; +} + +function encoderIds(definition: ViaDefinition, choices: number[]): number[] { + return [...new Set(viaActiveKeys(definition, choices).filter((key) => key.encoder !== undefined).map((key) => key.encoder as number))].sort((a, b) => a - b); +} + +async function layoutFile(client: any, info: HidInterfaceInfo) { + const { via, definition, choices } = await context(client, info); + const name = (code: number) => viaKeycodeToLayoutName(code, via.protocolVersion); + const keymap: number[][] = await client.readKeymap(definition.matrix, via.layerCount); + const macros = (via.macroCount ?? 0) > 0 ? await client.readMacros() : null; + const ids = encoderIds(definition, choices); + const encoders: [string, string][][] = Array.from({ length: ids.length ? ids[ids.length - 1] + 1 : 0 }, () => []); + for (const id of ids) { + for (let layer = 0; layer < via.layerCount; layer++) { + encoders[id].push([name(await client.readEncoder(layer, id, false)), name(await client.readEncoder(layer, id, true))]); + } + } + return JSON.stringify({ + name: definition.name, + vendorProductId: info.vendorId * 65536 + info.productId, + macros: macros ? macros.macros.map((bytes: number[]) => viaMacroToExpression(decodeViaMacro(bytes, via.protocolVersion), via.protocolVersion)) : [], + layers: keymap.map((layer) => layer.map(name)), + encoders, + }, null, 2); +} + +async function loadLayoutFile(client: any, info: HidInterfaceInfo, text: string) { + const { via, definition, choices } = await context(client, info); + let file: any; + try { + file = JSON.parse(text); + } catch { + throw new Error("That file is not a VIA layout file."); + } + if (!file || !Array.isArray(file.layers) || file.layers.length === 0) throw new Error("That file is not a VIA layout file."); + if (file.vendorProductId !== info.vendorId * 65536 + info.productId) throw new Error("That layout file is for a different keyboard."); + const { rows, cols } = definition.matrix; + const code = (entry: unknown) => { + const found = typeof entry === "string" ? viaKeycodeFromLayoutName(entry, via.protocolVersion) : null; + if (found === null) throw new Error(`The layout file has a key this app doesn't know: ${String(entry)}.`); + return found; + }; + const layers = file.layers.slice(0, via.layerCount).map((layer: unknown) => { + if (!Array.isArray(layer) || layer.length !== rows * cols) throw new Error("The layout file's layers don't match this keyboard."); + return layer.map(code); + }); + const macros = (via.macroCount ?? 0) > 0 && Array.isArray(file.macros) && file.macros.length > 0 ? await client.readMacros() : null; + let encoded: number[][] | null = null; + if (macros) { + if (file.macros.length !== macros.count) throw new Error("The layout file has a different number of macros."); + encoded = file.macros.map((expression: unknown) => encodeViaMacro(parseViaMacroExpression(String(expression), via.protocolVersion), via.protocolVersion)); + joinViaMacros(encoded!, macros.bufferSize); + } + const ids = new Set(encoderIds(definition, choices)); + const turns: { layer: number; id: number; clockwise: boolean; code: number }[] = []; + for (const [id, perLayer] of (Array.isArray(file.encoders) ? file.encoders : []).entries()) { + if (!ids.has(id) || !Array.isArray(perLayer)) continue; + for (const [layer, pair] of perLayer.entries()) { + if (layer >= via.layerCount || !Array.isArray(pair)) continue; + turns.push({ layer, id, clockwise: false, code: code(pair[0]) }, { layer, id, clockwise: true, code: code(pair[1]) }); + } + } + await client.writeKeymap(layers, definition.matrix); + if (encoded) await client.writeMacros(encoded); + for (const turn of turns) await client.setEncoder(turn.layer, turn.id, turn.clockwise, turn.code); +} + +export async function viaWrite(client: any, info: HidInterfaceInfo, id: string, value: unknown): Promise { + if (id === "via.file.save") return layoutFile(client, info); + if (id === "via.file.load") { + await loadLayoutFile(client, info, String(value)); + return null; + } + const { via, definition, choices, items } = await menuState(client, info); + const layout = /^via\.layout\.(\d+)$/.exec(id); + if (layout) { + const index = Number(layout[1]); + const label = definition.labels[index]; + if (label === undefined) throw new RangeError("That layout option doesn't exist."); + const next = [...choices]; + next[index] = typeof value === "boolean" ? Number(value) : Number(value); + await client.setLayoutOptions(viaPackLayoutChoices(definition.labels, next)); + return null; + } + const item = items.find((entry) => `via.v.${valueKey(entry.ids)}` === id); + if (!item) throw new Error("That setting isn't on this keyboard."); + const control = item.control; + const address = wire(item, via.protocolVersion); + const legacy = address !== item.ids; + let bytes: number[]; + let verify = true; + if (control.type === "color") bytes = hexToHsv(String(value)); + else if (control.type === "toggle") bytes = viaNumberToBytes(value ? control.on : control.off, item.bytes); + else if (control.type === "button") { + bytes = viaNumberToBytes(control.value, item.bytes); + verify = false; + } else { + const number = Number(value); + if (!Number.isInteger(number)) throw new RangeError("That value is out of range."); + if (control.type === "range" && (number < control.min || number > control.max)) throw new RangeError("That value is out of range."); + bytes = viaNumberToBytes(number, item.bytes); + } + let confirmed: number[] = await client.setCustomValue(address, bytes, verify); + if (verify && control.type === "range" && bytes.length === 1 && confirmed[0] !== bytes[0]) { + const target = bytes[0]!; + const retry = target + (target - confirmed[0]!); + if (retry >= 0 && retry <= 0xff) { + const second = await client.setCustomValue(address, [retry], true); + confirmed = Math.abs(second[0]! - target) <= Math.abs(confirmed[0]! - target) ? second : await client.setCustomValue(address, bytes, true); + } + } + await client.saveCustomChannel(item.ids[0]!, legacy); + return null; +} + +export const viaMacroPanel = (count: number) => ({ + slots: numbered(count, "Macro"), + buttons: [], + maxSteps: 128, + modifiers: true, + mouse: false, + readable: true, + warning: null, + note: "Put a macro on a key from the Macros group on the Keys tab. Saving keeps it on the keyboard.", +}); + +const usageOf = (key: string) => MODIFIERS[key] ?? hidUsage(key); + +function toSteps(actions: ViaMacroAction[]): MacroStep[] { + const steps: MacroStep[] = []; + const press = (usage: number, down: boolean) => { + if (usage >= 0xe4 && usage <= 0xe7) throw new Error("This macro uses a right-hand Ctrl, Shift, Alt or Win key, which this editor can't keep. Edit it in VIA."); + steps.push({ key: nameOf(usage), down, delay: 0 }); + }; + for (const action of actions) { + if (action.type === "delay") { + if (!steps.length) throw new Error("This macro starts with a pause, which this editor can't keep. Edit it in VIA so a key comes first."); + steps[steps.length - 1]!.delay += action.ms; + } else if (action.type === "tap") { + press(action.keycode, true); + press(action.keycode, false); + } else if (action.type === "down" || action.type === "up") { + press(action.keycode, action.type === "down"); + } else { + for (const char of action.text) { + const upper = char.toUpperCase(); + const shifted = /[A-Z]/.test(char); + if (char === " ") { + press(0x2c, true); + press(0x2c, false); + continue; + } + if (!/^[A-Z0-9]$/.test(upper)) throw new Error("This macro types text the app can't show, so it is left as it is."); + if (shifted) press(MODIFIERS.Shift!, true); + press(hidUsage(upper), true); + press(hidUsage(upper), false); + if (shifted) press(MODIFIERS.Shift!, false); + } + } + } + return steps; +} + +export async function viaMacroOp(client: any, op: string, args: any): Promise { + const via = (await client.readStatus()).via; + const macros = await client.readMacros(); + const slot = Number(args.slot) || 0; + if (slot < 0 || slot >= macros.count) throw new RangeError("That macro doesn't exist."); + if (op === "read") return toSteps(decodeViaMacro(macros.macros[slot] ?? [], via.protocolVersion)); + if (op !== "save") throw new Error(`Unknown macro operation ${op}`); + const delays = via.protocolVersion >= VIA_MACRO_DELAY_PROTOCOL; + const actions: ViaMacroAction[] = []; + if (!delays && (args.steps as MacroStep[]).some((step) => step.delay > 0)) throw new Error("This keyboard's firmware can't store pauses in macros. Remove the delays and save again."); + for (const step of args.steps as MacroStep[]) { + actions.push({ type: step.down ? "down" : "up", keycode: usageOf(step.key) }); + if (delays && step.delay > 0) actions.push({ type: "delay", ms: step.delay }); + } + const next = macros.macros.map((bytes: number[]) => [...bytes]); + next[slot] = encodeViaMacro(actions, via.protocolVersion); + joinViaMacros(next, macros.bufferSize); + await client.writeMacros(next); + return true; +} diff --git a/gpui/js/keyboards.ts b/gpui/js/keyboards.ts index ca121aba..d9fbfd94 100644 --- a/gpui/js/keyboards.ts +++ b/gpui/js/keyboards.ts @@ -9,6 +9,7 @@ import { invoke } from "@tauri-apps/api/core"; import { VIA_USAGE, VIA_USAGE_PAGE } from "@openmouse/keyboard-protocol/via"; import { WUQUE_FEATURES, wuqueOp } from "./keyboard-wuque"; +import { VIA_FEATURES, viaMacroOp, viaMacroPanel, viaOp, viaSections, viaWrite } from "./keyboard-via"; import { DEVICE_DRIVERS, type DeviceDriver } from "@openmouse/keyboard-protocol/drivers/registry"; import { SUPPORTED_HID_FILTERS } from "@openmouse/keyboard-protocol/drivers/vendors"; import { listHidInterfaces, TauriHidDevice, type HidInterfaceInfo } from "./native-hid/tauri-hid-device"; @@ -171,7 +172,7 @@ export function describeKeyboard(key: string, brand: string, status: any) { status: { ...status, firmware: version ? [version] : status.firmware ?? [], - keyboardFeatures: brand === "Wuque Studio" ? WUQUE_FEATURES : null, + keyboardFeatures: brand === "Wuque Studio" ? WUQUE_FEATURES : brand === "VIA" ? VIA_FEATURES : null, }, controls: null, tabs: { @@ -179,6 +180,7 @@ export function describeKeyboard(key: string, brand: string, status: any) { buttons: [], advanced: controls.length ? [{ title: "Keyboard", controls }] : [], lighting: null, + macros: brand === "VIA" && (status.via?.macroCount ?? 0) > 0 ? viaMacroPanel(status.via.macroCount) : null, }, }; } @@ -193,16 +195,31 @@ export async function connectKeyboard(info: KeyboardInterface) { const readout = describeKeyboard(info.key, brand, { ...status, pollingRateHz: rates.pollingRateHz, supportedPollingRates: rates.supportedPollingRates, // These controls are offered only after the hardware returns a profile. - ui: sections.length ? { ...status.ui, settingsReady: true, statusNote: undefined } : status.ui, + ui: sections.length ? { ...status.ui, settingsReady: true, statusNote: undefined } : brand === "VIA" ? { ...status.ui, settingsReady: true } : status.ui, }); readout.tabs.advanced.unshift(...sections); + if (brand === "VIA") { + const via = await viaSections(client, info).catch(() => null); + if (via) { + readout.tabs.advanced.unshift(...via.advanced as any[]); + (readout.tabs as any).keyboardLighting = via.lighting; + } + } return readout; }); } +export async function keyboardMacroOp(info: HidInterfaceInfo, op: string, args: any): Promise { + return withKeyboard(info, async (client, brand) => { + if (brand !== "VIA") throw new Error("This keyboard has no macros the app can edit."); + return viaMacroOp(client, op, args); + }); +} + /** Keys, actuation and lighting, where this app can change them. */ export async function keyboardOp(info: HidInterfaceInfo, op: string, args: any): Promise { return withKeyboard(info, async (client, brand) => { + if (brand === "VIA") return viaOp(client, info, op, args); if (brand !== "Wuque Studio") throw new Error("This app can't change that on this keyboard yet."); return wuqueOp(client, op, args); }); @@ -220,6 +237,16 @@ export async function writeKeyboard(info: KeyboardInterface, action: string, val return { tabs: { ...readout.tabs, advanced: [...sections, ...readout.tabs.advanced] } }; }); } + if (action.startsWith("control:via.")) { + return withKeyboard(info, async (client, brand) => { + if (brand !== "VIA") throw new Error("This control requires a VIA keyboard."); + const file = await viaWrite(client, info, action.slice("control:".length), value); + if (file !== null) return file; + const readout = describeKeyboard(info.key, brand, await client.readStatus()); + const via = await viaSections(client, info); + return { tabs: { ...readout.tabs, advanced: [...via.advanced as any[], ...readout.tabs.advanced], keyboardLighting: via.lighting } }; + }); + } if (action !== "pollingRate") throw new Error("This app can't change that on a keyboard yet."); return withKeyboard(info, async (client, brand) => { if (brand === "Logitech") { diff --git a/gpui/js/lib/changelog.ts b/gpui/js/lib/changelog.ts index daf4517d..52c8acda 100644 --- a/gpui/js/lib/changelog.ts +++ b/gpui/js/lib/changelog.ts @@ -16,7 +16,7 @@ export type ChangelogItem = export interface ChangelogEntry { version: string; - /** ISO date (YYYY-MM-DD), not a Date — this is display-only, never compared. */ + /** ISO date (YYYY-MM-DD), not a Date - this is display-only, never compared. */ date: string; changes: ChangelogItem[]; } diff --git a/gpui/js/lib/game-profiles.ts b/gpui/js/lib/game-profiles.ts index ccf83e86..5b93e07d 100644 --- a/gpui/js/lib/game-profiles.ts +++ b/gpui/js/lib/game-profiles.ts @@ -1,14 +1,14 @@ -// Per-game device profiles — a saved DPI/polling-rate configuration a user +// Per-game device profiles - a saved DPI/polling-rate configuration a user // can define once per game (pages/GamesPage.tsx, components/GameProfilePanel.tsx) // and have pushed to the connected mouse either on demand ("Apply now") or // automatically the instant that game's process is detected running // (hooks/use-game-watcher.ts's rising-edge check against // running_process_names). Persisted the same way as native-hid/device-store.ts -// — plain localStorage, keyed by games.json's own `id`, not a source of +// - plain localStorage, keyed by games.json's own `id`, not a source of // truth for anything the device itself reports. // -// Covers every writable setting DevicePerformanceTab exposes — DPI, -// polling rate, lift-off distance, and gaming surface mode — not just +// Covers every writable setting DevicePerformanceTab exposes - DPI, +// polling rate, lift-off distance, and gaming surface mode - not just // DPI/rate. Lift-off and surface mode are guarded behind the same // `status.supportedLiftOffDistances`/`status.gamingSurfaceMode` presence // checks DevicePerformanceTab itself uses (GameProfilePanel.tsx), so a @@ -16,7 +16,7 @@ // reports supporting. // // A field being `undefined` means "this profile doesn't touch that setting," -// not "set it to nothing" — a profile can be DPI-only, or rate-only. +// not "set it to nothing" - a profile can be DPI-only, or rate-only. // applyGameProfile() below skips whatever isn't set. import type { MouseStatus } from "@openmouse/protocol/drivers/mouse-types"; @@ -53,7 +53,7 @@ function load(): ProfileMap { const parsed: unknown = JSON.parse(raw); return parsed && typeof parsed === "object" ? (parsed as ProfileMap) : {}; } catch { - // Private-browsing-style storage blocks, corrupted JSON, whatever — this + // Private-browsing-style storage blocks, corrupted JSON, whatever - this // is a convenience, not a source of truth, so just start empty. return {}; } @@ -66,7 +66,7 @@ function persist() { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(profiles)); } catch { - // Best-effort — losing saved profiles just means re-entering them. + // Best-effort - losing saved profiles just means re-entering them. } } @@ -137,10 +137,10 @@ export function describeProfile(profile: GameProfile): string { * * Every other brand has no index to resolve (see write.ts's docs), so each * field is applied with its own short-lived generic open -> act -> close - * write — the same cost DevicePerformanceTab's individual controls pay. + * write - the same cost DevicePerformanceTab's individual controls pay. * * Applies every field independently rather than stopping at the first - * failure — a mouse that rejects one setting (e.g. an unsupported polling + * failure - a mouse that rejects one setting (e.g. an unsupported polling * rate) shouldn't also block the DPI change that would have worked fine. * Failures are collected and thrown together so the caller can show one * toast instead of a flurry of them. diff --git a/gpui/js/lib/logitech-controls.ts b/gpui/js/lib/logitech-controls.ts index 031a8c94..fa2ccea5 100644 --- a/gpui/js/lib/logitech-controls.ts +++ b/gpui/js/lib/logitech-controls.ts @@ -1,17 +1,17 @@ // Shared constants for editing a Logitech HID++ mouse's live-writable -// settings — used by both the always-on device control tab +// settings - used by both the always-on device control tab // (components/DevicePerformanceTab.tsx) and the per-game profile editor // (components/GameProfilePanel.tsx), so the two don't drift out of sync on // what counts as a "preset" DPI or a valid surface mode. import type { GamingSurfaceMode } from "../native-hid/logitech-actions"; -// Common sensitivity steps — same list the webapp offers, not every value +// Common sensitivity steps - same list the webapp offers, not every value // this sensor can actually hit (custom DPI inputs are for that). export const DPI_PRESETS = [400, 800, 1600, 3200, 6400, 8000]; // Logitech HERO 2-class sensors (PRO X Superlight 2, G502 X family, ...) // this driver has been tested against top out at 32000 DPI. Not every mouse -// on this driver actually goes that high — the device is the source of +// on this driver actually goes that high - the device is the source of // truth: setDpi()'s return value is what actually gets displayed, this is // just the input's outer bound. export const DPI_MIN = 50; diff --git a/gpui/js/macros.ts b/gpui/js/macros.ts index 34bc2c3e..02463fc0 100644 --- a/gpui/js/macros.ts +++ b/gpui/js/macros.ts @@ -34,11 +34,11 @@ export interface MacroPanel { note: string; } -const MODIFIERS: Record = { Ctrl: 0xe0, Shift: 0xe1, Alt: 0xe2, Win: 0xe3 }; +export const MODIFIERS: Record = { Ctrl: 0xe0, Shift: 0xe1, Alt: 0xe2, Win: 0xe3 }; const MOUSE = ["Left", "Right", "Middle", "Back", "Forward"]; -const numbered = (count: number, word: string): Choice[] => +export const numbered = (count: number, word: string): Choice[] => Array.from({ length: count }, (_, i) => ({ value: i, label: `${word} ${i + 1}` })); -const nameOf = (usage: number): string => { +export const nameOf = (usage: number): string => { const modifier = Object.keys(MODIFIERS).find((k) => MODIFIERS[k] === usage || MODIFIERS[k]! + 4 === usage); if (modifier) return modifier; const candidates = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", ...Array.from({ length: 24 }, (_, i) => `F${i + 1}`), diff --git a/gpui/js/more-controls.ts b/gpui/js/more-controls.ts index 6e43309e..2ac6c183 100644 --- a/gpui/js/more-controls.ts +++ b/gpui/js/more-controls.ts @@ -96,7 +96,7 @@ function mapSections(s: any, written: Record): Section[] { }; }); controls[0]!.description = "Shows what was set from this app."; - return [{ title: "SteelSeries — Button map", controls }]; + return [{ title: "SteelSeries - Button map", controls }]; } async function writeMap(info: HidInterfaceInfo, s: any, id: string, value: string) { @@ -143,6 +143,35 @@ export function moreControls(s: any, written: Record): Tabs { }], }); } + const logitech = s.driverName === "LogitechHidppClient"; + if (logitech && s.hostCount > 1 && s.currentHost != null) { + const options = Array.from({ length: s.hostCount }, (_, slot) => slot) + .filter((slot) => slot === s.currentHost || s.hostSlotsPaired?.[slot] === true) + .map((slot) => ({ value: slot, label: slot === s.currentHost ? `Computer ${slot + 1} (this one)` : `Computer ${slot + 1}` })); + if (options.length > 1) { + out.advanced.push({ + title: "Easy-Switch", + controls: [{ id: "x.lg.host", label: "Connected to", description: "Sends the mouse to another paired computer. Press the button underneath the mouse to bring it back.", kind: "choice", options, current: s.currentHost }], + }); + } + } + const diverted = Array.isArray(s.logitechButtons) ? s.logitechButtons.filter((b: any) => b.diverted) : []; + if (logitech && diverted.length) { + out.buttons.push({ + title: "Buttons held by another app", + controls: [{ + id: "x.lg.restoreButtons", label: diverted.map((b: any) => b.name).join(", "), + description: "Another program took these buttons over, so they do nothing on their own. Give them back to the mouse.", + kind: "choice", options: [{ value: "restore", label: "Give back" }], current: null, + }], + }); + } + if (logitech && s.hapticEnabled === true) { + out.advanced.push({ + title: "Haptics test", + controls: [{ id: "x.lg.hapticTest", label: "Test the haptics", description: "Plays a short buzz at the current strength.", kind: "choice", options: [{ value: "play", label: "Play" }], current: null }], + }); + } // Bunny hop lives in the stored profile, or in the mouse's memory while the // computer is in charge of it. if (capabilitiesForFormat(s.onboardProfileFormat?.id).bunnyHop) { @@ -175,7 +204,7 @@ export function moreControls(s: any, written: Record): Tabs { } if (has("setProximity")) { out.performance.push({ - title: "SteelSeries — Proximity", + title: "SteelSeries - Proximity", controls: [ { id: "x.prox.on", label: "Proximity sensor", description: "The three are sent together. Shows what was set here.", kind: "toggle", current: last("x.prox.on") ?? false }, { id: "x.prox.low", label: "Lower threshold", kind: "choice", options: PROXIMITY_STEPS, current: last("x.prox.low") ?? 10 }, @@ -205,6 +234,12 @@ export async function writeMore(info: HidInterfaceInfo, s: any, id: string, valu const name = String(value).trim(); await withLogitechClient(info, "rename the mouse", (client: any) => client.setFriendlyName(name)); s.friendlyName = name; + } else if (id === "x.lg.host") { + await withLogitechClient(info, "switch computers", (client: any) => client.requestHostSwitch(Number(value))); + } else if (id === "x.lg.restoreButtons") { + s.logitechButtons = await withLogitechClient(info, "give buttons back", (client: any) => client.clearButtonDiversion()); + } else if (id === "x.lg.hapticTest") { + await withLogitechClient(info, "play haptics", (client: any) => client.playHapticEffect()); } else if (id === "x.lg.hop" || id === "x.lg.hostHop") { const method = id === "x.lg.hop" ? "setBunnyHoppingMs" : "setHostBunnyHopMs"; await withLogitechClient(info, "set bunny hop", (client: any) => client[method](Number(value))); diff --git a/gpui/js/nape-controls.ts b/gpui/js/nape-controls.ts index 5c0dea4d..203c05a7 100644 --- a/gpui/js/nape-controls.ts +++ b/gpui/js/nape-controls.ts @@ -23,7 +23,7 @@ export function napeSections(s: any): Section[] { if (count < 1) return []; const layers = Array.from({ length: count }, (_, i) => ({ value: i + 1, label: `Layer ${i + 1}` })); const out: Section[] = [{ - title: "Nape — layers", + title: "Nape - layers", controls: [{ id: "x.nape.layer", label: "Layer in use", kind: "choice", options: layers, current: s.napeLayer ?? null }], }]; const map = s.napeKeymap; @@ -33,7 +33,7 @@ export function napeSections(s: any): Section[] { const key = (id: string, label: string, current: string): Control => ({ id, label, kind: "choice", options: actions(current), current }); out.push({ - title: "Nape — buttons and dial", + title: "Nape - buttons and dial", controls: [ { id: "x.nape.edit", label: "Editing", description: "Choose a layer to see and change.", kind: "choice", options: layers, current: map.layer }, { diff --git a/gpui/js/native-hid/brands.ts b/gpui/js/native-hid/brands.ts index 02102fc2..23dc2289 100644 --- a/gpui/js/native-hid/brands.ts +++ b/gpui/js/native-hid/brands.ts @@ -1,11 +1,11 @@ // Which drivers can drive a device, and which collection they talk on, come -// from `@openmouse/protocol` itself — its `DEVICE_DRIVERS` registry +// from `@openmouse/protocol` itself - its `DEVICE_DRIVERS` registry // (brand, supports, create, score) and its `SUPPORTED_HID_FILTERS`. // // This file used to carry a hand-maintained copy of all of that: 35 driver // imports, brand names, candidate order, product-id exclusions, and a guessed // Razer control collection. It had to, because the registry matches devices -// with `isSupported(device)`, which reads `device.collections` — and the Tauri +// with `isSupported(device)`, which reads `device.collections` - and the Tauri // transport could not supply collections (see tauri-hid-device.ts's own docs // saying so). That gap is closed: src-tauri/src/hid_descriptor.rs parses each // interface's report descriptor and the collections reach the device object, so @@ -27,7 +27,7 @@ export interface SupportedClient { export interface BrandedCandidate { /** The brand the registry attributes this driver to. */ brand: string; - /** Builds the driver for a device — the registry's own `create`. */ + /** Builds the driver for a device - the registry's own `create`. */ create: (device: HIDDevice) => SupportedClient | null; /** The registry's confidence that this driver fits, highest wins. */ score: (device: HIDDevice) => number; @@ -56,19 +56,19 @@ export function allKnownVendorIds(): number[] { /** * The collection a device's driver talks on, when the library declares one. * - * A request *filter* that names a usage is exactly that declaration — the + * A request *filter* that names a usage is exactly that declaration - the * library narrows those devices because it knows which collection the driver * uses (Logitech's HID++ interfaces on usage page 0xFF00, the Razer Viper V3's * Generic Desktop Mouse collection, and so on). A filter with no usage says the * opposite: "which interface carries the control channel has not been - * established, offer each one and let the driver reject what cannot answer" — + * established, offer each one and let the driver reject what cannot answer" - * and the transport does exactly that, fanned over every interface. * * Do not broaden this to the vendor's *other* entries. It looks tempting (seven * Razer filters name 0x01/0x02, and a DeathAdder V3 HyperSpeed's own filter is * bare), but MEASURED on that hardware: the interface which answers Razer's * commands is the composite one, not the single-collection Generic Desktop - * Mouse interface those filters name — a request written to the latter came + * Mouse interface those filters name - a request written to the latter came * back as a stale queued report and never as an answer. Ranking it first would * cost the connection that works. */ @@ -93,13 +93,13 @@ function preferredCollectionFor( /** * Every driver the library offers, in registry order, with the collection * preference its filters declare for this device. Callers keep the drivers that - * `supports(device)` claims and order them by `score(device)` — the same + * `supports(device)` claims and order them by `score(device)` - the same * decision the library makes in a browser, which is why no brand list lives * here any more. * * `create` is cast through `unknown`: a few driver classes (LogitechHidppClient, * for one) mark `open()` private in their own `.d.ts` since nothing inside - * mouse-protocol calls it externally, but every class does implement it — + * mouse-protocol calls it externally, but every class does implement it - * OpenMouse-Bridge's `native-hid/src/hid-device-adapter.mjs` already calls it * this way at runtime, from plain JS where compile-time privacy does not exist. * The cast tells TS to trust that, once, here. @@ -118,12 +118,12 @@ export function candidatesForVendorId(vendorId: number, productId: number): Bran /** * The drivers to try for one interface, best first. * - * The library decides: `supports(device)` — which reads `device.collections` — + * The library decides: `supports(device)` - which reads `device.collections` - * then `score(device)`. Where nothing claims the device, eligibility falls back * to the *vendor*, because on this host the collections are not always * available (hidapi cannot read a report descriptor on macOS, see * hid_descriptor.rs) and every one of those predicates needs them. The vendor - * gate is derived from the library on both sides — `VENDOR_ID`'s keys matched + * gate is derived from the library on both sides - `VENDOR_ID`'s keys matched * against the registry's brand names, normalised, since the library spells them * "Endgame Gear" there and `endgameGear` here. * @@ -139,7 +139,7 @@ export function candidatesForDevice(info: HidInterfaceInfo): BrandedCandidate[] // openmouse-hid merges every interface of a (vendorId, productId) into one // HidInterface. Drivers that expect a single-collection interface (such as // RazerViperV4ProHidClient's `device.collections.length === 1`) fail against - // the merged view, so also test each collection individually — matching what + // the merged view, so also test each collection individually - matching what // a browser hands `isSupported()`. const singleProbes = info.collections && info.collections.length > 1 diff --git a/gpui/js/native-hid/device-images.ts b/gpui/js/native-hid/device-images.ts index d46142a8..232e1e19 100644 --- a/gpui/js/native-hid/device-images.ts +++ b/gpui/js/native-hid/device-images.ts @@ -2,9 +2,9 @@ * Product photos for the device list and device card, keyed by the same * `vendorId:productId` string `HidInterfaceInfo.key` / `ConnectedDevice.key` * already use (see `tauri-hid-device.ts`'s `key()` and hid.rs's - * `interface_key()` — both hex-pad to `"0000:0000"`). + * `interface_key()` - both hex-pad to `"0000:0000"`). * - * Ported from the openmouse webapp's own `src/ui/device-images.ts` — same + * Ported from the openmouse webapp's own `src/ui/device-images.ts` - same * lookup table, same name-pattern fallback for shared receiver ids, just * re-keyed onto this app's own identifiers since there's no WebHID * `HIDDevice` here to read vendor/product off of directly. @@ -13,7 +13,7 @@ * Cloudflare R2 bucket the webapp serves from (see `DEVICE_IMAGE_BASE_URL` * below), not files bundled with this app. Previously every asset was * checked into `public/devices/` and had to be hand-copied from the webapp - * repo whenever new art landed there — the two copies drifted (this file's + * repo whenever new art landed there - the two copies drifted (this file's * DeathAdder V3 HyperSpeed entry kept resolving to the *corded* V3's photo * long after the webapp got a correct HyperSpeed-specific render, because * nothing forced the two lookup tables to agree). Pointing both apps at the @@ -146,7 +146,7 @@ const DEVICE_IMAGES: ReadonlyMap = new Map([ ]); /** - * Base URL of the public R2 bucket that hosts device art — the same bucket + * Base URL of the public R2 bucket that hosts device art - the same bucket * and custom domain the openmouse webapp's `src/ui/device-images.ts` uses. */ const DEVICE_IMAGE_BASE_URL = "https://img.openmouse.app/"; @@ -190,27 +190,27 @@ const ART_MAX_EXTENT = 50; /** * Where the product actually sits inside each artwork, as a fraction of the - * canvas — precomputed offline (alpha > 24 counts as ink; a product shot's + * canvas - precomputed offline (alpha > 24 counts as ink; a product shot's * last few fading pixels and any soft floor shadow don't) against the actual * files this app resolves to, both on `img.openmouse.app` and the local * overrides above. Keyed by filename, not URL, so it doesn't care whether a * given asset currently resolves to the CDN or a local override. * * This used to be measured at runtime by drawing each image to a canvas and - * reading its alpha channel (`getImageData`) — accurate, but it read pixels + * reading its alpha channel (`getImageData`) - accurate, but it read pixels * out of an `` loaded from `img.openmouse.app`, a different origin than * this app. That CDN sends no `Access-Control-Allow-Origin` header, which * taints the canvas and makes `getImageData` throw a SecurityError; every * tile silently fell back to plain `contain` sizing (CONFIRMED: this is why * a Logitech Superlight tile rendered visibly larger than a DeathAdder V3 - * tile next to it — the DeathAdder's fallback-sized render happened to look + * tile next to it - the DeathAdder's fallback-sized render happened to look * closer to "right" by coincidence, not because measuring worked). A static * table sidesteps CORS entirely and is exactly as accurate, since these * renders don't change after being uploaded. * * Regenerate by downloading each filename above and thresholding its alpha * channel's bounding box (`PIL.Image.split()[-1].point(...).getbbox()`, or - * equivalent) — same INK_ALPHA cutoff `measureInk` used to use (24). + * equivalent) - same INK_ALPHA cutoff `measureInk` used to use (24). */ const ART_BOUNDS: Readonly> = { "atk-f1-v2-ultra-max.png": { x: 0.2534, y: 0.0339, w: 0.4932, h: 0.9322, aspect: 1 }, @@ -272,7 +272,7 @@ const ART_BOUNDS: Readonly> = { /** * Where the product actually is inside one artwork, as a fraction of the * canvas. Synchronous now that it's a lookup rather than a canvas - * measurement — no image to wait for, so a caller no longer needs to render + * measurement - no image to wait for, so a caller no longer needs to render * once with a fallback style before the "real" size arrives. */ export function artBounds(filename: string): ArtBounds | null { @@ -280,7 +280,7 @@ export function artBounds(filename: string): ArtBounds | null { } /** - * Inline style that renders one artwork so its *subject* — not its canvas — + * Inline style that renders one artwork so its *subject* - not its canvas - * comes out the same size as every other tile's. * * The image is sized as a percentage of the square art box and scaled about @@ -323,9 +323,9 @@ export function deviceArtStyle(bounds: ArtBounds | null, target = ART_TARGET): s * `onError` handler for a device-artwork ``: retries the real source once * before settling for `unknown-device.png`. * - * The retry is the point. A single transient failure — a network hiccup + * The retry is the point. A single transient failure - a network hiccup * against `img.openmouse.app`, a request that raced the CDN's own cache - * warming — used to latch the placeholder onto that `` for the rest of + * warming - used to latch the placeholder onto that `` for the rest of * the page load, so a mouse whose artwork genuinely exists showed the * generic tile and looked unsupported. The retry carries a query string so * the browser cannot reuse its cached failure for that URL. @@ -344,7 +344,7 @@ export function deviceImageFallback(event: Event): void { /** * Best-known product photo for a device. `key` is `HidInterfaceInfo.key` / * `ConnectedDevice.key`; `displayName` is the product/friendly name (from - * `HidInterfaceInfo.productString` or `MouseStatus.name`) — used as a + * `HidInterfaceInfo.productString` or `MouseStatus.name`) - used as a * fallback for shared receiver product ids, same as the webapp. */ function resolveDeviceImageFilename(key: string | null | undefined, displayName: string): string { @@ -394,11 +394,11 @@ function resolveDeviceImageFilename(key: string | null | undefined, displayName: if (/\bmx\s*anywhere\s*3\b/i.test(displayName)) return "logitech-mx-anywhere-3.png"; if (/\bmx\s*ergo\b/i.test(displayName)) return "logitech-mx-ergo-s.png"; if (/\bdeathadder\s*v4\b/i.test(displayName)) return "razer-deathadder-v4-pro.png"; - // DeathAdder V3 Pro and HyperSpeed are the wireless SKUs of the V3 shell — + // DeathAdder V3 Pro and HyperSpeed are the wireless SKUs of the V3 shell - // this must be checked before the plain "v3" match below, or "V3 // HyperSpeed" would match that first and show the *corded* V3's photo on a // wireless mouse (CONFIRMED: exactly this happened before this line - // existed here — see the webapp's `src/ui/device-images.ts`, which already + // existed here - see the webapp's `src/ui/device-images.ts`, which already // had this split). if (/\bdeathadder\s*v3\s*(?:pro|hyperspeed)\b/i.test(displayName)) return "razer-deathadder-v3-hyperspeed.png"; if (/\bdeathadder\s*v3\b/i.test(displayName)) return "razer-deathadder-v3.png"; @@ -492,7 +492,7 @@ export function deviceImageCandidates( /** * Best-known product photo for a device. `key` is `HidInterfaceInfo.key` / * `ConnectedDevice.key`; `displayName` is the product/friendly name (from - * `HidInterfaceInfo.productString` or `MouseStatus.name`) — used as a + * `HidInterfaceInfo.productString` or `MouseStatus.name`) - used as a * fallback for shared receiver product ids, same as the webapp. */ export function deviceImage(key: string | null | undefined, displayName = ""): string { @@ -501,7 +501,7 @@ export function deviceImage(key: string | null | undefined, displayName = ""): s /** * The bare filename a device's artwork resolves to (no bucket URL). Lets a - * caller — currently just DeviceTile, for its ART_BOUNDS lookup — resolve + * caller - currently just DeviceTile, for its ART_BOUNDS lookup - resolve * the same filename `deviceImage` did without re-deriving it or reaching * into this module's URL-building. */ diff --git a/gpui/js/native-hid/device-store.ts b/gpui/js/native-hid/device-store.ts index d8fae785..d2612749 100644 --- a/gpui/js/native-hid/device-store.ts +++ b/gpui/js/native-hid/device-store.ts @@ -1,10 +1,10 @@ // Remembers the last device that actually answered `connectToInterface()`, // so the next launch can reconnect to it automatically instead of making the // user find it in the list and click Connect again. Nothing here talks to -// the wire — this is just a name tag persisted in the webview's own +// the wire - this is just a name tag persisted in the webview's own // localStorage, matched back against a fresh `listCandidateInterfaces()` -// scan by `HidInterfaceInfo.key` (a stable `vendorId:productId` string — -// see hid.rs's `interface_key()` — so it survives being plugged into a +// scan by `HidInterfaceInfo.key` (a stable `vendorId:productId` string - +// see hid.rs's `interface_key()` - so it survives being plugged into a // different USB port or restarting the app). import type { HidInterfaceInfo } from "./tauri-hid-device"; @@ -13,8 +13,8 @@ const STORAGE_KEY = "openmouse:last-device"; /** * `vendorId:productId` → the name the device reported about itself once it * answered. A receiver enumerates as itself ("USB Receiver", `046d:c54d`) - * and only reveals the mouse behind it — "PRO X SUPERLIGHT 2c", with its own - * artwork — after a connect reads it over HID++. The list reads this so a + * and only reveals the mouse behind it - "PRO X SUPERLIGHT 2c", with its own + * artwork - after a connect reads it over HID++. The list reads this so a * device that has ever been connected shows what it actually is, instead of * the dongle it arrives as. Nothing here opens anything: see scan.ts's own * rule about never touching a device during a plain enumeration. @@ -37,7 +37,7 @@ export function getRememberedDevice(): RememberedDevice | null { const parsed = JSON.parse(raw); return typeof parsed?.key === "string" ? (parsed as RememberedDevice) : null; } catch { - // Private-browsing-style storage blocks, corrupted JSON, whatever — this + // Private-browsing-style storage blocks, corrupted JSON, whatever - this // is a convenience, not a source of truth, so just skip auto-reconnect. return null; } @@ -56,7 +56,7 @@ export function getDeviceName(key: string): string | null { } } -/** Records the self-reported name for `key` — a receiver's real mouse. */ +/** Records the self-reported name for `key` - a receiver's real mouse. */ export function rememberDeviceName(key: string, name: string): void { if (!key || !name) return; try { @@ -82,7 +82,7 @@ export function rememberDevice(info: HidInterfaceInfo, brand: string): void { }; localStorage.setItem(STORAGE_KEY, JSON.stringify(record)); } catch { - // Best-effort — losing the remembered device just means the next + // Best-effort - losing the remembered device just means the next // launch falls back to manual connect. } } diff --git a/gpui/js/native-hid/hid-open-lock.ts b/gpui/js/native-hid/hid-open-lock.ts index bee53b73..ed7de830 100644 --- a/gpui/js/native-hid/hid-open-lock.ts +++ b/gpui/js/native-hid/hid-open-lock.ts @@ -1,4 +1,4 @@ -// Shared across every module that opens a HID interface — scan.ts's +// Shared across every module that opens a HID interface - scan.ts's // connectToInterface() (reads) and logitech-actions.ts's withClient() // (writes), and any future brand's own write module. // @@ -7,13 +7,13 @@ // the SAME open group, reader threads included. Two independent callers // walking that group at once (a status read racing a DPI write, two reads // racing each other) end up with their requests interleaved on the wire and -// their replies cross-matched into each other's promises — CONFIRMED on +// their replies cross-matched into each other's promises - CONFIRMED on // real hardware as the cause of a spurious "the mouse did not answer": one // walk's reply got consumed by the other walk's matching logic, so the // first walk waited forever for a reply that had already arrived and been // stolen. This is a plain module-level Set, not a ref, specifically so it // survives a dev-server hot-reload remounting whichever component started a -// walk — a ref tied to that component's instance can't see a walk started +// walk - a ref tied to that component's instance can't see a walk started // by the instance hot-reloading replaced it with. const openKeys = new Set(); @@ -27,7 +27,7 @@ export function isHidOpenLocked(key: string): boolean { /** * True for the specific error `withHidOpenLock` throws when already locked, * and for the same message arriving from Rust: `invoke` rejects with the - * command's error value, which is a plain string, not an Error — hid.rs's + * command's error value, which is a plain string, not an Error - hid.rs's * `with_hid_api` refuses a re-entrant enumeration (hidapi's macOS enumerator * pumps the main run loop, so the webview's next invoke lands inside an * in-flight `hid_open`) with this exact message. Both mean the same thing to @@ -41,7 +41,7 @@ export function isHidBusyError(error: unknown): boolean { /** * Runs `action` under the lock for `key`, refusing to start if another walk * for the same device is already running. Throws `isHidBusyError` rather - * than silently no-opping — callers decide what "someone else is using this + * than silently no-opping - callers decide what "someone else is using this * device" should look like: a second auto-reconnect attempt racing itself * isn't user-visible, so use-mouse-connection.ts's connect() swallows it, * while a write action colliding with a live read should surface as a real @@ -61,12 +61,12 @@ export async function withHidOpenLock(key: string, action: () => Promise): /** * Like `withHidOpenLock`, but retries on contention instead of failing on - * the first collision — for a caller where the write actually has to land, + * the first collision - for a caller where the write actually has to land, * not just "try once, it's fine if a background tick beats it." CONFIRMED * as a real problem, not theoretical: a game-profile write (logitech-actions.ts) * landing in the same window as the status auto-refresh's background poll * (use-mouse-connection.ts, every 5s) got rejected outright as "busy," and - * unlike that auto-refresh — which just tries again next tick regardless — + * unlike that auto-refresh - which just tries again next tick regardless - * a game launching is a one-shot moment nothing retries on its own. * * Retries every `intervalMs` until `action` succeeds or `timeoutMs` @@ -96,13 +96,13 @@ export async function withHidOpenLockRetrying( /** * True when the device answered a command with "queued, not processed": the * request echoed back before the mouse ran it. Razer-specific wording - * (`returned status 0x00` — RAZER_STATUS has no 0x00 at all; `ok` is 0x02, + * (`returned status 0x00` - RAZER_STATUS has no 0x00 at all; `ok` is 0x02, * `busy` 0x01, `timeout` 0x04), so it means "received, not done yet" rather * than a refusal, and the *same idempotent* operation is safe to repeat after * a short wait. CONFIRMED as what a wireless DeathAdder does on both paths * here: `setDpi` reporting `Class 0x04 command 0x05 returned status 0x00` and * then applying cleanly on a retry, and the status walk failing `Class 0x00 - * command 0x81` for every candidate until the mouse answered — the driver + * command 0x81` for every candidate until the mouse answered - the driver * reads a setter's reply exactly once and refuses to re-send it (hid.js's * awaitReply), which is right, so retrying the whole call is the caller's job. * diff --git a/gpui/js/native-hid/logitech-actions.ts b/gpui/js/native-hid/logitech-actions.ts index 7c8585df..c340f277 100644 --- a/gpui/js/native-hid/logitech-actions.ts +++ b/gpui/js/native-hid/logitech-actions.ts @@ -2,7 +2,7 @@ // // Read status is generic across brands (native-hid/scan.ts, brands.ts) since // every driver's `SupportedClient` shape only declares open/close/ -// readStatus — but actually commanding a device (DPI, polling rate, +// readStatus - but actually commanding a device (DPI, polling rate, // lift-off distance, ...) is brand- and feature-specific, with a different // method set per driver class. Rather than force a shared write interface // across every brand before any of them has a UI that needs one, this goes @@ -13,7 +13,7 @@ // that function's docs in scan.ts for why): holding a HID++ connection open // with a live reader thread froze the device's own input on real hardware, // so every write here opens fresh, does exactly one thing, and closes again -// immediately — same as a status read, never a persistent connection. +// immediately - same as a status read, never a persistent connection. import { LogitechHidppClient } from "@openmouse/protocol/drivers/logitech/hidpp"; import type { MouseStatus } from "@openmouse/protocol/drivers/mouse-types"; @@ -22,13 +22,13 @@ import { withHidOpenLockRetrying } from "./hid-open-lock"; const OPEN_TIMEOUT_MS = 10000; // resolveDeviceIndex() alone can cost as much as scan.ts's -// READ_STATUS_TIMEOUT_MS documents for the full readStatus() walk — it's a +// READ_STATUS_TIMEOUT_MS documents for the full readStatus() walk - it's a // receiver's own pairing-slot probe (up to 7 candidates * 6000ms), not a // cost specific to reading every feature. It's a strict subset of that walk, // so it can never exceed this budget. const RESOLVE_INDEX_TIMEOUT_MS = 45000; // A single write, once the index is resolved, is one request/response round -// trip, not the 20-30 of a full readStatus() walk — generous, but far short +// trip, not the 20-30 of a full readStatus() walk - generous, but far short // of that budget. const ACTION_TIMEOUT_MS = 15000; @@ -49,7 +49,7 @@ export type GamingSurfaceMode = NonNullable; * The subset of `LogitechHidppClient` this file actually calls. `open()` and * `resolveDeviceIndex()` are marked private in the class's own `.d.ts` * (nothing inside mouse-protocol calls them externally) even though every - * runtime build implements them — `apply.mjs` (plain JS, no compile-time + * runtime build implements them - `apply.mjs` (plain JS, no compile-time * privacy) already calls `open()` this same way, and `brands.ts` casts * through `unknown` for the same reason on the read-only path. Doing it once * here, not per call site. @@ -59,12 +59,12 @@ export interface WritableLogitechClient { close(): Promise; /** * Every setter reads `this.deviceIndex`, which falls back to the DIRECT - * index (0xFF) until this has actually run — `readStatus()` is the only + * index (0xFF) until this has actually run - `readStatus()` is the only * public method that calls it on its own. A mouse reached through a * receiver answers on a pairing slot, not 0xFF, so skipping this would * make a write on a receiver-paired mouse silently target the wrong HID++ * index (works by coincidence when directly wired, since 0xFF is correct - * there — exactly the kind of bug that stays invisible until tested + * there - exactly the kind of bug that stays invisible until tested * wireless). CONFIRMED by reading hidpp.js: readStatus() calls this with * no arguments before anything else; every write here does the same. */ @@ -82,12 +82,12 @@ async function withClient( label: string, action: (client: WritableLogitechClient) => Promise, ): Promise { - // Shared with scan.ts's connectToInterface() — see hid-open-lock.ts. A + // Shared with scan.ts's connectToInterface() - see hid-open-lock.ts. A // write racing a concurrent status read (or another write) on the same // device would otherwise share hid_open's idempotent-per-device group and // get its reply cross-matched with the other call's. // - // Retrying (not just a single attempt) — CONFIRMED necessary: a write + // Retrying (not just a single attempt) - CONFIRMED necessary: a write // landing in the same window as use-mouse-connection.ts's 5s background // status refresh got rejected outright as "busy" instead of just waiting // its turn. A manual click can be retried by the user; an automatic @@ -98,12 +98,12 @@ async function withClient( /** * Public version of `withClient`, for a caller that needs to run more than - * one action against a single open()+resolveDeviceIndex() session — e.g. + * one action against a single open()+resolveDeviceIndex() session - e.g. * lib/game-profiles.ts applying a profile's DPI and polling rate together. * Calling `setDpi()` then `setPollingRate()` back-to-back would pay that * open/resolve cost (up to RESOLVE_INDEX_TIMEOUT_MS for a receiver's own * pairing-slot probe) twice and double the window for colliding with the - * background status auto-refresh's own hid-open-lock — noticeably worse + * background status auto-refresh's own hid-open-lock - noticeably worse * for something meant to happen instantly the moment a game launches. */ export const withLogitechClient = withClient; @@ -124,7 +124,7 @@ async function withClientLocked( } } -/** Returns the DPI the mouse actually applied — the device can clamp/round a requested value. */ +/** Returns the DPI the mouse actually applied - the device can clamp/round a requested value. */ export const setDpi = (info: HidInterfaceInfo, dpi: number, dpiY?: number): Promise => withClient(info, "setDpi", (client) => client.setDpi(dpi, dpiY)); diff --git a/gpui/js/native-hid/scan.ts b/gpui/js/native-hid/scan.ts index 8313ea79..c248b102 100644 --- a/gpui/js/native-hid/scan.ts +++ b/gpui/js/native-hid/scan.ts @@ -1,16 +1,16 @@ // Two separate operations, deliberately kept apart: // // - `listCandidateInterfaces()` only enumerates HID interfaces (a plain -// hidapi device-list refresh) — it never opens anything, so it's safe to +// hidapi device-list refresh) - it never opens anything, so it's safe to // call freely and never risks the mouse-freeze bug a previous version of // this file had from opening devices during a blind auto-scan. // - `connectToInterface()` actually opens ONE specific interface the user -// picked and tries each of its candidate driver classes in turn — mirrors +// picked and tries each of its candidate driver classes in turn - mirrors // `probe()`/`main()` in OpenMouse-Bridge's `native-hid/src/apply.mjs`, // minus the Node subprocess: this runs directly in the Tauri webview // against `TauriHidDevice`. // -// `isSupported()` gating is skipped deliberately (see brands.ts) — a +// `isSupported()` gating is skipped deliberately (see brands.ts) - a // candidate is accepted once its `open()` and `readStatus()` both succeed // within their own budgets below, the same "does it actually answer" bar // apply.mjs uses. @@ -21,7 +21,7 @@ import { listHidInterfaces, TauriHidDevice, type HidInterfaceInfo } from "./taur import { withHidOpenLock } from "./hid-open-lock"; // `open()` never touches the wire (see TauriHidDevice.open()/LogitechHidppClient.open()) -// — it just claims the HID handle and registers a listener — so it has no +// - it just claims the HID handle and registers a listener - so it has no // business sharing a timeout sized for a multi-step protocol exchange. // Kept short so a genuinely broken open() fails fast. const OPEN_TIMEOUT_MS = 10000; @@ -31,18 +31,18 @@ const OPEN_TIMEOUT_MS = 10000; // // 1. Device-index discovery. For a known Logitech receiver, // `resolveDeviceIndex()` (mouse-protocol/src/drivers/logitech/hidpp.ts) -// probes `hidppDeviceIndexCandidates()` in turn — 7 candidates (pairing -// slots 0x01-0x06, then the direct index) — and on a non-Bolt receiver +// probes `hidppDeviceIndexCandidates()` in turn - 7 candidates (pairing +// slots 0x01-0x06, then the direct index) - and on a non-Bolt receiver // each one that doesn't answer burns its own full `REQUEST_TIMEOUT_MS` // (6000ms), not the much shorter `BOLT_INDEX_PROBE_TIMEOUT_MS` (800ms) -// Bolt gets. A receiver whose paired mouse sits on a late slot — or is -// simply out of range — can legitimately need 7 * 6000ms = 42000ms +// Bolt gets. A receiver whose paired mouse sits on a late slot - or is +// simply out of range - can legitimately need 7 * 6000ms = 42000ms // before `resolveDeviceIndex()` gives up. (A direct wired connection // only has 2 candidates, so this cost is small there.) // 2. The feature walk itself, once resolved. `readStatus()` reads name, // firmware, battery, DPI, DPI capabilities, report rate, onboard // profiles, analog buttons, haptics, friendly name, hosts, wheel state, -// mode status — 20-30+ separate request/response round trips on a +// mode status - 20-30+ separate request/response round trips on a // feature-rich mouse (a PRO X Superlight, live-tested here). Each one // still pays the same-vendor-id multi-split fallback in `try_each` // (src-tauri/src/hid.rs) before landing on the split that actually @@ -51,7 +51,7 @@ const OPEN_TIMEOUT_MS = 10000; // 8000ms, then 45000ms sharing this timeout with `open()` were both tried // first and both cut `readStatus()` off mid-walk on real hardware: a // Lightspeed receiver (needs #1's full budget) and a wired PRO X -// Superlight (needs #2's — confirmed making real progress, resolving the +// Superlight (needs #2's - confirmed making real progress, resolving the // device name and reading DPI/report-rate data, but still not finished at // 45000ms). Sized generously enough to cover both costs landing in the same // connect attempt, not tuned to either one alone. @@ -64,14 +64,14 @@ export interface CandidateInterface { } export interface ConnectedDevice { - /** The interface this snapshot came from — `HidInterfaceInfo.key` (stable `vendorId:productId`). */ + /** The interface this snapshot came from - `HidInterfaceInfo.key` (stable `vendorId:productId`). */ key: string; brand: string; status: MouseStatus; /** * `driver` of the class that actually answered, so - * capability questions — the sleep / low-power / debounce option lists only - * the driver class knows — can be put to the class whose validation this + * capability questions - the sleep / low-power / debounce option lists only + * the driver class knows - can be put to the class whose validation this * exact device obeys. Razer alone registers five candidate classes for one * vendor id and its Viper V4 Pro overrides the generic sleep list with a * subset, so asking the wrong class offers values the mouse rejects. @@ -93,7 +93,7 @@ let lastUnmatchedSignature: string | null = null; /** * Every currently-connected HID interface that at least one known brand's - * driver might answer on. Read-only — nothing here opens a device. + * driver might answer on. Read-only - nothing here opens a device. */ export async function listCandidateInterfaces(): Promise { const interfaces = await listHidInterfaces(allKnownVendorIds()); @@ -126,12 +126,12 @@ export async function listCandidateInterfaces(): Promise { /** * Opens one specific interface (as picked from `listCandidateInterfaces()`), * tries each of its candidate driver classes in turn until one answers, and - * closes it again immediately after reading its status once — this never + * closes it again immediately after reading its status once - this never * stays open in the background. Reproduced on real hardware: leaving a * device open with a continuously-running background reader (needed for * request/response protocols that reply via input reports, not feature * reports) froze the device's own input for as long as the connection - * stayed open, on more than one brand/collection — not tied to a specific + * stayed open, on more than one brand/collection - not tied to a specific * usage page after all. Read once, release immediately, and re-open only * for an explicit user action (a manual refresh, or eventually a write) * until that's understood well enough to hold a connection open safely. diff --git a/gpui/js/native-hid/tauri-hid-device.ts b/gpui/js/native-hid/tauri-hid-device.ts index c19a172a..6ed73a92 100644 --- a/gpui/js/native-hid/tauri-hid-device.ts +++ b/gpui/js/native-hid/tauri-hid-device.ts @@ -2,7 +2,7 @@ // they satisfy the WebHID `HIDDevice` interface mouse-protocol's driver // classes are written against (see // node_modules/@openmouse/protocol/dist/drivers/webhid.d.ts, an ambient-type -// declaration only — this file is the runtime implementation of that same +// declaration only - this file is the runtime implementation of that same // shape for a Tauri webview). // // This lets Full Desktop Mode reuse OpenMouse's actual, hardware-verified @@ -16,8 +16,8 @@ // `collections` is real: src-tauri/src/hid_descriptor.rs parses each // interface's HID report descriptor and hid.rs merges the group's collections // into `HidInterface.collections`, in WebHID's own shape. That matters because -// the protocol library's drivers gate on it — their static `isSupported(device)` -// reads `device.collections` — so `@openmouse/protocol/drivers/registry`'s own +// the protocol library's drivers gate on it - their static `isSupported(device)` +// reads `device.collections` - so `@openmouse/protocol/drivers/registry`'s own // `DEVICE_DRIVERS` can match devices here exactly as it does in a browser, // instead of the app carrying a hand-copied registry. // @@ -63,7 +63,7 @@ export async function listHidInterfaces(vendorIds: number[]): Promise act -> close way the -// status read already does — fresh short-lived connection under the shared +// status read already does - fresh short-lived connection under the shared // hid-open-lock, never a persistent one (see scan.ts's docs on why). // // Unlike logitech-actions.ts this needs no device-index resolution: Logitech @@ -30,13 +30,13 @@ import { isQueuedNotProcessedError, withHidOpenLockRetrying } from "./hid-open-l * What this device accepts for the controls whose valid values are set by the * device's own protocol, asked of the driver class that actually answered it. * - * These lists live on the driver classes (not in `MouseStatus`) and are pure — - * they read product ids / catalog entries, never the wire — so this needs no + * These lists live on the driver classes (not in `MouseStatus`) and are pure - + * they read product ids / catalog entries, never the wire - so this needs no * connection and no lock. Before this, the Performance tab hardcoded stand-in * lists (10 min-8 h sleep values, 0-20 ms debounce) that any driver with a * different set rejected outright: Razer takes 1-15 min of sleep, ATK 30 s-30 * min in its own steps, Ninjutso 1-15 min, WLMouse 30 s-30 min, and their - * debounce ceilings differ per protocol — every one of those writes simply + * debounce ceilings differ per protocol - every one of those writes simply * failed. * * `driver` is `ConnectedDevice.driver`; without it the first candidate for the @@ -47,7 +47,7 @@ export interface DeviceCapabilities { /** * Sleep-timeout values this device accepts, in the unit its own * `setSleepTimeout` takes (seconds for every driver that exposes a list). - * Null when its driver exposes none — then no value the app could offer is + * Null when its driver exposes none - then no value the app could offer is * known to be valid, so the control must not be shown. */ sleepTimeouts: readonly number[] | null; @@ -58,7 +58,7 @@ export interface DeviceCapabilities { /** Exact debounce values this device accepts, when its driver lists them rather than just a ceiling. */ debounceOptions: readonly number[] | null; /** - * Highest DPI this device accepts, when its driver reports one — per + * Highest DPI this device accepts, when its driver reports one - per * *product*, not per brand (a Razer DeathAdder V3 HyperSpeed takes 30000, * a Viper V3 Pro 35000). Null when the driver has no such ceiling to * report, in which case the UI falls back to its own bounds. @@ -75,11 +75,11 @@ export function deviceCapabilities(info: HidInterfaceInfo): DeviceCapabilities { dpiMax: null, }; // Whatever the walk would have chosen for this device, by the library's own - // rule — see brands.ts's candidatesForDevice. + // rule - see brands.ts's candidatesForDevice. const candidate = candidatesForDevice(info)[0]; if (!candidate) return empty; - // Constructing a client is side-effect free (no open, no listener — the + // Constructing a client is side-effect free (no open, no listener - the // classes only store the device and these getters read product ids and // catalogs), but this runs during render against every registered driver // class, so a getter that throws must read as "capability not offered" @@ -113,7 +113,7 @@ export function deviceCapabilities(info: HidInterfaceInfo): DeviceCapabilities { /** * DPI bounds to offer for a device, in precedence order: the device's own - * protocol hint (`ui.dpiStageEditor` — the exact values its setter validates + * protocol hint (`ui.dpiStageEditor` - the exact values its setter validates * against), then its driver's per-product ceiling (`maxDpi()`), then the * caller's fallback. Shared by the Performance tab and the game-profile * editor so both offer the same limits, and so neither keeps a per-brand @@ -133,7 +133,7 @@ export function dpiBounds( } const OPEN_TIMEOUT_MS = 10000; -// A single write is one request/response round trip — the same generous but +// A single write is one request/response round trip - the same generous but // far-short-of-a-readStatus-walk budget logitech-actions.ts uses. const ACTION_TIMEOUT_MS = 15000; // How long the write path waits for the mouse's queued command to be processed @@ -167,7 +167,7 @@ export type GamingSurfaceMode = NonNullable; /** * The cross-brand setter surface a driver class may implement. Every method - * is optional — each driver exposes a subset (a Ninjutso has setLighting, a + * is optional - each driver exposes a subset (a Ninjutso has setLighting, a * moddo does not; a Pulsar XS1 lacks setSleepTimeout, etc.). Cast each class * through `unknown` for the exact reason logitech-actions.ts documents: some * classes mark `open()` private in their `.d.ts` even though every runtime @@ -244,7 +244,7 @@ export type PrimaryButton = NonNullable; /** * Opens each candidate driver for `info` in turn and runs `action` against * the first whose `open()` and the action both succeed within their own - * budgets — the same "does it actually answer" bar connectToInterface() uses. + * budgets - the same "does it actually answer" bar connectToInterface() uses. * A candidate whose class lacks the setter the action calls (optional on * `WritableClient`) simply throws a TypeError caught here, so it's skipped * rather than failed; the first candidate that answers wins. @@ -261,7 +261,7 @@ async function withClient( // every brand the Logitech-specific path doesn't cover (it is where the // "No driver answered setDpi" modal comes from), and a click that lands // while the 5 s status walk holds the device lock must wait for it and then - // land — logitech-actions.ts's own client has retried on that contention + // land - logitech-actions.ts's own client has retried on that contention // since it was written, so a first click on a Razer failed where the same // click on a Logitech mouse succeeded. return withHidOpenLockRetrying(info.key, () => withClientLocked(info, label, action)); @@ -284,7 +284,7 @@ async function withClientLocked( const name = client.constructor.name || candidate.brand; let message = ""; // One delayed re-run per candidate when the mouse echoes the request back - // unprocessed — see DEVICE_BUSY_RETRY_DELAY_MS. Two, not one: the reply + // unprocessed - see DEVICE_BUSY_RETRY_DELAY_MS. Two, not one: the reply // that says "queued, not processed" can arrive while the status walk's // last request is still being processed on the mouse. for (let attempt = 0; attempt < DEVICE_BUSY_RETRIES; attempt += 1) { @@ -301,7 +301,7 @@ async function withClientLocked( await client.close().catch(() => undefined); if (attempt > 0) { void invoke("log_line", { - line: `[write] ${label} on ${info.key}: ${name} answered on try ${attempt + 1} — the mouse had the command queued, not processed`, + line: `[write] ${label} on ${info.key}: ${name} answered on try ${attempt + 1} - the mouse had the command queued, not processed`, }).catch(() => {}); } return result; @@ -325,7 +325,7 @@ async function withClientLocked( throw new Error(`No driver answered ${label}. Tried:\n ${attempts.join("\n ")}`); } -/** Returns the DPI the device actually applied — it can clamp/round. */ +/** Returns the DPI the device actually applied - it can clamp/round. */ export const setDpi = (info: HidInterfaceInfo, dpi: number, dpiY?: number): Promise => withClient(info, "setDpi", async (client) => { if (!client.setDpi) throw new Error("setDpi not supported"); @@ -510,7 +510,7 @@ export const setButtonMapping = (info: HidInterfaceInfo, button: string | number }); /** - * Scroll-up / scroll-down / sensitivity-button toggles — Razer gives them + * Scroll-up / scroll-down / sensitivity-button toggles - Razer gives them * their own command and deliberately keeps them out of * `RAZER_BUTTON_MAPPINGS`, so sending one through `setButtonMapping` always * threw ("… is not a button mapping this driver can send.") before any diff --git a/gpui/js/steelseries-controls.ts b/gpui/js/steelseries-controls.ts index 4485508d..76013c42 100644 --- a/gpui/js/steelseries-controls.ts +++ b/gpui/js/steelseries-controls.ts @@ -50,7 +50,7 @@ const brightness: Setting = { id: "brightness", method: "setLedBrightness", section: "Lighting", label: "Brightness", options: () => percent([0, 25, 50, 75, 100]), args: (v) => [Number(v)], }; -/** Zones 1–3, taking either `(zone, r, g, b)` or `(zone, colour)`. */ +/** Zones 1-3, taking either `(zone, r, g, b)` or `(zone, colour)`. */ const zones = (shape: "numbers" | "object"): Setting[] => [1, 2, 3].map((zone) => ({ id: `zone${zone}`, method: "setZoneColor", section: "Lighting", label: `Zone ${zone} colour`, options: swatches, @@ -142,7 +142,7 @@ export function steelseriesControls(s: any, written: Record): S id, label: setting.label, kind: "choice", options: setting.options(), description: "Shows the last value set here.", current: (written[id] as any) ?? null, }; - const title = `SteelSeries — ${setting.section}`; + const title = `SteelSeries - ${setting.section}`; const section = sections.find((x) => x.title === title); if (section) section.controls.push(control); else sections.push({ title, controls: [control] }); diff --git a/gpui/src/active_mouse.rs b/gpui/src/active_mouse.rs index 4584a1cf..54662744 100644 --- a/gpui/src/active_mouse.rs +++ b/gpui/src/active_mouse.rs @@ -63,7 +63,7 @@ mod win { thread_local! { static NAMES: RefCell>> = RefCell::new(HashMap::new()); - // Fast-path handle cache so high-polling-rate mice (1k–8k Hz) avoid + // Fast-path handle cache so high-polling-rate mice (1k-8k Hz) avoid // HashMap lookups, String clones, and Mutex locks on every WM_INPUT. static LAST_HANDLE: Cell = const { Cell::new(0) }; } diff --git a/gpui/src/app.rs b/gpui/src/app.rs index 841a5aca..a13d4fa9 100644 --- a/gpui/src/app.rs +++ b/gpui/src/app.rs @@ -232,6 +232,12 @@ pub struct AppView { /// What a slider shows while it is being dragged, before the write lands. slider_live: std::collections::HashMap, slider_seq: u64, + stage_sliders: std::collections::HashMap<(usize, bool), Entity>, + stage_unlinked: std::collections::HashSet, + stage_inputs: std::collections::HashMap<(usize, bool), Entity>, + profile_name: Option<(u32, Entity)>, + stage_seq: u64, + stage_sent: u64, _subscriptions: Vec, _game_watcher: Option, _mouse_monitor: Option, @@ -362,6 +368,12 @@ impl AppView { vibrancy_slider: Some(vibrancy_slider), control_sliders: Default::default(), slider_live: Default::default(), + stage_sliders: Default::default(), + stage_unlinked: Default::default(), + stage_inputs: Default::default(), + profile_name: None, + stage_seq: 0, + stage_sent: 0, slider_seq: 0, _subscriptions: Vec::new(), _game_watcher: Some(game_watcher), @@ -373,6 +385,9 @@ impl AppView { // The OS entry is the truth for launch-on-startup, not the saved flag. view.profiles = crate::profiles::Profiles::load(); view.settings.launch_on_startup = crate::autostart::is_enabled(); + if view.settings.tray_pinned { + crate::tray::pin(true); + } if view.settings.discord_presence { view.set_discord(true, cx); } @@ -397,6 +412,9 @@ impl AppView { self.devices.button_listen = None; self.devices.expanded = None; self.devices.button_heard = None; + self.stage_sliders.clear(); + self.stage_inputs.clear(); + self.profile_name = None; self.receiver.colour = None; self.macros.recorder = None; self.text_controls.listening.clear(); @@ -481,6 +499,12 @@ impl Default for AppView { page: Page::Overview, control_sliders: Default::default(), slider_live: Default::default(), + stage_sliders: Default::default(), + stage_unlinked: Default::default(), + stage_inputs: Default::default(), + profile_name: None, + stage_seq: 0, + stage_sent: 0, slider_seq: 0, sidebar_collapsed: false, settings: Settings::default(), @@ -940,6 +964,7 @@ impl Render for AppView { } } self.ensure_control_sliders(window, cx); + self.ensure_stage_sliders(window, cx); self.ensure_text_controls(window, cx); self.ensure_macro_recorder(cx); self.ensure_name_editor(window, cx); diff --git a/gpui/src/app/about_page.rs b/gpui/src/app/about_page.rs index ab6780ba..dc5e4c78 100644 --- a/gpui/src/app/about_page.rs +++ b/gpui/src/app/about_page.rs @@ -211,13 +211,13 @@ impl AppView { div() .text_sm() .text_color(muted) - .child("Open-source, driverless desktop configuration for gaming mice and keyboards — no bloat, no accounts, no telemetry."), + .child("Open-source, driverless desktop configuration for gaming mice and keyboards - no bloat, no accounts, no telemetry."), ), ), ) .child(quick_links); - // 2. Sponsors section — logo tiles matching openmouse.app, plus a subtle header link. + // 2. Sponsors section - logo tiles matching openmouse.app, plus a subtle header link. let sponsor_url = credits.links.sponsor.clone(); let sponsors_header = h_flex() .justify_between() diff --git a/gpui/src/app/appearance.rs b/gpui/src/app/appearance.rs index 4f7a59c0..2ab1f7cb 100644 --- a/gpui/src/app/appearance.rs +++ b/gpui/src/app/appearance.rs @@ -43,7 +43,7 @@ impl AppView { self.settings.save(); if theme == ThemeChoice::Dynamic { let vibrancy = self.settings.dynamic_vibrancy; - // Instant path: paint the cached hex synchronously (no I/O — + // Instant path: paint the cached hex synchronously (no I/O - // mirrors the web app reading `DYNAMIC_HEX_KEY`), then verify // the signature off-thread and correct only if the wallpaper // actually changed. Same wallpaper → instant, zero subprocess. @@ -196,7 +196,7 @@ impl AppView { return; } } - // Dynamic repaints from the cached sample — passing None would reset + // Dynamic repaints from the cached sample - passing None would reset // the shell to the fallback green on every vibrancy tick. let wallpaper = if self.settings.theme == ThemeChoice::Dynamic { crate::theme::cached_dynamic_accent() diff --git a/gpui/src/app/ascii.rs b/gpui/src/app/ascii.rs index 616ba6de..ff2febe7 100644 --- a/gpui/src/app/ascii.rs +++ b/gpui/src/app/ascii.rs @@ -170,7 +170,7 @@ impl AppView { /// Subtle ASCII field behind the whole shell. Rows and bands are cached by /// grid size; the accent color is applied at paint time, so switching themes /// recolors the field without regenerating it. A theme change also - /// replays the entrance — the art itself carries the transition, sliding + /// replays the entrance - the art itself carries the transition, sliding /// back in from the right with the top row arriving first. pub(super) fn render_ascii_background(&mut self, window: &Window, cx: &Context) -> AnyElement { // Kit's mono family resolves per platform (Menlo / Consolas / diff --git a/gpui/src/app/controls.rs b/gpui/src/app/controls.rs index 9d60f728..317dc55f 100644 --- a/gpui/src/app/controls.rs +++ b/gpui/src/app/controls.rs @@ -248,6 +248,20 @@ impl AppView { } } "text" => self.render_text_control(c, cx), + "color" => self.render_color_control(c), + "button" | "saveFile" | "openFile" => { + let label = c.options.first().map(|o| o.label.clone()).unwrap_or_else(|| c.label.clone()); + let (kind, value) = (c.kind.clone(), c.options.first().map(|o| o.value.clone()).unwrap_or(c.current.clone())); + Button::new(SharedString::from(format!("btn-{id}"))) + .compact() + .label(label) + .on_click(cx.listener(move |this, _, _, cx| match kind.as_str() { + "saveFile" => this.save_control_file(id.clone(), value.as_str().unwrap_or("layout.json").to_string(), cx), + "openFile" => this.open_control_file(id.clone(), cx), + _ => this.set_control(id.clone(), value.clone(), cx), + })) + .into_any_element() + } "shortcut" => self.render_shortcut_control(c, cx), "stepped" => { let slider_key = self.devices.tiles.get(self.devices.selected).map(|t| format!("{}/{}", t.key, c.id)); @@ -393,7 +407,7 @@ impl AppView { .text_sm() .font_weight(FontWeight::SEMIBOLD) .text_color(fg) - .child(format!("Profile {} — buttons", running.sector)), + .child(format!("Profile {} - buttons", running.sector)), ); for (n, current) in currents.iter().enumerate() { let label = name_of(n); @@ -666,7 +680,7 @@ impl AppView { } /// The mouse's own stored profiles (Logitech): which one runs, and whether - /// the mouse runs them at all. Read-only apart from switching — editing a + /// the mouse runs them at all. Read-only apart from switching - editing a /// profile writes flash, and the library flags that sequence as unproven. pub(super) fn render_onboard_profiles(&self, r: &DeviceReadout, cx: &mut Context) -> AnyElement { let fg = cx.theme().foreground; @@ -697,9 +711,9 @@ impl AppView { .min_w_0() .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).text_color(fg).child("Onboard memory mode")) .child(div().text_xs().text_color(muted).child(if onboard_mode { - "The mouse is running its own stored profile." + "The mouse is running its own stored profile. DPI, polling rate and lift-off changes are saved into that profile." } else { - "Software is controlling the mouse, so its stored profiles are bypassed. Changing DPI or polling rate in this app puts the mouse in this mode." + "Software is controlling the mouse, so its stored profiles are bypassed. Changing DPI or polling rate in this app while the mouse can't save them into its profile puts it in this mode." })), ) .child( @@ -766,12 +780,62 @@ impl AppView { h_flex() .gap_2() .items_center() - .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).text_color(fg).child(title)) + .child(match self.profile_name.as_ref().filter(|(s, _)| *s == sector) { + Some((_, input)) => div() + .w(px(220.)) + .on_mouse_down_out(cx.listener(|this, _, _, cx| this.save_profile_name(cx))) + .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { + if event.keystroke.key == "escape" { + this.profile_name = None; + cx.notify(); + } + })) + .child(gpui_kit::component::input::Input::new(input).small()) + .into_any_element(), + None => h_flex() + .gap_1() + .items_center() + .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).text_color(fg).child(title.clone())) + .when(r.onboard_profiles_writable && p.crc_valid && !busy, |row| { + let current = p.name.clone().unwrap_or_default(); + row.child( + Button::new(SharedString::from(format!("rename-profile-{sector}"))) + .ghost() + .xsmall() + .icon(IconName::Pencil) + .tooltip("Rename") + .on_click(cx.listener(move |this, _, window, cx| { + this.start_profile_rename(sector, current.clone(), window, cx) + })), + ) + }) + .into_any_element(), + }) .when(running, |row| row.child(accent_badge("Running", accent, ink))) .when(!p.enabled, |row| row.child(Tag::secondary().small().child("Disabled"))), ) .child(div().text_xs().text_color(muted).child(facts.join(" · "))), ) + .when(r.onboard_profiles_writable && !running && p.crc_valid, |row| { + let enabled = p.enabled; + row.child( + Button::new(SharedString::from(format!("enable-profile-{sector}"))) + .compact() + .ghost() + .label(if enabled { "Turn off" } else { "Turn on" }) + .disabled(busy) + .on_click(cx.listener(move |this, _, _, cx| { + this.ask_before_onboard( + "enable", + serde_json::json!({ "sector": sector, "enabled": !enabled }), + if enabled { "Turn this profile off?" } else { "Turn this profile on?" }, + "This rewrites the mouse's profile list in its flash memory.", + if enabled { "Turn off" } else { "Turn on" }, + cx, + ) + })), + ) + }) .when(p.enabled && !running && p.crc_valid, |row| { row.child( Button::new(SharedString::from(format!("use-profile-{sector}"))) @@ -795,11 +859,9 @@ impl AppView { )); } if r.onboard_profiles_writable { - let running = list.profiles.iter().find(|p| p.is_current && p.crc_valid && onboard_mode); - col = col.children(running.and_then(|p| self.render_logitech_stages(p, cx))); col = col.child( div().text_xs().text_color(muted).child( - "Saving stages rewrites the mouse's flash memory. Renaming profiles and turning slots on or off aren't offered here yet.", + "DPI stages for the running profile are on the Performance tab. Turning a profile on or off rewrites the mouse's flash memory.", ), ); } else { @@ -813,6 +875,44 @@ impl AppView { } } } + if r.onboard_factory { + col = col.child( + card().child( + h_flex() + .gap_4() + .items_center() + .justify_between() + .child( + div() + .flex() + .flex_col() + .gap_0p5() + .flex_1() + .min_w_0() + .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).text_color(fg).child("Factory profiles")) + .child(div().text_xs().text_color(muted).child( + "Writes Logitech's default profiles into the mouse, replacing every stored profile. Also sets up a mouse that has none yet.", + )), + ) + .child( + Button::new("factory-profiles") + .compact() + .label("Restore") + .disabled(busy) + .on_click(cx.listener(|this, _, _, cx| { + this.ask_before_onboard( + "factory", + serde_json::Value::Null, + "Restore the factory profiles?", + "Every stored profile is erased: DPI stages, polling rates, buttons, lighting and names. Logitech's defaults are written back with profile 1 running. This can't be undone.", + "Restore", + cx, + ) + })), + ), + ), + ); + } if let Some(error) = &self.devices.write_error { col = col.child(div().text_sm().text_color(cx.theme().danger).child(error.clone())); } @@ -839,6 +939,7 @@ impl AppView { let sections: Option<&Vec> = match self.devices.tab { DeviceTab::Buttons => Some(&r.tabs.buttons), DeviceTab::Advanced => Some(&r.tabs.advanced), + DeviceTab::Lighting if !r.tabs.keyboard_lighting.is_empty() => Some(&r.tabs.keyboard_lighting), _ => None, }; // The magnetic buttons lead the Buttons tab. @@ -846,6 +947,15 @@ impl AppView { if let Some(magnetic) = magnetic { col = col.child(self.render_magnetic(magnetic, cx)); } + let hits = r.tabs.hits_travel.as_ref().filter(|_| self.devices.tab == DeviceTab::Advanced && self.editing_profile().is_none()); + if let Some(hits) = hits { + let travel = super::travel_panel::Travel::from_hits(hits); + col = col.child( + super::widgets::panel(cx) + .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).text_color(fg).child("Live press depth")) + .child(self.render_travel(&travel, cx)), + ); + } // The stored profile's remapper, where the driver offers no other. let stored_buttons = self.devices.tab == DeviceTab::Buttons && r.onboard_profiles diff --git a/gpui/src/app/device_io.rs b/gpui/src/app/device_io.rs index 45de2040..f76d19e1 100644 --- a/gpui/src/app/device_io.rs +++ b/gpui/src/app/device_io.rs @@ -235,12 +235,18 @@ impl AppView { self.devices.expanded = None; self.devices.stage_picked = None; self.devices.stage_draft = None; + self.stage_seq += 1; + self.stage_sent = self.stage_seq; + self.stage_unlinked.clear(); + self.stage_sliders.clear(); + self.stage_inputs.clear(); + self.profile_name = None; self.devices.magnetic_both = None; self.keyboard.reset(); self.macros.reset(); self.devices.onboard = None; self.devices.write_error = None; - self.devices.queued.clear(); + self.devices.queued.retain(Queued::is_rescue); if matches!( self.devices.tiles[index].status, TileStatus::Idle | TileStatus::Failed(_) @@ -264,13 +270,15 @@ impl AppView { /// rate from the change notification it saw), so re-reading would show the /// old rate straight after a successful write. The Tauri app patches its /// status the same way. - pub(super) fn patch_readout(&mut self, key: &str, action: &str, applied: &serde_json::Value) { + pub(super) fn patch_readout(&mut self, key: &str, action: &str, applied: &serde_json::Value, cx: &mut Context) { let mut left_onboard = false; let Some(tile) = self.devices.tiles.iter_mut().find(|t| t.key == key) else { return }; let TileStatus::Connected(r) = &mut tile.status else { return }; - // A Logitech mouse behind its receiver is put under software control by - // these writes, which stops it running its stored profiles. - if matches!(action, "dpi" | "pollingRate" | "liftOff" | "surface") + let into_profile = matches!(action, "dpi" | "pollingRate" | "liftOff") + && r.onboard_profiles_writable + && r.mode.as_deref() == Some("Onboard"); + if !into_profile + && matches!(action, "dpi" | "pollingRate" | "liftOff") && r.onboard_profiles && r.connection.as_deref() == Some("Wireless") && r.mode.as_deref() == Some("Onboard") @@ -303,6 +311,9 @@ impl AppView { // Which profile is running is no longer what we last read. self.devices.onboard = None; } + if into_profile && matches!(action, "dpi" | "pollingRate" | "liftOff") { + self.load_onboard_profiles(cx); + } } /// Reads the open Logitech mouse's stored profiles. On demand: a full pass @@ -314,15 +325,28 @@ impl AppView { let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; let key = tile.key.clone(); self.devices.onboard_loading = true; - self.devices.write_error = None; cx.notify(); let service = self.hid_service(); cx.spawn(async move |view, cx| { let result = service.onboard_profiles(&key).await; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.onboard_loading = false; + let selected = v.devices.tiles.get(v.devices.selected); + if selected.map(|t| t.key.as_str()) != Some(key.as_str()) { + let wants = selected.is_some_and(|t| matches!(&t.status, TileStatus::Connected(r) if r.onboard_profiles)); + if wants && v.devices.onboard.is_none() { + v.load_onboard_profiles(cx); + } + cx.notify(); + return; + } match result { - Ok(Ok(list)) => v.devices.onboard = Some(list), + Ok(Ok(list)) => { + v.devices.onboard = Some(list); + if v.stage_seq == v.stage_sent { + v.devices.stage_draft = None; + } + } Ok(Err(error)) => v.write_failed(&key, &error, cx), Err(_) => v.write_failed(&key, "device runtime stopped", cx), } @@ -349,9 +373,10 @@ impl AppView { let result = service.onboard_action(&key, action, value.clone()).await; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.writing = None; + let failed = !matches!(result, Ok(Ok(_))); match result { Ok(Ok(applied)) => { - if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key) { + if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key).filter(|_| !matches!(action, "enable" | "rename")) { if let TileStatus::Connected(r) = &mut tile.status { r.mode = Some(if action == "mode" { applied.as_str().unwrap_or("Host").to_string() @@ -363,6 +388,17 @@ impl AppView { if action == "stages" { v.saved("DPI stages", cx); } + if action == "rename" { + v.profile_name = None; + v.saved("Profile name", cx); + } + if action == "enable" { + v.saved("Profile list", cx); + } + if action == "factory" { + v.devices.stage_draft = None; + v.show_toast("Factory profiles restored.", false, cx); + } if action == "useProfile" { v.show_toast(format!("Now running profile {}.", value), false, cx); } @@ -372,6 +408,10 @@ impl AppView { Ok(Err(error)) => v.write_failed(&key, &error, cx), Err(_) => v.write_failed(&key, "device runtime stopped", cx), } + if action == "factory" && failed { + v.devices.onboard = None; + v.load_onboard_profiles(cx); + } v.read_back(&key, Vec::new(), cx); v.next_write(cx); cx.notify(); @@ -383,6 +423,10 @@ impl AppView { /// Writes one Buttons/Advanced control (always immediate, as in the Tauri /// app) and shows the value that was sent once the mouse accepts it. pub(super) fn set_control(&mut self, id: String, value: serde_json::Value, cx: &mut Context) { + if id.starts_with("x.lg.") && self.editing_profile().is_some() { + self.show_toast("This acts on the mouse right away, so a game profile can't keep it.", true, cx); + return; + } if let Some((gid, dev)) = self.editing_profile() { self.edit_profile( &gid, @@ -438,12 +482,18 @@ impl AppView { Ok(Ok(applied)) => { // Keyboard profile edits return verified tabs with canonical values. // The typed expression may differ from the value stored by the device. - let confirmed_tabs = id.starts_with("logi.keyboard."); + let confirmed_tabs = id.starts_with("logi.keyboard.") || id.starts_with("via."); if !confirmed_tabs { expected.push(Expected { action: format!("control:{id}"), value: value.clone() }); } let name = v.control_name(&key, &id); v.saved(&name, cx); + if id.starts_with("via.") && id != "via.file.save" { + v.keyboard.drop_board(); + if matches!(v.devices.tab, DeviceTab::Keys | DeviceTab::Actuation) { + v.load_keyboard_tab(v.devices.tab, cx); + } + } // A control that reshapes the page (a switch gaining analog settings) returns the new layout. let new_tabs = applied.get("tabs").and_then(|t| serde_json::from_value::(t.clone()).ok()); if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key) { @@ -553,7 +603,7 @@ impl AppView { let mut expected = Vec::new(); match result { Ok(Ok(applied)) => { - v.patch_readout(&key, action, &applied); + v.patch_readout(&key, action, &applied, cx); if let Some(y) = requested_y { v.patch_dpi_y(&key, y); } @@ -665,7 +715,7 @@ impl AppView { None => v.saved("Changes", cx), } for (action, applied) in &applied_values { - v.patch_readout(&key, action, applied); + v.patch_readout(&key, action, applied, cx); if *action == "dpi" { if let Some(y) = staged.dpi_y { v.patch_dpi_y(&key, y); @@ -700,7 +750,7 @@ impl AppView { pub(super) fn blocked_by_profile(&mut self, cx: &mut Context) -> bool { match self.locked_game() { Some(game) => { - self.show_toast(format!("Locked while {game} is running — your game profile is in control."), true, cx); + self.show_toast(format!("Locked while {game} is running - your game profile is in control."), true, cx); true } None => false, diff --git a/gpui/src/app/device_overview.rs b/gpui/src/app/device_overview.rs index 11986f9f..8d82f019 100644 --- a/gpui/src/app/device_overview.rs +++ b/gpui/src/app/device_overview.rs @@ -62,7 +62,7 @@ impl AppView { } if let Some(game) = self.locked_game() { col = col.child(div().text_sm().text_color(muted).child(format!( - "Locked while {game} is running — these are your game profile's settings, and they're editable again once the game closes." + "Locked while {game} is running - these are your game profile's settings, and they're editable again once the game closes." ))); } if let Some(quick) = self.render_quick_settings(r, cx) { diff --git a/gpui/src/app/device_page.rs b/gpui/src/app/device_page.rs index d2c10d11..c7b5d5c9 100644 --- a/gpui/src/app/device_page.rs +++ b/gpui/src/app/device_page.rs @@ -140,8 +140,10 @@ impl AppView { let content: AnyElement = match &tile.status { TileStatus::Connected(r) if self.devices.tab == DeviceTab::Overview => self.render_device_overview(&tile.key, r, cx), - TileStatus::Connected(_) - if tile.keyboard && matches!(self.devices.tab, DeviceTab::Actuation | DeviceTab::Keys | DeviceTab::Lighting) => + TileStatus::Connected(r) + if tile.keyboard + && (matches!(self.devices.tab, DeviceTab::Actuation | DeviceTab::Keys) + || (self.devices.tab == DeviceTab::Lighting && r.keyboard.lighting)) => { self.render_keyboard(cx) } @@ -156,7 +158,7 @@ impl AppView { // Locked while a game profile is in control of this device. if let Some(game) = self.locked_game() { col = col.child(div().text_sm().text_color(muted).child(format!( - "Locked while {game} is running — these are your game profile's settings, and they're editable again once the game closes." + "Locked while {game} is running - these are your game profile's settings, and they're editable again once the game closes." ))); } @@ -168,7 +170,20 @@ impl AppView { .iter() .flat_map(|s| &s.controls) .any(|c| c.id.starts_with("perf.stage.x.")); - if let (Some(current), Some(c), false) = (r.dpi.filter(|d| *d > 0.0), &r.controls, staged_dpi) { + let profile_stages = r.onboard_profiles_writable && r.mode.as_deref() == Some("Onboard") && self.editing_profile().is_none(); + if profile_stages { + let running = self.devices.onboard.as_ref().and_then(|list| list.profiles.iter().find(|p| p.is_current && p.crc_valid)); + let note = if self.devices.onboard.is_none() || self.devices.onboard_loading { + "Reading the profile's DPI stages…" + } else { + "The running profile has no DPI stages this app can edit. Pick or set up a profile on the Profiles tab." + }; + match running.and_then(|p| self.render_logitech_stages(p, cx)) { + Some(stages) => col = col.child(stages), + None => col = col.child(div().text_sm().text_color(muted).child(note)), + } + } + if let (Some(current), Some(c), false) = (r.dpi.filter(|d| *d > 0.0), &r.controls, staged_dpi || profile_stages) { let unlinked = r.separate_axes && self.devices.unlinked_axes; let cur_y = r.dpi_y.unwrap_or(current); let x_now = staged.dpi.unwrap_or(current); @@ -308,7 +323,7 @@ impl AppView { } col = col.child(section("Lift-off distance", cx).child(h_flex().child(row.when(disabled, |r| r.opacity(0.45)))).child(div().text_xs().text_color(muted).child( if disabled { - "Available with a gaming surface mode selected — lift-off distance is ignored while surface tracking is off." + "Available with a gaming surface mode selected - lift-off distance is ignored while surface tracking is off." } else { "How far you can lift the mouse before tracking stops. Higher values keep tracking a little longer." }, @@ -383,7 +398,7 @@ impl AppView { let (has_buttons, has_lighting, has_advanced, has_profiles) = match &tile.status { TileStatus::Connected(r) => ( !r.tabs.buttons.is_empty() || r.onboard_profiles || r.tabs.macros.is_some(), - r.tabs.lighting.is_some(), + r.tabs.lighting.is_some() || !r.tabs.keyboard_lighting.is_empty(), !r.tabs.advanced.is_empty(), r.onboard_profiles, ), @@ -394,7 +409,7 @@ impl AppView { _ => Default::default(), }; // The key pages take the whole width; the picture makes way for them. - let wide = tile.keyboard && matches!(self.devices.tab, DeviceTab::Actuation | DeviceTab::Keys | DeviceTab::Lighting); + let wide = tile.keyboard && (matches!(self.devices.tab, DeviceTab::Actuation | DeviceTab::Keys) || (self.devices.tab == DeviceTab::Lighting && features.lighting)); let tabs: Vec = [ (DeviceTab::Overview, !profile_mode), // A keyboard's polling rate is on its Overview. @@ -414,19 +429,19 @@ impl AppView { for tab in tabs { tab_bar = tab_bar.child(self.chip( format!("tab-{}", tab.label()), - tab.label().to_string(), + if tile.keyboard && tab == DeviceTab::Buttons { "Macros".to_string() } else { tab.label().to_string() }, self.devices.tab == tab, cx, move |this, cx| { this.devices.tab = tab; - if features.actuation && matches!(tab, DeviceTab::Actuation | DeviceTab::Keys | DeviceTab::Lighting) { + if matches!(tab, DeviceTab::Actuation | DeviceTab::Keys) && (features.actuation || features.remap) || tab == DeviceTab::Lighting && features.lighting { // Selections mean different things on each of these. this.keyboard.clear_selection(); this.load_keyboard_tab(tab, cx); } // Logitech's stored profiles back both tabs; read them once. if has_profiles - && matches!(tab, DeviceTab::Profiles | DeviceTab::Buttons) + && matches!(tab, DeviceTab::Profiles | DeviceTab::Buttons | DeviceTab::Performance) && this.devices.onboard.is_none() { this.load_onboard_profiles(cx); @@ -442,20 +457,18 @@ impl AppView { .min_h_0() .gap_6() .items_start() - .when(!wide, |row| { - row.child( - div() - .flex() - .flex_col() - .items_center() - .gap_2() - .flex_none() - .child(self.render_device_art_editable(tile, art_side, 1.4, cx)) - .when_some(firmware, |this, fw| { - this.child(div().text_xs().text_color(muted).child(fw)) - }), - ) - }) + .child( + div() + .flex() + .flex_col() + .items_center() + .gap_2() + .flex_none() + .child(self.render_device_art_editable(tile, art_side, 1.4, cx)) + .when_some(firmware, |this, fw| { + this.child(div().text_xs().text_color(muted).child(fw)) + }), + ) // Tabs stay pinned above the scrollable controls column. .child( div() diff --git a/gpui/src/app/device_state.rs b/gpui/src/app/device_state.rs index d3814655..f893fe27 100644 --- a/gpui/src/app/device_state.rs +++ b/gpui/src/app/device_state.rs @@ -115,7 +115,7 @@ pub(super) struct Tile { pub(super) default_name: String, /// The registry's label for the driver; what gating and write routing use. pub(super) brand: String, - /// The brand to show (the product's own — see `ConnectedDevice::display_brand`). + /// The brand to show (the product's own - see `ConnectedDevice::display_brand`). pub(super) display_brand: String, pub(super) art: Option, pub(super) status: TileStatus, @@ -142,6 +142,8 @@ pub(super) struct KeyboardFeatures { pub(super) actuation: bool, pub(super) remap: bool, pub(super) lighting: bool, + #[serde(rename = "noSave")] + pub(super) no_save: bool, } #[derive(Clone)] @@ -162,6 +164,7 @@ pub(super) struct DeviceReadout { pub(super) onboard_profiles_writable: bool, /// Protocol-reported onboard profile format id (e.g. 5, 7, 8). pub(super) onboard_profile_format_id: Option, + pub(super) onboard_factory: bool, /// `Onboard`, `Host` or `Unknown` (Logitech). pub(super) mode: Option, pub(super) tabs: crate::hid::Tabs, @@ -227,6 +230,11 @@ impl DeviceReadout { .and_then(|f| f.get("writable")) .and_then(|v| v.as_bool()) .unwrap_or(false), + onboard_factory: s + .get("onboardProfileFormat") + .and_then(|f| f.get("factory")) + .and_then(|v| v.as_bool()) + .unwrap_or(false), onboard_profile_format_id: s .get("onboardProfileFormat") .and_then(|f| f.get("id").or_else(|| f.get("formatId"))) diff --git a/gpui/src/app/keyboard_panel.rs b/gpui/src/app/keyboard_panel.rs index fc1064b6..3fc86647 100644 --- a/gpui/src/app/keyboard_panel.rs +++ b/gpui/src/app/keyboard_panel.rs @@ -29,6 +29,7 @@ pub(super) struct Key { x: f32, y: f32, w: f32, + h: Option, code: u32, label: String, /// What the key does as the board ships. @@ -91,6 +92,11 @@ impl KeyboardPanel { *self = KeyboardPanel { round: self.round + 1, ..Default::default() }; } + pub(super) fn drop_board(&mut self) { + self.board = None; + self.round += 1; + } + pub(super) fn clear_selection(&mut self) { self.selected.clear(); self.draft.clear(); @@ -231,6 +237,13 @@ impl AppView { } fn save_button(&self, scope: &'static str, cx: &mut Context) -> Div { + let no_save = match self.devices.tiles.get(self.devices.selected).map(|t| &t.status) { + Some(TileStatus::Connected(r)) => r.keyboard.no_save, + _ => false, + }; + if no_save { + return div().text_xs().text_color(cx.theme().muted_foreground).child("Changes are saved on the keyboard at once."); + } h_flex() .gap_3() .items_center() @@ -266,8 +279,8 @@ impl AppView { let fg = cx.theme().foreground; let muted = cx.theme().muted_foreground; let accent = cx.theme().primary; - let rows = board.keys.iter().map(|k| k.y as u32 + 1).max().unwrap_or(0); - let mut grid = div().relative().w_full().h(px(rows as f32 * KEY_H)); + let bottom = board.keys.iter().map(|k| k.y + k.h.unwrap_or(1.0)).fold(0.0, f32::max); + let mut grid = div().relative().w_full().h(px(bottom.ceil() * KEY_H)); for key in &board.keys { let (row, col) = (key.row, key.col); let selected = self.keyboard.selected.contains(&(row, col)); @@ -300,7 +313,7 @@ impl AppView { .left(relative(key.x / board.width)) .w(relative(key.w / board.width)) .top(px(key.y * KEY_H)) - .h(px(KEY_H)) + .h(px(key.h.unwrap_or(1.0) * KEY_H)) .p_0p5() .child(face), ); @@ -532,18 +545,19 @@ impl AppView { h_flex() .justify_between() .items_center() - .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(format!( - "{} key · types {}", - key.standard_label, key.label - ))) - .child( + .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).child(if key.standard_label.is_empty() { + format!("Types {}", key.label) + } else { + format!("{} key · types {}", key.standard_label, key.label) + })) + .when(!key.standard_label.is_empty(), |header| header.child( Button::new("kb-default") .compact() .ghost() .label("Use default") .disabled(now == standard || self.keyboard.busy) .on_click(cx.listener(move |this, _, _, cx| this.assign_key(row, col, standard, cx))), - ), + )), ) .child(h_flex().child(groups)) .child(choices); diff --git a/gpui/src/app/logitech_stages.rs b/gpui/src/app/logitech_stages.rs index 912231e2..a9eb05ab 100644 --- a/gpui/src/app/logitech_stages.rs +++ b/gpui/src/app/logitech_stages.rs @@ -1,26 +1,25 @@ -//! The DPI stages stored in a Logitech mouse's running profile: change the -//! values, how many there are and which one it starts on, then save. +//! The DPI stages stored in a Logitech mouse's running profile, laid out like +//! the website's DPI card: a row per slot with a tick box, the starting-stage +//! button, the value and a slider. Edits are saved a moment after they stop. use super::*; use super::widgets::panel; use crate::hid::OnboardProfile; +use gpui_kit::base::slider::{SliderEvent, SliderScale, SliderState}; +use gpui_kit::component::checkbox::Checkbox; +use gpui_kit::component::input::{Input, InputEvent, InputState}; use serde_json::{json, Value}; const MOST: usize = 5; -const STEP: i64 = 50; -const PRESETS: [i64; 4] = [400, 800, 1600, 3200]; -/// Edits to one profile's stages that are not saved yet. #[derive(Clone, PartialEq)] pub(super) struct StageDraft { sector: u32, - /// The library's `DpiStage`s: `x`, `y` and `lod`. stages: Vec, default: usize, } impl StageDraft { - /// The profile's used stages, if it has any. fn from_profile(p: &OnboardProfile) -> Option { let stages: Vec = p.dpi_stages.iter().filter(|s| s["x"].as_i64().is_some_and(|x| x > 0)).cloned().collect(); @@ -28,8 +27,6 @@ impl StageDraft { (!stages.is_empty()).then_some(Self { sector: p.sector, stages, default }) } - /// Sets one stage's DPI. A Y that differs from X is the mouse's own - /// setting and stays. fn set_dpi(&mut self, index: usize, value: i64) { let Some(stage) = self.stages.get_mut(index) else { return }; let (Some(x), Some(y)) = (stage["x"].as_i64(), stage["y"].as_i64()) else { return }; @@ -40,10 +37,21 @@ impl StageDraft { } } - /// Moves one stage's DPI by `by`. - fn nudge(&mut self, index: usize, by: i64) { - if let Some(x) = self.stages.get(index).and_then(|s| s["x"].as_i64()) { - self.set_dpi(index, x + by); + fn x(&self, index: usize) -> Option { + self.stages.get(index).and_then(|s| s["x"].as_i64()) + } + + fn y(&self, index: usize) -> Option { + self.stages.get(index).and_then(|s| s["y"].as_i64()) + } + + fn set_axis(&mut self, index: usize, value: i64, y_axis: bool, linked: bool) { + let Some(stage) = self.stages.get_mut(index) else { return }; + if linked || !y_axis { + stage["x"] = json!(value); + } + if linked || y_axis { + stage["y"] = json!(value); } } @@ -70,163 +78,304 @@ impl StageDraft { } } } - - #[cfg(test)] - fn remove_last(&mut self) { - let last = self.stages.len().saturating_sub(1); - self.remove(last); - } } impl AppView { - /// The editor for the profile the mouse is running. - pub(super) fn render_logitech_stages(&self, profile: &OnboardProfile, cx: &mut Context) -> Option
{ + fn stage_linked(&self, draft: &StageDraft, index: usize) -> bool { + !self.stage_unlinked.contains(&index) && draft.x(index) == draft.y(index) + } + + fn running_profile(&self) -> Option<&OnboardProfile> { + let tile = self.devices.tiles.get(self.devices.selected)?; + let TileStatus::Connected(r) = &tile.status else { return None }; + if !r.onboard_profiles_writable || r.mode.as_deref() != Some("Onboard") || self.editing_profile().is_some() { + return None; + } + self.devices.onboard.as_ref()?.profiles.iter().find(|p| p.is_current && p.crc_valid) + } + + fn stage_draft_for(&self, profile: &OnboardProfile) -> Option { let saved = StageDraft::from_profile(profile)?; - let draft = self.devices.stage_draft.clone().filter(|d| d.sector == profile.sector).unwrap_or_else(|| saved.clone()); - let fg = cx.theme().foreground; - let muted = cx.theme().muted_foreground; - let can_add = draft.stages.len() < MOST; - let multiple = draft.stages.len() > 1; + Some(self.devices.stage_draft.clone().filter(|d| d.sector == profile.sector).unwrap_or(saved)) + } + + fn edit_stages(&mut self, draft: StageDraft, cx: &mut Context) { + self.devices.stage_draft = Some(draft.clone()); + self.stage_seq += 1; + let seq = self.stage_seq; + cx.notify(); + cx.spawn(async move |view, cx| { + cx.background_executor().timer(std::time::Duration::from_millis(600)).await; + let _ = view.update(cx, |this: &mut Self, cx| { + if this.stage_seq != seq { + return; + } + if this.devices.writing.is_some() { + this.edit_stages(draft, cx); + } else { + this.stage_sent = seq; + this.onboard_action("stages", json!({ "stages": draft.stages, "defaultIndex": draft.default, "sector": draft.sector }), cx); + } + }); + }) + .detach(); + } + + pub(super) fn ensure_stage_sliders(&mut self, window: &mut Window, cx: &mut Context) { + let Some(profile) = self.running_profile() else { return }; + let Some(draft) = self.stage_draft_for(profile) else { return }; + let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; + let TileStatus::Connected(r) = &tile.status else { return }; + let Some(c) = r.controls.as_ref() else { return }; + let (min, max, step) = (c.dpi.min.max(1.0), c.dpi.max, c.dpi.step.max(1.0)); + if max <= min { + return; + } + let axes: &[bool] = if r.separate_axes { &[false, true] } else { &[false] }; + for i in 0..MOST { + for &y_axis in axes { + let read = |d: &StageDraft, n: usize| if y_axis { d.y(n) } else { d.x(n) }; + let wanted = read(&draft, i).or(read(&draft, draft.stages.len() - 1)).unwrap_or(min as i64) as f64; + let wanted = wanted.clamp(min, max) as f32; + let text = (wanted as i64).to_string(); + match self.stage_inputs.get(&(i, y_axis)) { + Some(input) => { + let focused = input.read(cx).focus_handle(cx).is_focused(window); + if !focused && input.read(cx).value().as_ref() != text { + input.update(cx, |s, cx| s.set_value(text, window, cx)); + } + } + None => { + let input = cx.new(|cx| InputState::new(window, cx).default_value(text)); + let sub = cx.subscribe(&input, move |this: &mut Self, _, event: &InputEvent, cx| { + if matches!(event, InputEvent::PressEnter { .. } | InputEvent::Blur) { + this.commit_stage_input(i, y_axis, cx); + } + }); + self._subscriptions.push(sub); + self.stage_inputs.insert((i, y_axis), input); + } + } + if let Some(slider) = self.stage_sliders.get(&(i, y_axis)) { + if (slider.read(cx).value().end() - wanted).abs() > 0.5 { + slider.update(cx, |s, cx| s.set_value(wanted, window, cx)); + } + continue; + } + let slider = cx.new(|_| { + SliderState::new() + .max(max as f32) + .min(min as f32) + .step(step as f32) + .scale(SliderScale::Logarithmic) + .default_value(wanted) + }); + let sub = cx.subscribe_in(&slider, window, move |this: &mut Self, _s, event, _w, cx| { + let SliderEvent::Change(value) = event else { return }; + let Some(profile) = this.running_profile() else { return }; + let Some(mut draft) = this.stage_draft_for(profile) else { return }; + let v = ((value.end() as f64 / step).round() * step).clamp(min, max) as i64; + let now = if y_axis { draft.y(i) } else { draft.x(i) }; + if i >= draft.stages.len() || now == Some(v) { + return; + } + let linked = this.stage_linked(&draft, i); + draft.set_axis(i, v, y_axis, linked); + this.edit_stages(draft, cx); + }); + self._subscriptions.push(sub); + self.stage_sliders.insert((i, y_axis), slider); + } + } + } - let edit = |id: String, label: String, chosen: bool, change: Box, cx: &mut Context| { - let from = draft.clone(); - self.chip(id, label, chosen, cx, move |this, cx| { - let mut next = from.clone(); - change(&mut next); - this.devices.stage_draft = Some(next); - cx.notify(); - }) + pub(super) fn start_profile_rename(&mut self, sector: u32, current: String, window: &mut Window, cx: &mut Context) { + let input = cx.new(|cx| InputState::new(window, cx).default_value(current)); + input.update(cx, |state, cx| state.focus(window, cx)); + let sub = cx.subscribe(&input, |this: &mut Self, _, event: &InputEvent, cx| { + if matches!(event, InputEvent::PressEnter { .. }) { + this.save_profile_name(cx); + } + }); + self._subscriptions.push(sub); + self.profile_name = Some((sector, input)); + cx.notify(); + } + + pub(super) fn save_profile_name(&mut self, cx: &mut Context) { + let Some((sector, input)) = self.profile_name.clone() else { return }; + cx.notify(); + let name = input.read(cx).value().trim().to_string(); + let old = self + .devices + .onboard + .as_ref() + .and_then(|list| list.profiles.iter().find(|p| p.sector == sector)) + .and_then(|p| p.name.clone()) + .unwrap_or_default(); + if name.is_empty() || name == old { + self.profile_name = None; + } else if self.devices.writing.is_none() { + self.onboard_action("rename", json!({ "sector": sector, "name": name }), cx); + } + } + + fn commit_stage_input(&mut self, i: usize, y_axis: bool, cx: &mut Context) { + let Some(input) = self.stage_inputs.get(&(i, y_axis)) else { return }; + let typed: String = input.read(cx).value().chars().filter(char::is_ascii_digit).collect(); + let Ok(typed) = typed.parse::() else { + cx.notify(); + return; }; + let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; + let TileStatus::Connected(r) = &tile.status else { return }; + let Some(c) = r.controls.as_ref() else { return }; + let (min, max, step) = (c.dpi.min.max(1.0), c.dpi.max, c.dpi.step.max(1.0)); + let Some(profile) = self.running_profile() else { return }; + let Some(mut draft) = self.stage_draft_for(profile) else { return }; + let v = ((typed / step).round() * step).clamp(min, max) as i64; + let now = if y_axis { draft.y(i) } else { draft.x(i) }; + if i >= draft.stages.len() || now == Some(v) { + cx.notify(); + return; + } + let linked = self.stage_linked(&draft, i); + draft.set_axis(i, v, y_axis, linked); + self.edit_stages(draft, cx); + } + + pub(super) fn render_logitech_stages(&self, profile: &OnboardProfile, cx: &mut Context) -> Option
{ + let draft = self.stage_draft_for(profile)?; + let fg = cx.theme().foreground; + let muted = cx.theme().muted_foreground; + let accent = cx.theme().primary; + let busy = self.devices.writing.is_some(); + let used = draft.stages.len(); + let separate = matches!( + self.devices.tiles.get(self.devices.selected).map(|t| &t.status), + Some(TileStatus::Connected(r)) if r.separate_axes + ); let header = h_flex() .justify_between() .items_center() - .gap_3() + .child(div().text_sm().font_weight(FontWeight::SEMIBOLD).text_color(fg).child("Sensitivity (DPI)")) .child( - div() - .flex() - .flex_col() - .gap_0p5() - .child( - div() - .text_sm() - .font_weight(FontWeight::SEMIBOLD) - .text_color(fg) - .child(format!("Profile {} — DPI stages", profile.sector)), - ) - .child(div().text_xs().text_color(muted).child( - "DPI steps stored in this onboard profile.", - )), - ) - .when(can_add, |row| { + h_flex() + .gap_2() + .child(div().text_xs().text_color(muted).child("Slots in use")) + .child(div().text_xs().font_weight(FontWeight::SEMIBOLD).text_color(fg).child(format!("{used} / {MOST}"))), + ); + + let mut card = panel(cx).child(header).child(super::device_page::divider(cx)); + for i in 0..MOST { + let on = i < used; + let starting = on && draft.default == i; + let tick = { let from = draft.clone(); - row.child( - Button::new("lg-stage-add") - .compact() - .label("+ Add stage") - .on_click(cx.listener(move |this, _, _, cx| { - let mut next = from.clone(); + Checkbox::new(SharedString::from(format!("lg-stage-on-{i}"))) + .checked(on) + .disabled(busy || (on && used == 1) || (!on && i != used)) + .on_click(cx.listener(move |this, _: &bool, _, cx| { + let mut next = from.clone(); + if on { + next.remove(i); + this.stage_unlinked = this.stage_unlinked.iter().filter(|&&j| j != i).map(|&j| if j > i { j - 1 } else { j }).collect(); + } else { next.add(); - this.devices.stage_draft = Some(next); - cx.notify(); - })), - ) - }); - - let mut card = panel(cx).child(header); - for (i, stage) in draft.stages.iter().enumerate() { - let x = stage["x"].as_i64().unwrap_or(0); - let mut presets = segmented(cx); - for preset in PRESETS { - presets = presets.child(edit( - format!("lg-stage-p-{i}-{preset}"), - preset.to_string(), - x == preset, - Box::new(move |d| d.set_dpi(i, preset)), - cx, - )); - } - let stepper = segmented(cx) - .items_center() - .child(edit(format!("lg-stage-down-{i}"), "−".into(), false, Box::new(move |d| d.nudge(i, -STEP)), cx)) - .child( - div() - .min_w(px(68.)) - .text_center() - .text_sm() - .font_weight(FontWeight::MEDIUM) - .text_color(fg) - .child(format!("{x} DPI")), - ) - .child(edit(format!("lg-stage-up-{i}"), "+".into(), false, Box::new(move |d| d.nudge(i, STEP)), cx)); - - let mut left = h_flex() - .gap_2() - .items_center() - .child(div().text_sm().font_weight(FontWeight::MEDIUM).text_color(fg).child(format!("Stage {}", i + 1))); - if multiple { - let default_chip = edit( - format!("lg-stage-start-{i}"), - "Default".into(), - draft.default == i, - Box::new(move |d| d.default = i), - cx, - ); - left = left.child(segmented(cx).child(default_chip)); - } - - let mut right = h_flex().gap_2().items_center().child(presets).child(stepper); - if multiple { + } + this.edit_stages(next, cx); + })) + }; + let number = { let from = draft.clone(); - right = right.child( - Button::new(SharedString::from(format!("lg-stage-rm-{i}"))) - .ghost() - .compact() - .label("×") - .tooltip("Remove stage") - .on_click(cx.listener(move |this, _, _, cx| { + div() + .id(SharedString::from(format!("lg-stage-start-{i}"))) + .w(px(28.)) + .h(px(28.)) + .flex() + .items_center() + .justify_center() + .rounded_md() + .text_sm() + .font_weight(FontWeight::SEMIBOLD) + .border_1() + .border_color(if starting { accent } else { Hsla { a: 0.2, ..fg } }) + .bg(if starting { Hsla { a: 0.18, ..accent } } else { Hsla { a: 0.0, ..fg } }) + .text_color(if on { fg } else { muted }) + .when(on && !starting && !busy, |b| { + b.cursor_pointer().hover(move |b| b.bg(Hsla { a: 0.08, ..fg })).on_click(cx.listener(move |this, _, _, cx| { let mut next = from.clone(); - next.remove(i); - this.devices.stage_draft = Some(next); - cx.notify(); - })), - ); + next.default = i; + this.edit_stages(next, cx); + })) + }) + .child((i + 1).to_string()) + }; + let linked = !separate || self.stage_linked(&draft, i); + let value = |y_axis: bool| { + let cell = div().w(px(76.)).h(px(28.)).flex().items_center(); + match self.stage_inputs.get(&(i, y_axis)).filter(|_| on) { + Some(input) => { + let handle = input.read(cx).focus_handle(cx); + cell.on_mouse_down_out(cx.listener(move |this, _, window, cx| { + if handle.is_focused(window) { + this.commit_stage_input(i, y_axis, cx); + window.blur(cx); + } + })) + .child(Input::new(input).small().disabled(busy)) + } + None => cell.justify_center().text_sm().text_color(muted).child("Off"), + } + }; + let slider = |y_axis: bool| { + div().w_full().min_w_0().h(px(28.)).flex().items_center().when(on, |d| { + d.children(self.stage_sliders.get(&(i, y_axis)).map(|s| div().w_full().child(Slider::new(s).bg(accent).text_color(fg)))) + }) + }; + let mut sliders = div().flex().flex_col().gap_2().flex_1().min_w_0().child(slider(false)); + if !linked { + sliders = sliders.child(slider(true)); } - - card = card - .child(super::device_page::divider(cx)) - .child(h_flex().justify_between().items_center().gap_3().child(left).child(right)); - } - - let changed = draft != saved; - let sent = json!({ "stages": draft.stages, "defaultIndex": draft.default }); - let footer = h_flex() - .justify_end() - .gap_2() - .when(changed, |row| { - row.child( - Button::new("lg-stages-discard") - .ghost() - .compact() - .label("Discard") - .on_click(cx.listener(|this, _, _, cx| { - this.devices.stage_draft = None; - cx.notify(); - })), - ) - }) - .child( - Button::new("lg-stages-save") - .primary() + let link = separate.then(|| { + let from = draft.clone(); + div().w(px(28.)).h(px(28.)).flex().items_center().justify_center().child(Button::new(SharedString::from(format!("lg-stage-link-{i}"))) .compact() - .label("Save stages") - .disabled(!changed || self.devices.writing.is_some()) + .ghost() + .icon(if linked { IconName::Link2 } else { IconName::Unlink2 }) + .tooltip(if linked { "X and Y move together" } else { "X and Y are set separately" }) + .disabled(!on || busy) .on_click(cx.listener(move |this, _, _, cx| { - this.devices.stage_draft = None; - this.onboard_action("stages", sent.clone(), cx); - })), + if linked { + this.stage_unlinked.insert(i); + cx.notify(); + } else { + this.stage_unlinked.remove(&i); + let mut next = from.clone(); + if let Some(x) = next.x(i) { + next.set_axis(i, x, true, false); + } + this.edit_stages(next, cx); + } + }))) + }); + card = card.child( + h_flex() + .gap_3() + .items_start() + .opacity(if on { 1.0 } else { 0.55 }) + .child(div().h(px(28.)).flex().items_center().child(tick)) + .child(number) + .child(value(false)) + .children(link) + .when(separate, |row| row.child(value(true))) + .child(sliders), ); - Some(card.child(super::device_page::divider(cx)).child(footer)) + } + Some(card.child(div().text_xs().text_color(muted).child( + "Saved to this onboard profile a moment after you stop. The highlighted number is the stage the mouse starts on.", + ))) } } @@ -245,13 +394,13 @@ mod tests { .unwrap(); let mut draft = StageDraft::from_profile(&profile).unwrap(); assert_eq!((draft.stages.len(), draft.default), (2, 1), "unused slots are left out"); - draft.nudge(0, 50); - draft.nudge(1, 50); + draft.set_dpi(0, 450); + draft.set_dpi(1, 850); assert_eq!(draft.stages[0], json!({ "x": 450, "y": 450, "lod": 2 })); assert_eq!(draft.stages[1], json!({ "x": 850, "y": 900, "lod": 1 })); - draft.remove_last(); + draft.remove(1); assert_eq!((draft.stages.len(), draft.default), (1, 0)); - draft.remove_last(); + draft.remove(0); assert_eq!(draft.stages.len(), 1, "a mouse keeps one stage"); } } diff --git a/gpui/src/app/macro_panel.rs b/gpui/src/app/macro_panel.rs index 5d933dba..84f99e34 100644 --- a/gpui/src/app/macro_panel.rs +++ b/gpui/src/app/macro_panel.rs @@ -89,7 +89,7 @@ impl AppView { Ok(steps) => v.macros.steps = steps, Err(error) => v.macros.error = Some(error.to_string()), }, - Ok(Ok(_)) => v.show_toast("Macro saved to your mouse.", false, cx), + Ok(Ok(_)) => v.show_toast("Macro saved.", false, cx), Ok(Err(error)) => v.macros.error = Some(crate::write_safety::problem(&error)), Err(_) => v.macros.error = Some("device runtime stopped".to_string()), } @@ -102,6 +102,7 @@ impl AppView { pub(super) fn render_macros(&self, spec: &MacroPanel, cx: &mut Context) -> Div { let (fg, muted, accent) = (cx.theme().foreground, cx.theme().muted_foreground, cx.theme().primary); let slot = self.macros.slot; + let device = if self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.keyboard) { "keyboard" } else { "mouse" }; let button = self.macros.button.or_else(|| spec.buttons.first().map(|b| b.value)).unwrap_or(0); let note = |text: String| div().text_xs().text_color(muted).child(text); let label = |text: &'static str| div().text_xs().text_color(muted).child(text); @@ -227,7 +228,7 @@ impl AppView { cx.notify(); }))); if spec.readable { - actions = actions.child(small("macro-read", "Read from mouse", !busy).on_click(cx.listener(move |this, _, _, cx| { + actions = actions.child(small("macro-read", if device == "keyboard" { "Read from keyboard" } else { "Read from mouse" }, !busy).on_click(cx.listener(move |this, _, _, cx| { this.macro_run("read", json!({ "slot": slot, "button": button }), cx) }))); } @@ -236,7 +237,7 @@ impl AppView { actions = actions.child( Button::new("macro-save") .compact() - .label(if confirming { "Erase the others and save" } else { "Save to mouse" }) + .label(if confirming { "Erase the others and save" } else if device == "keyboard" { "Save to keyboard" } else { "Save to mouse" }) .disabled(busy) .on_click(cx.listener(move |this, _, _, cx| { if warns && !this.macros.confirming { diff --git a/gpui/src/app/magnetic_panel.rs b/gpui/src/app/magnetic_panel.rs index d353d9c9..2ef360d7 100644 --- a/gpui/src/app/magnetic_panel.rs +++ b/gpui/src/app/magnetic_panel.rs @@ -123,7 +123,7 @@ impl AppView { if let (Some(range), Some(point)) = (panel.trigger, shown.trigger_point) { let values = self.magnetic_values(id("trigger"), range, Some(point), !optical, None, panel.brand == "Keychron", cx); - let hint = format!("{}–{}", range.min, range.max); + let hint = format!("{}-{}", range.min, range.max); card = card.child(magnetic_row("Actuation point", Some(hint), values, cx)); } @@ -157,7 +157,7 @@ impl AppView { "Lower the actuation point to use it".to_string() } else { let unit = panel.rapid_unit.as_deref().map(|u| format!(" {u}")).unwrap_or_default(); - format!("{}–{most}{unit}", range.min) + format!("{}-{most}{unit}", range.min) }; card = card.child(magnetic_row("Rapid trigger", Some(hint), control, cx)); } else if shown.rapid_trigger.is_some() { diff --git a/gpui/src/app/overview.rs b/gpui/src/app/overview.rs index b3de0eac..cc47a371 100644 --- a/gpui/src/app/overview.rs +++ b/gpui/src/app/overview.rs @@ -195,9 +195,9 @@ impl AppView { TileStatus::Connecting => ("Connecting…".to_string(), muted), // A wireless mouse that is off or asleep answers nothing; say what to do. TileStatus::Failed(error) if error.to_lowercase().contains("asleep") || error.to_lowercase().contains("out of range") => { - ("Asleep or out of range — wake to retry".to_string(), cx.theme().danger) + ("Asleep or out of range - wake to retry".to_string(), cx.theme().danger) } - TileStatus::Failed(_) => ("Couldn't connect — click to retry".to_string(), cx.theme().danger), + TileStatus::Failed(_) => ("Couldn't connect - click to retry".to_string(), cx.theme().danger), TileStatus::Connected(_) => ("Connected".to_string(), muted), }; let kind_label = if t.keyboard { "Keyboard" } else { "Mouse" }; @@ -452,7 +452,7 @@ impl AppView { Ok(()) => { v.udev_fix = UdevFix::Idle; v.hid_blocked.clear(); - v.show_toast("Permissions updated — scanning for mice", false, cx); + v.show_toast("Permissions updated - scanning for mice", false, cx); v.scan_devices(cx); } Err((error, command)) => { diff --git a/gpui/src/app/plugins_page.rs b/gpui/src/app/plugins_page.rs index 1df3221a..f0ef68e2 100644 --- a/gpui/src/app/plugins_page.rs +++ b/gpui/src/app/plugins_page.rs @@ -339,7 +339,7 @@ impl AppView { this.settings.save(); this.marketplace_auth_modal = false; if let Some(pending) = this.pending_upload_theme.take() { - this.show_toast(format!("Signed in as {name} — publishing theme…"), false, cx); + this.show_toast(format!("Signed in as {name} - publishing theme…"), false, cx); this.upload_local_theme(pending, cx); } else { this.show_toast(format!("Signed in as {name}"), false, cx); @@ -777,7 +777,7 @@ impl AppView { .text_sm() .font_weight(FontWeight::MEDIUM) .text_color(fg) - .child(format!("Previewing “{preview_name}” — not saved yet.")), + .child(format!("Previewing “{preview_name}” - not saved yet.")), ) .child( h_flex() diff --git a/gpui/src/app/profile_ui.rs b/gpui/src/app/profile_ui.rs index 1d366b8d..e7e8e3e8 100644 --- a/gpui/src/app/profile_ui.rs +++ b/gpui/src/app/profile_ui.rs @@ -224,7 +224,7 @@ impl AppView { /// Applies every auto-apply profile that should be in force: for each game /// that is running and each connected device, unless that pair is already /// applied or being applied. Safe to call whenever a game starts or a - /// device connects — a device that shows up after the game launched is + /// device connects - a device that shows up after the game launched is /// picked up here too. pub(super) fn sync_running_profiles(&mut self, cx: &mut Context) { let running: Vec = self.games.iter().filter(|g| g.running).map(|g| g.id.clone()).collect(); @@ -254,7 +254,7 @@ impl AppView { continue; } let (name, described) = (active.game_name.clone(), active.restore.describe()); - let text = format!("{name} closed — restored your default {described}."); + let text = format!("{name} closed - restored your default {described}."); self.apply_profile_inner(id, &name, &active.device, active.restore, None, Some(text), true, cx); } } @@ -327,7 +327,7 @@ impl AppView { if auto { self.profile_inflight.push((game_id.to_string(), device.to_string())); } - self.apply_profile_inner(game_id, &name, device, profile, override_, Some(format!("Applied \"{name}\" profile — {described}.")), auto, cx); + self.apply_profile_inner(game_id, &name, device, profile, override_, Some(format!("Applied \"{name}\" profile - {described}.")), auto, cx); } pub(super) fn apply_profile_inner( @@ -356,7 +356,7 @@ impl AppView { ("gamingSurfaceMode", "surface"), ] { if let Some(value) = applied.get(field) { - v.patch_readout(&key, action, value); + v.patch_readout(&key, action, value, cx); } } // Only take over once the write is confirmed to have landed. diff --git a/gpui/src/app/safety.rs b/gpui/src/app/safety.rs index 2ee68108..5083e8dd 100644 --- a/gpui/src/app/safety.rs +++ b/gpui/src/app/safety.rs @@ -36,6 +36,11 @@ pub(super) enum Queued { } impl Queued { + pub(super) fn is_rescue(&self) -> bool { + matches!(self, Queued::Control { id, value, .. } + if (id == "logi.button.primary.0" && value.as_str() == Some("Left click")) || (id == "logi.remap.80" && value.as_i64() == Some(80))) + } + fn target(&self) -> (&str, &str) { match self { Queued::Setting { key, action, .. } => (key, action), @@ -47,6 +52,7 @@ impl Queued { pub(super) enum Pending { Control { key: String, id: String, value: Value }, + Onboard { key: String, action: &'static str, value: Value }, ClearProfile { game: String, device: String }, RemoveGame(String), } @@ -63,6 +69,14 @@ impl AppView { return; } let edit = self.devices.queued.remove(0); + let rescue = edit.is_rescue(); + let target = self.devices.tiles.iter().position(|t| t.key == edit.target().0 && matches!(t.status, TileStatus::Connected(_))); + if let (true, Some(index)) = (rescue, target) { + if index != self.devices.selected { + self.devices.selected = index; + self.show_toast("Restoring the left click on the mouse the shortcut was pressed for.", false, cx); + } + } // Writes go to the selected device; an edit for another is out of date. if self.devices.tiles.get(self.devices.selected).map(|t| t.key.as_str()) != Some(edit.target().0) { crate::logging::log("[device] dropped a waiting edit for a device no longer selected"); @@ -185,7 +199,14 @@ impl AppView { v.hid_service().into() }); let Ok(Some(service)) = service else { return }; - let read = service.connect(&key).await; + let mut read = service.connect(&key).await; + for _ in 0..10 { + if !matches!(&read, Ok(Err(error)) if error.contains("busy")) { + break; + } + cx.background_executor().timer(std::time::Duration::from_millis(500)).await; + read = service.connect(&key).await; + } let _ = view.update(cx, |v: &mut Self, cx| { if v.devices.writing.as_deref() == Some(CHECKING) { v.devices.writing = None; @@ -274,6 +295,25 @@ impl AppView { true } + pub(super) fn ask_before_onboard( + &mut self, + action: &'static str, + value: Value, + title: &str, + detail: &str, + proceed: &'static str, + cx: &mut Context, + ) { + let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; + self.confirm = Some(Confirm { + title: title.into(), + detail: detail.into(), + proceed, + then: Pending::Onboard { key: tile.key.clone(), action, value }, + }); + cx.notify(); + } + pub(super) fn ask_before_clearing_profile(&mut self, game: &str, device: &str, cx: &mut Context) { self.confirm = Some(Confirm { title: "Clear this profile?".into(), @@ -309,6 +349,13 @@ impl AppView { self.show_toast("That device is no longer selected. Nothing was changed.", true, cx); } } + Pending::Onboard { key, action, value } => { + if self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.key == key) { + self.onboard_action(action, value, cx); + } else { + self.show_toast("That device is no longer selected. Nothing was changed.", true, cx); + } + } Pending::RemoveGame(game) => self.remove_custom_game(&game, cx), Pending::ClearProfile { game, device } => { self.profiles.clear(&game, &device); diff --git a/gpui/src/app/settings_page.rs b/gpui/src/app/settings_page.rs index b1043d7c..0bcbcf7f 100644 --- a/gpui/src/app/settings_page.rs +++ b/gpui/src/app/settings_page.rs @@ -161,6 +161,9 @@ impl AppView { } else if switch_id == "tray-battery-switch" { this.settings.tray_battery_enabled = *enabled; this.refresh_tray_battery(); + } else if switch_id == "tray-pin-switch" { + this.settings.tray_pinned = *enabled; + crate::tray::pin(*enabled); } else if switch_id == "low-battery-switch" { this.settings.low_battery_alert = *enabled; this.battery.reset_alerts(); @@ -387,6 +390,16 @@ impl AppView { self.settings.tray_battery_enabled, cx, )); + if cfg!(windows) { + card = card.child(settings_divider(cx)).child(self.render_switch_row( + "tray-pin-switch", + IconName::Pin, + "Keep the icon on the taskbar", + "Show the tray icon next to the clock instead of behind the ^ arrow.", + self.settings.tray_pinned, + cx, + )); + } if self.settings.tray_battery_enabled { let selected = crate::tray::TrayBatteryTheme::ALL .iter() diff --git a/gpui/src/app/text_controls.rs b/gpui/src/app/text_controls.rs index 78887df3..20b377b2 100644 --- a/gpui/src/app/text_controls.rs +++ b/gpui/src/app/text_controls.rs @@ -4,15 +4,19 @@ use super::receiver_panel::combination; use super::*; use crate::hid::ControlSpec; +use gpui_kit::component::color_picker::{ColorPicker, ColorPickerEvent, ColorPickerState}; use gpui_kit::component::input::{Input, InputState}; use serde_json::json; use std::collections::HashMap; +const PICKED: &str = "picked"; + /// What the boxes of the open device page hold, by `/`. #[derive(Default)] pub(super) struct TextControls { /// A name box, and the value it was made with. pub(super) names: HashMap)>, + pub(super) colours: HashMap, Subscription)>, /// Boxes that listen for a key press. pub(super) listening: HashMap, /// The press heard but not yet assigned. @@ -29,7 +33,7 @@ impl AppView { let TileStatus::Connected(r) = &tile.status else { return }; let device = tile.key.as_str(); let needs_work = r.tabs.controls().any(|c| { - if c.kind != "text" && c.kind != "shortcut" { + if c.kind != "text" && c.kind != "shortcut" && c.kind != "color" { return false; } let matches_key = |k: &String| { @@ -40,6 +44,13 @@ impl AppView { }; if c.kind == "shortcut" { !self.text_controls.listening.keys().any(matches_key) + } else if c.kind == "color" { + let current = c.current.as_str().unwrap_or_default(); + !self + .text_controls + .colours + .iter() + .any(|(k, (made_with, _, _))| matches_key(k) && (made_with == PICKED || made_with.eq_ignore_ascii_case(current))) } else { let current = c.current.as_str().unwrap_or_default(); !self @@ -52,14 +63,37 @@ impl AppView { if !needs_work { return; } - let wanted: Vec<(String, String, String)> = r + let wanted: Vec<(String, String, String, String)> = r .tabs .controls() - .filter(|c| c.kind == "text" || c.kind == "shortcut") - .map(|c| (format!("{}/{}", tile.key, c.id), c.kind.clone(), c.current.as_str().unwrap_or_default().to_string())) + .filter(|c| c.kind == "text" || c.kind == "shortcut" || c.kind == "color") + .map(|c| (format!("{}/{}", tile.key, c.id), c.id.clone(), c.kind.clone(), c.current.as_str().unwrap_or_default().to_string())) .collect(); - for (key, kind, current) in wanted { - if kind == "shortcut" { + for (key, id, kind, current) in wanted { + if kind == "color" { + if let Some((made_with, state, _)) = self.text_controls.colours.get_mut(&key) { + if made_with != PICKED && !made_with.eq_ignore_ascii_case(¤t) { + *made_with = current.clone(); + let colour = super::controls::hex_color(¤t); + state.update(cx, |s, cx| s.set_value(colour, window, cx)); + } + continue; + } + let start = super::controls::hex_color(¤t); + let state = cx.new(|cx| ColorPickerState::new(window, cx).default_value(start)); + let held = key.clone(); + let changed = cx.subscribe(&state, move |this: &mut Self, _, event: &ColorPickerEvent, cx| { + let ColorPickerEvent::Change(Some(colour)) = event else { return }; + let rgb = Rgba::from(*colour); + let part = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; + let hex = format!("#{:02x}{:02x}{:02x}", part(rgb.r), part(rgb.g), part(rgb.b)); + if let Some(entry) = this.text_controls.colours.get_mut(&held) { + entry.0 = PICKED.to_string(); + } + this.set_control(id.clone(), json!(hex), cx); + }); + self.text_controls.colours.insert(key, (current, state, changed)); + } else if kind == "shortcut" { self.text_controls.listening.entry(key).or_insert_with(|| cx.focus_handle()); } else if self.text_controls.names.get(&key).is_none_or(|(made_with, _)| *made_with != current) { let value = current.clone(); @@ -96,6 +130,54 @@ impl AppView { h_flex().gap_2().items_center().child(div().w(px(220.)).child(Input::new(&state))).child(save).into_any_element() } + pub(super) fn render_color_control(&self, c: &ControlSpec) -> AnyElement { + match self.text_key(c).and_then(|k| self.text_controls.colours.get(&k)) { + Some((_, state, _)) => ColorPicker::new(state).into_any_element(), + None => div().into_any_element(), + } + } + + pub(super) fn save_control_file(&mut self, id: String, suggested: String, cx: &mut Context) { + let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; + let (key, brand) = (tile.key.clone(), tile.brand.clone()); + let dir = dirs::document_dir().or_else(dirs::home_dir).unwrap_or_default(); + let picked = cx.prompt_for_new_path(&dir, Some(&suggested)); + let service = self.hid_service(); + cx.spawn(async move |view, cx| { + let Ok(Ok(Some(path))) = picked.await else { return }; + let outcome = match service.write(&key, &brand, &format!("control:{id}"), json!(null)).await { + Ok(Ok(serde_json::Value::String(text))) => std::fs::write(&path, text).map_err(|_| "Couldn't write that file.".to_string()), + Ok(Ok(_)) => Err("The keyboard sent nothing to save.".to_string()), + Ok(Err(error)) => Err(error), + Err(_) => Err("device runtime stopped".to_string()), + }; + let _ = view.update(cx, |v: &mut Self, cx| match outcome { + Ok(()) => v.show_toast("Saved the layout file.", false, cx), + Err(error) => v.show_toast(error, true, cx), + }); + }) + .detach(); + } + + pub(super) fn open_control_file(&mut self, id: String, cx: &mut Context) { + let Some(key) = self.devices.tiles.get(self.devices.selected).map(|t| t.key.clone()) else { return }; + let picked = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: Some("Load".into()) }); + cx.spawn(async move |view, cx| { + let Ok(Ok(Some(paths))) = picked.await else { return }; + let Some(path) = paths.into_iter().next() else { return }; + let text = cx.background_executor().spawn(async move { std::fs::read_to_string(path) }).await; + let _ = view.update(cx, |v: &mut Self, cx| { + let same = v.devices.tiles.get(v.devices.selected).is_some_and(|t| t.key == key) && v.editing_profile().is_none(); + match text { + Ok(_) if !same => v.show_toast("The keyboard changed while the file was open. Nothing was loaded.", true, cx), + Ok(text) => v.set_control(id, json!(text), cx), + Err(_) => v.show_toast("Couldn't read that file.", true, cx), + } + }); + }) + .detach(); + } + /// Click, press a key or combination, then Assign. pub(super) fn render_shortcut_control(&self, c: &ControlSpec, cx: &mut Context) -> AnyElement { let Some((key, handle)) = self.text_key(c).and_then(|k| self.text_controls.listening.get(&k).map(|h| (k, h.clone()))) diff --git a/gpui/src/app/theme_studio.rs b/gpui/src/app/theme_studio.rs index 09fd48f1..b4a45cf9 100644 --- a/gpui/src/app/theme_studio.rs +++ b/gpui/src/app/theme_studio.rs @@ -401,7 +401,7 @@ impl AppView { let missing = crate::marketplace::missing_theme_fields(&css); if !missing.is_empty() { self.show_toast( - format!("Complete all fields first — missing or invalid: {}", missing.join(", ")), + format!("Complete all fields first - missing or invalid: {}", missing.join(", ")), true, cx, ); diff --git a/gpui/src/app/travel_panel.rs b/gpui/src/app/travel_panel.rs index dea36815..6199e771 100644 --- a/gpui/src/app/travel_panel.rs +++ b/gpui/src/app/travel_panel.rs @@ -12,7 +12,7 @@ const HEIGHT: f32 = 120.0; /// What the graphs need to know about a mouse with live travel. #[derive(Clone, PartialEq)] pub(super) struct Travel { - /// Keychron counts travel in levels 0–12; others show a percentage. + /// Keychron counts travel in levels 0-12; others show a percentage. levels: bool, /// Each button's trigger point on the graph's scale; none while optical. triggers: [Option; 2], @@ -36,6 +36,11 @@ impl Travel { Some(Self { levels, triggers: [trigger(0), trigger(1)] }) } + pub(super) fn from_hits(hits: &crate::hid::HitsTravel) -> Self { + let trigger = |side: usize| hits.triggers.get(side).copied().flatten(); + Self { levels: false, triggers: [trigger(0), trigger(1)] } + } + fn top(&self) -> f32 { if self.levels { 12.0 @@ -67,7 +72,7 @@ pub(super) struct LiveTravel { impl AppView { /// The device whose travel should be read right now, if any. fn travel_wanted(&self) -> Option { - if self.devices.tab != DeviceTab::Buttons || self.devices.writing.is_some() { + if !matches!(self.devices.tab, DeviceTab::Buttons | DeviceTab::Advanced) || self.devices.writing.is_some() { return None; } let open = if self.page == Page::Overview { @@ -79,7 +84,11 @@ impl AppView { }; let tile = self.devices.tiles.get(self.devices.selected).filter(|t| t.key == open)?; let TileStatus::Connected(r) = &tile.status else { return None }; - (r.tabs.magnetic.as_ref().is_some_and(|m| m.live_depth) && crate::activity::ACTIVITY.is_active()).then(|| tile.key.clone()) + let shown = match self.devices.tab { + DeviceTab::Buttons => r.tabs.magnetic.as_ref().is_some_and(|m| m.live_depth), + _ => r.tabs.hits_travel.is_some() && self.editing_profile().is_none(), + }; + (shown && crate::activity::ACTIVITY.is_active()).then(|| tile.key.clone()) } /// Starts reading when the graphs come into view; the loop ends itself when @@ -163,8 +172,8 @@ impl AppView { let latest = self.travel.samples.back().map(|(_, d)| travel.scaled(d[side])); let pressed = matches!((latest, trigger), (Some(now), Some(at)) if now >= at); let reading = match latest { - None => "–".to_string(), - Some(n) if travel.levels && n < 0.5 => "–".to_string(), + None => "-".to_string(), + Some(n) if travel.levels && n < 0.5 => "-".to_string(), Some(n) if travel.levels => format!("{n:.0}"), Some(n) => format!("{n:.0}%"), }; diff --git a/gpui/src/app/updates.rs b/gpui/src/app/updates.rs index 0596c316..c9f33a88 100644 --- a/gpui/src/app/updates.rs +++ b/gpui/src/app/updates.rs @@ -206,14 +206,14 @@ impl AppView { if should_toast { self.settings.last_notified_update_version = Some(info.version.clone()); self.settings.save(); - self.show_toast(format!("OpenMouse Desktop v{} is available — see Updates.", info.version), false, cx); + self.show_toast(format!("OpenMouse Desktop v{} is available - see Updates.", info.version), false, cx); } cx.notify(); } /// "Check for updates" button: runs a check right now (not waiting for - /// the next background-poll tick) and always surfaces *something* — - /// "up to date" included — since the user explicitly asked. + /// the next background-poll tick) and always surfaces *something* - + /// "up to date" included - since the user explicitly asked. pub(super) fn check_for_updates_now(&mut self, cx: &mut Context) { if self.checking_for_updates { return; @@ -227,14 +227,14 @@ impl AppView { view.checking_for_updates = false; match info { // A manual click always wants an answer, even "nothing to - // report" — `note_update_available` itself stays silent + // report" - `note_update_available` itself stays silent // once a version's already been nagged about. Some(info) if !crate::update_check::is_newer(APP_VERSION, &info.version) => { view.note_update_available(info, cx); view.show_toast("You're up to date.", false, cx); } Some(info) => view.note_update_available(info, cx), - None => view.show_toast("Couldn't check for updates — check your connection.", true, cx), + None => view.show_toast("Couldn't check for updates - check your connection.", true, cx), } }); }) @@ -247,7 +247,7 @@ impl AppView { /// supplies the branded row inside it. /// Updates: this version, and the release notes as a timeline (version and /// date on the left, changes grouped under New / Improved / Fixed on the - /// right). One virtualized list, so only the rows on screen are built — the + /// right). One virtualized list, so only the rows on screen are built - the /// page used to rebuild every release on each scroll tick and pinned a core. pub(super) fn render_updates(&self, cx: &mut Context) -> AnyElement { let colors = PageColors { diff --git a/gpui/src/audio.rs b/gpui/src/audio.rs index fecef0da..e2fb30b9 100644 --- a/gpui/src/audio.rs +++ b/gpui/src/audio.rs @@ -29,7 +29,7 @@ fn note(buffer: &mut [f32], start_s: f32, freq: f32, decay_s: f32) { let t = (i - first) as f32 / SAMPLE_RATE as f32; let attack = (t / 0.004).min(1.0); let envelope = attack * (-t / decay_s).exp(); - // Stop once the note has died away — but not during the attack, where the + // Stop once the note has died away - but not during the attack, where the // envelope starts at zero. if t > 0.004 && envelope < 0.0005 { break; @@ -106,7 +106,7 @@ fn cached(chime: Chime) -> &'static [u8] { } /// Plays the chime without waiting for it to finish. Returns whether the system -/// took it; a failure is never worth surfacing — it's feedback, not function. +/// took it; a failure is never worth surfacing - it's feedback, not function. #[track_caller] pub fn play(chime: Chime) -> bool { // So "what was that sound?" can be answered from the log. diff --git a/gpui/src/bin/main.rs b/gpui/src/bin/main.rs index 6aff369d..c7b8babe 100644 --- a/gpui/src/bin/main.rs +++ b/gpui/src/bin/main.rs @@ -200,7 +200,7 @@ fn open_main_window( #[cfg(not(target_os = "linux"))] let _ = activation_token; - // Tauri parity: `decorations: false` — hide the native macOS bar so + // Tauri parity: `decorations: false` - hide the native macOS bar so // Kit's custom `TitleBar` owns the top strip (drag, double-click // zoom, traffic lights), instead of rendering underneath it. // Three quarters of the screen in each direction, centered on it. diff --git a/gpui/src/games.rs b/gpui/src/games.rs index a2177a3b..cbd31624 100644 --- a/gpui/src/games.rs +++ b/gpui/src/games.rs @@ -54,7 +54,7 @@ impl Game { } /// `steamAppId` is inconsistently typed in the catalog (number for some -/// titles, string for others) — accept both. +/// titles, string for others) - accept both. fn de_steam_id<'de, D>(d: D) -> Result, D::Error> where D: serde::Deserializer<'de>, @@ -100,7 +100,7 @@ fn art_cache_path(dir: &std::path::Path, game: &Game) -> std::path::PathBuf { /// Longest edge of the card-sized copy handed to `img()`. /// /// Cards are 148×200 logical (267×400 device pixels at 1.5× scale). The -/// originals are 460×215–1440×2160, so decoding them costs 0.4–12.4 MB of RGBA +/// originals are 460×215-1440×2160, so decoding them costs 0.4-12.4 MB of RGBA /// each, and GPUI's asset store retains every decoded image until the process /// exits. Resampling once to 400 px keeps a full page of 15 cards at ~6 MB /// instead of ~58 MB. @@ -164,7 +164,7 @@ static CARD_ART_CACHE: std::sync::LazyLock< /// Art file cards should load: only the card-sized copy. /// /// Falling back to the original would decode a 12 MB cover the moment a card -/// paints, before prefetch has finished shrinking it — the exact spike this +/// paints, before prefetch has finished shrinking it - the exact spike this /// cache exists to avoid. Until the copy lands the card shows its letter tile, /// then repaints when prefetch notifies. pub fn card_art_path(game: &Game) -> Option { diff --git a/gpui/src/hid.rs b/gpui/src/hid.rs index c254a740..490135b4 100644 --- a/gpui/src/hid.rs +++ b/gpui/src/hid.rs @@ -3,7 +3,7 @@ //! The mouse protocols live in `@openmouse/protocol` (TypeScript, shared with //! the web app), so they are not ported: `js/build.mjs` bundles that package //! plus the Tauri app's own `src/native-hid/{scan,brands,tauri-hid-device}.ts` -//! — unmodified — and this module runs the bundle in an embedded QuickJS +//! - unmodified - and this module runs the bundle in an embedded QuickJS //! runtime. The only things the bundle needs from the host are what the Tauri //! app gets from its webview: the `hid_*` commands (served here by the shared //! `openmouse-hid` crate, the same transport the Tauri app uses) and the @@ -238,7 +238,7 @@ impl DeviceArt { } /// Validates a downloaded image by sniffing its file header rather than its -/// extension — temp files end in `.part`, which `image::image_dimensions` +/// extension - temp files end in `.part`, which `image::image_dimensions` /// rejects as an unsupported extension. fn is_valid_image(path: &std::path::Path) -> bool { image::ImageReader::open(path) @@ -299,7 +299,7 @@ pub struct CommandSection { } /// One reading of the two primary buttons' travel, as a share of full travel -/// (0–100), `age_ms` before it was collected. +/// (0-100), `age_ms` before it was collected. #[derive(Debug, Clone, Copy, Deserialize)] pub struct DepthSample { #[serde(rename = "ageMs")] @@ -419,12 +419,21 @@ pub struct Tabs { /// A configurable receiver's own settings. #[serde(default)] pub receiver: Vec
, + #[serde(rename = "keyboardLighting", default)] + pub keyboard_lighting: Vec
, /// The macro editor, where the mouse has one. #[serde(default)] pub macros: Option, /// Magnetic primary buttons, drawn as one panel. #[serde(default)] pub magnetic: Option, + #[serde(rename = "hitsTravel", default)] + pub hits_travel: Option, +} + +#[derive(Debug, Clone, Default, Deserialize)] +pub struct HitsTravel { + pub triggers: Vec>, } /// A slot or button a macro can go to. @@ -486,7 +495,7 @@ pub struct MagneticPanel { impl Tabs { /// Every control on every tab. pub fn controls(&self) -> impl Iterator { - [&self.performance, &self.buttons, &self.advanced, &self.receiver] + [&self.performance, &self.buttons, &self.advanced, &self.receiver, &self.keyboard_lighting] .into_iter() .flatten() .flat_map(|section| §ion.controls) @@ -499,6 +508,7 @@ impl Tabs { .chain(self.buttons.iter_mut()) .chain(self.advanced.iter_mut()) .chain(self.receiver.iter_mut()) + .chain(self.keyboard_lighting.iter_mut()) .flat_map(|section| &mut section.controls) } } @@ -592,7 +602,7 @@ impl HidService { drop(self.call("stopButtonDepth", None, |_| Ok(()))); } - /// The Logitech mouse's stored (onboard) profiles. Read on demand — a full + /// The Logitech mouse's stored (onboard) profiles. Read on demand - a full /// pass is dozens of round trips. pub fn onboard_profiles(&self, key: &str) -> oneshot::Receiver> { let args = serde_json::json!({ "key": key }); @@ -942,7 +952,7 @@ fn driver_storage_path() -> Option { } /// The Tauri `hid_*` command surface, by name, with Tauri's camelCase -/// argument keys — what `src/native-hid/tauri-hid-device.ts` sends. +/// argument keys - what `src/native-hid/tauri-hid-device.ts` sends. fn dispatch( api: &core::HidApiHandle, registry: &core::HidRegistry, @@ -1022,10 +1032,47 @@ fn dispatch( registry, v, p, num("reportId")? as u8, num("length")? as usize, )?) } + "via_definition" => { + let (v, p) = ids()?; + json(&via_definition(v, p)?) + } other => Err(format!("unknown command `{other}`")), } } +fn via_definition(vendor_id: u16, product_id: u16) -> Result, String> { + let id = vendor_id as u32 * 65536 + product_id as u32; + let cache = dirs::cache_dir().map(|d| d.join("openmouse").join("via-definitions").join(format!("{id}.json"))); + let mut reached = false; + for version in ["v3", "v2"] { + let output = crate::proc::quiet( + std::process::Command::new("curl") + .args(["-sSL", "--fail", "-m", "8"]) + .arg(format!("https://usevia.app/definitions/{version}/{id}.json")) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()), + ) + .output(); + let Ok(output) = output.map_err(|_| ()).and_then(|o| if o.status.success() { Ok(o) } else { Err(()) }) else { + continue; + }; + reached = true; + let text = String::from_utf8_lossy(&output.stdout).into_owned(); + if text.trim_start().starts_with('{') { + if let Some(cache) = &cache { + let _ = cache.parent().map(std::fs::create_dir_all); + let _ = std::fs::write(cache, &text); + } + return Ok(Some(text)); + } + } + match cache.and_then(|c| std::fs::read_to_string(c).ok()) { + Some(text) => Ok(Some(text)), + None if reached => Ok(None), + None => Err("Couldn't download this keyboard's layout from usevia.app.".to_string()), + } +} + mod erased { pub trait Ser { fn to_json(&self) -> Result; diff --git a/gpui/src/marketplace.rs b/gpui/src/marketplace.rs index 02dde20f..6ad68469 100644 --- a/gpui/src/marketplace.rs +++ b/gpui/src/marketplace.rs @@ -27,7 +27,7 @@ //! } //! ``` //! -//! Pure data tokens only — no arbitrary selectors or executable code. +//! Pure data tokens only - no arbitrary selectors or executable code. use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -747,7 +747,7 @@ pub fn submit_theme(installed: &InstalledTheme, session_token: &str) -> Result Option<&GameProfile> { self.get(game_id, device).or_else(|| if inherits_legacy { self.legacy(game_id) } else { None }) diff --git a/gpui/src/settings.rs b/gpui/src/settings.rs index 76ef866b..987949ee 100644 --- a/gpui/src/settings.rs +++ b/gpui/src/settings.rs @@ -4,7 +4,7 @@ //! //! Native home: `/openmouse/settings.json` (e.g. //! `~/Library/Application Support/openmouse/settings.json` on macOS). -//! Load is best-effort — corrupt/missing files yield defaults, never an error +//! Load is best-effort - corrupt/missing files yield defaults, never an error //! surface. Saves are synchronous small-file writes on explicit user action //! (release/apply), matching the Tauri `save*` call sites. @@ -138,6 +138,8 @@ struct StoredSettings { /// Visual style of the tray battery icon. #[serde(default = "default_tray_battery_theme")] tray_battery_theme: String, + #[serde(default)] + tray_pinned: bool, /// Show an on-screen warning when a wireless mouse drops below the threshold. #[serde(default = "default_true")] low_battery_alert: bool, @@ -209,6 +211,7 @@ impl Default for StoredSettings { obs_theme: default_obs_theme(), tray_battery_enabled: true, tray_battery_theme: default_tray_battery_theme(), + tray_pinned: false, low_battery_alert: true, low_battery_threshold: default_low_battery_threshold(), auto_check_updates: true, @@ -258,6 +261,7 @@ pub struct Settings { pub obs_theme: String, pub tray_battery_enabled: bool, pub tray_battery_theme: TrayBatteryTheme, + pub tray_pinned: bool, pub low_battery_alert: bool, pub low_battery_threshold: u8, pub auto_check_updates: bool, @@ -332,6 +336,7 @@ impl Settings { obs_theme: stored.obs_theme, tray_battery_enabled: stored.tray_battery_enabled, tray_battery_theme: TrayBatteryTheme::parse(&stored.tray_battery_theme), + tray_pinned: stored.tray_pinned, low_battery_alert: stored.low_battery_alert, low_battery_threshold: stored.low_battery_threshold.clamp(5, 50), auto_check_updates: stored.auto_check_updates, @@ -378,6 +383,7 @@ impl Settings { obs_theme: self.obs_theme.clone(), tray_battery_enabled: self.tray_battery_enabled, tray_battery_theme: self.tray_battery_theme.as_str().to_string(), + tray_pinned: self.tray_pinned, low_battery_alert: self.low_battery_alert, low_battery_threshold: self.low_battery_threshold, auto_check_updates: self.auto_check_updates, diff --git a/gpui/src/theme.rs b/gpui/src/theme.rs index 00e0edd0..bb452ed7 100644 --- a/gpui/src/theme.rs +++ b/gpui/src/theme.rs @@ -9,7 +9,7 @@ //! like Android's Material You (`wallpaper.rs` + `accentCssFromHex`). //! //! Colors are painted onto the live [`Theme`] via [`Theme::update`](gpui_kit::component::Theme::update), -//! which reconciles tokens and refreshes every window — so the vibrancy +//! which reconciles tokens and refreshes every window - so the vibrancy //! slider can call [`apply_choice`] per-tick with no JSON regen (mirrors //! `applyDynamicVibrancy`'s no-transition live preview). @@ -70,7 +70,7 @@ fn hsla(h: f32, s: f32, l: f32) -> Hsla { /// /// macOS reads the path via System Events, Windows via the registry; other /// platforms return an error and Dynamic falls back to green (same contract -/// as the Tauri command). Blocking call — run on a background executor, not +/// as the Tauri command). Blocking call - run on a background executor, not /// in render. /// Opens an image by extension, else by sniffing its bytes: Windows keeps a /// slideshow's current frame as `TranscodedWallpaper`, JPEG data with no extension. @@ -134,7 +134,7 @@ pub fn sample_wallpaper_accent() -> anyhow::Result<(u8, u8, u8)> { /// Run `osascript` with a timeout. A backgrounded process (nohup'd dev /// builds, launchd without the right session) can stall AppleEvents to -/// System Events FOREVER — hanging the main thread at startup with no window +/// System Events FOREVER - hanging the main thread at startup with no window /// and no log. Never let a wallpaper read block longer than this. #[cfg(target_os = "macos")] const OSASCRIPT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); @@ -251,7 +251,7 @@ pub fn wallpaper_signature() -> anyhow::Result { } /// Cached Dynamic sample: last-seen wallpaper signature + its accent hex. -/// Mirrors `DYNAMIC_SIGNATURE_KEY`/`DYNAMIC_HEX_KEY` in `themes.ts` — the web +/// Mirrors `DYNAMIC_SIGNATURE_KEY`/`DYNAMIC_HEX_KEY` in `themes.ts` - the web /// app skips the expensive resample when the cheap signature is unchanged, /// and so do we: switching back to Dynamic with the same wallpaper repaints /// instantly from cache instead of respawning osascript + decoding. @@ -308,7 +308,7 @@ fn mark_dynamic_signature(signature: Option) { /// theme and the window is active, slower otherwise, resampling + repainting /// only when the signature moves. The blocking osascript spawn + image decode /// run on the background executor (mirrors `spawn_blocking`); the UI thread -/// only pays for the repaint. Detached task — it ends when its view is dropped. +/// only pays for the repaint. Detached task - it ends when its view is dropped. pub fn spawn_wallpaper_watcher( cx: &mut App, view: &gpui_kit::Entity, @@ -483,7 +483,7 @@ fn dark_ramp(hue: f32, vibrancy: f32) -> (Hsla, Hsla, Hsla, Hsla, Hsla) { /// the Matt/Dynamic palette onto the public color fields. /// /// `wallpaper_hex` is the sampled dominant color for Dynamic; `None` uses -/// the fallback green. `vibrancy` is 0–200, 100 = as designed. `picked` is +/// the fallback green. `vibrancy` is 0-200, 100 = as designed. `picked` is /// the user's accent override: it wins over every theme's own accent. pub fn apply_choice( choice: ThemeChoice, @@ -497,7 +497,7 @@ pub fn apply_choice( if choice == ThemeChoice::System { // Resolve the OS appearance, then paint the Matt palette for it. // `sync_system_appearance` alone only flips the mode (Kit default - // colors) and leaves whatever the previous choice painted — a stale + // colors) and leaves whatever the previous choice painted - a stale // Dynamic tint surviving into System. Theme::sync_system_appearance(window, cx); if cx.theme().mode.is_dark() { @@ -579,7 +579,7 @@ pub fn set_surface_opacity(opacity: f32, cx: &mut App) { } /// The accent and the ink that sits on it, at this vibrancy. Ink is dark on -/// light accents and near-white on dark ones — same luminance rule as +/// light accents and near-white on dark ones - same luminance rule as /// `accentCssFromHex`. fn accent_and_ink(accent_hsl: (f32, f32, f32), vibrancy: f32) -> (Hsla, Hsla) { let (hue, sat, light) = accent_hsl; @@ -627,7 +627,7 @@ fn readable_ink(accent: Hsla) -> Hsla { } /// The accent a palette paints: the user's picked color when there is one -/// (verbatim — a picked color must not be re-saturated by the vibrancy +/// (verbatim - a picked color must not be re-saturated by the vibrancy /// slider), otherwise the theme's own accent at the current vibrancy. fn resolved_accent( default_hsl: (f32, f32, f32), @@ -643,7 +643,7 @@ fn resolved_accent( } } -/// Matt palette: exact `App.css` tokens — near-neutral surfaces, ONLY the +/// Matt palette: exact `App.css` tokens - near-neutral surfaces, ONLY the /// accent carrying hue. `is_light` selects the flipped light shell. fn paint_matt( is_light: bool, @@ -689,7 +689,7 @@ fn oled_shell() -> (Hsla, Hsla, Hsla, Hsla, Hsla, Hsla) { ( rgb_to_hsla((0, 0, 0)), // background: true black rgb_to_hsla((0, 0, 0)), // sidebar - rgb_to_hsla((32, 32, 34)), // border — the only separation on black + rgb_to_hsla((32, 32, 34)), // border - the only separation on black rgb_to_hsla((24, 24, 26)), // muted fill (badges, hover chips) rgb_to_hsla((150, 150, 156)), // muted foreground rgb_to_hsla((242, 242, 242)), // text @@ -805,7 +805,7 @@ fn paint_dynamic( p.accent_ink = readable_ink(p.accent); } // Every surface carries the wallpaper hue (mirrors the Tauri Dynamic - // ramp, where ink/sidebar/card all hold the accent hue) — pinning `bg` + // ramp, where ink/sidebar/card all hold the accent hue) - pinning `bg` // to neutral is what left the content area flat black next to a tinted // sidebar. paint_shared( @@ -854,7 +854,7 @@ fn paint_shared( }); } -/// Crossfade length for a theme switch — the same 380ms the web app puts on +/// Crossfade length for a theme switch - the same 380ms the web app puts on /// its theme tokens (`App.css`), so a native switch reads like the web one. pub const THEME_FADE_MS: u64 = 380; @@ -1036,7 +1036,7 @@ fn lerp_colors(from: ThemeColor, to: ThemeColor, t: f32) -> ThemeColor { /// which keeps mode switches, font resolution, and token reconciliation on the /// existing path. /// -/// Skipped when the palettes already match or the OS asks for reduced motion — +/// Skipped when the palettes already match or the OS asks for reduced motion - /// in both cases the caller's instant switch is the whole story. pub fn crossfade_colors(from: ThemeColor, to: ThemeColor, cx: &mut App) { let seq = THEME_FADE_SEQ.fetch_add(1, Ordering::Relaxed) + 1; @@ -1222,7 +1222,7 @@ mod tests { } /// A palette fade must land exactly on both ends and cross the hue wheel - /// the short way — a long-way lerp reads as a flash of unrelated color + /// the short way - a long-way lerp reads as a flash of unrelated color /// halfway through the switch. #[test] fn theme_crossfade_hits_both_ends_and_takes_the_short_hue_way() { diff --git a/gpui/src/tray.rs b/gpui/src/tray.rs index e3634a20..122d2e26 100644 --- a/gpui/src/tray.rs +++ b/gpui/src/tray.rs @@ -72,8 +72,8 @@ pub struct BatteryStatus { pub(crate) fn format_tooltip(status: Option<&BatteryStatus>) -> String { match status { - Some(b) if b.charging => format!("{} — {}% (Charging)", b.name, b.percent), - Some(b) => format!("{} — {}%", b.name, b.percent), + Some(b) if b.charging => format!("{} - {}% (Charging)", b.name, b.percent), + Some(b) => format!("{} - {}%", b.name, b.percent), None => "OpenMouse Desktop".to_string(), } } @@ -101,6 +101,61 @@ pub(crate) fn render_battery_rgba( } } +#[cfg(windows)] +static PIN_REQUEST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +#[cfg(windows)] +pub fn pin(on: bool) { + use std::sync::atomic::Ordering; + let request = PIN_REQUEST.fetch_add(1, Ordering::SeqCst) + 1; + std::thread::spawn(move || { + for _ in 0..15 { + if PIN_REQUEST.load(Ordering::SeqCst) != request || set_promoted(on) { + return; + } + std::thread::sleep(std::time::Duration::from_secs(2)); + } + }); +} + +#[cfg(not(windows))] +pub fn pin(_: bool) {} + +#[cfg(windows)] +fn set_promoted(on: bool) -> bool { + use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE}; + use winreg::RegKey; + let Ok(exe) = std::env::current_exe() else { return false }; + let exe = exe.to_string_lossy().into_owned(); + let Ok(root) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(r"Control Panel\NotifyIconSettings") else { + return false; + }; + let mut found = false; + for name in root.enum_keys().flatten() { + let Ok(key) = root.open_subkey_with_flags(&name, KEY_READ | KEY_WRITE) else { continue }; + let path: String = key.get_value("ExecutablePath").unwrap_or_default(); + if same_exe(&path, &exe) && key.set_value("IsPromoted", &u32::from(on)).is_ok() { + found = true; + } + } + found +} + +fn same_exe(entry: &str, exe: &str) -> bool { + let (entry, exe) = (entry.to_lowercase(), exe.to_lowercase()); + let resolved = entry.strip_prefix('{').and_then(|rest| rest.split_once('}')).and_then(|(guid, tail)| { + let var = match guid { + "6d809377-6af0-444b-8957-a3773f02200e" => "ProgramW6432", + "7c5a40ef-a0fb-4bfc-874a-c0f2e0b9fa8e" => "ProgramFiles(x86)", + "905e63b6-c1bf-494e-b29c-65b732d3d21a" => "ProgramFiles", + "f1b32785-6fba-4fcf-9d55-7b8e7f157091" => "LOCALAPPDATA", + _ => return None, + }; + std::env::var(var).ok().map(|root| format!("{}{tail}", root.to_lowercase())) + }); + entry == exe || resolved.is_some_and(|path| path == exe) +} + fn level_color(percent: u8, charging: bool) -> [u8; 4] { if charging { [52, 211, 153, 255] // emerald @@ -871,14 +926,25 @@ mod tests { theme: TrayBatteryTheme::Classic, alert_threshold: 15, }; - assert_eq!(format_tooltip(Some(&status)), "Superlight 2 — 84%"); + assert_eq!(format_tooltip(Some(&status)), "Superlight 2 - 84%"); assert_eq!(format_menu_status(Some(&status)), "Superlight 2 · 84%"); let charging = BatteryStatus { charging: true, ..status }; - assert_eq!(format_tooltip(Some(&charging)), "Superlight 2 — 84% (Charging)"); + assert_eq!(format_tooltip(Some(&charging)), "Superlight 2 - 84% (Charging)"); assert_eq!(format_menu_status(Some(&charging)), "Superlight 2 · 84% (Charging)"); } + #[test] + fn a_tray_entry_matches_its_exe_directly_or_through_a_known_folder() { + let Ok(root) = std::env::var("ProgramW6432") else { return }; + let exe = &format!(r"{root}\OpenMouse Desktop\OpenMouse Desktop.exe"); + assert!(same_exe(&format!(r"{}\openmouse desktop\OpenMouse Desktop.exe", root.to_lowercase()), exe)); + assert!(same_exe(r"{6D809377-6AF0-444B-8957-A3773F02200E}\OpenMouse Desktop\OpenMouse Desktop.exe", exe)); + assert!(!same_exe(r"C:\Other\OpenMouse Desktop.exe", exe)); + assert!(!same_exe(r"{6D809377-6AF0-444B-8957-A3773F02200E}", exe)); + assert!(!same_exe(r"{6D809377-6AF0-444B-8957-A3773F02200E}\OpenMouse Desktop\OpenMouse Desktop.exe", r"D:\Portable\OpenMouse Desktop\OpenMouse Desktop.exe")); + } + #[test] fn battery_icon_renders_valid_32x32_rgba_for_all_themes_and_ranges() { let px_at = |rgba: &[u8], x: usize, y: usize| -> [u8; 4] { diff --git a/gpui/src/update_check.rs b/gpui/src/update_check.rs index 2fd78c20..cb116b24 100644 --- a/gpui/src/update_check.rs +++ b/gpui/src/update_check.rs @@ -19,7 +19,7 @@ use crate::app::AppView; const LATEST_JSON_URL: &str = "https://github.com/OpenMouse-Project/Desktop/releases/latest/download/latest.json"; -/// Background cadence. There's no rush — a flaky network shouldn't nag, and +/// Background cadence. There's no rush - a flaky network shouldn't nag, and /// the startup check plus the manual "Check for updates" button cover the /// cases where someone actually wants a fresh answer right now. const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60); @@ -84,7 +84,7 @@ fn latest_json_url() -> String { .unwrap_or_else(|| LATEST_JSON_URL.to_string()) } -/// Fetches `latest.json` via the system `curl` — the same dependency-free +/// Fetches `latest.json` via the system `curl` - the same dependency-free /// convention `games::prefetch_art` uses for network access, rather than /// pulling in an HTTP client crate for one small GET. Blocking; callers must /// run this off the UI thread. @@ -464,7 +464,7 @@ pub fn verify_file_sha256(path: &Path, expected_hex: &str) -> Result<(), String> } let actual = sha256_file(path).map_err(|e| format!("Could not read downloaded file: {e}"))?; if actual != expected { - return Err("Checksum mismatch — the downloaded installer may be corrupted.".to_string()); + return Err("Checksum mismatch - the downloaded installer may be corrupted.".to_string()); } Ok(()) } @@ -585,7 +585,7 @@ impl Sha256 { /// True when `latest` is a newer version than `current`. Both are bare /// `x.y.z` strings (no prerelease tag, see `APP_VERSION`'s usage in /// `app.rs`); a missing/non-numeric component compares as `0`, so a -/// malformed string never panics — it just sorts low. +/// malformed string never panics - it just sorts low. pub fn is_newer(current: &str, latest: &str) -> bool { fn parts(v: &str) -> Vec { v.split('.').map(|p| p.parse().unwrap_or(0)).collect() @@ -596,7 +596,7 @@ pub fn is_newer(current: &str, latest: &str) -> bool { /// Startup check plus a 6-hour background poll, mirroring /// `theme::spawn_wallpaper_watcher`'s shape: the fetch runs on the /// background executor, the result lands on `AppView` via the foreground -/// executor. Respects the `auto_check_updates` setting. Detached — ends on its +/// executor. Respects the `auto_check_updates` setting. Detached - ends on its /// own once the view is dropped. pub fn spawn_update_watcher(cx: &mut App, view: &Entity) { let view = view.downgrade(); diff --git a/gpui/src/usb_topology.rs b/gpui/src/usb_topology.rs index 905f37ad..bcff6f9a 100644 --- a/gpui/src/usb_topology.rs +++ b/gpui/src/usb_topology.rs @@ -1,4 +1,4 @@ -//! USB & PCIe topology scanner — builds a logical routing map of USB host +//! USB & PCIe topology scanner - builds a logical routing map of USB host //! controllers, hubs, ports, and connected devices, and classifies each host //! controller's routing (CPU-direct vs. Chipset vs. discrete add-in). @@ -2215,7 +2215,7 @@ mod win { let mut mi00_is_kbd = false; let mut better_child_name: Option = None; - // Do not recurse into a USB hub's children — those are downstream + // Do not recurse into a USB hub's children - those are downstream // devices plugged into the hub, not interfaces of the hub itself. if !is_hub { walk_children(devinst, 0, &mut |child| { diff --git a/gpui/src/write_safety.rs b/gpui/src/write_safety.rs index c8723cde..f14959b3 100644 --- a/gpui/src/write_safety.rs +++ b/gpui/src/write_safety.rs @@ -71,6 +71,13 @@ pub fn warning(id: &str, label: &str, current: &Value, value: &Value) -> Option< proceed: "Reset", }); } + if id == "x.lg.host" && value != current { + return Some(Warning { + title: "Switch to another computer?", + detail: "The mouse leaves this computer straight away. Press the button underneath it to bring it back.", + proceed: "Switch", + }); + } if id == "omni.pair" { return (value.as_i64() == Some(1)).then_some(Warning { title: "Start pairing?", diff --git a/gpui/tests/fixtures/generic.json b/gpui/tests/fixtures/generic.json index b60af8b2..0e2ef46d 100644 --- a/gpui/tests/fixtures/generic.json +++ b/gpui/tests/fixtures/generic.json @@ -1 +1 @@ -{"ajazz":{"buttons":[{"title":"Buttons","controls":[{"id":"gen.button/Left button","label":"Left button","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Back","label":"Back"},{"value":"Forward","label":"Forward"},{"value":"Disable","label":"Disable"}],"current":"Left Click"},{"id":"gen.button/Right button","label":"Right button","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Back","label":"Back"},{"value":"Forward","label":"Forward"},{"value":"Disable","label":"Disable"}],"current":"Right Click"},{"id":"gen.button/Side 1","label":"Side 1","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Back","label":"Back"},{"value":"Forward","label":"Forward"},{"value":"Disable","label":"Disable"}],"current":"Back"},{"id":"gen.fixed/Macro slot","label":"Macro slot","description":"Set up with a macro or custom binding — not editable here.","kind":"info","current":"Macro 3"}]}],"advanced":[],"performance":[],"lighting":null},"dareu":{"buttons":[],"advanced":[{"title":"Profiles","controls":[{"id":"gen.profile","label":"Active profile","description":"Switches the mouse's stored profile.","kind":"choice","options":[{"value":1,"label":"FPS"},{"value":2,"label":"Profile 2"},{"value":3,"label":"Work"},{"value":4,"label":"Profile 4"},{"value":5,"label":"Profile 5"}],"current":2}]}],"performance":[],"lighting":null},"pulsar":{"buttons":[],"advanced":[{"title":"Scroll wheel","controls":[{"id":"pulsar.wheel","label":"Wheel acceleration","kind":"toggle","current":true}]},{"title":"Pulsar Pro","controls":[{"id":"pulsar.profile","label":"Active profile","kind":"choice","options":[{"value":1,"label":"1"},{"value":2,"label":"2"},{"value":3,"label":"3"},{"value":4,"label":"4"},{"value":5,"label":"5"},{"value":6,"label":"6"}],"current":3}]}],"performance":[],"lighting":null},"logitech":{"buttons":[],"advanced":[],"performance":[],"lighting":null},"mchose":{"buttons":[],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"gen.powerMode","label":"Power mode","description":"Trades battery life against performance.","kind":"choice","options":[{"value":"Low","label":"Low"},{"value":"Balanced","label":"Balanced"},{"value":"High","label":"High"}],"current":"Balanced"}]}],"lighting":null},"noOptions":{"buttons":[],"advanced":[],"performance":[],"lighting":null}} +{"ajazz":{"buttons":[{"title":"Buttons","controls":[{"id":"gen.button/Left button","label":"Left button","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Back","label":"Back"},{"value":"Forward","label":"Forward"},{"value":"Disable","label":"Disable"}],"current":"Left Click"},{"id":"gen.button/Right button","label":"Right button","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Back","label":"Back"},{"value":"Forward","label":"Forward"},{"value":"Disable","label":"Disable"}],"current":"Right Click"},{"id":"gen.button/Side 1","label":"Side 1","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Back","label":"Back"},{"value":"Forward","label":"Forward"},{"value":"Disable","label":"Disable"}],"current":"Back"},{"id":"gen.fixed/Macro slot","label":"Macro slot","description":"Set up with a macro or custom binding - not editable here.","kind":"info","current":"Macro 3"}]}],"advanced":[],"performance":[],"lighting":null},"dareu":{"buttons":[],"advanced":[{"title":"Profiles","controls":[{"id":"gen.profile","label":"Active profile","description":"Switches the mouse's stored profile.","kind":"choice","options":[{"value":1,"label":"FPS"},{"value":2,"label":"Profile 2"},{"value":3,"label":"Work"},{"value":4,"label":"Profile 4"},{"value":5,"label":"Profile 5"}],"current":2}]}],"performance":[],"lighting":null},"pulsar":{"buttons":[],"advanced":[{"title":"Scroll wheel","controls":[{"id":"pulsar.wheel","label":"Wheel acceleration","kind":"toggle","current":true}]},{"title":"Pulsar Pro","controls":[{"id":"pulsar.profile","label":"Active profile","kind":"choice","options":[{"value":1,"label":"1"},{"value":2,"label":"2"},{"value":3,"label":"3"},{"value":4,"label":"4"},{"value":5,"label":"5"},{"value":6,"label":"6"}],"current":3}]}],"performance":[],"lighting":null},"logitech":{"buttons":[],"advanced":[],"performance":[],"lighting":null},"mchose":{"buttons":[],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"gen.powerMode","label":"Power mode","description":"Trades battery life against performance.","kind":"choice","options":[{"value":"Low","label":"Low"},{"value":"Balanced","label":"Balanced"},{"value":"High","label":"High"}],"current":"Balanced"}]}],"lighting":null},"noOptions":{"buttons":[],"advanced":[],"performance":[],"lighting":null}} diff --git a/gpui/tests/fixtures/performance.json b/gpui/tests/fixtures/performance.json index 9cc8e303..5ecbd46b 100644 --- a/gpui/tests/fixtures/performance.json +++ b/gpui/tests/fixtures/performance.json @@ -1 +1 @@ -{"razer":{"buttons":[{"title":"Razer — Buttons","controls":[{"id":"razer.button.rightClick","label":"Right Click","description":"Choose what this button sends.","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Mouse Button 4","label":"Mouse Button 4"},{"value":"Mouse Button 5","label":"Mouse Button 5"},{"value":"Disabled","label":"Disabled"}],"current":null},{"id":"razer.button.mouse4","label":"Mouse Button 4","description":"Choose what this button sends.","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Mouse Button 4","label":"Mouse Button 4"},{"value":"Mouse Button 5","label":"Mouse Button 5"},{"value":"Disabled","label":"Disabled"}],"current":null},{"id":"razer.button.mouse5","label":"Mouse Button 5","description":"Choose what this button sends.","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Mouse Button 4","label":"Mouse Button 4"},{"value":"Mouse Button 5","label":"Mouse Button 5"},{"value":"Disabled","label":"Disabled"}],"current":null}]},{"title":"Razer — Scroll & toggles","controls":[{"id":"razer.toggle.scrollUp","label":"Scroll Up","description":"Scroll Up","kind":"info","current":"Disabled"},{"id":"razer.toggle.scrollDown","label":"Scroll Down","description":"Scroll Down","kind":"info","current":"Disabled"},{"id":"razer.toggle.sensitivityButton","label":"Sensitivity Button","description":"Cycle Up Sensitivity Stages","kind":"info","current":"Disabled"}]}],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"perf.sleep","label":"Sleep timeout","description":"How long the mouse stays awake when idle before sleeping.","kind":"choice","options":[{"value":60,"label":"1 min"},{"value":120,"label":"2 min"},{"value":180,"label":"3 min"},{"value":300,"label":"5 min"},{"value":600,"label":"10 min"},{"value":900,"label":"15 min"}],"current":300},{"id":"perf.motionSync","label":"Motion sync","description":"Synchronizes X/Y sensor sampling for smoother diagonals.","kind":"toggle","current":true},{"id":"perf.angleSnapping","label":"Angle snapping","description":"Rounds movement to straight lines and diagonals for a steadier cursor.","kind":"toggle","current":false},{"id":"perf.rippleControl","label":"Ripple control","description":"Filters sensor ripple at high polling rates for more stable tracking.","kind":"toggle","current":false},{"id":"perf.lowPower","label":"Low power mode","description":"Slows the mouse down to save battery below this level.","kind":"choice","options":[{"value":5,"label":"5%"},{"value":10,"label":"10%"},{"value":12,"label":"12%"},{"value":15,"label":"15%"},{"value":20,"label":"20%"},{"value":25,"label":"25%"},{"value":30,"label":"30%"}],"current":12}]}],"lighting":null},"atk":{"buttons":[],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"perf.motionSync","label":"Motion sync","description":"Synchronizes X/Y sensor sampling for smoother diagonals.","kind":"toggle","current":false},{"id":"perf.performanceMode","label":"Performance / hyper mode","description":"Runs the sensor at its full performance setting.","kind":"toggle","current":true},{"id":"perf.dpiStage","label":"DPI stages","description":"On-device sensitivity stages; pick the active one.","kind":"choice","options":[{"value":0,"label":"Stage 1"},{"value":1,"label":"Stage 2"},{"value":2,"label":"Stage 3"}],"current":1},{"id":"perf.debounce","label":"Debounce","description":"Filters out physical switch bounce (0–8 ms). Higher is steadier, slightly more click lag.","kind":"choice","options":[{"value":0,"label":"0 ms"},{"value":1,"label":"1 ms"},{"value":2,"label":"2 ms"},{"value":3,"label":"3 ms"},{"value":4,"label":"4 ms"},{"value":5,"label":"5 ms"},{"value":6,"label":"6 ms"},{"value":7,"label":"7 ms"},{"value":8,"label":"8 ms"}],"current":4}]}],"lighting":null},"zaun":{"buttons":[],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"perf.usbSpeed","label":"USB speed","description":"Full pins polling to 1000 Hz; High enables faster rates.","kind":"choice","options":[{"value":"Full","label":"Full"},{"value":"High","label":"High"}],"current":"High"},{"id":"perf.primaryButton","label":"Primary button","description":"Which button acts as the primary click.","kind":"choice","options":[{"value":"Left","label":"Left"},{"value":"Right","label":"Right"}],"current":"Left"}]}],"lighting":null},"hidden":{"buttons":[],"advanced":[],"performance":[],"lighting":null},"noDebounce":{"buttons":[],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"perf.debounce","label":"Debounce","description":"Filters out physical switch bounce (0–0 ms). Higher is steadier, slightly more click lag.","kind":"choice","options":[{"value":0,"label":"0 ms"}],"current":0}]}],"lighting":null},"superlight":{"buttons":[],"advanced":[],"performance":[],"lighting":null}} +{"razer":{"buttons":[{"title":"Razer - Buttons","controls":[{"id":"razer.button.rightClick","label":"Right Click","description":"Choose what this button sends.","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Mouse Button 4","label":"Mouse Button 4"},{"value":"Mouse Button 5","label":"Mouse Button 5"},{"value":"Disabled","label":"Disabled"}],"current":null},{"id":"razer.button.mouse4","label":"Mouse Button 4","description":"Choose what this button sends.","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Mouse Button 4","label":"Mouse Button 4"},{"value":"Mouse Button 5","label":"Mouse Button 5"},{"value":"Disabled","label":"Disabled"}],"current":null},{"id":"razer.button.mouse5","label":"Mouse Button 5","description":"Choose what this button sends.","kind":"choice","options":[{"value":"Left Click","label":"Left Click"},{"value":"Right Click","label":"Right Click"},{"value":"Mouse Button 4","label":"Mouse Button 4"},{"value":"Mouse Button 5","label":"Mouse Button 5"},{"value":"Disabled","label":"Disabled"}],"current":null}]},{"title":"Razer - Scroll & toggles","controls":[{"id":"razer.toggle.scrollUp","label":"Scroll Up","description":"Scroll Up","kind":"info","current":"Disabled"},{"id":"razer.toggle.scrollDown","label":"Scroll Down","description":"Scroll Down","kind":"info","current":"Disabled"},{"id":"razer.toggle.sensitivityButton","label":"Sensitivity Button","description":"Cycle Up Sensitivity Stages","kind":"info","current":"Disabled"}]}],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"perf.sleep","label":"Sleep timeout","description":"How long the mouse stays awake when idle before sleeping.","kind":"choice","options":[{"value":60,"label":"1 min"},{"value":120,"label":"2 min"},{"value":180,"label":"3 min"},{"value":300,"label":"5 min"},{"value":600,"label":"10 min"},{"value":900,"label":"15 min"}],"current":300},{"id":"perf.motionSync","label":"Motion sync","description":"Synchronizes X/Y sensor sampling for smoother diagonals.","kind":"toggle","current":true},{"id":"perf.angleSnapping","label":"Angle snapping","description":"Rounds movement to straight lines and diagonals for a steadier cursor.","kind":"toggle","current":false},{"id":"perf.rippleControl","label":"Ripple control","description":"Filters sensor ripple at high polling rates for more stable tracking.","kind":"toggle","current":false},{"id":"perf.lowPower","label":"Low power mode","description":"Slows the mouse down to save battery below this level.","kind":"choice","options":[{"value":5,"label":"5%"},{"value":10,"label":"10%"},{"value":12,"label":"12%"},{"value":15,"label":"15%"},{"value":20,"label":"20%"},{"value":25,"label":"25%"},{"value":30,"label":"30%"}],"current":12}]}],"lighting":null},"atk":{"buttons":[],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"perf.motionSync","label":"Motion sync","description":"Synchronizes X/Y sensor sampling for smoother diagonals.","kind":"toggle","current":false},{"id":"perf.performanceMode","label":"Performance / hyper mode","description":"Runs the sensor at its full performance setting.","kind":"toggle","current":true},{"id":"perf.dpiStage","label":"DPI stages","description":"On-device sensitivity stages; pick the active one.","kind":"choice","options":[{"value":0,"label":"Stage 1"},{"value":1,"label":"Stage 2"},{"value":2,"label":"Stage 3"}],"current":1},{"id":"perf.debounce","label":"Debounce","description":"Filters out physical switch bounce (0-8 ms). Higher is steadier, slightly more click lag.","kind":"choice","options":[{"value":0,"label":"0 ms"},{"value":1,"label":"1 ms"},{"value":2,"label":"2 ms"},{"value":3,"label":"3 ms"},{"value":4,"label":"4 ms"},{"value":5,"label":"5 ms"},{"value":6,"label":"6 ms"},{"value":7,"label":"7 ms"},{"value":8,"label":"8 ms"}],"current":4}]}],"lighting":null},"zaun":{"buttons":[],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"perf.usbSpeed","label":"USB speed","description":"Full pins polling to 1000 Hz; High enables faster rates.","kind":"choice","options":[{"value":"Full","label":"Full"},{"value":"High","label":"High"}],"current":"High"},{"id":"perf.primaryButton","label":"Primary button","description":"Which button acts as the primary click.","kind":"choice","options":[{"value":"Left","label":"Left"},{"value":"Right","label":"Right"}],"current":"Left"}]}],"lighting":null},"hidden":{"buttons":[],"advanced":[],"performance":[],"lighting":null},"noDebounce":{"buttons":[],"advanced":[],"performance":[{"title":"More settings","controls":[{"id":"perf.debounce","label":"Debounce","description":"Filters out physical switch bounce (0-0 ms). Higher is steadier, slightly more click lag.","kind":"choice","options":[{"value":0,"label":"0 ms"}],"current":0}]}],"lighting":null},"superlight":{"buttons":[],"advanced":[],"performance":[],"lighting":null}} diff --git a/gpui/vendor/gpui-pre-apple/src/metal_atlas.rs b/gpui/vendor/gpui-pre-apple/src/metal_atlas.rs index a635bc46..5ae39d20 100644 --- a/gpui/vendor/gpui-pre-apple/src/metal_atlas.rs +++ b/gpui/vendor/gpui-pre-apple/src/metal_atlas.rs @@ -339,7 +339,7 @@ mod tests { // NOT return a stale tile referencing the deleted texture. let tile_a2 = insert_tile(&atlas, key_a, small); - // The texture must actually exist — this would panic before the fix. + // The texture must actually exist - this would panic before the fix. assert!(atlas.metal_texture(tile_a2.texture_id).is_some()); } diff --git a/gpui/vendor/gpui-pre-apple/vendor/gpui/src/platform.rs b/gpui/vendor/gpui-pre-apple/vendor/gpui/src/platform.rs index c08d9646..2ee2e186 100644 --- a/gpui/vendor/gpui-pre-apple/vendor/gpui/src/platform.rs +++ b/gpui/vendor/gpui-pre-apple/vendor/gpui/src/platform.rs @@ -2116,7 +2116,7 @@ impl PlatformInputHandler { } bounds_for_range(line_start..line_start) } else { - // No active composition — use the selection endpoint. + // No active composition - use the selection endpoint. let offset = if selection.reversed { selection.range.start } else { @@ -2335,7 +2335,7 @@ pub trait InputHandler: 'static { /// /// This is the reverse data-flow direction from [`Self::selected_text_range`]: /// platforms call it when the system text machinery moves the selection on the - /// application's behalf — e.g. the user drags a system selection handle or + /// application's behalf - e.g. the user drags a system selection handle or /// invokes Select All from system UI (iOS `UITextInput setSelectedTextRange:`, /// Android `InputConnection.setSelection`). /// diff --git a/gpui/vendor/gpui-pre-apple/vendor/gpui/src/window.rs b/gpui/vendor/gpui-pre-apple/vendor/gpui/src/window.rs index 1214b035..1c035b74 100644 --- a/gpui/vendor/gpui-pre-apple/vendor/gpui/src/window.rs +++ b/gpui/vendor/gpui-pre-apple/vendor/gpui/src/window.rs @@ -386,8 +386,8 @@ pub(crate) fn with_element_arena(callback: impl FnOnce(&mut Arena) -> R) -> R /// Call [`ElementArenaScope::exit`] with the same arena that was entered to /// obtain the [`ArenaClearNeeded`] token the draw now owes; requiring `exit` /// makes it impossible to request a clear before the scope has ended. The -/// scope's teardown — restoring the thread-local and balancing `begin_scope` -/// with `end_scope` — happens in `Drop`, so the arena's scope depth stays +/// scope's teardown - restoring the thread-local and balancing `begin_scope` +/// with `end_scope` - happens in `Drop`, so the arena's scope depth stays /// balanced on every path, including when a panic unwinds a draw before `exit` /// is reached. (If teardown lived only in `exit`, such a panic would leave the /// scope depth permanently elevated and defer every future clear, leaking @@ -431,8 +431,8 @@ impl ElementArenaScope { ); self.exited = true; // Teardown (restoring the thread-local and ending the arena's - // clear-deferral scope) runs in `Drop`, which fires both here — `self` - // is dropped as `exit` returns, before the token reaches the caller — + // clear-deferral scope) runs in `Drop`, which fires both here - `self` + // is dropped as `exit` returns, before the token reaches the caller - // and when a panic unwinds the draw before `exit` is reached. ArenaClearNeeded::new(arena) } @@ -975,7 +975,7 @@ pub(crate) struct TooltipRequest { /// The ids of the elements being drawn, root first, with the hash of every /// prefix alongside: a [`GlobalElementId`] for the current element is then /// the ids cloned out and the hash on top of the stack, without walking the -/// path — the ids of every ancestor, string names byte by byte — for each +/// path - the ids of every ancestor, string names byte by byte - for each /// element on every frame. #[derive(Clone, Default)] pub(crate) struct ElementIdStack { @@ -1789,7 +1789,7 @@ impl Window { // bypasses the view cache. // // Returning here skips `complete_frame`, which on Wayland would - // stall the window's frame callbacks (no `surface.commit()`) — + // stall the window's frame callbacks (no `surface.commit()`) - // but calling it would hit the App borrow panic above, and this // branch is unreachable there in practice: only Windows pumps // platform events (and thus requests frames) mid-draw. diff --git a/install-linux.sh b/install-linux.sh index cc316ba1..44ab11be 100644 --- a/install-linux.sh +++ b/install-linux.sh @@ -552,7 +552,7 @@ run_preview() { "${TAG:-latest stable}" \ "~/.local/share/openmouse-desktop" \ "mouse-only hidraw udev rule (uses sudo)" - info "Preview mode — no files or system settings will be modified." + info "Preview mode - no files or system settings will be modified." step 1 5 "Checking system dependencies" info "Required: udev, xkbcommon, xcb, wayland, vulkan, polkit, curl, tar" @@ -585,7 +585,7 @@ run_preview() { step 4 5 "Configuring hidraw mouse permissions (udev)" note "Password may be requested via sudo to allow non-root mouse access" ok "Installed /etc/udev/rules.d/69-openmouse-desktop.rules" - ok "Reloaded udev rules — replug your mouse if already connected" + ok "Reloaded udev rules - replug your mouse if already connected" step 5 5 "Setting up desktop integration" ok "App menu launcher installed (~/.local/share/applications)" @@ -761,7 +761,7 @@ main() { $sudo udevadm settle --timeout=5 2>/dev/null || true udev_status="udev rule active (no root required)" ok "Installed $UDEV_RULE" - ok "Reloaded udev rules — replug your mouse if already connected" + ok "Reloaded udev rules - replug your mouse if already connected" fi else info "Skipped (--no-udev)" diff --git a/marketplace-worker/src/index.js b/marketplace-worker/src/index.js index 970c23d7..59d96633 100644 --- a/marketplace-worker/src/index.js +++ b/marketplace-worker/src/index.js @@ -2,19 +2,19 @@ * OpenMouse Marketplace Worker (Cloudflare Workers + R2) * * Public endpoints: - * GET /index.json — Published Marketplace catalog (themes + future plugins) - * GET /themes/.css — Published CSS theme file - * GET /auth/discord/start — Starts Desktop Discord OAuth2 login - * GET /auth/discord/callback — Completes Discord OAuth2 and redirects to localhost + * GET /index.json - Published Marketplace catalog (themes + future plugins) + * GET /themes/.css - Published CSS theme file + * GET /auth/discord/start - Starts Desktop Discord OAuth2 login + * GET /auth/discord/callback - Completes Discord OAuth2 and redirects to localhost * * Authenticated (Discord session token) endpoints: - * POST /api/themes/submit — Direct in-app theme submission + * POST /api/themes/submit - Direct in-app theme submission * * Admin endpoints (Authorization: Bearer ): - * POST /api/admin/themes//verify — Toggle "Verified by OpenMouse" - * POST /api/admin/themes//approve — Publish a pending submission - * DELETE /api/admin/themes/ — Remove a theme from the catalog - * POST /api/admin/users//ban — Ban a Discord user id from submitting + * POST /api/admin/themes//verify - Toggle "Verified by OpenMouse" + * POST /api/admin/themes//approve - Publish a pending submission + * DELETE /api/admin/themes/ - Remove a theme from the catalog + * POST /api/admin/users//ban - Ban a Discord user id from submitting */ const MAX_CSS_BYTES = 64 * 1024; @@ -379,7 +379,7 @@ export default { .map(([label]) => label); if (missingTokens.length > 0) { return json( - { error: `Theme is incomplete — missing or invalid color tokens: ${missingTokens.join(", ")}` }, + { error: `Theme is incomplete - missing or invalid color tokens: ${missingTokens.join(", ")}` }, 400, ); } diff --git a/public/credits.json b/public/credits.json index 6d1c3b9d..67b53ac6 100644 --- a/public/credits.json +++ b/public/credits.json @@ -25,6 +25,7 @@ "contributors": [ { "name": "snekxs", "url": "https://github.com/snekxs" }, { "name": "jazzstack", "url": "https://github.com/jazzstack" }, + { "name": "onyxhq-dev", "url": "https://github.com/onyxhq-dev" }, { "name": "dwei30", "url": "https://github.com/dwei30" }, { "name": "viix0dev", "url": "https://github.com/viix0dev" }, { "name": "nyedle", "url": "https://github.com/nyedle" }, From 76674e4125614977643516798fa4f4b5f6bdee9b Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 18:04:03 +0100 Subject: [PATCH 2/6] fix: review findings across the app, game profile restore, DPI nudges - Writes stay on the open device after a rescan; pending DPI stage saves keep their mouse - Logitech flash writes are no longer cut off by an outer 15 s timeout - Game profiles save their restore values to disk and restore onboard buttons on close - Settings and profiles are written atomically; unreadable files are set aside - Game detection checks every 2 s in the background too - Quick DPI +/- steps through the mouse's supported values and stacks rapid presses - HID: a failed request no longer drops the device, slow devices don't block others - Themes, marketplace, updates, tray, keyboards: fixes from the full review --- crates/openmouse-hid/src/lib.rs | 70 ++++++--- crates/openmouse-presence/src/lib.rs | 63 +++++--- gpui/js/controls.ts | 13 +- gpui/js/entry.ts | 14 +- gpui/js/globals.ts | 2 +- gpui/js/keyboard-logitech.ts | 8 +- gpui/js/keyboard-via.ts | 32 ++-- gpui/js/keyboards.ts | 35 ++--- gpui/js/native-hid/logitech-actions.ts | 6 +- gpui/src/app.rs | 2 + gpui/src/app/appearance.rs | 23 ++- gpui/src/app/chrome.rs | 12 +- gpui/src/app/controls.rs | 20 ++- gpui/src/app/device_io.rs | 96 ++++++++++-- gpui/src/app/device_overview.rs | 17 ++- gpui/src/app/device_page.rs | 16 +- gpui/src/app/device_state.rs | 3 + gpui/src/app/keyboard_panel.rs | 8 +- gpui/src/app/logitech_stages.rs | 57 +++++-- gpui/src/app/magnetic_panel.rs | 9 +- gpui/src/app/plugins_page.rs | 13 +- gpui/src/app/profile_ui.rs | 196 +++++++++++++++++-------- gpui/src/app/safety.rs | 21 ++- gpui/src/app/settings_page.rs | 14 +- gpui/src/app/theme_studio.rs | 25 +++- gpui/src/app/updates.rs | 5 + gpui/src/app/usb_map_page.rs | 6 + gpui/src/audio.rs | 40 +++-- gpui/src/autostart.rs | 22 ++- gpui/src/bin/main.rs | 2 + gpui/src/game_watcher.rs | 5 +- gpui/src/games/install_scan.rs | 6 +- gpui/src/hid.rs | 12 +- gpui/src/marketplace.rs | 48 +++--- gpui/src/native_window.rs | 2 + gpui/src/profiles.rs | 78 +++++++--- gpui/src/settings.rs | 25 +++- gpui/src/theme.rs | 50 ++++++- gpui/src/tray.rs | 9 +- gpui/src/update_check.rs | 21 ++- gpui/src/usb_topology.rs | 174 +++++++++++++++++----- 41 files changed, 936 insertions(+), 344 deletions(-) diff --git a/crates/openmouse-hid/src/lib.rs b/crates/openmouse-hid/src/lib.rs index 1ea5ae75..d6d904b8 100644 --- a/crates/openmouse-hid/src/lib.rs +++ b/crates/openmouse-hid/src/lib.rs @@ -241,7 +241,7 @@ mod windows_hid_enumerate { } let mut buf: Vec = vec![0u8; required as usize]; let detail = buf.as_mut_ptr() as *mut SP_DEVICE_INTERFACE_DETAIL_DATA_W; - (*detail).cbSize = mem::size_of::() as DWORD; + (*detail).cbSize = if cfg!(target_pointer_width = "64") { 8 } else { 6 }; if SetupDiGetDeviceInterfaceDetailW( dev_info, &iface, @@ -495,7 +495,7 @@ impl Default for HidApiHandle { } #[derive(Default)] -pub struct HidRegistry(Mutex>); +pub struct HidRegistry(Mutex>>); /// Extra device-interface paths discovered on Windows via `SetupDi*` that /// hidapi's own enumeration missed (sub-collection paths with `&colNN` in @@ -549,6 +549,10 @@ fn linux_sysfs_descriptor(path: &str) -> Option> { (!bytes.is_empty()).then_some(bytes) } +fn descriptor_cache_key(vendor_id: u16, product_id: u16, path: &str) -> String { + format!("{} {path}", interface_key(vendor_id, product_id)) +} + fn read_descriptor_for_path( api: &HidApi, vendor_id: u16, @@ -556,7 +560,8 @@ fn read_descriptor_for_path( path_cstr: &std::ffi::CStr, path: &str, ) -> Option> { - if let Some(cached) = DESCRIPTORS.lock().get(path) { + let cache_key = descriptor_cache_key(vendor_id, product_id, path); + if let Some(cached) = DESCRIPTORS.lock().get(&cache_key) { return Some(cached.clone()); } // A brief open, closed by the drop below: it is the only way to ask an @@ -602,14 +607,14 @@ fn read_descriptor_for_path( } }; let (collections, layout) = parsed?; - LAYOUTS.lock().insert(path.to_string(), layout); + LAYOUTS.lock().insert(cache_key.clone(), layout); if !collections.is_empty() { applog!( "[hid] descriptor for {vendor_id:04x}:{product_id:04x} {path}: {} collection(s)", collections.len() ); } - DESCRIPTORS.lock().insert(path.to_string(), collections.clone()); + DESCRIPTORS.lock().insert(cache_key, collections.clone()); Some(collections) } @@ -652,7 +657,7 @@ fn interface_collections( // On Windows, also inspect SetupDi sub-collection paths (`&colNN`) that // hidapi's own enumeration may have skipped. for path in extra_paths { - if seen_paths.contains(path.as_str()) { + if seen_paths.iter().any(|seen| seen.eq_ignore_ascii_case(path)) { continue; } if let Ok(cpath) = CString::new(path.as_str()) { @@ -976,7 +981,7 @@ pub fn hid_open( for split in &stale.splits { split.stop.store(true, Ordering::Relaxed); } - for reader in stale.readers { + for reader in &stale.readers { reader.thread().unpark(); } } @@ -1059,10 +1064,10 @@ pub fn hid_open( // hidapi missed but SetupDi enumerated. #[cfg(target_os = "windows")] { - if let Some(extra) = EXTRA_WINDOWS_PATHS.lock().remove(&(vendor_id, product_id)) + if let Some(extra) = EXTRA_WINDOWS_PATHS.lock().get(&(vendor_id, product_id)).cloned() { for path in &extra { - if !paths.iter().any(|p| p == path) { + if !paths.iter().any(|p| p.eq_ignore_ascii_case(path)) { applog!( "[hid] hid_open: extra windows path for {vendor_id:04x}:{product_id:04x}: {path}" ); @@ -1117,7 +1122,11 @@ pub fn hid_open( let mut readers = Vec::new(); for (index, (path, device)) in devices.into_iter().enumerate() { let stop = Arc::new(AtomicBool::new(false)); - let layout = LAYOUTS.lock().get(&path).cloned().unwrap_or_default(); + let layout = LAYOUTS + .lock() + .get(&descriptor_cache_key(vendor_id, product_id, &path)) + .cloned() + .unwrap_or_default(); let split = Arc::new(OpenSplit { device: Mutex::new(device), stop: stop.clone(), @@ -1136,14 +1145,14 @@ pub fn hid_open( registry.0.lock().insert( group_key, - OpenGroup { + Arc::new(OpenGroup { splits, readers, disconnected, routes: Mutex::new(HashMap::new()), silent: Mutex::new(HashSet::new()), last_sent: Mutex::new(HashMap::new()), - }, + }), ); applog!("[hid] hid_open: done, registered group"); Ok(()) @@ -1516,8 +1525,8 @@ pub fn hid_send_report( frame.extend_from_slice(&data); send_each(&group.splits, &frame, false, vendor_id == RAZER_VENDOR_ID, false) }); - if result.is_err() { - drop_group(registry, vendor_id, product_id); + if let Err(error) = &result { + drop_group_if_disconnected(registry, vendor_id, product_id, error); } applog!("[hid] hid_send_report done: {result:?}"); result @@ -1553,8 +1562,8 @@ pub fn hid_send_feature_report( declaring_only, ) }); - if result.is_err() { - drop_group(registry, vendor_id, product_id); + if let Err(error) = &result { + drop_group_if_disconnected(registry, vendor_id, product_id, error); } applog!("[hid] hid_send_feature_report done: {result:?}"); result @@ -1587,8 +1596,8 @@ pub fn hid_get_input_report( }); outcome.and(result.ok_or_else(|| "no split returned data".to_string())) }); - if result.is_err() { - drop_group(registry, vendor_id, product_id); + if let Err(error) = &result { + drop_group_if_disconnected(registry, vendor_id, product_id, error); } applog!("[hid] hid_get_input_report done: {result:?}"); result @@ -1664,8 +1673,8 @@ pub fn hid_get_feature_report( }, } }); - if result.is_err() { - drop_group(registry, vendor_id, product_id); + if let Err(error) = &result { + drop_group_if_disconnected(registry, vendor_id, product_id, error); } applog!("[hid] hid_get_feature_report done: {result:?}"); result @@ -1682,12 +1691,14 @@ fn with_open_group( product_id: u16, operation: impl FnOnce(&OpenGroup) -> Result, ) -> Result { - let map = registry.0.lock(); - let group = map + let group = registry + .0 + .lock() .get(&(vendor_id, product_id)) + .cloned() .ok_or_else(|| "This HID interface is not open.".to_string())?; - wake_readers(group); - operation(group) + wake_readers(&group); + operation(&group) } /// Every split index, with the interfaces whose descriptor declares the report @@ -1817,6 +1828,17 @@ pub fn hid_prune_disconnected(registry: &HidRegistry, queried_vendors: &[u16], p } } +fn drop_group_if_disconnected(registry: &HidRegistry, vendor_id: u16, product_id: u16, error: &str) { + let flagged = registry + .0 + .lock() + .get(&(vendor_id, product_id)) + .is_some_and(|group| group.disconnected.load(Ordering::Relaxed)); + if flagged || is_disconnected_error(error) { + drop_group(registry, vendor_id, product_id); + } +} + fn drop_group(registry: &HidRegistry, vendor_id: u16, product_id: u16) { if let Some(group) = registry.0.lock().remove(&(vendor_id, product_id)) { applog!("[hid] dropped the handles for {vendor_id:04x}:{product_id:04x}: they no longer work"); diff --git a/crates/openmouse-presence/src/lib.rs b/crates/openmouse-presence/src/lib.rs index 1befa4fc..cdf30cf2 100644 --- a/crates/openmouse-presence/src/lib.rs +++ b/crates/openmouse-presence/src/lib.rs @@ -106,6 +106,29 @@ struct Connection { #[derive(Default)] pub struct Presence { connection: Mutex>, + wanted: std::sync::atomic::AtomicBool, +} + +fn connect(guard: &mut Option) -> Result<(), String> { + if let Some(connection) = guard.as_mut() { + applog!("[discord] client exists, reconnecting to refresh"); + if let Err(error) = connection.client.reconnect() { + applog!("[discord] reconnect failed: {error}"); + *guard = None; + return Err(error.to_string()); + } + applog!("[discord] reconnected"); + } else { + applog!("[discord] opening IPC connection for client {CLIENT_ID}"); + let mut client = DiscordIpcClient::new(CLIENT_ID); + if let Err(error) = client.connect() { + applog!("[discord] connection failed: {error}"); + return Err(error.to_string()); + } + applog!("[discord] IPC connection established"); + *guard = Some(Connection { client, started: now_millis() }); + } + Ok(()) } impl Presence { @@ -115,26 +138,9 @@ impl Presence { /// trusted - otherwise the switch would look on while nothing is connected. pub fn enable(&self) -> Result<(), String> { applog!("[discord] enable requested"); + self.wanted.store(true, std::sync::atomic::Ordering::Relaxed); let mut guard = self.connection.lock(); - - if let Some(connection) = guard.as_mut() { - applog!("[discord] client exists, reconnecting to refresh"); - if let Err(error) = connection.client.reconnect() { - applog!("[discord] reconnect failed: {error}"); - return Err(error.to_string()); - } - applog!("[discord] reconnected"); - } else { - applog!("[discord] opening IPC connection for client {CLIENT_ID}"); - let mut client = DiscordIpcClient::new(CLIENT_ID); - if let Err(error) = client.connect() { - applog!("[discord] connection failed: {error}"); - return Err(error.to_string()); - } - applog!("[discord] IPC connection established"); - *guard = Some(Connection { client, started: now_millis() }); - } - + connect(&mut guard)?; let connection = guard.as_mut().expect("connection just established"); let started = connection.started; set_activity_and_confirm(&mut connection.client, initial_activity(started)) @@ -143,10 +149,20 @@ impl Presence { pub fn update_activity(&self, details: String, state_text: String) -> Result<(), String> { applog!("[discord] activity update requested: details={details:?}, state={state_text:?}"); let mut guard = self.connection.lock(); - let Some(connection) = guard.as_mut() else { - applog!("[discord] activity update skipped: RPC is not enabled"); - return Err("Discord RPC is not enabled".to_string()); - }; + if guard.is_none() { + if !self.wanted.load(std::sync::atomic::Ordering::Relaxed) { + applog!("[discord] activity update skipped: RPC is not enabled"); + return Err("Discord RPC is not enabled".to_string()); + } + connect(&mut guard)?; + } + let connection = guard.as_mut().expect("connection present"); + let started = connection.started; + if set_activity_and_confirm(&mut connection.client, build_activity(details.clone(), state_text.clone(), started)).is_ok() { + return Ok(()); + } + connect(&mut guard)?; + let connection = guard.as_mut().expect("connection present"); let started = connection.started; set_activity_and_confirm(&mut connection.client, build_activity(details, state_text, started)) } @@ -158,6 +174,7 @@ impl Presence { pub fn disable(&self) -> Result<(), String> { applog!("[discord] disable requested"); + self.wanted.store(false, std::sync::atomic::Ordering::Relaxed); let mut guard = self.connection.lock(); if let Some(mut connection) = guard.take() { if let Err(error) = connection.client.close() { diff --git a/gpui/js/controls.ts b/gpui/js/controls.ts index 2aea5f00..5e805065 100644 --- a/gpui/js/controls.ts +++ b/gpui/js/controls.ts @@ -252,7 +252,7 @@ function extras(s: any): Section[] { const rel = [{ value: 0, label: "Normal" }, { value: 1, label: "Early" }, { value: 2, label: "Late" }]; // Edit both switches as one, or each on its own. Starts linked when they already match. const keys = ["ClickMode", "ClickRelease", "TmrThr", "TmrHyst"]; - if (s.slxLinked === undefined) s.slxLinked = linkLeftRight ?? keys.every((k) => s[`finalmouse${k}L`] === s[`finalmouse${k}R`]); + if (s.slxLinked === undefined) s.slxLinked = linkLeftRight !== false && keys.every((k) => s[`finalmouse${k}L`] === s[`finalmouse${k}R`]); const linked: boolean = s.slxLinked; out.push({ title: "Starlight X", controls: [{ id: "slx.link", label: "Link left & right", description: "Change both buttons together.", kind: "toggle", current: linked }] }); for (const side of linked ? (["L"] as const) : (["L", "R"] as const)) { @@ -342,7 +342,7 @@ function hits(s: any, brand: string): Section[] { const t = s.analogButtonTuning; if (brand !== "Logitech" || !t || !Array.isArray(t.buttons) || t.buttons.length === 0) return []; const same = (k: string) => t.buttons.every((b: any) => b[k] === t.buttons[0][k]); - if (s.hitsLinked === undefined) s.hitsLinked = t.buttons.length > 1 && (linkLeftRight ?? ["actuation", "rapidTrigger", "haptics", "rapidTriggerEnabled"].every(same)); + if (s.hitsLinked === undefined) s.hitsLinked = t.buttons.length > 1 && linkLeftRight !== false && ["actuation", "rapidTrigger", "haptics", "rapidTriggerEnabled"].every(same); const linked: boolean = s.hitsLinked && t.buttons.length > 1; const out: Section[] = []; if (t.buttons.length > 1) { @@ -455,7 +455,7 @@ function deviceInfo(status: any): Section[] { const slot = typeof status.currentHost === "number" ? `slot ${status.currentHost + 1} of ${status.hostCount}` : `${status.hostCount} slots`; info("hosts", "Easy-Switch", paired === null ? slot : `${slot} · ${paired} paired`); } - info("nape", "Layer", typeof status.napeLayer === "number" && status.napeLayerCount ? `${status.napeLayer + 1} of ${status.napeLayerCount}` : null); + info("nape", "Layer", typeof status.napeLayer === "number" && status.napeLayerCount ? `${status.napeLayer} of ${status.napeLayerCount}` : null); return c.length ? [{ title: "Device info", controls: c }] : []; } @@ -617,12 +617,12 @@ export function describeControls(brand: string, status: any, caps: DeviceCapabil const keychron = keychronControls(status); // A remapper replaces the read-only list of the same buttons. const remappable = new Set(more.buttons.flatMap((s) => s.controls).map((c) => c.id.replace("x.atkButton.", "atk.info."))); - const listed = advanced(status, brand) + const unlisted = (sections: Section[]) => sections .map((section) => ({ ...section, controls: section.controls.filter((c) => !remappable.has(c.id)) })) .filter((section) => section.controls.length > 0); const tabs = gatherButtons({ buttons: [...razerAndEgg(brand, status), ...genericButtons(status), ...logitechRemap(status), ...more.buttons], - advanced: [...listed, ...hits(status, brand), ...extras(status), ...genericFeatures(status), + advanced: [...unlisted(advanced(status, brand)), ...hits(status, brand), ...unlisted(extras(status)), ...genericFeatures(status), ...keychron.advanced, ...more.advanced, ...deviceInfo(status)], performance: [...stageSections(status), ...performanceExtras(brand, status, caps), ...keychron.performance, ...more.performance], }); @@ -671,6 +671,7 @@ async function applyHits(info: HidInterfaceInfo, t: any, buttons: Iterable { + if (info.key.startsWith("mock:")) return value; if (isStageControl(id)) return writeStage(info, status, id, value); if (isExtraControl(id)) return writeExtra(info, status, id, value); if (id.startsWith("keychron.")) return writeKeychron(info, status, id, value); @@ -723,7 +724,7 @@ export async function writeControl(info: HidInterfaceInfo, status: any, id: stri const l = (k: string) => status[`finalmouse${k}L`]; await callClientMethod(info, "setClickMode", l("ClickMode"), l("ClickMode"), l("ClickRelease"), l("ClickRelease")); if (l("TmrThr") != null) await callClientMethod(info, "setTmrActuation", l("TmrThr") / 100, l("TmrThr") / 100, l("TmrHyst"), l("TmrHyst")); - for (const k of ["ClickMode", "ClickRelease", "TmrThr", "TmrHyst", "TmrMsp"]) status[`finalmouse${k}R`] = status[`finalmouse${k}L`]; + for (const k of ["ClickMode", "ClickRelease", "TmrThr", "TmrHyst"]) status[`finalmouse${k}R`] = status[`finalmouse${k}L`]; } return; } diff --git a/gpui/js/entry.ts b/gpui/js/entry.ts index 39e43904..4da310b4 100644 --- a/gpui/js/entry.ts +++ b/gpui/js/entry.ts @@ -106,6 +106,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); await travel.stop(key); + if (isMockKey(key)) return JSON.stringify(action === "read" ? [] : true); if (candidate.kind === "keyboard") return JSON.stringify(await keyboardMacroOp(candidate.info, action, args)); return JSON.stringify(await macroOp(candidate.info, lastStatus.get(key) ?? {}, action, args)); }, @@ -144,7 +145,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); const sorted = [...options].sort((a, b) => a - b); status.dpiOptions = sorted; const gaps = sorted.slice(1).map((v, i) => v - sorted[i]).filter((gap) => gap > 0); - Object.assign(bounds, { min: sorted[0], max: sorted[sorted.length - 1], step: Math.min(...gaps) }); + Object.assign(bounds, { min: sorted[0], max: sorted[sorted.length - 1], step: Math.min(...gaps), options: sorted }); } if (status.onboardProfileFormat) status.onboardProfileFormat.factory = factoryDirectoryForFormat(status.onboardProfileFormat.id, 255) !== null; } @@ -276,6 +277,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); await travel.stop(key); const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); + if (isMockKey(key)) return "{}"; const applied: Record = {}; const errors: string[] = []; try { @@ -341,8 +343,14 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); const onboard = lastStatus.get(key); const options: number[] | undefined = onboard?.dpiOptions; if (brand === "Logitech" && action === "dpi" && options?.length) { - const snap = (v: number) => options.reduce((best, o) => (Math.abs(o - v) < Math.abs(best - v) ? o : best)); - value = typeof value === "number" ? snap(value) : { ...value, x: snap(value.x), y: snap(value.y) }; + const snap = (v: number, from: unknown) => { + const near = options.reduce((best, o) => (Math.abs(o - v) < Math.abs(best - v) ? o : best)); + if (typeof from !== "number" || near !== from || v === from) return near; + return (v > from ? options.find((o) => o > from) : [...options].reverse().find((o) => o < from)) ?? near; + }; + value = typeof value === "number" ? snap(value, onboard.dpi) : { ...value, x: snap(value.x, onboard.dpi), y: snap(value.y, onboard.dpiY ?? onboard.dpi) }; + onboard.dpi = typeof value === "number" ? value : value.x; + if (typeof value !== "number") onboard.dpiY = value.y; } if (brand === "Logitech" && (action === "dpi" || action === "pollingRate" || action === "liftOff") && onboard?.deviceMode === "Onboard" && onboard?.onboardProfileFormat?.writable) { return JSON.stringify(await withLogitechClient(info, `profile ${action}`, async (client: any) => { diff --git a/gpui/js/globals.ts b/gpui/js/globals.ts index 020c3152..435e3477 100644 --- a/gpui/js/globals.ts +++ b/gpui/js/globals.ts @@ -107,7 +107,7 @@ g.TextDecoder ??= class TextDecoder { else if (c < 0xe0) cp = ((c & 31) << 6) | (b[i++] & 63); else if (c < 0xf0) { cp = ((c & 15) << 12) | ((b[i++] & 63) << 6) | (b[i++] & 63); } else { cp = ((c & 7) << 18) | ((b[i++] & 63) << 12) | ((b[i++] & 63) << 6) | (b[i++] & 63); } - out += String.fromCodePoint(cp); + out += c >= 0xf8 || cp > 0x10ffff || i > b.length ? String.fromCharCode(0xfffd) : String.fromCodePoint(cp); } return out; } diff --git a/gpui/js/keyboard-logitech.ts b/gpui/js/keyboard-logitech.ts index c6bfeec3..7e37ff49 100644 --- a/gpui/js/keyboard-logitech.ts +++ b/gpui/js/keyboard-logitech.ts @@ -63,12 +63,14 @@ function showEffect(effect: LogitechOnboardMemory["profiles"][number]["effects"] return label ? [label, effect.color && hex(effect.color), effect.periodMs].filter(value => value != null).join(" ") : ""; } +const keyName = (name: string) => /^(.|f\d+)$/i.test(name) ? name.toUpperCase() : name.charAt(0).toUpperCase() + name.slice(1); + function disabledKeys(value: string): number[] { if (value.toLowerCase() === "none") return []; // Use the driver's physical key map once the package version that exposes it is installed. const controls = Reflect.get(protocol, "G915_X_TKL_GAME_MODE_KEYS") as ReadonlyMap | undefined; return value.split(/[\s,]+/).map(name => { - const id = controls?.get(hidUsage(name.length === 1 ? name.toUpperCase() : name)); + const id = controls?.get(hidUsage(keyName(name))); if (id === undefined) throw new Error(`The key ${name} is unavailable for Game Mode.`); return id; }); @@ -165,9 +167,9 @@ export async function writeLogitechKeyboard(client: LogitechKeyboardHidClient, k else if (field === "binding") { const parts = /^([^=]+)\s*=\s*([^=]+)$/.exec(entry); if (!parts) throw new Error("Enter an assignment such as F5 = Ctrl+B or F5 = Original."); - const sourceUsage = hidUsage(parts[1].trim()); + const sourceUsage = hidUsage(keyName(parts[1].trim())); const target = parts[2].trim(); - const shortcut = target.toLowerCase() === "original" ? { usage: null, modifiers: 0 } : parseShortcut(target); + const shortcut = target.toLowerCase() === "original" ? { usage: null, modifiers: 0 } : parseShortcut(target.split("+").map(keyName).join("+")); changes = { binding: { sourceUsage, targetUsage: shortcut.usage, modifiers: shortcut.modifiers } }; } else if (Object.hasOwn(targets, field)) { const effect = parseEffect(entry); diff --git a/gpui/js/keyboard-via.ts b/gpui/js/keyboard-via.ts index a92adbd1..94374ff7 100644 --- a/gpui/js/keyboard-via.ts +++ b/gpui/js/keyboard-via.ts @@ -20,10 +20,12 @@ const GROUP_NAMES: Record = { }; const definitions = new Map(); +const missing = new Map(); export async function viaDefinition(info: HidInterfaceInfo): Promise { const id = `${info.vendorId}:${info.productId}`; if (definitions.has(id)) return definitions.get(id)!; + if (Date.now() - (missing.get(id) ?? -Infinity) < 60000) return null; const text = await invoke("via_definition", { vendorId: info.vendorId, productId: info.productId }); let definition: ViaDefinition | null = null; try { @@ -31,7 +33,8 @@ export async function viaDefinition(info: HidInterfaceInfo): Promise key.encoder !== undefined).map((key) => key.encoder as number))].sort((a, b) => a - b); +function encoderIds(definition: ViaDefinition): number[] { + const keys = [...definition.keys, ...Object.values(definition.optionKeys).flatMap((options) => Object.values(options).flat())]; + return [...new Set(keys.filter((key) => key.encoder !== undefined).map((key) => key.encoder as number))].sort((a, b) => a - b); } async function layoutFile(client: any, info: HidInterfaceInfo) { - const { via, definition, choices } = await context(client, info); + const { via, definition } = await context(client, info); const name = (code: number) => viaKeycodeToLayoutName(code, via.protocolVersion); const keymap: number[][] = await client.readKeymap(definition.matrix, via.layerCount); const macros = (via.macroCount ?? 0) > 0 ? await client.readMacros() : null; - const ids = encoderIds(definition, choices); + const ids = encoderIds(definition); const encoders: [string, string][][] = Array.from({ length: ids.length ? ids[ids.length - 1] + 1 : 0 }, () => []); for (const id of ids) { for (let layer = 0; layer < via.layerCount; layer++) { @@ -221,7 +225,7 @@ async function layoutFile(client: any, info: HidInterfaceInfo) { } async function loadLayoutFile(client: any, info: HidInterfaceInfo, text: string) { - const { via, definition, choices } = await context(client, info); + const { via, definition } = await context(client, info); let file: any; try { file = JSON.parse(text); @@ -247,7 +251,7 @@ async function loadLayoutFile(client: any, info: HidInterfaceInfo, text: string) encoded = file.macros.map((expression: unknown) => encodeViaMacro(parseViaMacroExpression(String(expression), via.protocolVersion), via.protocolVersion)); joinViaMacros(encoded!, macros.bufferSize); } - const ids = new Set(encoderIds(definition, choices)); + const ids = new Set(encoderIds(definition)); const turns: { layer: number; id: number; clockwise: boolean; code: number }[] = []; for (const [id, perLayer] of (Array.isArray(file.encoders) ? file.encoders : []).entries()) { if (!ids.has(id) || !Array.isArray(perLayer)) continue; @@ -267,9 +271,9 @@ export async function viaWrite(client: any, info: HidInterfaceInfo, id: string, await loadLayoutFile(client, info, String(value)); return null; } - const { via, definition, choices, items } = await menuState(client, info); const layout = /^via\.layout\.(\d+)$/.exec(id); if (layout) { + const { definition, choices } = await context(client, info); const index = Number(layout[1]); const label = definition.labels[index]; if (label === undefined) throw new RangeError("That layout option doesn't exist."); @@ -278,6 +282,7 @@ export async function viaWrite(client: any, info: HidInterfaceInfo, id: string, await client.setLayoutOptions(viaPackLayoutChoices(definition.labels, next)); return null; } + const { via, definition, choices, items } = await menuState(client, info); const item = items.find((entry) => `via.v.${valueKey(entry.ids)}` === id); if (!item) throw new Error("That setting isn't on this keyboard."); const control = item.control; @@ -309,7 +314,7 @@ export async function viaWrite(client: any, info: HidInterfaceInfo, id: string, return null; } -export const viaMacroPanel = (count: number) => ({ +export const viaMacroPanel = (count: number, protocol: number) => ({ slots: numbered(count, "Macro"), buttons: [], maxSteps: 128, @@ -317,7 +322,9 @@ export const viaMacroPanel = (count: number) => ({ mouse: false, readable: true, warning: null, - note: "Put a macro on a key from the Macros group on the Keys tab. Saving keeps it on the keyboard.", + note: protocol >= VIA_MACRO_DELAY_PROTOCOL + ? "Put a macro on a key from the Macros group on the Keys tab. Saving keeps it on the keyboard." + : "Put a macro on a key from the Macros group on the Keys tab. This keyboard's firmware can't store pauses, so the delays are left out when you save.", }); const usageOf = (key: string) => MODIFIERS[key] ?? hidUsage(key); @@ -337,7 +344,7 @@ function toSteps(actions: ViaMacroAction[]): MacroStep[] { press(action.keycode, false); } else if (action.type === "down" || action.type === "up") { press(action.keycode, action.type === "down"); - } else { + } else if (action.type === "text") { for (const char of action.text) { const upper = char.toUpperCase(); const shifted = /[A-Z]/.test(char); @@ -352,6 +359,8 @@ function toSteps(actions: ViaMacroAction[]): MacroStep[] { press(hidUsage(upper), false); if (shifted) press(MODIFIERS.Shift!, false); } + } else { + throw new Error("This macro has a step this editor can't show, so it is left as it is. Edit it in VIA."); } } return steps; @@ -366,7 +375,6 @@ export async function viaMacroOp(client: any, op: string, args: any): Promise= VIA_MACRO_DELAY_PROTOCOL; const actions: ViaMacroAction[] = []; - if (!delays && (args.steps as MacroStep[]).some((step) => step.delay > 0)) throw new Error("This keyboard's firmware can't store pauses in macros. Remove the delays and save again."); for (const step of args.steps as MacroStep[]) { actions.push({ type: step.down ? "down" : "up", keycode: usageOf(step.key) }); if (delays && step.delay > 0) actions.push({ type: "delay", ms: step.delay }); diff --git a/gpui/js/keyboards.ts b/gpui/js/keyboards.ts index d9fbfd94..cd3374a8 100644 --- a/gpui/js/keyboards.ts +++ b/gpui/js/keyboards.ts @@ -111,25 +111,20 @@ export async function listKeyboards(taken: Set, previous: ReadonlyMap(info: KeyboardInterface, work: (client: any, brand: string) => Promise): Promise { - return withHidOpenLock(info.receiverKey ?? info.key, async () => { - const driver = driverFor(info); - const client = driver?.create(deviceFor(info)) as any; - if (!driver || !client) throw new Error("No keyboard driver claims this device."); - let timer: ReturnType | undefined; - try { - return await Promise.race([ - (async () => { - await client.open(); - return work(client, driver.brand); - })(), - new Promise((_, reject) => { - timer = setTimeout(() => reject(new Error("The keyboard took too long to answer.")), READ_TIMEOUT_MS); - }), - ]); - } finally { - clearTimeout(timer); - await client.close().catch(() => undefined); - } + return new Promise((resolve, reject) => { + withHidOpenLock(info.receiverKey ?? info.key, async () => { + const driver = driverFor(info); + const client = driver?.create(deviceFor(info)) as any; + if (!driver || !client) throw new Error("No keyboard driver claims this device."); + const timer = setTimeout(() => reject(new Error("The keyboard took too long to answer.")), READ_TIMEOUT_MS); + try { + await client.open(); + resolve(await work(client, driver.brand)); + } finally { + clearTimeout(timer); + await client.close().catch(() => undefined); + } + }).catch(reject); }); } @@ -180,7 +175,7 @@ export function describeKeyboard(key: string, brand: string, status: any) { buttons: [], advanced: controls.length ? [{ title: "Keyboard", controls }] : [], lighting: null, - macros: brand === "VIA" && (status.via?.macroCount ?? 0) > 0 ? viaMacroPanel(status.via.macroCount) : null, + macros: brand === "VIA" && (status.via?.macroCount ?? 0) > 0 ? viaMacroPanel(status.via.macroCount, status.via.protocolVersion) : null, }, }; } diff --git a/gpui/js/native-hid/logitech-actions.ts b/gpui/js/native-hid/logitech-actions.ts index c340f277..ff196b71 100644 --- a/gpui/js/native-hid/logitech-actions.ts +++ b/gpui/js/native-hid/logitech-actions.ts @@ -27,10 +27,6 @@ const OPEN_TIMEOUT_MS = 10000; // cost specific to reading every feature. It's a strict subset of that walk, // so it can never exceed this budget. const RESOLVE_INDEX_TIMEOUT_MS = 45000; -// A single write, once the index is resolved, is one request/response round -// trip, not the 20-30 of a full readStatus() walk - generous, but far short -// of that budget. -const ACTION_TIMEOUT_MS = 15000; function withTimeout(promise: Promise, ms: number, label: string): Promise { return new Promise((resolve, reject) => { @@ -118,7 +114,7 @@ async function withClientLocked( try { await withTimeout(client.open(), OPEN_TIMEOUT_MS, "LogitechHidppClient.open()"); await withTimeout(client.resolveDeviceIndex(), RESOLVE_INDEX_TIMEOUT_MS, "LogitechHidppClient.resolveDeviceIndex()"); - return await withTimeout(action(client), ACTION_TIMEOUT_MS, label); + return await action(client); } finally { await client.close().catch(() => undefined); } diff --git a/gpui/src/app.rs b/gpui/src/app.rs index a13d4fa9..34c04510 100644 --- a/gpui/src/app.rs +++ b/gpui/src/app.rs @@ -384,6 +384,7 @@ impl AppView { }; // The OS entry is the truth for launch-on-startup, not the saved flag. view.profiles = crate::profiles::Profiles::load(); + crate::autostart::refresh(); view.settings.launch_on_startup = crate::autostart::is_enabled(); if view.settings.tray_pinned { crate::tray::pin(true); @@ -416,6 +417,7 @@ impl AppView { self.stage_inputs.clear(); self.profile_name = None; self.receiver.colour = None; + self.text_controls.colours.clear(); self.macros.recorder = None; self.text_controls.listening.clear(); // Theme Studio's inputs belong to the old window, and the new window diff --git a/gpui/src/app/appearance.rs b/gpui/src/app/appearance.rs index 2ab1f7cb..3540fb62 100644 --- a/gpui/src/app/appearance.rs +++ b/gpui/src/app/appearance.rs @@ -64,23 +64,18 @@ impl AppView { .background_executor() .spawn(async { crate::theme::dynamic_accent() }) .await; - // Fallback green only if sampling truly fails. - let accent = accent.unwrap_or((93, 222, 137)); let _ = view.update(cx, |view: &mut Self, cx| { - if view.settings.theme != ThemeChoice::Dynamic { + if view.settings.theme != ThemeChoice::Dynamic + || view.settings.custom_theme.is_some() + || view.marketplace_preview.is_some() + { return; } - view.settings.dynamic_hex = Some(accent); - view.settings.save(); - crate::theme::apply_choice( - ThemeChoice::Dynamic, - Some(accent), - vibrancy, - view.settings.window_opacity / 100.0, - view.settings.accent, - None, - cx, - ); + if accent.is_some() { + view.settings.dynamic_hex = accent; + view.settings.save(); + } + view.repaint_theme(None, cx); cx.notify(); }); } diff --git a/gpui/src/app/chrome.rs b/gpui/src/app/chrome.rs index d0219fa7..34e8ab11 100644 --- a/gpui/src/app/chrome.rs +++ b/gpui/src/app/chrome.rs @@ -168,8 +168,7 @@ impl AppView { Page::Plugins => this.plugin_open = None, _ => {} } - this.page = page; - cx.notify(); + this.set_page(page, cx); }), )); } @@ -219,17 +218,15 @@ impl AppView { self.footer_row("footer-updates", updates_icon, "Updates", Some(&updates_subtitle), on_updates, has_update, collapsed, cx) .rounded_t_xl() .on_click(cx.listener(|this, _, _, cx| { - this.page = Page::Updates; - cx.notify(); + this.set_page(Page::Updates, cx); })), ) .child(div().h(px(1.)).w_full().bg(Hsla { a: 0.8, ..border })) .child( self.footer_row("footer-about", about_icon, "About", Some("Credits & sponsors"), on_about, false, collapsed, cx) .on_click(cx.listener(|this, _, _, cx| { - this.page = Page::About; + this.set_page(Page::About, cx); this.refresh_credits_once(cx); - cx.notify(); })), ) .child(div().h(px(1.)).w_full().bg(Hsla { a: 0.8, ..border })) @@ -242,8 +239,7 @@ impl AppView { self.footer_row("footer-settings", gear, Page::Settings.label(), None, self.page == Page::Settings, false, collapsed, cx) .rounded_b_xl() .on_click(cx.listener(|this, _, _, cx| { - this.page = Page::Settings; - cx.notify(); + this.set_page(Page::Settings, cx); })), ); let _ = accent; diff --git a/gpui/src/app/controls.rs b/gpui/src/app/controls.rs index 317dc55f..43d101ae 100644 --- a/gpui/src/app/controls.rs +++ b/gpui/src/app/controls.rs @@ -83,6 +83,7 @@ impl AppView { /// Creates the sliders the selected device's number controls need. The write /// waits until the drag pauses, so a sweep sends one command, not hundreds. pub(super) fn ensure_control_sliders(&mut self, window: &mut Window, cx: &mut Context) { + self.sync_selected(); if self.devices.open.is_none() && self.profile_editor.is_none() { return; } @@ -172,16 +173,23 @@ impl AppView { /// Shows a slider's new position at once and writes it when it stops moving. pub(super) fn schedule_control(&mut self, id: String, live_key: String, position: f64, sent: serde_json::Value, cx: &mut Context) { - self.slider_live.insert(live_key, position); + self.slider_live.insert(live_key.clone(), position); self.slider_seq += 1; let seq = self.slider_seq; + let target = (self.editing_profile(), self.selected_key()); cx.notify(); cx.spawn(async move |view, cx| { cx.background_executor().timer(std::time::Duration::from_millis(350)).await; let _ = view.update(cx, |this: &mut Self, cx| { - if this.slider_seq == seq { - this.set_control(id, sent, cx); + if this.slider_seq != seq { + return; } + if (this.editing_profile(), this.selected_key()) != target { + this.slider_live.remove(&live_key); + cx.notify(); + return; + } + this.set_control(id, sent, cx); }); }) .detach(); @@ -378,7 +386,7 @@ impl AppView { ) .into_any_element(); } - let Some(read) = &self.devices.onboard else { + let Some(read) = self.onboard() else { return col .child(note(if self.devices.onboard_loading { "Reading the mouse's buttons…" @@ -524,7 +532,7 @@ impl AppView { pub(super) fn render_button_modal(&self, cx: &mut Context) -> Option { let id = self.devices.expanded.clone()?; let n: usize = id.strip_prefix(BUTTON_ID)?.parse().ok()?; - let read = self.devices.onboard.as_ref()?; + let read = self.onboard()?; let current = self.shown_button_commands(read.profiles.iter().find(|p| p.is_current)?).get(n)?.clone(); let (fg, muted, border) = (cx.theme().foreground, cx.theme().muted_foreground, cx.theme().border); let close = |this: &mut Self, cx: &mut Context| { @@ -726,7 +734,7 @@ impl AppView { ), ); - match &self.devices.onboard { + match self.onboard() { None => { col = col.child(div().text_sm().text_color(muted).child(if self.devices.onboard_loading { "Reading the mouse's profiles…" diff --git a/gpui/src/app/device_io.rs b/gpui/src/app/device_io.rs index f76d19e1..8bd5ae5d 100644 --- a/gpui/src/app/device_io.rs +++ b/gpui/src/app/device_io.rs @@ -30,7 +30,10 @@ impl AppView { return; } for (id, value) in writes { - self.write_control(id.to_string(), value, cx); + match self.selected_key().filter(|_| self.devices.writing.is_some()) { + Some(key) => self.queue(Queued::Control { key, id: id.to_string(), value, rescue: true }), + None => self.write_control(id.to_string(), value, cx), + } } } @@ -75,6 +78,7 @@ impl AppView { }; let _ = view.update(cx, |v: &mut Self, cx| { // Keep what is already known about devices that are still here. + let keep = v.selected_key(); let mut old: Vec = std::mem::take(&mut v.devices.tiles); v.devices.tiles = candidates .iter() @@ -86,7 +90,7 @@ impl AppView { } }) .collect(); - v.devices.selected = v.devices.selected.min(v.devices.tiles.len().saturating_sub(1)); + v.reselect(keep); v.devices.scanning = false; v.close_unplugged_page(&old, cx); cx.notify(); @@ -223,14 +227,42 @@ impl AppView { }); } + pub(super) fn selected_key(&self) -> Option { + self.devices.tiles.get(self.devices.selected).map(|t| t.key.clone()) + } + + pub(super) fn onboard(&self) -> Option<&crate::hid::OnboardProfiles> { + let selected = self.devices.tiles.get(self.devices.selected)?; + self.devices.onboard.as_ref().filter(|_| self.devices.onboard_key.as_deref() == Some(selected.key.as_str())) + } + + pub(super) fn sync_selected(&mut self) { + if self.editing_profile().is_some() { + return; + } + if let Some(i) = self.devices.open.as_ref().and_then(|k| self.devices.tiles.iter().position(|t| &t.key == k)) { + self.devices.selected = i; + } + } + + fn reselect(&mut self, key: Option) { + self.devices.selected = key + .and_then(|k| self.devices.tiles.iter().position(|t| t.key == k)) + .unwrap_or_else(|| self.devices.selected.min(self.devices.tiles.len().saturating_sub(1))); + } + /// Opens a device's settings page, connecting it first if needed. pub(super) fn open_device(&mut self, key: &str, cx: &mut Context) { let Some(index) = self.devices.tiles.iter().position(|t| t.key == key) else { return }; + if self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.key != key) { + self.flush_stages(cx); + } self.remember_device(key); self.devices.open = Some(key.to_string()); self.devices.selected = index; self.devices.staged = Staged::default(); self.devices.unlinked_axes = false; + self.devices.dpi_pending = None; self.devices.tab = DeviceTab::Overview; self.devices.expanded = None; self.devices.stage_picked = None; @@ -311,6 +343,23 @@ impl AppView { // Which profile is running is no longer what we last read. self.devices.onboard = None; } + let selected = self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.key == key); + if into_profile && selected && action == "dpi" { + if let (Some(dpi), Some(draft)) = (applied.as_f64(), self.devices.stage_draft.as_mut()) { + draft.set_default_dpi(dpi.round() as i64); + } + } + if into_profile && selected && action == "liftOff" { + let lod = match applied.as_str() { + Some("Low") => Some(1), + Some("Medium") => Some(2), + Some("High") => Some(3), + _ => None, + }; + if let (Some(lod), Some(draft)) = (lod, self.devices.stage_draft.as_mut()) { + draft.set_lod(lod); + } + } if into_profile && matches!(action, "dpi" | "pollingRate" | "liftOff") { self.load_onboard_profiles(cx); } @@ -334,7 +383,7 @@ impl AppView { let selected = v.devices.tiles.get(v.devices.selected); if selected.map(|t| t.key.as_str()) != Some(key.as_str()) { let wants = selected.is_some_and(|t| matches!(&t.status, TileStatus::Connected(r) if r.onboard_profiles)); - if wants && v.devices.onboard.is_none() { + if wants && v.onboard().is_none() { v.load_onboard_profiles(cx); } cx.notify(); @@ -343,6 +392,7 @@ impl AppView { match result { Ok(Ok(list)) => { v.devices.onboard = Some(list); + v.devices.onboard_key = Some(key.clone()); if v.stage_seq == v.stage_sent { v.devices.stage_draft = None; } @@ -360,11 +410,14 @@ impl AppView { /// also puts the mouse in Onboard mode, which is the only mode that runs /// them). Neither writes flash. pub(super) fn onboard_action(&mut self, action: &'static str, value: serde_json::Value, cx: &mut Context) { + let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; + self.onboard_action_for(tile.key.clone(), action, value, cx); + } + + pub(super) fn onboard_action_for(&mut self, key: String, action: &'static str, value: serde_json::Value, cx: &mut Context) { if self.busy(cx) { return; } - let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; - let key = tile.key.clone(); self.devices.writing = Some(action.to_string()); self.devices.write_error = None; cx.notify(); @@ -458,7 +511,7 @@ impl AppView { let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; let (key, brand) = (tile.key.clone(), tile.brand.clone()); if self.devices.writing.is_some() { - self.queue(Queued::Control { key, id, value }); + self.queue(Queued::Control { key, id, value, rescue: false }); return; } // "Link left & right" is one preference for every device that has it. @@ -477,6 +530,11 @@ impl AppView { let result = service.write(&key, &brand, &format!("control:{id}"), value.clone()).await; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.writing = None; + if !matches!(result, Ok(Ok(_))) { + if let Some(entry) = v.text_controls.colours.get_mut(&format!("{key}/{id}")) { + entry.0.clear(); + } + } let mut expected = Vec::new(); match result { Ok(Ok(applied)) => { @@ -502,7 +560,8 @@ impl AppView { } } // A Logitech button: reflect it in the stored profile we hold. - if let Some(n) = id.strip_prefix("logi.button.primary.").and_then(|n| n.parse::().ok()) { + let ours = v.devices.onboard_key.as_deref() == Some(key.as_str()); + if let Some(n) = id.strip_prefix("logi.button.primary.").and_then(|n| n.parse::().ok()).filter(|_| ours) { if let Some(running) = v .devices .onboard @@ -603,6 +662,9 @@ impl AppView { let mut expected = Vec::new(); match result { Ok(Ok(applied)) => { + if action == "dpi" && !v.devices.queued.iter().any(|q| matches!(q, Queued::Setting { action: "dpi", .. })) { + v.devices.dpi_pending = None; + } v.patch_readout(&key, action, &applied, cx); if let Some(y) = requested_y { v.patch_dpi_y(&key, y); @@ -703,13 +765,15 @@ impl AppView { } let _ = view.update(cx, |v: &mut Self, cx| { v.devices.writing = None; - let s = &mut v.devices.staged; - if done.dpi.is_some() { s.dpi = None; } - if done.dpi_y.is_some() { s.dpi_y = None; } - if done.polling.is_some() { s.polling = None; } - if done.lod.is_some() { s.lod = None; } - if done.surface.is_some() { s.surface = None; } - if done.light != LightEdit::default() { s.light = LightEdit::default(); } + if v.selected_key().as_deref() == Some(key.as_str()) { + let s = &mut v.devices.staged; + if done.dpi.is_some() && s.dpi == done.dpi { s.dpi = None; } + if done.dpi_y.is_some() && s.dpi_y == done.dpi_y { s.dpi_y = None; } + if done.polling.is_some() && s.polling == done.polling { s.polling = None; } + if done.lod.is_some() && s.lod == done.lod { s.lod = None; } + if done.surface.is_some() && s.surface == done.surface { s.surface = None; } + if done.light != LightEdit::default() && s.light == done.light { s.light = LightEdit::default(); } + } match &failure { Some(error) => v.write_failed(&key, error, cx), None => v.saved("Changes", cx), @@ -886,9 +950,9 @@ impl AppView { "[device] hiding non-mouse interface {key}: {error}" )); v.devices.ignored_keys.insert(key.clone()); + let keep = v.selected_key(); v.devices.tiles.retain(|t| t.key != key); - v.devices.selected = - v.devices.selected.min(v.devices.tiles.len().saturating_sub(1)); + v.reselect(keep); if v.devices.open.as_deref() == Some(key.as_str()) { v.devices.open = None; } diff --git a/gpui/src/app/device_overview.rs b/gpui/src/app/device_overview.rs index 8d82f019..4ecad602 100644 --- a/gpui/src/app/device_overview.rs +++ b/gpui/src/app/device_overview.rs @@ -128,16 +128,27 @@ impl AppView { rows.push(div().child(self.render_control(picker, cx))); } else if let (Some(current), Some(c)) = (r.dpi.filter(|d| *d > 0.0), &r.controls) { let (min, max, step) = (c.dpi.min, c.dpi.max, c.dpi.step.max(1.0)); - let shown = staged.dpi.unwrap_or(current); + let options = c.dpi.options.clone(); + let shown = self.devices.dpi_pending.or(staged.dpi).unwrap_or(current); let cur_y = r.dpi_y.unwrap_or(current); let set = move |this: &mut Self, x: f64, cx: &mut Context| { let y = this.devices.unlinked_axes.then(|| this.devices.staged.dpi_y.unwrap_or(cur_y)); this.edit_dpi(x, y, cx); }; let nudge = |id: &'static str, label: &'static str, by: f64, cx: &mut Context| { + let options = options.clone(); Button::new(id).compact().label(label).on_click(cx.listener(move |this, _, _, cx| { - let from = this.devices.staged.dpi.unwrap_or(current); - set(this, (from + by).clamp(min, max), cx); + let from = this.devices.dpi_pending.or(this.devices.staged.dpi).unwrap_or(current); + let next = if by > 0.0 { + options.iter().copied().find(|o| *o > from).unwrap_or(from + by) + } else { + options.iter().rev().copied().find(|o| *o < from).unwrap_or(from + by) + } + .clamp(min, max); + if this.settings.instant_apply { + this.devices.dpi_pending = Some(next); + } + set(this, next, cx); })) }; let stepper = h_flex() diff --git a/gpui/src/app/device_page.rs b/gpui/src/app/device_page.rs index c7b5d5c9..fdedd93b 100644 --- a/gpui/src/app/device_page.rs +++ b/gpui/src/app/device_page.rs @@ -172,9 +172,12 @@ impl AppView { .any(|c| c.id.starts_with("perf.stage.x.")); let profile_stages = r.onboard_profiles_writable && r.mode.as_deref() == Some("Onboard") && self.editing_profile().is_none(); if profile_stages { - let running = self.devices.onboard.as_ref().and_then(|list| list.profiles.iter().find(|p| p.is_current && p.crc_valid)); - let note = if self.devices.onboard.is_none() || self.devices.onboard_loading { + let running = self.onboard().and_then(|list| list.profiles.iter().find(|p| p.is_current && p.crc_valid)); + let unread = self.onboard().is_none() && !self.devices.onboard_loading; + let note = if self.devices.onboard_loading { "Reading the profile's DPI stages…" + } else if unread { + "DPI stages haven't been read yet." } else { "The running profile has no DPI stages this app can edit. Pick or set up a profile on the Profiles tab." }; @@ -182,6 +185,13 @@ impl AppView { Some(stages) => col = col.child(stages), None => col = col.child(div().text_sm().text_color(muted).child(note)), } + if unread { + col = col.child( + Button::new("stages-read-again") + .label("Read DPI stages") + .on_click(cx.listener(|this, _, _, cx| this.load_onboard_profiles(cx))), + ); + } } if let (Some(current), Some(c), false) = (r.dpi.filter(|d| *d > 0.0), &r.controls, staged_dpi || profile_stages) { let unlinked = r.separate_axes && self.devices.unlinked_axes; @@ -442,7 +452,7 @@ impl AppView { // Logitech's stored profiles back both tabs; read them once. if has_profiles && matches!(tab, DeviceTab::Profiles | DeviceTab::Buttons | DeviceTab::Performance) - && this.devices.onboard.is_none() + && this.onboard().is_none() { this.load_onboard_profiles(cx); } diff --git a/gpui/src/app/device_state.rs b/gpui/src/app/device_state.rs index f893fe27..6498fa2d 100644 --- a/gpui/src/app/device_state.rs +++ b/gpui/src/app/device_state.rs @@ -20,9 +20,11 @@ pub(super) struct Devices { /// X and Y DPI edited separately (mice with separate axes); linked by default, /// since a single number on screen hides a differing Y. pub(super) unlinked_axes: bool, + pub(super) dpi_pending: Option, pub(super) tab: DeviceTab, /// Stored profiles of the open Logitech device, once read (on demand). pub(super) onboard: Option, + pub(super) onboard_key: Option, pub(super) onboard_loading: bool, /// The long-list control whose options are currently unfolded. pub(super) expanded: Option, @@ -42,6 +44,7 @@ pub(super) struct Devices { pub(super) queued: Vec, /// Writes made to each device, so only the latest one reads it back. pub(super) write_rounds: std::collections::HashMap, + pub(super) polling_written: std::collections::HashSet, pub(super) write_error: Option, } diff --git a/gpui/src/app/keyboard_panel.rs b/gpui/src/app/keyboard_panel.rs index 3fc86647..45e27616 100644 --- a/gpui/src/app/keyboard_panel.rs +++ b/gpui/src/app/keyboard_panel.rs @@ -94,6 +94,7 @@ impl KeyboardPanel { pub(super) fn drop_board(&mut self) { self.board = None; + self.busy = false; self.round += 1; } @@ -153,6 +154,11 @@ impl AppView { Err(_) => Err("device runtime stopped".to_string()), }; if let Err(error) = result { + if op == "setActuation" { + if let Some(layer) = v.keyboard.board.as_ref().map(|b| b.layer) { + v.load_layer(layer, cx); + } + } v.keyboard.error = Some(error); } cx.notify(); @@ -170,7 +176,7 @@ impl AppView { Ok(()) }); } - } else if self.keyboard.board.is_none() { + } else if self.keyboard.board.as_ref().is_none_or(|b| tab == DeviceTab::Actuation && b.layer != 0) { self.load_layer(0, cx); } } diff --git a/gpui/src/app/logitech_stages.rs b/gpui/src/app/logitech_stages.rs index a9eb05ab..c437646b 100644 --- a/gpui/src/app/logitech_stages.rs +++ b/gpui/src/app/logitech_stages.rs @@ -14,29 +14,40 @@ const MOST: usize = 5; #[derive(Clone, PartialEq)] pub(super) struct StageDraft { + key: String, sector: u32, stages: Vec, default: usize, } impl StageDraft { - fn from_profile(p: &OnboardProfile) -> Option { + fn from_profile(key: &str, p: &OnboardProfile) -> Option { let stages: Vec = p.dpi_stages.iter().filter(|s| s["x"].as_i64().is_some_and(|x| x > 0)).cloned().collect(); let default = (p.default_dpi_index.unwrap_or(0) as usize).min(stages.len().saturating_sub(1)); - (!stages.is_empty()).then_some(Self { sector: p.sector, stages, default }) + (!stages.is_empty()).then_some(Self { key: key.to_string(), sector: p.sector, stages, default }) } fn set_dpi(&mut self, index: usize, value: i64) { let Some(stage) = self.stages.get_mut(index) else { return }; let (Some(x), Some(y)) = (stage["x"].as_i64(), stage["y"].as_i64()) else { return }; - let next = value.clamp(100, 32_000); + let next = value.max(1); stage["x"] = json!(next); if y == x { stage["y"] = json!(next); } } + pub(super) fn set_lod(&mut self, lod: i64) { + for stage in &mut self.stages { + stage["lod"] = json!(lod); + } + } + + pub(super) fn set_default_dpi(&mut self, value: i64) { + self.set_dpi(self.default, value); + } + fn x(&self, index: usize) -> Option { self.stages.get(index).and_then(|s| s["x"].as_i64()) } @@ -91,16 +102,40 @@ impl AppView { if !r.onboard_profiles_writable || r.mode.as_deref() != Some("Onboard") || self.editing_profile().is_some() { return None; } - self.devices.onboard.as_ref()?.profiles.iter().find(|p| p.is_current && p.crc_valid) + self.onboard()?.profiles.iter().find(|p| p.is_current && p.crc_valid) } fn stage_draft_for(&self, profile: &OnboardProfile) -> Option { - let saved = StageDraft::from_profile(profile)?; - Some(self.devices.stage_draft.clone().filter(|d| d.sector == profile.sector).unwrap_or(saved)) + let key = &self.devices.tiles.get(self.devices.selected)?.key; + let saved = StageDraft::from_profile(key, profile)?; + Some(self.devices.stage_draft.clone().filter(|d| d.sector == profile.sector && &d.key == key).unwrap_or(saved)) + } + + fn stages_locked(&self, draft: &StageDraft) -> bool { + self.profile_overrides.iter().any(|o| o.device == draft.key) + } + + pub(super) fn flush_stages(&mut self, cx: &mut Context) { + if self.stage_seq == self.stage_sent { + return; + } + let Some(draft) = self.devices.stage_draft.clone() else { return }; + if self.stages_locked(&draft) { + return; + } + if self.devices.writing.is_some() { + self.show_toast("The mouse was busy, so your last DPI stage change wasn't saved.", true, cx); + return; + } + self.stage_sent = self.stage_seq; + self.onboard_action_for(draft.key, "stages", json!({ "stages": draft.stages, "defaultIndex": draft.default, "sector": draft.sector }), cx); } fn edit_stages(&mut self, draft: StageDraft, cx: &mut Context) { - self.devices.stage_draft = Some(draft.clone()); + if self.blocked_by_profile(cx) { + return; + } + self.devices.stage_draft = Some(draft); self.stage_seq += 1; let seq = self.stage_seq; cx.notify(); @@ -110,11 +145,15 @@ impl AppView { if this.stage_seq != seq { return; } + let Some(draft) = this.devices.stage_draft.clone() else { return }; + if this.stages_locked(&draft) { + return; + } if this.devices.writing.is_some() { this.edit_stages(draft, cx); } else { this.stage_sent = seq; - this.onboard_action("stages", json!({ "stages": draft.stages, "defaultIndex": draft.default, "sector": draft.sector }), cx); + this.onboard_action_for(draft.key, "stages", json!({ "stages": draft.stages, "defaultIndex": draft.default, "sector": draft.sector }), cx); } }); }) @@ -392,7 +431,7 @@ mod tests { "dpiStages": [{ "x": 400, "y": 400, "lod": 2 }, { "x": 800, "y": 900, "lod": 1 }, { "x": 0, "y": 0, "lod": 0 }], })) .unwrap(); - let mut draft = StageDraft::from_profile(&profile).unwrap(); + let mut draft = StageDraft::from_profile("k", &profile).unwrap(); assert_eq!((draft.stages.len(), draft.default), (2, 1), "unused slots are left out"); draft.set_dpi(0, 450); draft.set_dpi(1, 850); diff --git a/gpui/src/app/magnetic_panel.rs b/gpui/src/app/magnetic_panel.rs index 2ef360d7..fa74335c 100644 --- a/gpui/src/app/magnetic_panel.rs +++ b/gpui/src/app/magnetic_panel.rs @@ -122,7 +122,7 @@ impl AppView { } if let (Some(range), Some(point)) = (panel.trigger, shown.trigger_point) { - let values = self.magnetic_values(id("trigger"), range, Some(point), !optical, None, panel.brand == "Keychron", cx); + let values = self.magnetic_values(id("trigger"), range, Some(point), !optical, None, None, panel.brand == "Keychron", cx); let hint = format!("{}-{}", range.min, range.max); card = card.child(magnetic_row("Actuation point", Some(hint), values, cx)); } @@ -139,7 +139,7 @@ impl AppView { .child(self.value_chip(id("release"), "Separate", separate, json!(first), !optical, cx)), )); if separate { - control = control.child(self.magnetic_values(id("release"), range, shown.release_point, !optical, None, false, cx)); + control = control.child(self.magnetic_values(id("release"), range, shown.release_point, !optical, None, Some(9), false, cx)); } card = card.child(magnetic_row("Release point", None, control, cx)); } @@ -151,7 +151,7 @@ impl AppView { let switch = segmented(cx) .child(self.value_chip(id("rtOn"), "Off", !on, json!(false), !optical, cx)) .child(self.value_chip(id("rtOn"), "On", on, json!(true), available, cx)); - let values = self.magnetic_values(id("rt"), range, shown.rapid_trigger, available && on, Some(most), false, cx); + let values = self.magnetic_values(id("rt"), range, shown.rapid_trigger, available && on, Some(most), None, false, cx); let control = div().flex().flex_col().gap_2().child(h_flex().child(switch)).child(values); let hint = if most < range.min { "Lower the actuation point to use it".to_string() @@ -201,6 +201,7 @@ impl AppView { current: Option, enabled: bool, most: Option, + skip: Option, advice: bool, cx: &mut Context, ) -> Div { @@ -223,7 +224,7 @@ impl AppView { for value in range.min..=most.max(range.min) { let chosen = current == Some(value); numbers = numbers.child( - self.value_chip(id.clone(), &value.to_string(), chosen, json!(value), enabled && value <= most, cx) + self.value_chip(id.clone(), &value.to_string(), chosen, json!(value), enabled && value <= most && skip != Some(value), cx) .flex_1() .flex() .justify_center() diff --git a/gpui/src/app/plugins_page.rs b/gpui/src/app/plugins_page.rs index f0ef68e2..3e16ec5e 100644 --- a/gpui/src/app/plugins_page.rs +++ b/gpui/src/app/plugins_page.rs @@ -809,7 +809,18 @@ impl AppView { let local_only: Vec<&crate::marketplace::InstalledTheme> = self .installed_themes .iter() - .filter(|t| !self.marketplace_catalog.themes.iter().any(|c| c.id == t.theme.id)) + .filter(|t| { + let own = self + .settings + .marketplace_session + .as_ref() + .is_some_and(|s| s.username == t.theme.author); + own || !self + .marketplace_catalog + .themes + .iter() + .any(|c| c.id == t.theme.id && c.author == t.theme.author) + }) .collect(); if !local_only.is_empty() { let mut local_grid = h_flex().flex_wrap().gap_4().items_stretch(); diff --git a/gpui/src/app/profile_ui.rs b/gpui/src/app/profile_ui.rs index e7e8e3e8..4804dbdf 100644 --- a/gpui/src/app/profile_ui.rs +++ b/gpui/src/app/profile_ui.rs @@ -98,13 +98,11 @@ fn tile_with_profile(tile: &Tile, profile: &crate::profiles::GameProfile) -> Til copy } -/// While a game's profile is in control: what to put back when it closes. pub(super) struct ProfileOverride { pub(super) game_id: String, pub(super) game_name: String, /// The device the profile was applied to (and will be restored on). pub(super) device: String, - pub(super) restore: crate::profiles::GameProfile, } impl AppView { @@ -227,6 +225,10 @@ impl AppView { /// device connects - a device that shows up after the game launched is /// picked up here too. pub(super) fn sync_running_profiles(&mut self, cx: &mut Context) { + self.sync_profiles(None, cx); + } + + fn sync_profiles(&mut self, closed: Option<&str>, cx: &mut Context) { let running: Vec = self.games.iter().filter(|g| g.running).map(|g| g.id.clone()).collect(); let devices: Vec = self.connected_devices().into_iter().map(|(k, _)| k).collect(); for game in running { @@ -237,31 +239,78 @@ impl AppView { } let pair = (game.clone(), device.clone()); let taken = self.profile_overrides.iter().any(|o| o.game_id == game && &o.device == device); - if taken || self.profile_inflight.contains(&pair) { + if taken || self.profile_inflight.contains(&pair) || self.profile_inflight.contains(&(String::new(), device.clone())) { continue; } self.apply_profile(&game, device, profile, true, cx); } } + let restores = crate::profiles::restores(); + for device in devices { + let Some(restore) = restores.get(&device) else { continue }; + if self.profile_overrides.iter().any(|o| o.device == device) || self.profile_inflight.iter().any(|(_, d)| d == &device) { + continue; + } + if !restore.is_meaningful() { + crate::profiles::set_restore(&device, None); + continue; + } + let described = restore.describe(); + let text = match closed { + Some(name) => format!("{name} closed - restored your default {described}."), + None => format!("Restored your default {described}."), + }; + self.profile_inflight.push((String::new(), device.clone())); + self.apply_profile_inner("", closed.unwrap_or("default"), &device, restore.clone(), None, Some(text), true, cx); + } } /// The game closed: put back what each of its profiles replaced. pub(super) fn on_game_closed(&mut self, id: &str, cx: &mut Context) { - let (closing, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut self.profile_overrides).into_iter().partition(|o| o.game_id == id); - self.profile_overrides = keep; - for active in closing { - if !active.restore.is_meaningful() { - continue; - } - let (name, described) = (active.game_name.clone(), active.restore.describe()); - let text = format!("{name} closed - restored your default {described}."); - self.apply_profile_inner(id, &name, &active.device, active.restore, None, Some(text), true, cx); - } + self.profile_overrides.retain(|o| o.game_id != id); + let name = self.game_name(id); + self.sync_profiles(Some(&name), cx); } /// Pushes a profile to one connected device. `auto` marks a launch-triggered /// apply, which remembers the pre-game settings to restore on close. pub(super) fn apply_profile(&mut self, game_id: &str, device: &str, profile: crate::profiles::GameProfile, auto: bool, cx: &mut Context) { + let wants_buttons = auto + && profile.controls.keys().any(|id| id.starts_with(ONBOARD_BUTTON)); + if !wants_buttons { + return self.apply_profile_with(game_id, device, profile, auto, None, cx); + } + let selected = self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.key == device); + if let Some(list) = self.onboard().filter(|_| selected) { + let buttons = onboard_buttons(list); + return self.apply_profile_with(game_id, device, profile, auto, Some(buttons), cx); + } + let pair = (game_id.to_string(), device.to_string()); + self.profile_inflight.push(pair.clone()); + let read = self.hid_service().onboard_profiles(device); + let (game_id, device) = pair.clone(); + cx.spawn(async move |view, cx| { + let buttons = read.await.ok().and_then(Result::ok).map(|list| onboard_buttons(&list)); + let _ = view.update(cx, |v: &mut Self, cx| { + v.profile_inflight.retain(|p| p != &pair); + if !v.games.iter().any(|g| g.id == game_id && g.running) { + return; + } + v.apply_profile_with(&game_id, &device, profile, auto, buttons, cx); + }); + }) + .detach(); + } + + fn apply_profile_with( + &mut self, + game_id: &str, + device: &str, + profile: crate::profiles::GameProfile, + auto: bool, + buttons: Option>, + cx: &mut Context, + ) { let Some(r) = self.connected_devices().into_iter().find(|(k, _)| k == device).map(|(_, r)| r) else { self.announce("Connect this device to apply a profile.".into(), true, auto, cx); return; @@ -269,58 +318,64 @@ impl AppView { let name = self.game_name(game_id); let described = profile.describe(); let override_ = if auto { - // The first game to take over a device defines its "default"; a - // second game taking over from a running one only changes who is in - // control. - let restore = match self.profile_overrides.iter().find(|o| o.device == device) { - Some(active) => active.restore.clone(), - None => { - let mut controls = std::collections::BTreeMap::new(); - for id in profile.controls.keys() { - if let Some(spec) = r.tabs.controls().find(|c| &c.id == id) { - if !spec.current.is_null() { - controls.insert(id.clone(), spec.current.clone()); - } - } else if let (Some(rest), Some(mag)) = (id.strip_prefix("mag."), &r.tabs.magnetic) { - if let Some((field, target)) = rest.split_once('.') { - let indices: Vec = match target { - "both" => (0..mag.buttons.len()).collect(), - other => other.parse::().ok().filter(|&i| i < mag.buttons.len()).into_iter().collect(), + let snapshot = { + let mut controls = std::collections::BTreeMap::new(); + for id in profile.controls.keys() { + if let Some(spec) = r.tabs.controls().find(|c| &c.id == id) { + if !spec.current.is_null() { + controls.insert(id.clone(), spec.current.clone()); + } + } else if let (Some(rest), Some(mag)) = (id.strip_prefix("mag."), &r.tabs.magnetic) { + if let Some((field, target)) = rest.split_once('.') { + let indices: Vec = match target { + "both" => (0..mag.buttons.len()).collect(), + other => other.parse::().ok().filter(|&i| i < mag.buttons.len()).into_iter().collect(), + }; + for i in indices { + let b = &mag.buttons[i]; + let val = match field { + "switch" => b.switch_type.as_ref().map(|s| serde_json::json!(s)), + "trigger" => b.trigger_point.map(|v| serde_json::json!(v)), + "release" => Some(b.release_point.map_or(serde_json::Value::Null, |v| serde_json::json!(v))), + "rtOn" => Some(serde_json::json!(b.rapid_trigger_enabled)), + "rt" => b.rapid_trigger.map(|v| serde_json::json!(v)), + _ => None, }; - for i in indices { - let b = &mag.buttons[i]; - let val = match field { - "switch" => b.switch_type.as_ref().map(|s| serde_json::json!(s)), - "trigger" => b.trigger_point.map(|v| serde_json::json!(v)), - "release" => Some(b.release_point.map_or(serde_json::Value::Null, |v| serde_json::json!(v))), - "rtOn" => Some(serde_json::json!(b.rapid_trigger_enabled)), - "rt" => b.rapid_trigger.map(|v| serde_json::json!(v)), - _ => None, - }; - if let Some(v) = val { - controls.insert(format!("mag.{field}.{i}"), v); - } + if let Some(v) = val { + controls.insert(format!("mag.{field}.{i}"), v); } } } } - let lighting = profile - .lighting - .as_ref() - .and_then(|_| r.tabs.lighting.as_ref().and_then(snapshot_lighting)); - crate::profiles::GameProfile { - dpi: profile.dpi.and(r.dpi), - dpi_y: profile.dpi_y.and(r.dpi_y.or(r.dpi)), - polling: profile.polling.and(r.polling_hz.map(|hz| hz as u32)), - lod: profile.lod.as_ref().and(r.lod.clone()), - surface: profile.surface.as_ref().and(r.surface.clone()), - controls, - lighting, - auto_apply: false, + } + for (id, action) in buttons.into_iter().flatten() { + if profile.controls.contains_key(&id) { + controls.entry(id).or_insert(action); } } + let lighting = profile + .lighting + .as_ref() + .and_then(|_| r.tabs.lighting.as_ref().and_then(snapshot_lighting)); + crate::profiles::GameProfile { + dpi: profile.dpi.and(r.dpi), + dpi_y: profile.dpi_y.and(r.dpi_y.or(r.dpi)), + polling: profile.polling.and(r.polling_hz.map(|hz| hz as u32)), + lod: profile.lod.as_ref().and(r.lod.clone()), + surface: profile.surface.as_ref().and(r.surface.clone()), + controls, + lighting, + auto_apply: false, + } + }; + let restore = match crate::profiles::restores().remove(device) { + Some(saved) => saved.or(&snapshot), + None => snapshot, }; - Some(ProfileOverride { game_id: game_id.to_string(), game_name: name.clone(), device: device.to_string(), restore }) + if restore.is_meaningful() { + crate::profiles::set_restore(device, Some(restore)); + } + Some(ProfileOverride { game_id: game_id.to_string(), game_name: name.clone(), device: device.to_string() }) } else { None }; @@ -347,6 +402,10 @@ impl AppView { let result = service.apply_profile(&key, profile.to_js()).await; let _ = view.update(cx, |v: &mut Self, cx| { v.profile_inflight.retain(|(g, d)| !(g == &game_id && d == &key)); + let restoring = game_id.is_empty(); + let running = v.games.iter().any(|g| g.id == game_id && g.running); + let orphaned = override_.is_some() && !running; + let restored = restoring && matches!(result, Ok(Ok(_))); match result { Ok(Ok(applied)) => { for (field, action) in [ @@ -360,9 +419,12 @@ impl AppView { } } // Only take over once the write is confirmed to have landed. - if let Some(o) = override_ { + if let Some(o) = override_.filter(|_| running) { v.profile_overrides.push(o); } + if restoring { + crate::profiles::set_restore(&key, None); + } if let Some(text) = success { v.announce(text, false, overlay, cx); } @@ -379,6 +441,9 @@ impl AppView { } } v.read_back(&key, Vec::new(), cx); + if orphaned || restored { + v.sync_running_profiles(cx); + } }); }) .detach(); @@ -388,7 +453,8 @@ impl AppView { pub(super) fn edit_profile(&mut self, game_id: &str, device: &str, change: impl FnOnce(&mut crate::profiles::GameProfile), cx: &mut Context) { let mut profile = self.profile_for(game_id, device).unwrap_or_default(); change(&mut profile); - self.profiles.set(game_id, device, profile); + let heir = self.legacy_heir().as_deref() == Some(device); + self.profiles.set(game_id, device, profile, heir); self.profiles.save(); cx.notify(); } @@ -642,3 +708,15 @@ impl AppView { .into_any_element() } } + +const ONBOARD_BUTTON: &str = "logi.button.primary."; + +fn onboard_buttons(list: &crate::hid::OnboardProfiles) -> std::collections::BTreeMap { + let Some(running) = list.profiles.iter().find(|p| p.is_current) else { return Default::default() }; + running + .button_assignments + .iter() + .enumerate() + .filter_map(|(n, a)| a.get("action").and_then(|v| v.as_str()).filter(|a| *a != "Custom").map(|a| (format!("{ONBOARD_BUTTON}{n}"), serde_json::json!(a)))) + .collect() +} diff --git a/gpui/src/app/safety.rs b/gpui/src/app/safety.rs index 5083e8dd..ff3284bd 100644 --- a/gpui/src/app/safety.rs +++ b/gpui/src/app/safety.rs @@ -31,14 +31,13 @@ pub(super) struct Confirm { /// replaces it. pub(super) enum Queued { Setting { key: String, action: &'static str, value: Value }, - Control { key: String, id: String, value: Value }, + Control { key: String, id: String, value: Value, rescue: bool }, Apply { key: String }, } impl Queued { pub(super) fn is_rescue(&self) -> bool { - matches!(self, Queued::Control { id, value, .. } - if (id == "logi.button.primary.0" && value.as_str() == Some("Left click")) || (id == "logi.remap.80" && value.as_i64() == Some(80))) + matches!(self, Queued::Control { rescue: true, .. }) } fn target(&self) -> (&str, &str) { @@ -73,7 +72,12 @@ impl AppView { let target = self.devices.tiles.iter().position(|t| t.key == edit.target().0 && matches!(t.status, TileStatus::Connected(_))); if let (true, Some(index)) = (rescue, target) { if index != self.devices.selected { - self.devices.selected = index; + let key = edit.target().0.to_string(); + if self.devices.open.is_some() { + self.open_device(&key, cx); + } else { + self.devices.selected = index; + } self.show_toast("Restoring the left click on the mouse the shortcut was pressed for.", false, cx); } } @@ -150,8 +154,9 @@ impl AppView { /// Shows a failed write on the device's page, or as a message if the user /// has moved elsewhere. pub(super) fn write_failed(&mut self, key: &str, error: &str, cx: &mut Context) { + self.devices.dpi_pending = None; // Later edits were made expecting this one; writing them could mislead. - self.devices.queued.clear(); + self.devices.queued.retain(Queued::is_rescue); let problem = write_safety::problem(error); let on_its_page = self.page == Page::Overview && self.devices.open.as_deref() == Some(key); if on_its_page { @@ -181,6 +186,9 @@ impl AppView { if key.starts_with("mock:") { return; } + if expected.iter().any(|e| e.action == "pollingRate") { + self.devices.polling_written.insert(key.to_string()); + } let round = { let round = self.devices.write_rounds.entry(key.to_string()).or_default(); *round += 1; @@ -246,7 +254,8 @@ impl AppView { let mut new = DeviceReadout::from_status(&device.status, device.controls.clone(), device.tabs.unwrap_or_default()); // A Logitech mouse answers with the old polling rate just after a live // change (see `patch_readout`): keep the confirmed one. - let stale_polling = tile.brand == "Logitech" && expected.iter().any(|e| e.action == "pollingRate"); + let polling_written = self.devices.polling_written.remove(key); + let stale_polling = tile.brand == "Logitech" && polling_written; if stale_polling { new.polling_hz = old.polling_hz; } diff --git a/gpui/src/app/settings_page.rs b/gpui/src/app/settings_page.rs index 0bcbcf7f..2f660848 100644 --- a/gpui/src/app/settings_page.rs +++ b/gpui/src/app/settings_page.rs @@ -117,6 +117,15 @@ impl AppView { this.set_launch_on_startup(*enabled); } else if switch_id == "auto-updates-switch" { this.settings.auto_check_updates = *enabled; + if *enabled { + cx.spawn(async move |view, cx| { + let info = cx.background_executor().spawn(async { crate::update_check::fetch_latest() }).await; + if let Some(info) = info { + let _ = view.update(cx, |view, cx| view.note_update_available(info, cx)); + } + }) + .detach(); + } } else if switch_id == "discord-device" { this.settings.discord_show_device = *enabled; this.refresh_presence(cx); @@ -170,8 +179,9 @@ impl AppView { this.check_low_battery_alerts(cx); } else if switch_id == "instant-apply-switch" { this.settings.instant_apply = *enabled; - // Nothing may stay staged once edits stop being staged. - this.devices.staged = Staged::default(); + if *enabled { + this.apply_staged(cx); + } } else { this.settings.discord_presence = *enabled; this.set_discord(*enabled, cx); diff --git a/gpui/src/app/theme_studio.rs b/gpui/src/app/theme_studio.rs index b4a45cf9..4ff60a8f 100644 --- a/gpui/src/app/theme_studio.rs +++ b/gpui/src/app/theme_studio.rs @@ -190,6 +190,16 @@ impl ThemeStudio { let desc = self.description.read(cx).value().trim().to_string(); let id = self.editing_id.clone().unwrap_or_else(|| sanitize_id(&name)); + let raw = self.css_editor.read(cx).value().to_string(); + let version = crate::marketplace::parse_metadata_comments(&raw) + .remove("version") + .unwrap_or_else(|| "1.0.0".to_string()); + let mut extras: Vec<(String, String)> = crate::marketplace::parse_css_variables(&raw) + .into_iter() + .filter(|(k, _)| !COLOR_SLOTS.iter().any(|(var, _, _)| var == k)) + .collect(); + extras.sort(); + let values: Vec = self .colors .iter() @@ -199,8 +209,9 @@ impl ThemeStudio { .iter() .zip(values.iter()) .map(|((var, _, _), val)| (*var, val.as_str())) + .chain(extras.iter().map(|(k, v)| (k.as_str(), v.as_str()))) .collect(); - let css = build_theme_css(&name, &author, "1.0.0", &desc, self.is_light, &pairs); + let css = build_theme_css(&name, &author, &version, &desc, self.is_light, &pairs); (id, css) } @@ -397,7 +408,17 @@ impl AppView { fn save_studio_theme(&mut self, also_upload: bool, window: &mut Window, cx: &mut Context) { let Some(studio) = &self.theme_studio else { return }; - let (id, css) = studio.current_css(cx); + let (mut id, css) = studio.current_css(cx); + if studio.editing_id.is_none() { + if let Some(dir) = crate::marketplace::themes_dir() { + let base = id.clone(); + let mut n = 2; + while dir.join(format!("{id}.css")).exists() { + id = format!("{base}-{n}"); + n += 1; + } + } + } let missing = crate::marketplace::missing_theme_fields(&css); if !missing.is_empty() { self.show_toast( diff --git a/gpui/src/app/updates.rs b/gpui/src/app/updates.rs index c9f33a88..11533bc8 100644 --- a/gpui/src/app/updates.rs +++ b/gpui/src/app/updates.rs @@ -202,6 +202,11 @@ impl AppView { } let should_toast = is_new && self.settings.last_notified_update_version.as_deref() != Some(info.version.as_str()); + if matches!(self.update_state, UpdateState::Failed(_)) + && self.update_available.as_ref().map(|u| u.version.as_str()) != Some(info.version.as_str()) + { + self.update_state = UpdateState::Idle; + } self.update_available = is_new.then(|| info.clone()); if should_toast { self.settings.last_notified_update_version = Some(info.version.clone()); diff --git a/gpui/src/app/usb_map_page.rs b/gpui/src/app/usb_map_page.rs index 2cb9deab..3777d293 100644 --- a/gpui/src/app/usb_map_page.rs +++ b/gpui/src/app/usb_map_page.rs @@ -25,6 +25,7 @@ pub(super) struct UsbMapState { pub topology: Option, pub advice: Option, pub scanning: bool, + pub rescan_pending: bool, pub show_empty_ports: bool, pub selected: Option, pub scan_seq: u64, @@ -176,9 +177,11 @@ impl AppView { /// Scans USB & PCIe topology off the UI thread and updates `self.usb_map`. pub(super) fn scan_usb_topology(&mut self, cx: &mut Context) { if self.usb_map.scanning { + self.usb_map.rescan_pending = true; return; } self.usb_map.scanning = true; + self.usb_map.rescan_pending = false; cx.notify(); let mut supported: SupportedDeviceMap = HashMap::new(); @@ -226,6 +229,9 @@ impl AppView { v.usb_map.recently_changed = changed; v.usb_map.scan_seq = v.usb_map.scan_seq.wrapping_add(1); v.usb_map.scanning = false; + if v.usb_map.rescan_pending { + v.scan_usb_topology(cx); + } cx.notify(); }); }) diff --git a/gpui/src/audio.rs b/gpui/src/audio.rs index e2fb30b9..bc99b843 100644 --- a/gpui/src/audio.rs +++ b/gpui/src/audio.rs @@ -188,19 +188,37 @@ mod other { } } // PulseAudio/PipeWire first, then ALSA; whichever exists plays it. - for player in [("paplay", vec![]), ("aplay", vec!["-q"])] { - let mut command = std::process::Command::new(player.0); - command - .args(&player.1) - .arg(&path) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()); - if crate::proc::quiet(&mut command).spawn().is_ok() { - return true; + let aplay = |path: &std::path::Path| spawn("aplay", &["-q"], path); + match spawn("paplay", &[], &path) { + Ok(mut child) => { + std::thread::spawn(move || { + if !child.wait().is_ok_and(|status| status.success()) { + if let Ok(mut child) = aplay(&path) { + let _ = child.wait(); + } + } + }); + true } + Err(_) => match aplay(&path) { + Ok(mut child) => { + std::thread::spawn(move || child.wait()); + true + } + Err(_) => false, + }, } - false + } + + fn spawn(player: &str, args: &[&str], path: &std::path::Path) -> std::io::Result { + let mut command = std::process::Command::new(player); + command + .args(args) + .arg(path) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + crate::proc::quiet(&mut command).spawn() } } diff --git a/gpui/src/autostart.rs b/gpui/src/autostart.rs index 601f4ece..2236ad44 100644 --- a/gpui/src/autostart.rs +++ b/gpui/src/autostart.rs @@ -16,7 +16,27 @@ pub const ARG: &str = "--autostart"; const NAME: &str = "OpenMouse Desktop"; fn exe() -> Result { - std::env::current_exe().map_err(|e| format!("could not locate the app: {e}")) + let exe = std::env::current_exe().map_err(|e| format!("could not locate the app: {e}"))?; + if is_temporary(&exe) { + return Err("Move OpenMouse to Applications first, then turn this on.".to_string()); + } + Ok(exe) +} + +fn is_temporary(exe: &std::path::Path) -> bool { + cfg!(target_os = "macos") && { + let path = exe.to_string_lossy(); + let mut parts = path.split('/').skip(1); + let on_disk_image = parts.next() == Some("Volumes") + && parts.nth(1).is_some_and(|bundle| bundle.ends_with(".app")); + on_disk_image || path.contains("/AppTranslocation/") + } +} + +pub fn refresh() { + if is_enabled() && exe().is_ok() { + let _ = enable(); + } } #[cfg(target_os = "macos")] diff --git a/gpui/src/bin/main.rs b/gpui/src/bin/main.rs index c7b8babe..559eae3f 100644 --- a/gpui/src/bin/main.rs +++ b/gpui/src/bin/main.rs @@ -222,6 +222,8 @@ fn open_main_window( // skips its own controls, so the fallback stays correct. #[cfg(target_os = "linux")] window_decorations: Some(WindowDecorations::Client), + #[cfg(not(target_os = "linux"))] + focus: !openmouse_gpui::autostart::launched_by_os(), ..TitleBar::window_options() }; diff --git a/gpui/src/game_watcher.rs b/gpui/src/game_watcher.rs index 8233dc56..992562bd 100644 --- a/gpui/src/game_watcher.rs +++ b/gpui/src/game_watcher.rs @@ -11,10 +11,7 @@ use sysinfo::{ProcessRefreshKind, ProcessStatus, ProcessesToUpdate, System, Upda const PROCESS_INTERVAL: Duration = Duration::from_secs(2); const INSTALL_INTERVAL: Duration = Duration::from_secs(10); -// While the window is not active the scans slow down rather than stop: a game -// can still launch behind the window and its profile should still apply, just -// a few seconds later. Coming back to the window rescans straight away. -const PROCESS_INTERVAL_INACTIVE: Duration = Duration::from_secs(10); +const PROCESS_INTERVAL_INACTIVE: Duration = Duration::from_secs(2); const INSTALL_INTERVAL_INACTIVE: Duration = Duration::from_secs(60); /// Dropping the view drops these tasks, including any awaited background task. diff --git a/gpui/src/games/install_scan.rs b/gpui/src/games/install_scan.rs index 61a1a7c8..fc8257b2 100644 --- a/gpui/src/games/install_scan.rs +++ b/gpui/src/games/install_scan.rs @@ -207,7 +207,11 @@ fn scan_steam(roots: &[PathBuf], ids: &mut HashSet) { if let Some(flags) = state.text("stateflags") { // Steam EAppStateFullyInstalled (4); incomplete downloads must // not become installed simply because they created a folder. - if !flags.parse::().is_ok_and(|flags| flags & 4 != 0) { + let updating = state.map("installeddepots").is_some_and(|depots| !depots.0.is_empty()); + if !flags + .parse::() + .is_ok_and(|flags| flags & 4 != 0 || (updating && flags & 1 == 0 && flags & 0x702 != 0)) + { continue; } } diff --git a/gpui/src/hid.rs b/gpui/src/hid.rs index 490135b4..d01c6c7f 100644 --- a/gpui/src/hid.rs +++ b/gpui/src/hid.rs @@ -265,6 +265,8 @@ pub struct DpiBounds { pub min: f64, pub max: f64, pub step: f64, + #[serde(default)] + pub options: Vec, } /// What the device page may offer, resolved by the shared JS (per-product DPI @@ -1053,12 +1055,18 @@ fn via_definition(vendor_id: u16, product_id: u16) -> Result, Str .stderr(std::process::Stdio::null()), ) .output(); - let Ok(output) = output.map_err(|_| ()).and_then(|o| if o.status.success() { Ok(o) } else { Err(()) }) else { + let Ok(output) = output else { continue; }; + if output.status.code() == Some(22) { + reached = true; + } + if !output.status.success() { + continue; + } reached = true; let text = String::from_utf8_lossy(&output.stdout).into_owned(); - if text.trim_start().starts_with('{') { + if serde_json::from_str::(&text).is_ok_and(|v| v.is_object()) { if let Some(cache) = &cache { let _ = cache.parent().map(std::fs::create_dir_all); let _ = std::fs::write(cache, &text); diff --git a/gpui/src/marketplace.rs b/gpui/src/marketplace.rs index 6ad68469..4b783151 100644 --- a/gpui/src/marketplace.rs +++ b/gpui/src/marketplace.rs @@ -56,6 +56,7 @@ pub struct MarketplaceSession { /// Maximum accepted `.css` theme file size (256 KiB). const MAX_THEME_BYTES: usize = 256 * 1024; +const MAX_CATALOG_BYTES: usize = 8 * 1024 * 1024; /// Parsed CSS theme ready to paint onto the live GPUI [`Theme`](gpui_kit::component::Theme). #[derive(Debug, Clone)] @@ -288,7 +289,7 @@ fn title_case_id(id: &str) -> String { } /// Extracts `@key: value` pairs from `/* ... */` block comments. -fn parse_metadata_comments(css: &str) -> HashMap { +pub(crate) fn parse_metadata_comments(css: &str) -> HashMap { let mut map = HashMap::new(); let mut rest = css; while let Some(start) = rest.find("/*") { @@ -313,7 +314,7 @@ fn parse_metadata_comments(css: &str) -> HashMap { } /// Strips `/* ... */` comments and extracts `--name: value;` declarations. -fn parse_css_variables(css: &str) -> HashMap { +pub(crate) fn parse_css_variables(css: &str) -> HashMap { let mut stripped = String::with_capacity(css.len()); let mut rest = css; while let Some(start) = rest.find("/*") { @@ -389,6 +390,9 @@ pub fn build_theme_css( pub fn parse_css_color(raw: &str) -> Option { let s = raw.trim(); if let Some(hex) = s.strip_prefix('#') { + if !hex.is_ascii() { + return None; + } let (r, g, b, a) = match hex.len() { 3 => { let r = u8::from_str_radix(&hex[0..1], 16).ok()? * 17; @@ -647,6 +651,7 @@ pub fn sign_in_with_discord() -> Result { while Instant::now() < deadline { match listener.accept() { Ok((mut stream, _)) => { + let _ = stream.set_nonblocking(false); let _ = stream.set_read_timeout(Some(Duration::from_secs(5))); let mut buf = [0u8; 4096]; let n = stream.read(&mut buf).unwrap_or(0); @@ -670,15 +675,18 @@ pub fn sign_in_with_discord() -> Result { } } } + if got_nonce.as_deref() != Some(nonce.as_str()) { + let _ = stream.write_all( + b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ); + continue; + } let ok_html = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nConnection: close\r\n\r\n\ \

Signed in to OpenMouse Desktop

You can close this tab and return to the app.

"; let _ = stream.write_all(ok_html.as_bytes()); let _ = stream.flush(); - if got_nonce.as_deref() != Some(nonce.as_str()) { - return Err("Login state mismatch; please try again.".to_string()); - } if let (Some(token), Some(username), Some(user_id)) = (token, user, uid) { if !token.is_empty() && !username.is_empty() { return Ok(MarketplaceSession { user_id, username, token }); @@ -763,7 +771,12 @@ pub fn submit_theme(installed: &InstalledTheme, session_token: &str) -> Result Result Result Result { .css_url .as_deref() .ok_or_else(|| "Theme has no download URL.".to_string())?; - curl_get(url) + curl_get(url, MAX_THEME_BYTES) } /// Loads the Marketplace catalog: tries the remote index (`OPENMOUSE_MARKETPLACE_URL` @@ -839,10 +850,11 @@ pub fn fetch_theme_css(entry: &MarketplaceTheme) -> Result { pub fn fetch_catalog() -> MarketplaceCatalog { let mut catalog = bundled_catalog(); let url = std::env::var("OPENMOUSE_MARKETPLACE_URL").unwrap_or_else(|_| DEFAULT_CATALOG_URL.to_string()); - if let Ok(body) = curl_get(&url) { + if let Ok(body) = curl_get(&url, MAX_CATALOG_BYTES) { if let Ok(remote) = serde_json::from_str::(&body) { // Remote entries win on matching id; append any new community themes. - for item in remote.themes { + for mut item in remote.themes { + item.id = sanitize_id(&item.id); if let Some(existing) = catalog.themes.iter_mut().find(|t| t.id == item.id) { *existing = item; } else { @@ -855,7 +867,7 @@ pub fn fetch_catalog() -> MarketplaceCatalog { catalog } -fn curl_get(url: &str) -> Result { +fn curl_get(url: &str, max_bytes: usize) -> Result { let mut cmd = std::process::Command::new("curl"); #[cfg(windows)] { @@ -863,14 +875,14 @@ fn curl_get(url: &str) -> Result { cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW } let output = cmd - .args(["-fsSL", "--max-time", "10", url]) + .args(["-fsSL", "--max-time", "10", "--max-filesize", &max_bytes.to_string(), url]) .output() .map_err(|e| format!("Network request failed: {e}"))?; if !output.status.success() { return Err(format!("Server returned status {}", output.status)); } - if output.stdout.len() > MAX_THEME_BYTES { - return Err("Downloaded file exceeded 256 KB limit.".to_string()); + if output.stdout.len() > max_bytes { + return Err(format!("Downloaded file exceeded {} KB limit.", max_bytes / 1024)); } String::from_utf8(output.stdout).map_err(|_| "Downloaded file is not valid UTF-8.".to_string()) } diff --git a/gpui/src/native_window.rs b/gpui/src/native_window.rs index 76b12e69..35a76edb 100644 --- a/gpui/src/native_window.rs +++ b/gpui/src/native_window.rs @@ -184,6 +184,8 @@ pub fn configure_overlay(width: f64, height: f64, corner: OverlayCorner, margin: // canJoinAllSpaces | stationary | ignoresCycle | fullScreenAuxiliary let behavior: usize = (1 << 0) | (1 << 4) | (1 << 6) | (1 << 8); let _: () = msg_send![window, setCollectionBehavior: behavior]; + let _: () = msg_send![window, setCanHide: objc::runtime::NO]; + let _: () = msg_send![window, orderFrontRegardless]; return; } } diff --git a/gpui/src/profiles.rs b/gpui/src/profiles.rs index df13ff9d..a8673d16 100644 --- a/gpui/src/profiles.rs +++ b/gpui/src/profiles.rs @@ -153,22 +153,55 @@ fn path() -> Option { dirs::config_dir().map(|dir| dir.join("openmouse").join("game-profiles.json")) } +fn restores_path() -> Option { + dirs::config_dir().map(|dir| dir.join("openmouse").join("game-restores.json")) +} + +fn save_json(path: Option, value: &impl Serialize) { + let Some(path) = path else { return }; + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + if let Ok(text) = serde_json::to_string_pretty(value) { + let _ = crate::settings::write_atomic(&path, &text); + } +} + +pub fn restores() -> BTreeMap { + restores_path().and_then(|p| crate::settings::read_json(&p)).unwrap_or_default() +} + +pub fn set_restore(device: &str, restore: Option) { + let mut all = restores(); + match restore { + Some(r) => all.insert(device.to_string(), r), + None => all.remove(device), + }; + save_json(restores_path(), &all); +} + +impl GameProfile { + pub fn or(mut self, other: &GameProfile) -> GameProfile { + self.dpi = self.dpi.or(other.dpi); + self.dpi_y = self.dpi_y.or(other.dpi_y); + self.polling = self.polling.or(other.polling); + self.lod = self.lod.or_else(|| other.lod.clone()); + self.surface = self.surface.or_else(|| other.surface.clone()); + for (id, value) in &other.controls { + self.controls.entry(id.clone()).or_insert_with(|| value.clone()); + } + self.lighting = self.lighting.or_else(|| other.lighting.clone()); + self + } +} + impl Profiles { pub fn load() -> Self { - path() - .and_then(|p| std::fs::read_to_string(p).ok()) - .and_then(|text| serde_json::from_str(&text).ok()) - .unwrap_or_default() + path().and_then(|p| crate::settings::read_json(&p)).unwrap_or_default() } pub fn save(&self) { - let Some(path) = path() else { return }; - if let Some(parent) = path.parent() { - let _ = std::fs::create_dir_all(parent); - } - if let Ok(text) = serde_json::to_string_pretty(self) { - let _ = std::fs::write(path, text); - } + save_json(path(), self); } /// This device's own profile for the game, if it has one. @@ -198,12 +231,13 @@ impl Profiles { } /// Stores `profile` for the device, or drops it when it no longer does - /// anything. A legacy profile is superseded once the game has a device one. - pub fn set(&mut self, game_id: &str, device: &str, profile: GameProfile) { + pub fn set(&mut self, game_id: &str, device: &str, profile: GameProfile, inherits_legacy: bool) { if profile.is_meaningful() || profile.auto_apply { let per = self.0.entry(game_id.to_string()).or_default(); per.insert(device.to_string(), profile); - per.remove(ANY_DEVICE); + if inherits_legacy { + per.remove(ANY_DEVICE); + } } else { self.clear(game_id, device); } @@ -251,8 +285,8 @@ mod tests { #[test] fn profiles_are_per_device() { let mut ps = Profiles::default(); - ps.set("cs2", "046d:c54d", dpi(400.0)); - ps.set("cs2", "31e3:1322", dpi(1600.0)); + ps.set("cs2", "046d:c54d", dpi(400.0), false); + ps.set("cs2", "31e3:1322", dpi(1600.0), false); assert_eq!(ps.get("cs2", "046d:c54d").unwrap().dpi, Some(400.0)); assert_eq!(ps.get("cs2", "31e3:1322").unwrap().dpi, Some(1600.0)); ps.clear("cs2", "046d:c54d"); @@ -264,8 +298,8 @@ mod tests { #[test] fn empty_profiles_are_dropped() { let mut ps = Profiles::default(); - ps.set("cs2", "a:b", dpi(400.0)); - ps.set("cs2", "a:b", GameProfile::default()); + ps.set("cs2", "a:b", dpi(400.0), false); + ps.set("cs2", "a:b", GameProfile::default(), false); assert!(ps.get("cs2", "a:b").is_none() && !ps.has_any("cs2")); } @@ -283,7 +317,9 @@ mod tests { // Editing under a device takes it over. let mut mine = ps.effective("valorant", "046d:c54d", true).cloned().unwrap(); mine.dpi = Some(1600.0); - ps.set("valorant", "046d:c54d", mine); + ps.set("valorant", "31e3:1322", dpi(400.0), false); + assert!(ps.legacy("valorant").is_some()); + ps.set("valorant", "046d:c54d", mine, true); assert!(ps.legacy("valorant").is_none()); assert_eq!(ps.get("valorant", "046d:c54d").unwrap().polling, Some(8000)); } @@ -303,7 +339,7 @@ mod tests { assert_eq!(js["lighting"]["mode"], "static"); let mut ps = Profiles::default(); - ps.set("valorant", "3434:d05a", p.clone()); + ps.set("valorant", "3434:d05a", p.clone(), false); let back: Profiles = serde_json::from_str(&serde_json::to_string(&ps).unwrap()).unwrap(); assert_eq!(back.get("valorant", "3434:d05a"), Some(&p)); } @@ -311,7 +347,7 @@ mod tests { #[test] fn round_trips_the_new_format() { let mut ps = Profiles::default(); - ps.set("cs2", "046d:c54d", dpi(400.0)); + ps.set("cs2", "046d:c54d", dpi(400.0), false); let back: Profiles = serde_json::from_str(&serde_json::to_string(&ps).unwrap()).unwrap(); assert_eq!(back.get("cs2", "046d:c54d").unwrap().dpi, Some(400.0)); } diff --git a/gpui/src/settings.rs b/gpui/src/settings.rs index 987949ee..43816abc 100644 --- a/gpui/src/settings.rs +++ b/gpui/src/settings.rs @@ -9,7 +9,7 @@ //! (release/apply), matching the Tauri `save*` call sites. use std::collections::BTreeMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; @@ -293,6 +293,24 @@ fn theme_to_str(choice: ThemeChoice) -> &'static str { } } +pub(crate) fn write_atomic(path: &Path, text: &str) -> std::io::Result<()> { + let part = path.with_extension("json.part"); + std::fs::write(&part, text)?; + std::fs::rename(part, path) +} + +pub(crate) fn read_json(path: &Path) -> Option { + let text = std::fs::read_to_string(path).ok()?; + match serde_json::from_str(&text) { + Ok(value) => Some(value), + Err(error) => { + crate::logging::log(&format!("[settings] {} unreadable, moved to .bad: {error}", path.display())); + let _ = std::fs::rename(path, path.with_extension("json.bad")); + None + } + } +} + fn settings_path() -> Option { dirs::config_dir().map(|dir| dir.join("openmouse").join(SETTINGS_FILE)) } @@ -300,8 +318,7 @@ fn settings_path() -> Option { impl Settings { pub fn load() -> Self { let stored: StoredSettings = settings_path() - .and_then(|path| std::fs::read_to_string(path).ok()) - .and_then(|text| serde_json::from_str(&text).ok()) + .and_then(|path| read_json(&path)) .unwrap_or_default(); Self { dynamic_hex: stored.dynamic_hex.map(|[r, g, b]| (r, g, b)), @@ -389,7 +406,7 @@ impl Settings { auto_check_updates: self.auto_check_updates, }; if let Ok(text) = serde_json::to_string_pretty(&stored) { - let _ = std::fs::write(path, text); + let _ = write_atomic(&path, &text); } } } diff --git a/gpui/src/theme.rs b/gpui/src/theme.rs index bb452ed7..fff9dd0a 100644 --- a/gpui/src/theme.rs +++ b/gpui/src/theme.rs @@ -479,6 +479,28 @@ fn dark_ramp(hue: f32, vibrancy: f32) -> (Hsla, Hsla, Hsla, Hsla, Hsla) { ) } +type SystemParams = (Option<(u8, u8, u8)>, f32, f32, Option<(u8, u8, u8)>); + +thread_local! { + static SYSTEM_LIVE: std::cell::Cell> = const { std::cell::Cell::new(None) }; + static APPEARANCE_WATCHED: std::cell::RefCell> = + std::cell::RefCell::new(std::collections::HashSet::new()); +} + +fn watch_appearance(window: &mut Window) { + let id = window.window_handle().window_id(); + if !APPEARANCE_WATCHED.with_borrow_mut(|watched| watched.insert(id)) { + return; + } + window + .observe_window_appearance(|window, cx| { + if let Some((wallpaper, vibrancy, opacity, picked)) = SYSTEM_LIVE.get() { + apply_choice(ThemeChoice::System, wallpaper, vibrancy, opacity, picked, Some(window), cx); + } + }) + .detach(); +} + /// Apply a theme choice through the live [`Theme`]: set the mode, then paint /// the Matt/Dynamic palette onto the public color fields. /// @@ -494,6 +516,11 @@ pub fn apply_choice( window: Option<&mut Window>, cx: &mut App, ) { + let mut window = window; + if let Some(w) = window.as_deref_mut() { + watch_appearance(w); + } + SYSTEM_LIVE.set((choice == ThemeChoice::System).then_some((wallpaper_hex, vibrancy, opacity, picked))); if choice == ThemeChoice::System { // Resolve the OS appearance, then paint the Matt palette for it. // `sync_system_appearance` alone only flips the mode (Kit default @@ -537,6 +564,11 @@ pub fn apply_custom_theme( window: Option<&mut Window>, cx: &mut App, ) { + let mut window = window; + if let Some(w) = window.as_deref_mut() { + watch_appearance(w); + } + SYSTEM_LIVE.set(None); let mode = if css.is_light { ThemeMode::Light } else { ThemeMode::Dark }; Theme::change(mode, window, cx); paint_shared( @@ -573,6 +605,7 @@ pub(crate) fn best_contrast_ink(accent: Hsla) -> Hsla { /// Tint the scene background without fading foreground text or controls. /// Kit's Root owns the background paint; app shell layers remain clear. pub fn set_surface_opacity(opacity: f32, cx: &mut App) { + SYSTEM_LIVE.set(SYSTEM_LIVE.get().map(|(w, v, _, p)| (w, v, opacity, p))); Theme::update(cx, |theme| { theme.colors.background.a = opacity.clamp(0.0, 1.0); }); @@ -1047,19 +1080,34 @@ pub fn crossfade_colors(from: ThemeColor, to: ThemeColor, cx: &mut App) { // applied the target, and letting one frame paint with it first shows up // as a flash of the new theme before the fade begins. Theme::update(cx, |theme| theme.colors = from); + let first = cx.theme().colors; let duration = Duration::from_millis(THEME_FADE_MS).as_secs_f32(); cx.spawn(async move |cx| { let start = Instant::now(); + let (mut from, mut to, mut last) = (from, to, first); loop { if THEME_FADE_SEQ.load(Ordering::Relaxed) != seq { return; } + let current = cx.update(|cx| cx.theme().colors); + if current != last { + let mut alpha_only = current; + alpha_only.background.a = last.background.a; + if alpha_only != last { + return; + } + from.background.a = current.background.a; + to.background.a = current.background.a; + } let t = (start.elapsed().as_secs_f32() / duration).clamp(0.0, 1.0); // Ease-out cubic: most of the color movement lands early, like the // web transition, instead of crawling through the middle. let eased = 1.0 - (1.0 - t).powi(3); let colors = lerp_colors(from, to, eased); - cx.update(move |cx| Theme::update(cx, |theme| theme.colors = colors)); + last = cx.update(move |cx| { + Theme::update(cx, |theme| theme.colors = colors); + cx.theme().colors + }); if t >= 1.0 { return; } diff --git a/gpui/src/tray.rs b/gpui/src/tray.rs index 122d2e26..524f5bda 100644 --- a/gpui/src/tray.rs +++ b/gpui/src/tray.rs @@ -104,15 +104,20 @@ pub(crate) fn render_battery_rgba( #[cfg(windows)] static PIN_REQUEST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +#[cfg(windows)] +static PIN_WRITE: std::sync::Mutex<()> = std::sync::Mutex::new(()); + #[cfg(windows)] pub fn pin(on: bool) { use std::sync::atomic::Ordering; let request = PIN_REQUEST.fetch_add(1, Ordering::SeqCst) + 1; std::thread::spawn(move || { for _ in 0..15 { + let write = PIN_WRITE.lock().unwrap_or_else(|e| e.into_inner()); if PIN_REQUEST.load(Ordering::SeqCst) != request || set_promoted(on) { return; } + drop(write); std::thread::sleep(std::time::Duration::from_secs(2)); } }); @@ -676,6 +681,7 @@ mod imp { extern "system" { fn ShowWindow(hwnd: isize, cmd: i32) -> i32; fn SetForegroundWindow(hwnd: isize) -> i32; + fn IsIconic(hwnd: isize) -> i32; } #[link(name = "kernel32")] @@ -685,6 +691,7 @@ mod imp { } const SW_HIDE: i32 = 0; + const SW_SHOW: i32 = 5; /// Shows a hidden window and un-minimizes a minimized one. const SW_RESTORE: i32 = 9; /// The app icon `build.rs` embeds as the exe's first icon resource. @@ -715,7 +722,7 @@ mod imp { pub fn show_window(window: &mut Window) { if let Some(hwnd) = hwnd_of(window) { unsafe { - ShowWindow(hwnd, SW_RESTORE); + ShowWindow(hwnd, if IsIconic(hwnd) != 0 { SW_RESTORE } else { SW_SHOW }); SetForegroundWindow(hwnd); } } diff --git a/gpui/src/update_check.rs b/gpui/src/update_check.rs index cb116b24..3980021e 100644 --- a/gpui/src/update_check.rs +++ b/gpui/src/update_check.rs @@ -174,7 +174,7 @@ pub fn download_and_verify( let mut child = crate::proc::quiet( std::process::Command::new("curl") - .args(["-sSfL", "--connect-timeout", "15", "-m", "600", "-o"]) + .args(["-sSfL", "--connect-timeout", "15", "--speed-limit", "1024", "--speed-time", "120", "-o"]) .arg(&part_path) .arg(&asset.url) .stdin(std::process::Stdio::null()) @@ -401,20 +401,20 @@ while kill -0 "$PID" 2>/dev/null && [ "$i" -lt 80 ]; do i=$((i + 1)) done -TMP=$(mktemp -d /tmp/openmouse-update.XXXXXX) +TMP=$(mktemp -d /tmp/openmouse-update.XXXXXX) || { nohup "$EXE" >/dev/null 2>&1 & exit 1; } cleanup() { rm -rf "$TMP"; } - -if ! tar -C "$TMP" -xzf "$TARBALL"; then +fail() { + rm -f "${EXE}.new" cleanup + nohup "$EXE" >/dev/null 2>&1 & exit 1 -fi +} + +tar -C "$TMP" -xzf "$TARBALL" || fail SRC_DIR="$TMP/openmouse-desktop" SRC_BIN="$SRC_DIR/openmouse-desktop" -if [ ! -f "$SRC_BIN" ]; then - cleanup - exit 1 -fi +[ -f "$SRC_BIN" ] || fail if cp "$SRC_BIN" "${EXE}.new" && chmod 0755 "${EXE}.new" && mv -f "${EXE}.new" "$EXE"; then [ -f "$SRC_DIR/openmouse-app-icon.png" ] && cp "$SRC_DIR/openmouse-app-icon.png" "$DIR/openmouse-app-icon.png" 2>/dev/null || true @@ -423,8 +423,7 @@ if cp "$SRC_BIN" "${EXE}.new" && chmod 0755 "${EXE}.new" && mv -f "${EXE}.new" " rm -f "$TARBALL" nohup "$EXE" >/dev/null 2>&1 & else - rm -f "${EXE}.new" - cleanup + fail fi "#; let mut cmd = std::process::Command::new("/bin/sh"); diff --git a/gpui/src/usb_topology.rs b/gpui/src/usb_topology.rs index bcff6f9a..5ea67db7 100644 --- a/gpui/src/usb_topology.rs +++ b/gpui/src/usb_topology.rs @@ -2382,24 +2382,20 @@ mod linux { ); // Merge ports across the controller's USB 2.0 + 3.x root hubs. + let mut hubs = hubs; + hubs.sort(); + let mut offsets: HashMap = HashMap::new(); + let mut next_offset = 0u32; + for hub_dir in &hubs { + let name = hub_dir.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + offsets.insert(name.to_string(), next_offset); + next_offset += max_child(hub_dir); + } let mut ports = Vec::new(); - let mut next_port = 1u32; - for hub_dir in hubs { - let children = collect_usb_children(&hub_dir, supported); - for dev in children { - let speed = read_usb_speed(&dev.0); - ports.push(UsbPort { - port_number: next_port, - is_connected: true, - speed: Some(speed), - user_connectable: None, - physical_location: None, - companion_port: None, - supported_usb3: None, - device: Some(dev.1), - }); - next_port += 1; - } + for hub_dir in &hubs { + let name = hub_dir.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + let offset = offsets.get(name).copied().unwrap_or(0); + ports.extend(hub_ports(hub_dir, offset, &offsets, supported)); } let name = format!( @@ -2491,6 +2487,114 @@ mod linux { } } + fn max_child(hub_dir: &Path) -> u32 { + read_trimmed(&hub_dir.join("maxchild")).and_then(|s| s.parse().ok()).unwrap_or(0) + } + + fn file_name(path: &Path) -> &str { + path.file_name().and_then(|n| n.to_str()).unwrap_or_default() + } + + fn sub_dirs(dir: &Path) -> Vec { + fs::read_dir(dir) + .map(|entries| entries.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect()) + .unwrap_or_default() + } + + fn port_number_of(dev_dir: &Path) -> Option { + file_name(dev_dir).rsplit(['-', '.']).next()?.parse().ok() + } + + fn port_dir(hub_dir: &Path, port: u32) -> Option { + let suffix = format!("-port{port}"); + sub_dirs(hub_dir) + .into_iter() + .filter(|i| file_name(i).contains(':')) + .find_map(|i| sub_dirs(&i).into_iter().find(|p| file_name(p).ends_with(&suffix))) + } + + fn hub_ports( + hub_dir: &Path, + offset: u32, + root_offsets: &HashMap, + supported: &SupportedDeviceMap, + ) -> Vec { + let usb3 = matches!(read_usb_speed(hub_dir), UsbSpeed::Super | UsbSpeed::SuperPlus); + let mut connected: HashMap = collect_usb_children(hub_dir, supported) + .into_iter() + .filter_map(|child| Some((port_number_of(&child.0)?, child))) + .collect(); + let count = max_child(hub_dir).max(connected.keys().copied().max().unwrap_or(0)); + (1..=count) + .map(|n| { + let dir = port_dir(hub_dir, n); + let user_connectable = dir + .as_ref() + .and_then(|d| read_trimmed(&d.join("connect_type"))) + .and_then(|t| match t.as_str() { + "hotplug" => Some(true), + "hardwired" | "not used" => Some(false), + _ => None, + }); + let companion_port = dir + .as_ref() + .and_then(|d| fs::read_link(d.join("peer")).ok()) + .and_then(|peer| { + let (hub, port) = file_name(&peer).split_once("-port")?; + Some(root_offsets.get(hub)? + port.parse::().ok()?) + }); + let device = connected.remove(&n); + UsbPort { + port_number: offset + n, + is_connected: device.is_some(), + speed: device.as_ref().map(|(p, _)| read_usb_speed(p)), + user_connectable, + physical_location: None, + companion_port, + supported_usb3: Some(usb3), + device: device.map(|(_, d)| d), + } + }) + .collect() + } + + fn inspect_interfaces(dev_dir: &Path, speed: UsbSpeed) -> (bool, bool, bool, bool, Option) { + let (mut is_mouse, mut is_keyboard, mut mi00_is_mouse, mut mi00_is_kbd) = (false, false, false, false); + let mut best_interval_us: Option = None; + let mut has_isochronous = false; + for iface in sub_dirs(dev_dir).into_iter().filter(|i| file_name(i).contains(':')) { + let class = read_hex_u16(&iface.join("bInterfaceClass")); + let protocol = read_hex_u16(&iface.join("bInterfaceProtocol")); + let on_mi00 = read_hex_u16(&iface.join("bInterfaceNumber")) == Some(0); + if class == Some(0x03) && protocol == Some(0x02) { + is_mouse = true; + mi00_is_mouse |= on_mi00; + } + if class == Some(0x03) && protocol == Some(0x01) { + is_keyboard = true; + mi00_is_kbd |= on_mi00; + } + for ep in sub_dirs(&iface).into_iter().filter(|e| file_name(e).starts_with("ep_")) { + let attributes = read_hex_u16(&ep.join("bmAttributes")).unwrap_or(0) & 0x03; + let is_in = read_hex_u16(&ep.join("bEndpointAddress")).unwrap_or(0) & 0x80 != 0; + let interval = read_hex_u16(&ep.join("bInterval")).unwrap_or(0) as u32; + if attributes == 1 { + has_isochronous = true; + } else if attributes == 3 && is_in && interval > 0 { + let us = match speed { + UsbSpeed::High | UsbSpeed::Super | UsbSpeed::SuperPlus => { + 125u32.saturating_mul(1u32 << (interval - 1).min(15)) + } + _ => interval.saturating_mul(1000), + }; + best_interval_us = Some(best_interval_us.map_or(us, |cur| cur.min(us))); + } + } + } + let is_primary_mouse = (is_mouse && !is_keyboard) || (is_mouse && mi00_is_mouse && !mi00_is_kbd); + (is_mouse, is_primary_mouse, is_keyboard, has_isochronous, best_interval_us) + } + fn collect_usb_children( parent_dir: &Path, supported: &SupportedDeviceMap, @@ -2511,22 +2615,16 @@ mod linux { let manufacturer = read_trimmed(&p.join("manufacturer")); let is_hub = read_trimmed(&p.join("bDeviceClass")).as_deref() == Some("09"); let openmouse_brand = supported.get(&(vid, pid)).cloned(); + let (is_mouse, iface_primary_mouse, is_keyboard, has_isochronous, polling_interval_us) = + inspect_interfaces(&p, read_usb_speed(&p)); + let lower_name = name.to_ascii_lowercase(); + let is_primary_mouse = !is_hub + && (iface_primary_mouse + || lower_name.contains("mouse") + || lower_name.contains("receiver") + || lower_name.contains("dongle")); let nested = if is_hub { - let kids = collect_usb_children(&p, supported); - let ports = kids - .into_iter() - .enumerate() - .map(|(i, (kp, kd))| UsbPort { - port_number: (i + 1) as u32, - is_connected: true, - speed: Some(read_usb_speed(&kp)), - user_connectable: None, - physical_location: None, - companion_port: None, - supported_usb3: None, - device: Some(kd), - }) - .collect::>(); + let ports = hub_ports(&p, 0, &HashMap::new(), supported); Some(Box::new(UsbHub { name: name.clone(), is_root: false, @@ -2545,17 +2643,17 @@ mod linux { manufacturer, instance_id: p.file_name().and_then(|n| n.to_str()).map(String::from), is_hub, - is_mouse: false, - is_primary_mouse: false, - is_keyboard: false, + is_mouse, + is_primary_mouse, + is_keyboard, is_openmouse_supported: openmouse_brand.is_some(), openmouse_brand, usb_version: read_trimmed(&p.join("version")), max_power_ma: read_trimmed(&p.join("bMaxPower")) .and_then(|s| s.trim_end_matches("mA").parse().ok()), - polling_rate_hz: None, - polling_interval_us: None, - has_isochronous: false, + polling_rate_hz: polling_interval_us.map(|us| 1_000_000 / us), + polling_interval_us, + has_isochronous, open_pipes: 0, hub: nested, }, From 38703f8dfa018004cfe2142dfbb0ebd5da8243ac Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 18:09:11 +0100 Subject: [PATCH 3/6] fix: find a Logitech mouse that wakes up after its receiver was checked A receiver that answers with no mouse behind it is asked again every few seconds until the mouse answers, then the mouse is added and connected. --- gpui/src/app/device_io.rs | 41 ++++++++++++++++++++++++++++++++++++ gpui/src/app/device_state.rs | 1 + 2 files changed, 42 insertions(+) diff --git a/gpui/src/app/device_io.rs b/gpui/src/app/device_io.rs index 8bd5ae5d..f1746600 100644 --- a/gpui/src/app/device_io.rs +++ b/gpui/src/app/device_io.rs @@ -121,6 +121,16 @@ impl AppView { } let _ = view.update(cx, |v: &mut Self, cx| { v.reconnect(cx); + if let Some(key) = v.devices.wake_connect.take() { + let waiting = v.devices.tiles.iter().any(|t| t.key == key && !matches!(t.status, TileStatus::Connected(_) | TileStatus::Connecting)); + if waiting { + let keep = v.selected_key(); + let _ = v.connect_task(&key, false, cx).map(|task| task.detach()); + if v.devices.open.is_some() { + v.reselect(keep); + } + } + } v.ensure_usb_topology(cx); v.check_conflicting_apps(cx); }); @@ -227,6 +237,34 @@ impl AppView { }); } + fn retry_receiver(&mut self, key: String, cx: &mut Context) { + let service = self.hid_service(); + cx.spawn(async move |view, cx| { + let executor = cx.background_executor().clone(); + loop { + crate::activity::ACTIVITY.sleep(&executor, Duration::from_secs(5), Duration::from_secs(15)).await; + let still = view.update(cx, |v: &mut Self, _| v.devices.ignored_keys.contains(&key)); + if !matches!(still, Ok(true)) { + return; + } + match service.connect(&key).await { + Ok(Ok(_)) => { + let _ = view.update(cx, |v: &mut Self, cx| { + crate::logging::log(&format!("[device] a mouse woke up behind receiver {key}")); + v.devices.ignored_keys.remove(&key); + v.devices.wake_connect = Some(key.clone()); + v.scan_devices(cx); + }); + return; + } + Ok(Err(error)) if error.to_ascii_lowercase().contains("is not a mouse") => continue, + _ => return, + } + } + }) + .detach(); + } + pub(super) fn selected_key(&self) -> Option { self.devices.tiles.get(self.devices.selected).map(|t| t.key.clone()) } @@ -950,6 +988,9 @@ impl AppView { "[device] hiding non-mouse interface {key}: {error}" )); v.devices.ignored_keys.insert(key.clone()); + if error.contains("Receiver") { + v.retry_receiver(key.clone(), cx); + } let keep = v.selected_key(); v.devices.tiles.retain(|t| t.key != key); v.reselect(keep); diff --git a/gpui/src/app/device_state.rs b/gpui/src/app/device_state.rs index 6498fa2d..28363baf 100644 --- a/gpui/src/app/device_state.rs +++ b/gpui/src/app/device_state.rs @@ -12,6 +12,7 @@ pub(super) struct Devices { /// Device keys that proved not to be configurable mice/keyboards (e.g. a /// Logitech HID++ headset) and should stay hidden for this session. pub(super) ignored_keys: std::collections::HashSet, + pub(super) wake_connect: Option, pub(super) selected: usize, /// Key of the device whose settings page is open, if any. pub(super) open: Option, From d138ceac6c4c1596f73212136ddb185d97fefc49 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 21:38:22 +0100 Subject: [PATCH 4/6] refactor(logitech): use the protocol's snapDpi for DPI and stage snapping --- gpui/js/entry.ts | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/gpui/js/entry.ts b/gpui/js/entry.ts index 60642614..479fdd9d 100644 --- a/gpui/js/entry.ts +++ b/gpui/js/entry.ts @@ -2,6 +2,7 @@ // the same list/connect flow the Tauri app runs (src/native-hid/scan.ts), // bundled unmodified, behind two JSON-in/JSON-out functions for Rust. +import { snapDpi } from "@openmouse/protocol/logitech"; import "./globals"; import "./wlmouse-apply"; import { macroOp } from "./macros"; @@ -241,10 +242,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); if (action === "stages") { const { sector, ...plan } = value; const options: number[] | null = lastStatus.get(key)?.dpiOptions ?? await client.getDpiOptions().catch(() => null); - if (options?.length) { - const snap = (v: number) => options.reduce((best, o) => (Math.abs(o - v) < Math.abs(best - v) ? o : best)); - plan.stages = plan.stages.map((stage: any) => ({ ...stage, x: snap(stage.x), y: snap(stage.y) })); - } + if (options?.length) plan.stages = plan.stages.map((stage: any) => ({ ...stage, x: snapDpi(options, stage.x), y: snapDpi(options, stage.y) })); await client.writeActiveProfile({ sector, dpiStages: plan }); return value; } @@ -346,11 +344,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); const onboard = lastStatus.get(key); const options: number[] | undefined = onboard?.dpiOptions; if (brand === "Logitech" && action === "dpi" && options?.length) { - const snap = (v: number, from: unknown) => { - const near = options.reduce((best, o) => (Math.abs(o - v) < Math.abs(best - v) ? o : best)); - if (typeof from !== "number" || near !== from || v === from) return near; - return (v > from ? options.find((o) => o > from) : [...options].reverse().find((o) => o < from)) ?? near; - }; + const snap = (v: number, from: unknown) => snapDpi(options, v, typeof from === "number" ? from : undefined); value = typeof value === "number" ? snap(value, onboard.dpi) : { ...value, x: snap(value.x, onboard.dpi), y: snap(value.y, onboard.dpiY ?? onboard.dpi) }; onboard.dpi = typeof value === "number" ? value : value.x; if (typeof value !== "number") onboard.dpiY = value.y; From fca6f5a891d57d03cf4d2c1d1bf4a8d1410a490b Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 22:17:06 +0100 Subject: [PATCH 5/6] fix: PR 74 review findings, round 4 - Left-click rescue writes go to their own mouse without opening its page, so nothing else is reset or flushed - Split DPI writes report the snapped Y; the stage draft follows both axes; a failed DPI write restores the cached value - Onboard lift-off changes reactivate the running profile - Stage drafts: a factory restore or a profile read only clears the draft it belongs to; a save cancelled by a game profile says so - Game profiles: a cancelled button pre-read resumes syncing; the next profile waits for the restore's read-back; restore snapshots are kept in memory if the file can't be written - Read-back keeps the confirmed polling rate only when that round wrote one - The Apply bar stays while staged edits remain, even with instant apply on - DPI +/- doesn't leave a pending value while a game profile holds the mouse - VIA: pauses are refused on firmware that can't store them, long pauses are split, writes on another keyboard don't reset the open one, a definition must have a matrix and layouts before it's cached - Keyboards release their lock before the caller continues - A receiver whose retry fails can be found again by a later scan - Colour pickers resync once their write settles - Discord presence sets its wanted flag under the connection lock --- crates/openmouse-presence/src/lib.rs | 4 +-- gpui/js/entry.ts | 14 ++++++++- gpui/js/keyboard-via.ts | 10 ++++--- gpui/js/keyboards.ts | 4 +-- gpui/src/app/device_io.rs | 43 ++++++++++++++++++---------- gpui/src/app/device_overview.rs | 2 +- gpui/src/app/device_page.rs | 5 ++-- gpui/src/app/device_state.rs | 1 + gpui/src/app/logitech_stages.rs | 12 +++++++- gpui/src/app/profile_ui.rs | 9 ++++-- gpui/src/app/safety.rs | 17 +++++------ gpui/src/hid.rs | 2 +- gpui/src/profiles.rs | 6 +++- 13 files changed, 88 insertions(+), 41 deletions(-) diff --git a/crates/openmouse-presence/src/lib.rs b/crates/openmouse-presence/src/lib.rs index cdf30cf2..42a1ed5f 100644 --- a/crates/openmouse-presence/src/lib.rs +++ b/crates/openmouse-presence/src/lib.rs @@ -138,8 +138,8 @@ impl Presence { /// trusted - otherwise the switch would look on while nothing is connected. pub fn enable(&self) -> Result<(), String> { applog!("[discord] enable requested"); - self.wanted.store(true, std::sync::atomic::Ordering::Relaxed); let mut guard = self.connection.lock(); + self.wanted.store(true, std::sync::atomic::Ordering::Relaxed); connect(&mut guard)?; let connection = guard.as_mut().expect("connection just established"); let started = connection.started; @@ -174,8 +174,8 @@ impl Presence { pub fn disable(&self) -> Result<(), String> { applog!("[discord] disable requested"); - self.wanted.store(false, std::sync::atomic::Ordering::Relaxed); let mut guard = self.connection.lock(); + self.wanted.store(false, std::sync::atomic::Ordering::Relaxed); if let Some(mut connection) = guard.take() { if let Err(error) = connection.client.close() { applog!("[discord] disconnect failed: {error}"); diff --git a/gpui/js/entry.ts b/gpui/js/entry.ts index 479fdd9d..dffaf352 100644 --- a/gpui/js/entry.ts +++ b/gpui/js/entry.ts @@ -311,6 +311,17 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); * makes. Resolves to the value the device actually applied. */ async write(argsJson: string): Promise { + const { key, action } = JSON.parse(argsJson) as { key: string; action: string }; + const status = lastStatus.get(key); + const before = status && { dpi: status.dpi, dpiY: status.dpiY }; + try { + return await (globalThis as any).__api.writeOnce(argsJson); + } catch (error) { + if (action === "dpi" && before) Object.assign(status, before); + throw error; + } + }, + async writeOnce(argsJson: string): Promise { let { key, brand, action, value } = JSON.parse(argsJson) as { key: string; brand: string; @@ -358,6 +369,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); if (!lod || !profile.dpiStages.some((stage: any) => stage.lod > 0)) throw new Error("This profile doesn't store a lift-off distance. Switch the mouse to host mode to change it."); const stages = profile.dpiStages.map((stage: any) => ({ ...stage, lod })); await client.writeActiveProfile({ sector: profile.sector, dpiStages: { stages, defaultIndex: Math.min(profile.defaultDpiIndex ?? 0, stages.length - 1) } }); + await client.setCurrentProfile(profile.sector); return value; } if (action === "pollingRate") { @@ -371,7 +383,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); await client.writeActiveProfile({ sector: profile.sector, dpiStages: { stages, defaultIndex: index } }); } await client.setCurrentProfile(profile.sector); - return typeof value === "number" ? value : Math.round(value.x ?? value); + return typeof value === "number" ? value : { x: Math.round(value.x), y: Math.round(value.y) }; })); } switch (action) { diff --git a/gpui/js/keyboard-via.ts b/gpui/js/keyboard-via.ts index 94374ff7..fc3cf0ce 100644 --- a/gpui/js/keyboard-via.ts +++ b/gpui/js/keyboard-via.ts @@ -2,7 +2,7 @@ import { invoke } from "@tauri-apps/api/core"; import { decodeViaMacro, describeViaKeycode, encodeViaMacro, evaluateViaCondition, joinViaMacros, parseViaDefinition, parseViaMacroExpression, parseViaMenus, viaActiveKeys, viaKeycodeFromLayoutName, viaKeycodePicker, viaKeycodeToLayoutName, viaLayoutChoices, viaMacroToExpression, - viaNumberToBytes, viaPackLayoutChoices, viaValueToNumber, VIA_MACRO_DELAY_PROTOCOL, type ViaDefinition, type ViaKeycodeGroupId, + viaNumberToBytes, viaPackLayoutChoices, viaValueToNumber, VIA_MACRO_DELAY_PROTOCOL, VIA_MACRO_MAX_DELAY_MS, type ViaDefinition, type ViaKeycodeGroupId, type ViaMacroAction, type ViaMenuItem, } from "@openmouse/keyboard-protocol/via"; import { hidUsage } from "./keys"; @@ -324,7 +324,7 @@ export const viaMacroPanel = (count: number, protocol: number) => ({ warning: null, note: protocol >= VIA_MACRO_DELAY_PROTOCOL ? "Put a macro on a key from the Macros group on the Keys tab. Saving keeps it on the keyboard." - : "Put a macro on a key from the Macros group on the Keys tab. This keyboard's firmware can't store pauses, so the delays are left out when you save.", + : "Put a macro on a key from the Macros group on the Keys tab. This keyboard's firmware can't store pauses, so every delay must be 0.", }); const usageOf = (key: string) => MODIFIERS[key] ?? hidUsage(key); @@ -374,10 +374,12 @@ export async function viaMacroOp(client: any, op: string, args: any): Promise= VIA_MACRO_DELAY_PROTOCOL; + const steps = args.steps as MacroStep[]; + if (!delays && steps.some((step) => step.delay > 0)) throw new RangeError("This keyboard's firmware can't store pauses. Set every delay to 0."); const actions: ViaMacroAction[] = []; - for (const step of args.steps as MacroStep[]) { + for (const step of steps) { actions.push({ type: step.down ? "down" : "up", keycode: usageOf(step.key) }); - if (delays && step.delay > 0) actions.push({ type: "delay", ms: step.delay }); + for (let left = step.delay; left > 0; left -= VIA_MACRO_MAX_DELAY_MS) actions.push({ type: "delay", ms: Math.min(VIA_MACRO_MAX_DELAY_MS, left) }); } const next = macros.macros.map((bytes: number[]) => [...bytes]); next[slot] = encodeViaMacro(actions, via.protocolVersion); diff --git a/gpui/js/keyboards.ts b/gpui/js/keyboards.ts index ed3865b9..129fa84f 100644 --- a/gpui/js/keyboards.ts +++ b/gpui/js/keyboards.ts @@ -120,12 +120,12 @@ async function withKeyboard(info: KeyboardInterface, work: (client: any, bran const timer = setTimeout(() => reject(new Error("The keyboard took too long to answer.")), READ_TIMEOUT_MS); try { await client.open(); - resolve(await work(client, driver.brand)); + return await work(client, driver.brand); } finally { clearTimeout(timer); if (!client.keepOpen) await client.close().catch(() => undefined); } - }).catch(reject); + }).then(resolve, reject); }); } diff --git a/gpui/src/app/device_io.rs b/gpui/src/app/device_io.rs index 2ad37dbb..9058bcee 100644 --- a/gpui/src/app/device_io.rs +++ b/gpui/src/app/device_io.rs @@ -258,7 +258,10 @@ impl AppView { return; } Ok(Err(error)) if error.to_ascii_lowercase().contains("is not a mouse") => continue, - _ => return, + _ => { + let _ = view.update(cx, |v: &mut Self, _| v.devices.ignored_keys.remove(&key)); + return; + } } } }) @@ -331,6 +334,9 @@ impl AppView { if let Some(Tile { status: TileStatus::Connected(r), .. }) = self.devices.tiles.iter_mut().find(|t| t.key == key) { r.dpi_y = Some(y); } + if let Some(draft) = self.devices.stage_draft.as_mut().filter(|d| d.key == key) { + draft.set_default_y(y.round() as i64); + } } /// Reflects a confirmed write in the page. The value is what the driver @@ -358,9 +364,8 @@ impl AppView { } match action { "dpi" => { - r.dpi = applied.as_f64().or(r.dpi); - // Linked writes put Y on X as well; an unlinked pair sets Y after this. - r.dpi_y = r.dpi; + r.dpi = applied.as_f64().or_else(|| applied.get("x").and_then(|x| x.as_f64())).or(r.dpi); + r.dpi_y = applied.get("y").and_then(|y| y.as_f64()).or(r.dpi); } "pollingRate" => r.polling_hz = applied.as_f64().or(r.polling_hz), "liftOff" => r.lod = applied.as_str().map(str::to_string).or_else(|| r.lod.take()), @@ -383,8 +388,12 @@ impl AppView { } let selected = self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.key == key); if into_profile && selected && action == "dpi" { - if let (Some(dpi), Some(draft)) = (applied.as_f64(), self.devices.stage_draft.as_mut()) { + let x = applied.as_f64().or_else(|| applied.get("x").and_then(|x| x.as_f64())); + if let (Some(dpi), Some(draft)) = (x, self.devices.stage_draft.as_mut()) { draft.set_default_dpi(dpi.round() as i64); + if let Some(y) = applied.get("y").and_then(|y| y.as_f64()) { + draft.set_default_y(y.round() as i64); + } } } if into_profile && selected && action == "liftOff" { @@ -431,7 +440,7 @@ impl AppView { Ok(Ok(list)) => { v.devices.onboard = Some(list); v.devices.onboard_key = Some(key.clone()); - if v.stage_seq == v.stage_sent { + if v.stage_seq == v.stage_sent && v.devices.writing.as_deref() != Some("stages") { v.devices.stage_draft = None; } } @@ -487,7 +496,9 @@ impl AppView { v.saved("Profile list", cx); } if action == "factory" { - v.devices.stage_draft = None; + if v.devices.stage_draft.as_ref().is_some_and(|d| d.key == key) { + v.devices.stage_draft = None; + } v.show_toast("Factory profiles restored.", false, cx); } if action == "useProfile" { @@ -568,10 +579,11 @@ impl AppView { let result = service.write(&key, &brand, &format!("control:{id}"), value.clone()).await; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.writing = None; - if !matches!(result, Ok(Ok(_))) { - if let Some(entry) = v.text_controls.colours.get_mut(&format!("{key}/{id}")) { - entry.0.clear(); - } + if let Some(entry) = v.text_controls.colours.get_mut(&format!("{key}/{id}")) { + entry.0 = match (&result, value.as_str()) { + (Ok(Ok(_)), Some(hex)) => hex.to_string(), + _ => String::new(), + }; } let mut expected = Vec::new(); match result { @@ -586,7 +598,7 @@ impl AppView { } let name = v.control_name(&key, &id); v.saved(&name, cx); - if id.starts_with("via.") && id != "via.file.save" { + if id.starts_with("via.") && id != "via.file.save" && v.devices.open.as_deref() == Some(key.as_str()) { v.keyboard.drop_board(); if matches!(v.devices.tab, DeviceTab::Keys | DeviceTab::Actuation) { v.load_keyboard_tab(v.devices.tab, cx); @@ -764,9 +776,10 @@ impl AppView { v.devices.dpi_pending = None; } v.patch_readout(&key, action, &applied, cx); - if let Some(y) = requested_y { + if let Some(y) = requested_y.filter(|_| applied.get("y").is_none()) { v.patch_dpi_y(&key, y); } + let applied = applied.get("x").cloned().unwrap_or(applied); v.refresh_presence(cx); expected.push(Expected { action: action.to_string(), value: applied }); v.saved(setting_name(action), cx); @@ -879,7 +892,7 @@ impl AppView { for (action, applied) in &applied_values { v.patch_readout(&key, action, applied, cx); if *action == "dpi" { - if let Some(y) = staged.dpi_y { + if let Some(y) = staged.dpi_y.filter(|_| applied.get("y").is_none()) { v.patch_dpi_y(&key, y); } } @@ -887,7 +900,7 @@ impl AppView { v.refresh_presence(cx); let expected = applied_values .into_iter() - .map(|(action, value)| Expected { action: action.to_string(), value }) + .map(|(action, value)| Expected { action: action.to_string(), value: value.get("x").cloned().unwrap_or(value) }) .collect(); v.read_back(&key, expected, cx); v.next_write(cx); diff --git a/gpui/src/app/device_overview.rs b/gpui/src/app/device_overview.rs index 4ecad602..d44f01ba 100644 --- a/gpui/src/app/device_overview.rs +++ b/gpui/src/app/device_overview.rs @@ -145,7 +145,7 @@ impl AppView { options.iter().rev().copied().find(|o| *o < from).unwrap_or(from + by) } .clamp(min, max); - if this.settings.instant_apply { + if this.settings.instant_apply && this.editing_profile().is_none() && this.locked_game().is_none() { this.devices.dpi_pending = Some(next); } set(this, next, cx); diff --git a/gpui/src/app/device_page.rs b/gpui/src/app/device_page.rs index fdedd93b..3ce94dc4 100644 --- a/gpui/src/app/device_page.rs +++ b/gpui/src/app/device_page.rs @@ -16,7 +16,6 @@ impl AppView { let muted = cx.theme().muted_foreground; let busy = self.devices.writing.is_some(); let staged = &self.devices.staged; - let instant = self.settings.instant_apply; // One quiet line under the name: brand, link and battery. let mut facts = h_flex().gap_3().items_center().text_sm().text_color(muted).child(tile.display_brand.clone()); @@ -54,7 +53,7 @@ impl AppView { let body = self.render_device_body(tile, view_width, view_height, false, cx); - let show_bar = !instant && !staged.is_empty(); + let show_bar = !staged.is_empty(); let apply_bar = div() .absolute() .left(px(PAGE_PAD)) @@ -461,7 +460,7 @@ impl AppView { )); } - let pad_bottom = !profile_mode && !instant && !staged.is_empty(); + let pad_bottom = !profile_mode && !staged.is_empty(); h_flex() .flex_1() .min_h_0() diff --git a/gpui/src/app/device_state.rs b/gpui/src/app/device_state.rs index 28363baf..94772d20 100644 --- a/gpui/src/app/device_state.rs +++ b/gpui/src/app/device_state.rs @@ -46,6 +46,7 @@ pub(super) struct Devices { /// Writes made to each device, so only the latest one reads it back. pub(super) write_rounds: std::collections::HashMap, pub(super) polling_written: std::collections::HashSet, + pub(super) sync_after_read: std::collections::HashSet, pub(super) write_error: Option, } diff --git a/gpui/src/app/logitech_stages.rs b/gpui/src/app/logitech_stages.rs index c437646b..94304e7f 100644 --- a/gpui/src/app/logitech_stages.rs +++ b/gpui/src/app/logitech_stages.rs @@ -14,7 +14,7 @@ const MOST: usize = 5; #[derive(Clone, PartialEq)] pub(super) struct StageDraft { - key: String, + pub(super) key: String, sector: u32, stages: Vec, default: usize, @@ -48,6 +48,12 @@ impl StageDraft { self.set_dpi(self.default, value); } + pub(super) fn set_default_y(&mut self, value: i64) { + if let Some(stage) = self.stages.get_mut(self.default) { + stage["y"] = json!(value.max(1)); + } + } + fn x(&self, index: usize) -> Option { self.stages.get(index).and_then(|s| s["x"].as_i64()) } @@ -121,6 +127,7 @@ impl AppView { } let Some(draft) = self.devices.stage_draft.clone() else { return }; if self.stages_locked(&draft) { + self.show_toast("A game profile took over the mouse, so the DPI stage change wasn't saved.", true, cx); return; } if self.devices.writing.is_some() { @@ -147,6 +154,9 @@ impl AppView { } let Some(draft) = this.devices.stage_draft.clone() else { return }; if this.stages_locked(&draft) { + this.devices.stage_draft = None; + this.stage_sent = seq; + this.show_toast("A game profile took over the mouse, so the DPI stage change wasn't saved.", true, cx); return; } if this.devices.writing.is_some() { diff --git a/gpui/src/app/profile_ui.rs b/gpui/src/app/profile_ui.rs index 4804dbdf..1d0798ef 100644 --- a/gpui/src/app/profile_ui.rs +++ b/gpui/src/app/profile_ui.rs @@ -294,6 +294,7 @@ impl AppView { let _ = view.update(cx, |v: &mut Self, cx| { v.profile_inflight.retain(|p| p != &pair); if !v.games.iter().any(|g| g.id == game_id && g.running) { + v.sync_running_profiles(cx); return; } v.apply_profile_with(&game_id, &device, profile, auto, buttons, cx); @@ -440,10 +441,14 @@ impl AppView { v.announce(format!("Couldn't apply \"{name}\" profile. {problem}"), true, overlay, cx); } } - v.read_back(&key, Vec::new(), cx); if orphaned || restored { - v.sync_running_profiles(cx); + if key.starts_with("mock:") { + v.sync_running_profiles(cx); + } else { + v.devices.sync_after_read.insert(key.clone()); + } } + v.read_back(&key, Vec::new(), cx); }); }) .detach(); diff --git a/gpui/src/app/safety.rs b/gpui/src/app/safety.rs index ff3284bd..1d7e13a3 100644 --- a/gpui/src/app/safety.rs +++ b/gpui/src/app/safety.rs @@ -70,16 +70,14 @@ impl AppView { let edit = self.devices.queued.remove(0); let rescue = edit.is_rescue(); let target = self.devices.tiles.iter().position(|t| t.key == edit.target().0 && matches!(t.status, TileStatus::Connected(_))); - if let (true, Some(index)) = (rescue, target) { + if let (true, Some(index), Queued::Control { id, value, .. }) = (rescue, target, &edit) { if index != self.devices.selected { - let key = edit.target().0.to_string(); - if self.devices.open.is_some() { - self.open_device(&key, cx); - } else { - self.devices.selected = index; - } self.show_toast("Restoring the left click on the mouse the shortcut was pressed for.", false, cx); } + let shown = std::mem::replace(&mut self.devices.selected, index); + self.write_control(id.clone(), value.clone(), cx); + self.devices.selected = shown; + return; } // Writes go to the selected device; an edit for another is out of date. if self.devices.tiles.get(self.devices.selected).map(|t| t.key.as_str()) != Some(edit.target().0) { @@ -235,6 +233,9 @@ impl AppView { } } } + if v.devices.sync_after_read.remove(&key) { + v.sync_running_profiles(cx); + } v.next_write(cx); cx.notify(); }); @@ -255,7 +256,7 @@ impl AppView { // A Logitech mouse answers with the old polling rate just after a live // change (see `patch_readout`): keep the confirmed one. let polling_written = self.devices.polling_written.remove(key); - let stale_polling = tile.brand == "Logitech" && polling_written; + let stale_polling = tile.brand == "Logitech" && polling_written && expected.iter().any(|e| e.action == "pollingRate"); if stale_polling { new.polling_hz = old.polling_hz; } diff --git a/gpui/src/hid.rs b/gpui/src/hid.rs index d80b4cb3..8ca1efdb 100644 --- a/gpui/src/hid.rs +++ b/gpui/src/hid.rs @@ -1130,7 +1130,7 @@ fn via_definition(vendor_id: u16, product_id: u16) -> Result, Str } reached = true; let text = String::from_utf8_lossy(&output.stdout).into_owned(); - if serde_json::from_str::(&text).is_ok_and(|v| v.is_object()) { + if serde_json::from_str::(&text).is_ok_and(|v| v.get("matrix").is_some_and(|m| m.is_object()) && v.get("layouts").is_some_and(|l| l.is_object())) { if let Some(cache) = &cache { let _ = cache.parent().map(std::fs::create_dir_all); let _ = std::fs::write(cache, &text); diff --git a/gpui/src/profiles.rs b/gpui/src/profiles.rs index a8673d16..a64fe977 100644 --- a/gpui/src/profiles.rs +++ b/gpui/src/profiles.rs @@ -167,8 +167,11 @@ fn save_json(path: Option, value: &impl Serialize) { } } +static RESTORES: std::sync::Mutex>> = std::sync::Mutex::new(None); + pub fn restores() -> BTreeMap { - restores_path().and_then(|p| crate::settings::read_json(&p)).unwrap_or_default() + let mut held = RESTORES.lock().unwrap_or_else(|e| e.into_inner()); + held.get_or_insert_with(|| restores_path().and_then(|p| crate::settings::read_json(&p)).unwrap_or_default()).clone() } pub fn set_restore(device: &str, restore: Option) { @@ -178,6 +181,7 @@ pub fn set_restore(device: &str, restore: Option) { None => all.remove(device), }; save_json(restores_path(), &all); + *RESTORES.lock().unwrap_or_else(|e| e.into_inner()) = Some(all); } impl GameProfile { From 513692cbccd4816e13c242f5ff4828be1cf65a38 Mon Sep 17 00:00:00 2001 From: Onyx Date: Fri, 4 Dec 2026 22:47:00 +0100 Subject: [PATCH 6/6] fix(rescue): restore the left click on a mouse when another device is selected The shortcut used only the selected device, so with a keyboard open it found no left button. It now falls back to the first connected mouse that has one, and writes to it without leaving the open page. --- gpui/src/app/device_io.rs | 49 ++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/gpui/src/app/device_io.rs b/gpui/src/app/device_io.rs index 9058bcee..78cb74b1 100644 --- a/gpui/src/app/device_io.rs +++ b/gpui/src/app/device_io.rs @@ -10,31 +10,38 @@ impl AppView { /// The rescue shortcut (`crate::rescue_hotkey`): gives the selected mouse's /// left button its click back, in the running onboard profile or in an - /// MX-style remap. Other connected mice are left alone. Goes through the - /// ordinary write queue, so it lands after a write in flight and replaces a - /// waiting edit of the same button, and the mouse is read back after. + /// MX-style remap. With a keyboard or nothing selected, the first connected + /// mouse that has one is used. Goes through the ordinary write queue, so it + /// lands after a write in flight and replaces a waiting edit of the same + /// button, and the mouse is read back after. pub fn restore_left_click(&mut self, cx: &mut Context) { - let mut writes = Vec::new(); - if let Some(TileStatus::Connected(r)) = self.devices.tiles.get(self.devices.selected).map(|t| &t.status) { - if r.onboard_profiles_writable && r.mode.as_deref() == Some("Onboard") { - writes.push(("logi.button.primary.0", serde_json::json!("Left click"))); - } - // Not judged by the control's shown value: a remap still being - // written shows the old one. - if r.tabs.controls().any(|c| c.id == "logi.remap.80") { - writes.push(("logi.remap.80", serde_json::json!(80))); + let writes_for = |tile: &Tile| { + let mut writes = Vec::new(); + if let TileStatus::Connected(r) = &tile.status { + if r.onboard_profiles_writable && r.mode.as_deref() == Some("Onboard") { + writes.push(("logi.button.primary.0", serde_json::json!("Left click"))); + } + if r.tabs.controls().any(|c| c.id == "logi.remap.80") { + writes.push(("logi.remap.80", serde_json::json!(80))); + } } - } - if writes.is_empty() { - self.show_toast("The selected mouse has no left button to restore.", false, cx); + writes + }; + let target = self + .devices + .tiles + .get(self.devices.selected) + .filter(|t| !writes_for(t).is_empty()) + .or_else(|| self.devices.tiles.iter().find(|t| !writes_for(t).is_empty())); + let Some(tile) = target else { + self.show_toast("No connected mouse has a left button to restore.", false, cx); return; + }; + let key = tile.key.clone(); + for (id, value) in writes_for(tile) { + self.queue(Queued::Control { key: key.clone(), id: id.to_string(), value, rescue: true }); } - for (id, value) in writes { - match self.selected_key().filter(|_| self.devices.writing.is_some()) { - Some(key) => self.queue(Queued::Control { key, id: id.to_string(), value, rescue: true }), - None => self.write_control(id.to_string(), value, cx), - } - } + self.next_write(cx); } /// Lists supported devices, loads their artwork, and connects the first.