From d6448d56e9b249aa567984df70107f530a522bfd Mon Sep 17 00:00:00 2001 From: softmaxe <94467584+softmaxe@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:04:28 +0800 Subject: [PATCH 1/3] refactor(hidpp): remove ineffective blocking mode and short-write checks hidapi's macOS backend ignores the blocking flag in read_timeout and reports a successful write at full length, so neither path can change behavior on the only supported platform. --- README.md | 7 ++-- README.zh-CN.md | 2 +- src/hidpp.rs | 104 ++++++++++++++---------------------------------- 3 files changed, 33 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 2e7ad27..796c8bb 100644 --- a/README.md +++ b/README.md @@ -163,10 +163,9 @@ headset. There is no device selector. It reads `UNIFIED_BATTERY` at `0x1004` and falls back to `BATTERY_STATUS` at `0x1000` when the unified feature is unavailable, does not answer, or returns an -incomplete response. Once a battery feature is found, HID access errors and -incomplete writes stop the read. During discovery, an interface that fails is -skipped; its error is reported only if no other interface finds the mouse or -reports it offline. +incomplete response. Once a battery feature is found, HID access errors stop the +read. During discovery, an interface that fails is skipped; its error is +reported only if no other interface finds the mouse or reports it offline. If neither feature yields a battery status, the command reports an error instead of inventing a `0%` reading. diff --git a/README.zh-CN.md b/README.zh-CN.md index 88b2f90..ee8d88d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -131,7 +131,7 @@ xattr -dr com.apple.quarantine "$(brew --prefix gbat)" `gbat` 以共享模式打开 Logitech HID++ 接口。它会检查接收器的设备索引 `1` 到 `6` 和 USB 直连索引 `0xFF`,先尝试 `1` 和 `0xFF`,再使用首个报告支持电池功能的接口及设备索引。它只按 Logitech 厂商 ID 筛选,连接多个 Logitech HID++ 设备时,可能读到另一只鼠标、键盘或耳机,且无法指定设备。 -它优先读取 `0x1004` 的 `UNIFIED_BATTERY`。该功能不可用、未响应或返回不完整响应时,会回退到 `0x1000` 的 `BATTERY_STATUS`。找到电池功能后,HID 访问错误和写入不完整会直接终止读取。探测阶段某个接口出错时会跳过它,只有其他接口都没找到鼠标、也没有报告离线时,才返回该错误。如果两个功能都未返回电池状态,命令会报错,不会将读取失败显示为 `0%`。 +它优先读取 `0x1004` 的 `UNIFIED_BATTERY`。该功能不可用、未响应或返回不完整响应时,会回退到 `0x1000` 的 `BATTERY_STATUS`。找到电池功能后,HID 访问错误会直接终止读取。探测阶段某个接口出错时会跳过它,只有其他接口都没找到鼠标、也没有报告离线时,才返回该错误。如果两个功能都未返回电池状态,命令会报错,不会将读取失败显示为 `0%`。 ## 许可证 diff --git a/src/hidpp.rs b/src/hidpp.rs index 37422cf..1fb9000 100644 --- a/src/hidpp.rs +++ b/src/hidpp.rs @@ -42,10 +42,6 @@ pub struct BatteryStatus { #[derive(Debug)] pub enum HidppError { Hid(HidError), - ShortWrite { - expected: usize, - actual: usize, - }, /// A reply matched the request but is too short to decode. `match_report` /// already checked the report ID, device index, feature index, and function /// byte, and turned error reports into their own outcomes. @@ -59,10 +55,6 @@ impl fmt::Display for HidppError { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Hid(error) => write!(formatter, "HID access failed: {error}"), - Self::ShortWrite { expected, actual } => write!( - formatter, - "short HID++ write: expected {expected} bytes, wrote {actual}" - ), Self::ShortResponse { minimum, actual } => write!( formatter, "short HID++ response: expected at least {minimum} bytes, got {actual}" @@ -141,14 +133,16 @@ enum BatteryFeature { /// Report I/O and the monotonic timeline used by a request. trait RequestIo { - fn write(&self, report: &[u8]) -> Result; + fn write(&self, report: &[u8]) -> Result<(), HidError>; fn read_timeout(&self, buffer: &mut [u8], timeout_ms: i32) -> Result; fn now(&self) -> Instant; } impl RequestIo for HidDevice { - fn write(&self, report: &[u8]) -> Result { - HidDevice::write(self, report) + // hidapi's macOS backend writes a report whole or fails, so the returned + // byte count carries no information. + fn write(&self, report: &[u8]) -> Result<(), HidError> { + HidDevice::write(self, report).map(drop) } fn read_timeout(&self, buffer: &mut [u8], timeout_ms: i32) -> Result { @@ -206,17 +200,6 @@ fn request_timeout(io: &impl RequestIo, deadline: Instant) -> Duration { .min(RESPONSE_TIMEOUT) } -fn send_short(io: &impl RequestIo, report: [u8; 7]) -> Result<(), HidppError> { - let actual = io.write(&report)?; - if actual != report.len() { - return Err(HidppError::ShortWrite { - expected: report.len(), - actual, - }); - } - Ok(()) -} - /// The reply `report` gives to the request, or `None` if it answers something /// else. A HID++ 2.0 reply echoes the request's function and software ID, so /// matching that byte too rejects stale reports and replies meant for another @@ -271,18 +254,15 @@ impl Device<'_, Io> { ) -> Result { let function_byte = (function << 4) | SW_ID; flush(self.io)?; - send_short( - self.io, - [ - REPORT_ID_SHORT, - self.index, - feature_index, - function_byte, - payload[0], - payload[1], - payload[2], - ], - )?; + self.io.write(&[ + REPORT_ID_SHORT, + self.index, + feature_index, + function_byte, + payload[0], + payload[1], + payload[2], + ])?; let deadline = self.io.now() + timeout; loop { @@ -377,9 +357,7 @@ impl Device<'_, Io> { Err(error @ HidppError::ShortResponse { .. }) => match query_legacy() { Ok(Some(status)) => Ok(Some(status)), Ok(None) | Err(HidppError::ShortResponse { .. }) => Err(error), - Err(legacy_error @ (HidppError::Hid(_) | HidppError::ShortWrite { .. })) => { - Err(legacy_error) - } + Err(legacy_error @ HidppError::Hid(_)) => Err(legacy_error), }, Err(error) => Err(error), } @@ -401,18 +379,12 @@ fn candidate_interfaces(api: &HidApi) -> Vec<&hidapi::DeviceInfo> { candidates } -fn open_interface(api: &HidApi, info: &hidapi::DeviceInfo) -> Result { - let interface = api.open_path(info.path())?; - interface.set_blocking_mode(false)?; - Ok(interface) -} - /// Read the battery status through the first candidate HID interface and /// device index that expose a battery feature. pub fn read_battery(api: &HidApi) -> Result { let interfaces = candidate_interfaces(api) .into_iter() - .map(|info| move || open_interface(api, info)); + .map(|info| move || api.open_path(info.path()).map_err(HidppError::Hid)); read_battery_from(interfaces, Instant::now) } @@ -552,7 +524,7 @@ mod tests { }, Write { report: Vec, - result: Result, + result: Result<(), HidError>, advance: Duration, }, } @@ -574,7 +546,7 @@ mod tests { fn write(report: &[u8]) -> Self { Self::Write { report: report.to_vec(), - result: Ok(report.len()), + result: Ok(()), advance: Duration::ZERO, } } @@ -651,7 +623,7 @@ mod tests { } impl RequestIo for ScriptedIo { - fn write(&self, report: &[u8]) -> Result { + fn write(&self, report: &[u8]) -> Result<(), HidError> { let ScriptStep::Write { report: expected, result, @@ -1259,17 +1231,11 @@ mod tests { enum IoFailure { FlushRead, Write, - ShortWrite, ResponseRead, } impl IoFailure { - const ALL: [Self; 4] = [ - Self::FlushRead, - Self::Write, - Self::ShortWrite, - Self::ResponseRead, - ]; + const ALL: [Self; 3] = [Self::FlushRead, Self::Write, Self::ResponseRead]; /// The script for `request` up to and including this failure. fn steps(self, request: &[u8]) -> Vec { @@ -1278,37 +1244,25 @@ mod tests { result: Err(HidError::InitializationError), advance: Duration::ZERO, }; - let write = |result| ScriptStep::Write { - report: request.to_vec(), - result, - advance: Duration::ZERO, - }; match self { Self::FlushRead => vec![failed_read(0)], Self::Write => vec![ ScriptStep::flush(&[]), - write(Err(HidError::InitializationError)), + ScriptStep::Write { + report: request.to_vec(), + result: Err(HidError::InitializationError), + advance: Duration::ZERO, + }, ], - Self::ShortWrite => vec![ScriptStep::flush(&[]), write(Ok(3))], Self::ResponseRead => exchange(request, [failed_read(1_500)]), } } fn assert_error(self, result: Result) { - match (self, result) { - ( - Self::ShortWrite, - Err(HidppError::ShortWrite { - expected: 7, - actual: 3, - }), - ) - | ( - Self::FlushRead | Self::Write | Self::ResponseRead, - Err(HidppError::Hid(HidError::InitializationError)), - ) => {} - (failure, result) => panic!("{failure:?} produced {result:?}"), - } + assert!( + matches!(result, Err(HidppError::Hid(HidError::InitializationError))), + "{self:?} produced {result:?}" + ); } } From a33ea98c0972d197cb6a108eea2a2d6b393bc113 Mon Sep 17 00:00:00 2001 From: softmaxe <94467584+softmaxe@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:04:28 +0800 Subject: [PATCH 2/3] refactor(raycast)!: drop legacy binary variables and repo-root lookup GBAT_BINARY is the only override, and the script no longer looks for a binary in the repository root, where no build or install puts one. BREAKING CHANGE: GPWBAT_BINARY and GPW2_BATTERY_BINARY are ignored. --- README.md | 10 ++++------ README.zh-CN.md | 4 ++-- raycast/mouse-battery.sh | 7 +------ 3 files changed, 7 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 796c8bb..54d95a1 100644 --- a/README.md +++ b/README.md @@ -94,8 +94,8 @@ Settings, then run `Logitech Mouse Battery`.

The script checks `PATH`, `/opt/homebrew/bin`, `/usr/local/bin`, -`$HOME/.local/bin`, and the repository's `target/release` and root directories, -in that order. +`$HOME/.local/bin`, and the repository's `target/release` directory, in that +order. For a custom binary path, add this line to `mouse-battery.sh` before `set -euo pipefail`: @@ -106,10 +106,8 @@ export GBAT_BINARY="/path/to/gbat" Setting this variable in Terminal only affects scripts launched from that shell. -Explicit paths take priority over the search above. The script checks -`GBAT_BINARY`, then the legacy variables `GPWBAT_BINARY` and -`GPW2_BATTERY_BINARY`, and uses the first non-empty value. That path must point -to an executable file. +`GBAT_BINARY` takes priority over the search above and must point to an +executable file. ## Build from source diff --git a/README.zh-CN.md b/README.zh-CN.md index ee8d88d..d8d95fa 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -77,7 +77,7 @@ gbat gbat Raycast Script Command 演示

-脚本依次检查 `PATH`、`/opt/homebrew/bin`、`/usr/local/bin`、`$HOME/.local/bin`,以及仓库的 `target/release` 目录和根目录。 +脚本依次检查 `PATH`、`/opt/homebrew/bin`、`/usr/local/bin`、`$HOME/.local/bin`,以及仓库的 `target/release` 目录。 如果可执行文件位于其他位置,在 `mouse-battery.sh` 的 `set -euo pipefail` 之前加入: @@ -87,7 +87,7 @@ export GBAT_BINARY="/path/to/gbat" 在 Terminal 中设置这个变量,只会影响从该 Shell 启动的脚本。 -指定路径的优先级高于上述搜索。脚本依次检查 `GBAT_BINARY`、旧变量 `GPWBAT_BINARY` 和 `GPW2_BATTERY_BINARY`,使用第一个非空值。该路径必须指向可执行文件。 +`GBAT_BINARY` 的优先级高于上述搜索,且必须指向可执行文件。 ## 从源码构建 diff --git a/raycast/mouse-battery.sh b/raycast/mouse-battery.sh index 99fb129..5d0e413 100755 --- a/raycast/mouse-battery.sh +++ b/raycast/mouse-battery.sh @@ -14,10 +14,6 @@ project_dir="${script_dir:h}" if [[ -n "${GBAT_BINARY:-}" ]]; then binary_path="$GBAT_BINARY" -elif [[ -n "${GPWBAT_BINARY:-}" ]]; then - binary_path="$GPWBAT_BINARY" -elif [[ -n "${GPW2_BATTERY_BINARY:-}" ]]; then - binary_path="$GPW2_BATTERY_BINARY" elif binary_path="$(command -v gbat 2>/dev/null)" && [[ -x "$binary_path" ]]; then : else @@ -26,8 +22,7 @@ else "/opt/homebrew/bin/gbat" \ "/usr/local/bin/gbat" \ "$HOME/.local/bin/gbat" \ - "$project_dir/target/release/gbat" \ - "$project_dir/gbat"; do + "$project_dir/target/release/gbat"; do if [[ -x "$candidate" ]]; then binary_path="$candidate" break From 6f1cc6d458e41c98793828a7c40666cf04738142 Mon Sep 17 00:00:00 2001 From: softmaxe <94467584+softmaxe@users.noreply.github.com> Date: Fri, 30 Oct 2026 16:04:28 +0800 Subject: [PATCH 3/3] docs: record the demo with VHS alone VHS 0.12.1 renders and replaces the GIF itself, so the FFmpeg pipeline that worked around 0.12.0 is no longer needed. --- docs/record-demo.sh | 36 +++--------------------------------- docs/recording.md | 12 +++++------- 2 files changed, 8 insertions(+), 40 deletions(-) diff --git a/docs/record-demo.sh b/docs/record-demo.sh index d951816..3002c75 100755 --- a/docs/record-demo.sh +++ b/docs/record-demo.sh @@ -22,17 +22,13 @@ printf 'Recording %s\n' "$version" work_dir=$(mktemp -d "$project_root/target/record-demo.XXXXXX") trap 'rm -r "$work_dir"' EXIT trap 'exit 1' HUP INT TERM -frames="$work_dir/frames" candidate="$work_dir/demo.gif" -# VHS 0.12.0 cancels its render context before starting FFmpeg. Keep its PNG -# frames and render separately. A temporary GIF output also makes VHS generate -# bar.png and mask.png; no tape output can overwrite the published GIF. -awk -v frames="$frames" -v video="$work_dir/vhs.gif" ' +# Render to a temporary file so a failed recording keeps the published GIF. +awk -v output="$candidate" ' /^[[:space:]]*Output[[:space:]]/ { if (!replaced) { - print "Output \"" video "\"" - print "Output \"" frames "/\"" + print "Output \"" output "\"" replaced = 1 } next @@ -42,32 +38,6 @@ awk -v frames="$frames" -v video="$work_dir/vhs.gif" ' ' demo.tape > "$work_dir/demo.tape" vhs "$work_dir/demo.tape" -# Match demo.tape: 1100x500, 30 fps, 24 px padding, a 30 px window bar, -# Catppuccin Mocha background, and the border mask generated by VHS. -ffmpeg -hide_banner -loglevel error -y \ - -framerate 30 -start_number 1 -i "$frames/frame-text-%05d.png" \ - -framerate 30 -start_number 1 -i "$frames/frame-cursor-%05d.png" \ - -f lavfi -i 'color=#1e1e2e:s=1100x500:r=30' \ - -framerate 30 -i "$frames/bar.png" \ - -framerate 30 -i "$frames/mask.png" \ - -filter_complex ' - [0][1]overlay[merged]; - [merged]scale=1052:422:force_original_aspect_ratio=1[scaled]; - [scaled]fps=30,setpts=PTS/1.0[speed]; - [speed]pad=1100:470:(ow-iw)/2:(oh-ih)/2:#1e1e2e[padded]; - [padded]fillborders=left=24:right=24:top=24:bottom=24:mode=fixed:color=#1e1e2e[filled]; - [3]loop=-1:size=1[loopbar]; - [loopbar][filled]overlay=0:30:shortest=1[withbar]; - [4]loop=-1:size=1[loopmask]; - [withbar][loopmask]alphamerge=shortest=1[rounded]; - [2]scale=1100:500[bg]; - [bg][rounded]overlay=(W-w)/2:(H-h)/2:shortest=1[withbg]; - [withbg]split[plt_a][plt_b]; - [plt_a]palettegen=max_colors=256[plt]; - [plt_b][plt]paletteuse[palette] - ' \ - -map '[palette]' "$candidate" - test -s "$candidate" ffmpeg -hide_banner -loglevel error -xerror -i "$candidate" -f null - cp "$candidate" "$project_root/assets/demo.gif" diff --git a/docs/recording.md b/docs/recording.md index 800f931..e198b11 100644 --- a/docs/recording.md +++ b/docs/recording.md @@ -30,15 +30,13 @@ The script builds with `--locked`, verifies a real battery read, and records sets `GBAT_BINARY` to that same build, so all four commands use it. There is no sample-output wrapper. -The recorder exports PNG frames with VHS, encodes them with FFmpeg, and checks -that the GIF can be decoded before replacing `assets/demo.gif`. Temporary files -are removed on exit. This avoids a VHS `0.12.0` issue where the recording context -is cancelled before rendering, leaving the existing GIF untouched despite a -successful exit. See the upstream [render call](https://github.com/charmbracelet/vhs/blob/v0.12.0/evaluator.go#L187). +The recorder renders to a temporary GIF and checks that FFmpeg can decode it +before replacing `assets/demo.gif`. Temporary files are removed on exit. + +Use VHS `0.12.1` or later: `0.12.0` can exit successfully without rendering, +which leaves the existing GIF untouched. The checked-in capture used VHS `0.12.1`, ttyd `1.7.7`, and FFmpeg `9.0.2`. -If you change the tape's dimensions, frame rate, padding, theme, or window bar, -update the matching FFmpeg settings in [`record-demo.sh`](record-demo.sh). ## Preserve the original Raycast animation