From 06be911bec9b0b74443ba48c7e2a32d04077f007 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:49:14 +0100 Subject: [PATCH 01/28] feat(hidpp): read and write the 0x1F20 power-off timeout AdcMeasurementFeature gains get_power_off_timeout (function 1) and set_power_off_timeout (function 2), in minutes with 0 meaning never. A G933 answers both at feature version 0; the write's echo is the confirmation, as with the sidetone level. --- .../src/feature/adc_measurement.rs | 101 +++++++++++++++++- 1 file changed, 99 insertions(+), 2 deletions(-) diff --git a/crates/openlogi-hidpp/src/feature/adc_measurement.rs b/crates/openlogi-hidpp/src/feature/adc_measurement.rs index c9b429f515..79dfb628f0 100644 --- a/crates/openlogi-hidpp/src/feature/adc_measurement.rs +++ b/crates/openlogi-hidpp/src/feature/adc_measurement.rs @@ -12,6 +12,12 @@ //! the link changes, which //! [`AdcMeasurementFeature::is_status_broadcast`] recognizes. //! +//! Functions `1` and `2` read and write the headset's automatic power-off +//! timeout in minutes, `0` meaning never. Solaar (`ADCPower`) documents them +//! for version 2 and later; a G933 (`046d:0a5b`) answers both at version 0 +//! (measured on the device). A device that reports the feature without them +//! answers function `1` with a HID++ error. +//! //! The wire layout is not in a public Logitech spec: the voltage as a //! big-endian millivolt `u16` followed by one flags byte was //! reverse-engineered. The flag values follow the Linux kernel @@ -63,6 +69,26 @@ impl AdcMeasurementFeature { Err(e) => Err(e), } } + + /// Reads the automatic power-off timeout in minutes, `0` meaning never + /// (function `1`). + pub async fn get_power_off_timeout(&self) -> Result { + Ok(self.endpoint.call(1, [0; 3]).await?.extend_payload()[0]) + } + + /// Sets the automatic power-off timeout in minutes, `0` meaning never + /// (function `2`), and returns the timeout the device echoes. + /// + /// The echo is the confirmation to use, as with the sidetone level: a + /// G933 echoes the value it stored, and reads it back afterwards + /// (measured on the device). + pub async fn set_power_off_timeout(&self, minutes: u8) -> Result { + Ok(self + .endpoint + .call(2, [minutes, 0, 0]) + .await? + .extend_payload()[0]) + } } /// A reading from the `0x1F20` `getAdcMeasurement` function, or its event `0` @@ -121,8 +147,79 @@ pub enum AdcChargingStatus { #[cfg(test)] mod tests { - use super::{AdcChargingStatus, AdcMeasurement}; - use crate::protocol::v20::Hidpp20Error; + use std::sync::Arc; + + use super::{AdcChargingStatus, AdcMeasurement, AdcMeasurementFeature}; + use crate::{ + channel::{ + HidppMessage, + mock::{MockRawHidChannel, MockRawHidHandle, channel_with_reader}, + }, + feature::CreatableFeature, + nibble::U4, + protocol::v20::{ErrorType, Hidpp20Error, Message, MessageHeader}, + }; + + /// The `0x1F20` feature index on a G933. + const ADC_INDEX: u8 = 8; + + async fn device() -> (AdcMeasurementFeature, MockRawHidHandle) { + let (raw, handle) = MockRawHidChannel::new(); + let channel = Arc::new(channel_with_reader(raw).await); + (AdcMeasurementFeature::new(channel, 0xff, ADC_INDEX), handle) + } + + fn reply(function: u8, minutes: u8) -> Message { + let header = MessageHeader { + device_index: 0xff, + feature_index: ADC_INDEX, + function_id: U4::from_lo(function), + software_id: U4::from_lo(1), + }; + Message::Short(header, [minutes, 0, 0]) + } + + #[test] + fn reads_the_power_off_timeout_with_function_one() { + futures::executor::block_on(async { + let (feature, handle) = device().await; + // A G933 set to 15 minutes answers `0f`. + handle.queue_response(reply(1, 0x0f).into()); + assert_eq!(feature.get_power_off_timeout().await.unwrap(), 15); + assert_eq!( + handle.written_reports(), + [vec![0x10, 0xff, ADC_INDEX, 0x11, 0, 0, 0]] + ); + }); + } + + #[test] + fn a_power_off_write_returns_the_timeout_the_device_echoes() { + futures::executor::block_on(async { + let (feature, handle) = device().await; + // The G933 echoed `1e` for a 30-minute write. + handle.queue_response(reply(2, 0x1e).into()); + assert_eq!(feature.set_power_off_timeout(30).await.unwrap(), 30); + assert_eq!( + handle.written_reports(), + [vec![0x10, 0xff, ADC_INDEX, 0x21, 30, 0, 0]] + ); + }); + } + + #[test] + fn a_device_without_the_power_off_functions_answers_an_error() { + futures::executor::block_on(async { + let (feature, handle) = device().await; + // The device rejects feature 8, function/software byte 0x11, + // with INVALID_FUNCTION_ID (0x07). + handle.queue_response(HidppMessage::Short([0xff, 0xff, ADC_INDEX, 0x11, 0x07, 0])); + assert!(matches!( + feature.get_power_off_timeout().await, + Err(Hidpp20Error::Feature(ErrorType::InvalidFunctionId)) + )); + }); + } /// Builds a 16-byte payload from the 3 meaningful bytes. fn payload(voltage_mv: u16, flags: u8) -> [u8; 16] { From 9d944eeac46595e620861cff67b2a7e4469dcd80 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:50:17 +0100 Subject: [PATCH 02/28] feat(core): add the headset power-off timeout type and capability PowerOffTimeout holds a headset's automatic power-off timeout in minutes, 0..=90 with 0 meaning never. HidppOperation gains ReadPowerOffTimeout and WritePowerOffTimeout after WriteSidetone, and Capabilities::power_off_timeout is appended after change_host, set when the feature table lists 0x1F20. The flag is not gated on DeviceKind::Headset: capability decisions come from the feature table, not the kind, as sidetone does. A device that lists 0x1F20 only for its battery refuses function 1, and that refusal reads as unsupported. The wire-format inventory pin carries the new field. --- .../src/config/tests/identity.rs | 1 + crates/openlogi-core/src/device.rs | 15 +++ crates/openlogi-core/src/diagnostics.rs | 1 + crates/openlogi-core/src/hid.rs | 2 + crates/openlogi-core/src/hid/error.rs | 10 +- .../src/hid/power_off_timeout.rs | 100 ++++++++++++++++++ crates/openlogi-desktop/src/app/tests.rs | 4 + .../src/state/devices/tests.rs | 1 + crates/openlogi-ipc/tests/wire_format.rs | 3 +- 9 files changed, 134 insertions(+), 3 deletions(-) create mode 100644 crates/openlogi-core/src/hid/power_off_timeout.rs diff --git a/crates/openlogi-core/src/config/tests/identity.rs b/crates/openlogi-core/src/config/tests/identity.rs index 72b3c9a00b..bfb038c8c3 100644 --- a/crates/openlogi-core/src/config/tests/identity.rs +++ b/crates/openlogi-core/src/config/tests/identity.rs @@ -38,6 +38,7 @@ fn device_identity_roundtrips_and_is_iterable() { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, }, light_capabilities: None, driver_id: None, diff --git a/crates/openlogi-core/src/device.rs b/crates/openlogi-core/src/device.rs index d78dfed4f4..aee2998764 100644 --- a/crates/openlogi-core/src/device.rs +++ b/crates/openlogi-core/src/device.rs @@ -247,6 +247,13 @@ pub struct Capabilities { /// identity. #[serde(default)] pub change_host: bool, + /// A headset's automatic power-off timeout can be read and changed — + /// functions `1`/`2` of HID++ `0x1F20 AdcMeasurement`. The feature + /// table cannot say whether a device answers them, so a read that the + /// device refuses reports the setting unsupported. Appended after + /// `change_host`: crosses the IPC and the persisted identity. + #[serde(default)] + pub power_off_timeout: bool, } impl Capabilities { @@ -307,6 +314,7 @@ impl Capabilities { m_keys: ids.contains(&0x8020), macro_record: ids.contains(&0x8030), change_host: ids.contains(&0x1814), + power_off_timeout: ids.contains(&0x1f20), } } @@ -937,6 +945,7 @@ mod tests { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, }), settings_revision: 0, hidpp10: false, @@ -1066,6 +1075,7 @@ mod tests { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, } ); assert!(!Capabilities::from_feature_ids(&[0x0003, 0x1b04]).thumbwheel); @@ -1099,6 +1109,7 @@ mod tests { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, } ); // A G713: the gaming-key features and onboard profiles, no @@ -1140,6 +1151,10 @@ mod tests { // The G535's table: sidetone, and battery through 0x1f20. let headset = Capabilities::from_feature_ids(&[0x0001, 0x0003, 0x0005, 0x8300, 0x1f20]); assert!(headset.sidetone && !headset.buttons && !headset.pointer); + // 0x1f20 offers the power-off timeout until a read finds the device + // does not answer it; 0x8300 alone does not. + assert!(headset.power_off_timeout); + assert!(!Capabilities::from_feature_ids(&[0x0001, 0x8300]).power_off_timeout); } #[test] diff --git a/crates/openlogi-core/src/diagnostics.rs b/crates/openlogi-core/src/diagnostics.rs index 4150d147ae..d2f04e2f13 100644 --- a/crates/openlogi-core/src/diagnostics.rs +++ b/crates/openlogi-core/src/diagnostics.rs @@ -696,6 +696,7 @@ mod tests { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, }), dpi: Some("1600 dpi (range 200–8000, 5 steps)".to_string()), config_key: "4082d".to_string(), diff --git a/crates/openlogi-core/src/hid.rs b/crates/openlogi-core/src/hid.rs index 8f9cbd5803..1c6d7f5d43 100644 --- a/crates/openlogi-core/src/hid.rs +++ b/crates/openlogi-core/src/hid.rs @@ -19,6 +19,7 @@ pub mod light; pub mod onboard; pub mod pairing; pub mod pointer_speed; +pub mod power_off_timeout; pub mod report_rate; pub mod route; pub mod scroll; @@ -39,6 +40,7 @@ pub use light::{LightCommand, commands_for_light_settings}; pub use onboard::{OnboardMode, OnboardProfile, OnboardState, ProfileIndex}; pub use pairing::{Click, PairingError, PasskeyMethod, ReceiverSelector}; pub use pointer_speed::PointerSpeed; +pub use power_off_timeout::PowerOffTimeout; pub use report_rate::{ReportRate, ReportRateInfo}; pub use route::{ DIRECT_DEVICE_INDEX, DeviceRoute, KeypadDescriptor, LOGITECH_VENDOR_ID, RECEIVERS, diff --git a/crates/openlogi-core/src/hid/error.rs b/crates/openlogi-core/src/hid/error.rs index 6f1e2d3a32..39fcb58ca6 100644 --- a/crates/openlogi-core/src/hid/error.rs +++ b/crates/openlogi-core/src/hid/error.rs @@ -362,9 +362,15 @@ pub enum HidppOperation { /// Read the `0x8300` sidetone level. Appended after `ChangeHost` — /// variant order is wire format. ReadSidetone, - /// Write the `0x8300` sidetone level. Appended last — variant order is - /// wire format. + /// Write the `0x8300` sidetone level. Appended after `ReadSidetone` — + /// variant order is wire format. WriteSidetone, + /// Read the `0x1F20` automatic power-off timeout. Appended after + /// `WriteSidetone` — variant order is wire format. + ReadPowerOffTimeout, + /// Write the `0x1F20` automatic power-off timeout. Appended last — + /// variant order is wire format. + WritePowerOffTimeout, } /// HID++ feature error kind in a serializable wire-safe form. diff --git a/crates/openlogi-core/src/hid/power_off_timeout.rs b/crates/openlogi-core/src/hid/power_off_timeout.rs new file mode 100644 index 0000000000..8099e39de7 --- /dev/null +++ b/crates/openlogi-core/src/hid/power_off_timeout.rs @@ -0,0 +1,100 @@ +//! Headset automatic power-off timeout — pure data, no I/O. +//! +//! The HID++ reads and writes that carry a [`PowerOffTimeout`] live in +//! `openlogi_device::write::power_off_timeout`. + +use nutype::nutype; + +const RAW_MAX: u8 = 90; + +/// How many idle minutes a headset waits before it switches itself off: `0` +/// is never. +/// +/// HID++ `0x1F20` carries the timeout in one byte. HeadsetControl offers +/// `0..=90` for the G933, so a value outside that range does not parse. +#[nutype( + const_fn, + validate(less_or_equal = RAW_MAX), + derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + TryFrom, + Into, + Display, + Serialize, + Deserialize + ) +)] +pub struct PowerOffTimeout(u8); + +impl PowerOffTimeout { + /// The headset never switches itself off. + pub const NEVER: Self = match Self::try_new(0) { + Ok(timeout) => timeout, + Err(_) => panic!("valid never power-off timeout"), + }; + + /// The longest timeout. + pub const MAX: Self = match Self::try_new(RAW_MAX) { + Ok(timeout) => timeout, + Err(_) => panic!("valid maximum power-off timeout"), + }; + + /// The timeout nearest to `raw` minutes inside the range: anything above + /// 90 is [`Self::MAX`]. + #[must_use] + pub fn clamped(raw: u8) -> Self { + let Ok(timeout) = Self::try_new(raw.min(RAW_MAX)) else { + unreachable!("a clamped power-off timeout is always valid"); + }; + timeout + } + + /// The timeout in minutes, `0` meaning never. + #[must_use] + pub fn minutes(self) -> u8 { + self.into_inner() + } +} + +#[cfg(test)] +mod tests { + use super::PowerOffTimeout; + + #[test] + fn only_zero_to_ninety_minutes_parse() { + assert_eq!(PowerOffTimeout::try_new(0), Ok(PowerOffTimeout::NEVER)); + assert_eq!(PowerOffTimeout::try_new(90), Ok(PowerOffTimeout::MAX)); + assert!( + PowerOffTimeout::try_new(91).is_err(), + "91 is above the range" + ); + } + + #[test] + fn clamping_keeps_values_in_range_and_caps_the_rest() { + assert_eq!(PowerOffTimeout::clamped(15).minutes(), 15); + assert_eq!(PowerOffTimeout::clamped(255), PowerOffTimeout::MAX); + } + + #[derive(Debug, serde::Deserialize)] + struct Holder { + timeout: PowerOffTimeout, + } + + #[test] + fn deserializing_rejects_an_out_of_range_timeout() { + assert!( + toml::from_str::("timeout = 91").is_err(), + "the wire type keeps the range" + ); + let holder: Holder = toml::from_str("timeout = 30").unwrap(); + assert_eq!(holder.timeout.minutes(), 30); + } +} diff --git a/crates/openlogi-desktop/src/app/tests.rs b/crates/openlogi-desktop/src/app/tests.rs index ecc80cfa8a..888e9af116 100644 --- a/crates/openlogi-desktop/src/app/tests.rs +++ b/crates/openlogi-desktop/src/app/tests.rs @@ -1317,6 +1317,7 @@ fn tabs_prefer_buttons_when_a_keyboard_kind_measures_a_pointer() { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, }); let tabs = DetailTab::tabs_for(&record(DeviceKind::Keyboard, caps)); assert!( @@ -1360,6 +1361,7 @@ fn tabs_follow_capabilities_not_kind() { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, }); // After 0x0005 kind-correction the record has kind=Mouse, not Keyboard. let tabs = DetailTab::tabs_for(&record(DeviceKind::Mouse, caps)); @@ -1450,6 +1452,7 @@ fn keyboard_without_asset_hides_buttons_tab() { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, }); let tabs = DetailTab::tabs_for(&record(DeviceKind::Keyboard, caps)); assert!( @@ -1487,6 +1490,7 @@ fn keyboard_with_buttons_shows_keys_tab() { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, }); let keyboard = record(DeviceKind::Keyboard, caps); let tabs = DetailTab::tabs_for(&keyboard); diff --git a/crates/openlogi-desktop/src/state/devices/tests.rs b/crates/openlogi-desktop/src/state/devices/tests.rs index ac21bbbf66..90c2ee71b3 100644 --- a/crates/openlogi-desktop/src/state/devices/tests.rs +++ b/crates/openlogi-desktop/src/state/devices/tests.rs @@ -372,6 +372,7 @@ fn mouse_identity(name: &str) -> DeviceIdentity { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: false, }, light_capabilities: None, model_info: None, diff --git a/crates/openlogi-ipc/tests/wire_format.rs b/crates/openlogi-ipc/tests/wire_format.rs index 644af8d463..5e11fe19d5 100644 --- a/crates/openlogi-ipc/tests/wire_format.rs +++ b/crates/openlogi-ipc/tests/wire_format.rs @@ -975,6 +975,7 @@ fn device_inventory() { m_keys: false, macro_record: false, change_host: false, + power_off_timeout: true, }), settings_revision: 7, hidpp10: false, @@ -982,7 +983,7 @@ fn device_inventory() { }]; assert_wire( &inventory, - "010d426f6c74205265636569766572fb6d04fb48c501084630304443414645010101094d58204d535452335301fb34b00001010150020001030106323134304c5a0102030400010100fb34b0fb8240000b01010100000101010101000101010101010100000001000000000700", + "010d426f6c74205265636569766572fb6d04fb48c501084630304443414645010101094d58204d535452335301fb34b00001010150020001030106323134304c5a0102030400010100fb34b0fb8240000b0101010000010101010100010101010101010000000100000000010700", ); } From 029b0e66deebec68cfa53dc3f041de530cd5e5eb Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:51:49 +0100 Subject: [PATCH 03/28] feat(device): read and write a headset's power-off timeout get_power_off_timeout/set_power_off_timeout and their _on variants talk to 0x1F20 functions 1 and 2. A write returns the headset's echo. A device that lists 0x1F20 for its battery but refuses function 1 reads as FeatureUnsupported; a Busy answer stays a retryable error. --- crates/openlogi-device/src/lib.rs | 38 ++-- crates/openlogi-device/src/write.rs | 7 +- .../src/write/power_off_timeout.rs | 126 ++++++++++++ .../src/write/power_off_timeout/tests.rs | 181 ++++++++++++++++++ 4 files changed, 333 insertions(+), 19 deletions(-) create mode 100644 crates/openlogi-device/src/write/power_off_timeout.rs create mode 100644 crates/openlogi-device/src/write/power_off_timeout/tests.rs diff --git a/crates/openlogi-device/src/lib.rs b/crates/openlogi-device/src/lib.rs index 560065226d..5d134be7d9 100644 --- a/crates/openlogi-device/src/lib.rs +++ b/crates/openlogi-device/src/lib.rs @@ -81,27 +81,29 @@ pub use write::{ HidppFeatureErrorKind, HidppOperation, HostConnection, HostOs, HostOsInfo, HostOsKind, KeyDisplay, KeyImageJpeg, LITRA_BEAM_PRODUCT_ID, LITRA_GLOW_PRODUCT_ID, LightChange, LightCommand, LightControls, LightWatch, LightingMethod, LitraDescriptor, LitraModel, - OsLayoutOutcome, OsMask, OsVersion, PointerSpeed, RAW_BATTERY_FEATURES, RAW_FEATURE_PARAMS, - RawFeatureAnswers, RawFeatureCall, RawFeatureReply, ReportRate, ReportRateInfo, - ReprogControlEntry, ScrollReportingTarget, ScrollResolution, ScrollWheelMode, SidetoneLevel, - WriteError, apply_litra, commands_for_light_settings, dump_features, dump_firmware_entities, - dump_reprog_controls, encode_litra_command, ensure_haptics_armed_on, find_litra, get_backlight, - get_backlight_on, get_disable_keys, get_disable_keys_on, get_dpi, get_dpi_info, - get_dpi_info_on, get_easy_switch_hosts, get_easy_switch_hosts_on, get_fn_lock, get_fn_lock_on, - get_force_sensing_on, get_onboard, get_onboard_on, get_pointer_speed_on, get_report_rate_info, - get_report_rate_info_on, get_scroll_wheel_mode, get_scroll_wheel_mode_on, get_sidetone, - get_sidetone_on, get_smartshift_status, get_smartshift_status_on, get_unit_id_on, - keep_os_layout_on, key_display_for, litra_model_for_route, matches_litra, play_haptic, - play_haptic_on, raw_feature_calls, read_battery_raw, read_litra_state, rename_easy_switch_host, + OsLayoutOutcome, OsMask, OsVersion, PointerSpeed, PowerOffTimeout, RAW_BATTERY_FEATURES, + RAW_FEATURE_PARAMS, RawFeatureAnswers, RawFeatureCall, RawFeatureReply, ReportRate, + ReportRateInfo, ReprogControlEntry, ScrollReportingTarget, ScrollResolution, ScrollWheelMode, + SidetoneLevel, WriteError, apply_litra, commands_for_light_settings, dump_features, + dump_firmware_entities, dump_reprog_controls, encode_litra_command, ensure_haptics_armed_on, + find_litra, get_backlight, get_backlight_on, get_disable_keys, get_disable_keys_on, get_dpi, + get_dpi_info, get_dpi_info_on, get_easy_switch_hosts, get_easy_switch_hosts_on, get_fn_lock, + get_fn_lock_on, get_force_sensing_on, get_onboard, get_onboard_on, get_pointer_speed_on, + get_power_off_timeout, get_power_off_timeout_on, get_report_rate_info, get_report_rate_info_on, + get_scroll_wheel_mode, get_scroll_wheel_mode_on, get_sidetone, get_sidetone_on, + get_smartshift_status, get_smartshift_status_on, get_unit_id_on, keep_os_layout_on, + key_display_for, litra_model_for_route, matches_litra, play_haptic, play_haptic_on, + raw_feature_calls, read_battery_raw, read_litra_state, rename_easy_switch_host, rename_easy_switch_host_on, restore_haptics_on, set_disable_keys, set_disable_keys_on, set_disable_keys_write_through_on, set_dpi, set_dpi_led_on, set_dpi_on, set_dpi_target_on, set_fn_lock, set_fn_lock_on, set_force_sensing_on, set_keyboard_color, set_keyboard_color_on, - set_keyboard_color_with, set_keyboard_color_with_on, set_pointer_speed_on, set_report_rate, - set_report_rate_on, set_scroll_inversion, set_scroll_inversion_on, set_scroll_resolution, - set_scroll_resolution_on, set_scroll_wheel_mode, set_scroll_wheel_mode_on, set_sidetone, - set_sidetone_on, set_smartshift, set_smartshift_on, set_smartshift_sensitivity, - set_smartshift_torque, toggle_smartshift, toggle_smartshift_on, update_backlight, - update_backlight_on, watch_button_spy, watch_litra, write_key_image_on, + set_keyboard_color_with, set_keyboard_color_with_on, set_pointer_speed_on, + set_power_off_timeout, set_power_off_timeout_on, set_report_rate, set_report_rate_on, + set_scroll_inversion, set_scroll_inversion_on, set_scroll_resolution, set_scroll_resolution_on, + set_scroll_wheel_mode, set_scroll_wheel_mode_on, set_sidetone, set_sidetone_on, set_smartshift, + set_smartshift_on, set_smartshift_sensitivity, set_smartshift_torque, toggle_smartshift, + toggle_smartshift_on, update_backlight, update_backlight_on, watch_button_spy, watch_litra, + write_key_image_on, }; /// Scripted transport helpers for tests in higher layers. diff --git a/crates/openlogi-device/src/write.rs b/crates/openlogi-device/src/write.rs index 5437f6a79a..1091e763f0 100644 --- a/crates/openlogi-device/src/write.rs +++ b/crates/openlogi-device/src/write.rs @@ -37,6 +37,7 @@ mod litra; mod onboard; mod os_layout; mod pointer_scaling; +mod power_off_timeout; mod report_rate; mod sidetone; mod smartshift; @@ -96,13 +97,17 @@ pub use openlogi_core::hid::{ EasySwitchHosts, EasySwitchSlot, HostConnection, HostOsInfo, HostOsKind, }; pub use openlogi_core::hid::{ - ForceSensingInfo, PointerSpeed, ReportRate, ReportRateInfo, SidetoneLevel, + ForceSensingInfo, PointerSpeed, PowerOffTimeout, ReportRate, ReportRateInfo, SidetoneLevel, }; pub use os_layout::{HostOs, OsLayoutOutcome, OsVersion, keep_os_layout_on}; pub use pointer_scaling::{ PointerScaling, get_pointer_scaling, get_pointer_speed_on, set_pointer_scaling, set_pointer_speed_on, }; +pub use power_off_timeout::{ + get_power_off_timeout, get_power_off_timeout_on, set_power_off_timeout, + set_power_off_timeout_on, +}; pub(crate) use report_rate::set_report_rate_on_channel; pub use report_rate::{ get_report_rate_info, get_report_rate_info_on, set_report_rate, set_report_rate_on, diff --git a/crates/openlogi-device/src/write/power_off_timeout.rs b/crates/openlogi-device/src/write/power_off_timeout.rs new file mode 100644 index 0000000000..732a006918 --- /dev/null +++ b/crates/openlogi-device/src/write/power_off_timeout.rs @@ -0,0 +1,126 @@ +//! HID++ `0x1F20 AdcMeasurement` functions `1`/`2`: how many idle minutes a +//! headset waits before it switches itself off. +//! +//! The headset keeps the timeout across power cycles, so nothing here is +//! saved or written again on reconnect. + +use std::sync::Arc; + +use hidpp::{ + channel::HidppChannel, + device::Device, + feature::CreatableFeature, + feature::adc_measurement::AdcMeasurementFeature, + protocol::v20::{ErrorType, Hidpp20Error}, +}; +use openlogi_core::hid::PowerOffTimeout; +use tracing::debug; + +use super::{HidppOperation, WriteError, classify_hidpp_error, open_feature, with_route}; +use crate::SharedChannel; +use crate::backend::HidBackend; +use crate::channel::route::DeviceRoute; + +/// Read the automatic power-off timeout of the headset `route` reaches. +pub async fn get_power_off_timeout( + backend: &dyn HidBackend, + route: &DeviceRoute, +) -> Result { + let index = route.device_index(); + with_route(backend, route, move |channel| async move { + let feature = open_adc_feature(&channel, index).await?; + read(&feature).await + }) + .await +} + +/// Write `timeout` to the headset `route` reaches and return the timeout it +/// confirms. +pub async fn set_power_off_timeout( + backend: &dyn HidBackend, + route: &DeviceRoute, + timeout: PowerOffTimeout, +) -> Result { + let index = route.device_index(); + with_route(backend, route, move |channel| async move { + let feature = open_adc_feature(&channel, index).await?; + write(&feature, index, timeout).await + }) + .await +} + +/// Read the automatic power-off timeout on an already-open +/// [`SharedChannel`]. +pub async fn get_power_off_timeout_on( + shared: &SharedChannel, +) -> Result { + let feature = open_adc_feature(shared.channel(), shared.device_index()).await?; + read(&feature).await +} + +/// Write `timeout` on an already-open [`SharedChannel`] and return the +/// timeout the headset confirms. +pub async fn set_power_off_timeout_on( + shared: &SharedChannel, + timeout: PowerOffTimeout, +) -> Result { + let index = shared.device_index(); + let feature = open_adc_feature(shared.channel(), index).await?; + write(&feature, index, timeout).await +} + +/// A device can list `0x1F20` for its battery without answering function +/// `1`, and it refuses the call with a HID++ error, so a refused read is the +/// feature being unsupported. `Busy` is a transient answer, not a refusal. +async fn read(feature: &AdcMeasurementFeature) -> Result { + let raw = feature + .get_power_off_timeout() + .await + .map_err(|error| match error { + Hidpp20Error::Feature(kind) if kind != ErrorType::Busy => { + WriteError::FeatureUnsupported { + feature_hex: AdcMeasurementFeature::ID, + } + } + error => classify(error, HidppOperation::ReadPowerOffTimeout), + })?; + parse(raw, HidppOperation::ReadPowerOffTimeout) +} + +/// The confirmation is the write's own echo, as for the sidetone level. +async fn write( + feature: &AdcMeasurementFeature, + index: u8, + timeout: PowerOffTimeout, +) -> Result { + let raw = feature + .set_power_off_timeout(timeout.minutes()) + .await + .map_err(|error| classify(error, HidppOperation::WritePowerOffTimeout))?; + let applied = parse(raw, HidppOperation::WritePowerOffTimeout)?; + debug!(index, %timeout, %applied, "power-off timeout written"); + Ok(applied) +} + +/// A timeout above the supported range is a reply this type cannot carry. +fn parse(raw: u8, operation: HidppOperation) -> Result { + PowerOffTimeout::try_new(raw) + .map_err(|_| classify(Hidpp20Error::UnsupportedResponse, operation)) +} + +fn classify(error: Hidpp20Error, operation: HidppOperation) -> WriteError { + classify_hidpp_error(error, operation, AdcMeasurementFeature::ID) +} + +async fn open_adc_feature( + channel: &Arc, + index: u8, +) -> Result, WriteError> { + let mut device = Device::new(Arc::clone(channel), index) + .await + .map_err(|_| WriteError::DeviceUnreachable { index })?; + open_feature::(&mut device).await +} + +#[cfg(test)] +mod tests; diff --git a/crates/openlogi-device/src/write/power_off_timeout/tests.rs b/crates/openlogi-device/src/write/power_off_timeout/tests.rs new file mode 100644 index 0000000000..4ac80b7ec7 --- /dev/null +++ b/crates/openlogi-device/src/write/power_off_timeout/tests.rs @@ -0,0 +1,181 @@ +//! Tests for the `0x1F20` power-off timeout reads and writes. + +use std::assert_matches; +use std::sync::{Arc, Mutex}; + +use super::*; +use crate::channel::route::DeviceRoute; +use crate::channel::scripted::{ScriptedRawHidChannel, feature_error, scripted_channel}; + +/// The `0x1F20` feature index on a G933. +const ADC_INDEX: u8 = 0x08; +/// HID++ 2.0 `InvalidFunctionId`, what a device without functions `1`/`2` +/// answers. +const INVALID_FUNCTION_ID: u8 = 0x07; +/// HID++ 2.0 `Busy`. +const BUSY: u8 = 0x08; + +/// A G933 as measured: it echoes each write and reads the new timeout back. +struct Headset { + /// The stored timeout in minutes. + minutes: u8, + /// The error code function `1` answers instead of the timeout, for a + /// device that lists `0x1F20` for its battery only. + read_error: Option, + /// Every timeout written. + writes: Vec, +} + +impl Headset { + fn g933(minutes: u8) -> Self { + Self { + minutes, + read_error: None, + writes: Vec::new(), + } + } + + fn respond(&mut self, request: &[u8]) -> Option> { + if request.len() < 7 || !matches!(request[0], 0x10 | 0x11) { + return None; + } + let function = request[3] >> 4; + let mut payload = [0u8; 16]; + match (request[2], function) { + (0x00, 0x01) => payload[0] = 4, + (0x00, 0x00) => { + if u16::from_be_bytes([request[4], request[5]]) == 0x1f20 { + payload[0] = ADC_INDEX; + } + } + (ADC_INDEX, 0x01) => { + if let Some(error) = self.read_error { + return Some(feature_error(request, error)); + } + payload[0] = self.minutes; + } + (ADC_INDEX, 0x02) => { + self.writes.push(request[4]); + self.minutes = request[4]; + payload[0] = request[4]; + } + _ => return None, + } + let mut response = vec![0u8; 20]; + response[0] = 0x11; + response[1..4].copy_from_slice(&request[1..4]); + response[4..].copy_from_slice(&payload); + Some(response) + } +} + +async fn headset_channel(headset: &Arc>) -> SharedChannel { + let headset = Arc::clone(headset); + let (raw, _handle) = ScriptedRawHidChannel::with_dynamic_responder(move |request| { + headset.lock().expect("headset lock").respond(request) + }); + let route = DeviceRoute::Direct { + vendor_id: 0x046d, + product_id: 0x0a5b, + }; + SharedChannel::new(scripted_channel(raw).await, route) +} + +fn minutes(raw: u8) -> PowerOffTimeout { + PowerOffTimeout::try_new(raw).expect("a timeout in range") +} + +#[tokio::test] +async fn reads_the_timeout_the_headset_reports() { + let headset = Arc::new(Mutex::new(Headset::g933(15))); + let shared = headset_channel(&headset).await; + + assert_eq!( + get_power_off_timeout_on(&shared).await.unwrap(), + minutes(15) + ); + assert!( + headset.lock().unwrap().writes.is_empty(), + "a read writes nothing" + ); +} + +#[tokio::test] +async fn a_write_returns_the_echo_and_reads_back() { + let headset = Arc::new(Mutex::new(Headset::g933(15))); + let shared = headset_channel(&headset).await; + + assert_eq!( + set_power_off_timeout_on(&shared, minutes(30)) + .await + .unwrap(), + minutes(30) + ); + assert_eq!( + get_power_off_timeout_on(&shared).await.unwrap(), + minutes(30) + ); + assert_eq!(headset.lock().unwrap().writes, [30]); +} + +#[tokio::test] +async fn never_is_written_as_zero() { + let headset = Arc::new(Mutex::new(Headset::g933(15))); + let shared = headset_channel(&headset).await; + + assert_eq!( + set_power_off_timeout_on(&shared, PowerOffTimeout::NEVER) + .await + .unwrap(), + PowerOffTimeout::NEVER + ); + assert_eq!(headset.lock().unwrap().writes, [0]); +} + +#[tokio::test] +async fn a_refused_read_means_the_device_does_not_support_the_timeout() { + let headset = Arc::new(Mutex::new(Headset { + read_error: Some(INVALID_FUNCTION_ID), + ..Headset::g933(0) + })); + let shared = headset_channel(&headset).await; + + assert_matches!( + get_power_off_timeout_on(&shared).await, + Err(WriteError::FeatureUnsupported { + feature_hex: 0x1f20 + }) + ); +} + +#[tokio::test] +async fn a_busy_read_stays_a_retryable_error() { + let headset = Arc::new(Mutex::new(Headset { + read_error: Some(BUSY), + ..Headset::g933(0) + })); + let shared = headset_channel(&headset).await; + + assert_matches!( + get_power_off_timeout_on(&shared).await, + Err(WriteError::HidppFeature { + operation: HidppOperation::ReadPowerOffTimeout, + feature_hex: 0x1f20, + .. + }) + ); +} + +#[tokio::test] +async fn a_timeout_above_the_range_is_an_unsupported_response() { + let headset = Arc::new(Mutex::new(Headset::g933(120))); + let shared = headset_channel(&headset).await; + + assert_matches!( + get_power_off_timeout_on(&shared).await, + Err(WriteError::UnsupportedResponse { + operation: HidppOperation::ReadPowerOffTimeout, + feature_hex: 0x1f20 + }) + ); +} From 4f19174dc05ad013251ad958561a2edfc769b172 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:51:49 +0100 Subject: [PATCH 04/28] feat(device): re-measure cached devices for the power-off capability Bump the probe-cache schema to v21 so a cached 0x1F20 headset gains Capabilities::power_off_timeout without waiting for a fresh probe. --- crates/openlogi-device/src/inventory/persist.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/openlogi-device/src/inventory/persist.rs b/crates/openlogi-device/src/inventory/persist.rs index 8130406690..9d220ea438 100644 --- a/crates/openlogi-device/src/inventory/persist.rs +++ b/crates/openlogi-device/src/inventory/persist.rs @@ -60,7 +60,9 @@ use super::features::{BatteryProbe, ProbedFeatures}; /// which also records HID++ 1.0, and adds the HID++ 1.0 battery registers to /// `BatteryProbe`. /// v20 adds the `Capabilities::change_host` flag (`0x1814` host switching). -const SCHEMA_VERSION: u32 = 20; +/// v21 adds the `Capabilities::power_off_timeout` flag (`0x1F20` headset +/// power-off timeout). +const SCHEMA_VERSION: u32 = 21; impl ProbeCacheError { /// Report why a store could not keep a snapshot. From 4fc5300c749469f601a77b0d17e60ea521dcc42c Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:52:10 +0100 Subject: [PATCH 05/28] feat(hid): expose the headset power-off timeout on this host --- crates/openlogi-hid/src/host.rs | 18 ++++++++++++++++-- crates/openlogi-hid/src/lib.rs | 13 +++++++------ 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/crates/openlogi-hid/src/host.rs b/crates/openlogi-hid/src/host.rs index 60a0f79296..661f1d955b 100644 --- a/crates/openlogi-hid/src/host.rs +++ b/crates/openlogi-hid/src/host.rs @@ -27,8 +27,8 @@ use openlogi_device::inventory::{Enumerator, InventoryError}; use openlogi_device::pairing::PairingReceiver; use openlogi_device::write::{ self as device, Dpi, DpiInfo, FeatureEntry, FirmwareEntity, HapticWaveform, LightingMethod, - LitraModel, PointerScaling, ReprogControlEntry, ScrollResolution, ScrollWheelMode, - SidetoneLevel, + LitraModel, PointerScaling, PowerOffTimeout, ReprogControlEntry, ScrollResolution, + ScrollWheelMode, SidetoneLevel, }; use openlogi_device::{ButtonSpyError, ButtonSpyWatch, LightWatch}; use openlogi_device::{DeviceIoGate, DeviceIoSignal, DeviceRoute}; @@ -85,6 +85,20 @@ pub async fn set_sidetone( device::set_sidetone(&*native_backend(), route, level).await } +/// Read the automatic power-off timeout of the headset `route` reaches. +pub async fn get_power_off_timeout(route: &DeviceRoute) -> Result { + device::get_power_off_timeout(&*native_backend(), route).await +} + +/// Write an automatic power-off timeout to the headset `route` reaches and +/// return the timeout it confirms. +pub async fn set_power_off_timeout( + route: &DeviceRoute, + timeout: PowerOffTimeout, +) -> Result { + device::set_power_off_timeout(&*native_backend(), route, timeout).await +} + /// Read the pointer-motion scaling of the device `route` reaches. pub async fn get_pointer_scaling(route: &DeviceRoute) -> Result { device::get_pointer_scaling(&*native_backend(), route).await diff --git a/crates/openlogi-hid/src/lib.rs b/crates/openlogi-hid/src/lib.rs index 29318d2125..04bc52011b 100644 --- a/crates/openlogi-hid/src/lib.rs +++ b/crates/openlogi-hid/src/lib.rs @@ -33,12 +33,13 @@ pub use hidpp::feature::device_information::DeviceEntityType; pub use host::{ apply_litra, channel_pool, dump_features, dump_firmware_entities, dump_reprog_controls, enumerate, enumerate_hid_only, enumerate_standalone, get_backlight, get_dpi, get_dpi_info, - get_onboard, get_pointer_scaling, get_scroll_wheel_mode, get_sidetone, get_smartshift_status, - list_pairing_receivers, play_haptic, raw_feature_calls, read_battery_raw, read_litra_state, - set_dpi, set_fn_lock, set_keyboard_color, set_keyboard_color_with, set_pointer_scaling, - set_scroll_inversion, set_scroll_resolution, set_scroll_wheel_mode, set_sidetone, - set_smartshift, set_smartshift_sensitivity, set_smartshift_torque, toggle_smartshift, - update_backlight, walk_per_key_zones, watch_button_spy, watch_hotplug, watch_litra, + get_onboard, get_pointer_scaling, get_power_off_timeout, get_scroll_wheel_mode, get_sidetone, + get_smartshift_status, list_pairing_receivers, play_haptic, raw_feature_calls, + read_battery_raw, read_litra_state, set_dpi, set_fn_lock, set_keyboard_color, + set_keyboard_color_with, set_pointer_scaling, set_power_off_timeout, set_scroll_inversion, + set_scroll_resolution, set_scroll_wheel_mode, set_sidetone, set_smartshift, + set_smartshift_sensitivity, set_smartshift_torque, toggle_smartshift, update_backlight, + walk_per_key_zones, watch_button_spy, watch_hotplug, watch_litra, }; pub use lighting::{set_keyboard_color_on, set_keyboard_color_with_on}; pub use probe_cache::FileProbeCacheStore; From 64d7dcc983dcc7b308592df362d34204e1d2a554 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:52:58 +0100 Subject: [PATCH 06/28] feat(agent-core): read and write a headset's power-off timeout SharedHandles gains read_power_off_timeout and set_power_off_timeout. Writes are ordered per headset like the sidetone writes: a write superseded before its turn reads the headset instead. --- .../openlogi-agent-core/src/orchestrator.rs | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/openlogi-agent-core/src/orchestrator.rs b/crates/openlogi-agent-core/src/orchestrator.rs index c3aac3218e..d85f007bb7 100644 --- a/crates/openlogi-agent-core/src/orchestrator.rs +++ b/crates/openlogi-agent-core/src/orchestrator.rs @@ -31,9 +31,9 @@ use openlogi_core::device_order::{DeviceIdentity, DeviceStableId, PhysicalDevice use openlogi_hid::{ BacklightChange, BacklightState, CaptureChannelSlot, ChannelPool, ChannelRegistry, DeviceIoGate, DeviceRoute, DisableKeysMask, Dpi, DpiInfo, EasySwitchHosts, FnLockState, - ForceSensingInfo, GamingWanted, HidppOperation, HostOs, PointerSpeed, ReportRate, - ReportRateInfo, SidetoneLevel, SmartShiftStatus, WriteError, commands_for_light_settings, - is_reserved_keyboard_control, key_display_for, + ForceSensingInfo, GamingWanted, HidppOperation, HostOs, PointerSpeed, PowerOffTimeout, + ReportRate, ReportRateInfo, SidetoneLevel, SmartShiftStatus, WriteError, + commands_for_light_settings, is_reserved_keyboard_control, key_display_for, }; #[cfg(test)] use openlogi_ipc::ChosenLight; @@ -200,6 +200,8 @@ pub struct SharedHandles { force_sensing_order: WriteOrder, /// Orders the GUI's sidetone writes per headset. sidetone_order: WriteOrder, + /// Orders the GUI's power-off timeout writes per headset. + power_off_timeout_order: WriteOrder, /// Orders the GUI's backlight writes per keyboard. backlight_order: WriteOrder, /// Orders host renames per device. @@ -318,6 +320,18 @@ impl SharedHandles { .await } + /// Read the automatic power-off timeout of the headset at `route`. + pub async fn read_power_off_timeout( + &self, + route: &DeviceRoute, + ) -> Result { + self.device(route) + .run(HidppOperation::ReadPowerOffTimeout, |c| async move { + openlogi_hid::get_power_off_timeout_on(&c).await + }) + .await + } + /// Read the DPI and the DPI values of the mouse at `route`. pub async fn read_dpi(&self, route: &DeviceRoute) -> Result { self.device(route) @@ -469,6 +483,26 @@ impl SharedHandles { .await } + /// Write `timeout` to the headset at `route` and return the timeout it + /// confirms. When a newer power-off timeout write for the headset is + /// requested before this one gets its turn, this one reads the headset + /// instead of writing a timeout that is about to be replaced. + pub async fn set_power_off_timeout( + &self, + route: &DeviceRoute, + timeout: PowerOffTimeout, + ) -> Result { + let ticket = self.power_off_timeout_order.request(route); + self.device(route) + .run_in_turn( + HidppOperation::WritePowerOffTimeout, + &ticket, + |c| async move { openlogi_hid::set_power_off_timeout_on(&c, timeout).await }, + |c| async move { openlogi_hid::get_power_off_timeout_on(&c).await }, + ) + .await + } + /// Write `dpi` to the mouse at `route`. On a DPI mouse the write ends /// precision mode, so the pointer moves at the DPI the settings app /// shows, and darkens the DPI LED when the precision speed ends with it. @@ -922,6 +956,7 @@ impl Orchestrator { pointer_speeds: Arc::default(), force_sensing_order: WriteOrder::default(), sidetone_order: WriteOrder::default(), + power_off_timeout_order: WriteOrder::default(), backlight_order: WriteOrder::default(), host_name_order: WriteOrder::default(), host_switch_order: WriteOrder::default(), From f80ea867a2d435932da79eddf803a38c74c9fdae Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:54:56 +0100 Subject: [PATCH 07/28] feat(fixture): record a headset's power-off timeout in device profiles ProfileDeviceSettings::power_off_timeout defaults to unsupported so older profiles keep loading. Since 0x1F20 is also listed for the battery, a profile may hold the timeout unsupported while the inventory advertises it; only a timeout without the advertised feature is rejected. --- .../src/bin/mock_agent/profile.rs | 1 + .../src/cmd/fixture/record_profile.rs | 2 + crates/openlogi-device/src/replay/tests.rs | 1 + crates/openlogi-fixture/src/fs/tests.rs | 40 +++++++++++++++++++ crates/openlogi-fixture/src/schema.rs | 30 +++++++++++++- 5 files changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/openlogi-agent/src/bin/mock_agent/profile.rs b/crates/openlogi-agent/src/bin/mock_agent/profile.rs index 3fa6eb0425..e96411546f 100644 --- a/crates/openlogi-agent/src/bin/mock_agent/profile.rs +++ b/crates/openlogi-agent/src/bin/mock_agent/profile.rs @@ -36,6 +36,7 @@ pub(super) fn unsupported_settings(route: DeviceRoute) -> ProfileDeviceSettings force_sensing: ProfileSetting::Unsupported, disable_keys: ProfileSetting::Unsupported, sidetone: ProfileSetting::Unsupported, + power_off_timeout: ProfileSetting::Unsupported, lighting: ProfileSupport::Unsupported, light: ProfileSupport::Unsupported, } diff --git a/crates/openlogi-cli/src/cmd/fixture/record_profile.rs b/crates/openlogi-cli/src/cmd/fixture/record_profile.rs index dbead09409..a4dcc6cab5 100644 --- a/crates/openlogi-cli/src/cmd/fixture/record_profile.rs +++ b/crates/openlogi-cli/src/cmd/fixture/record_profile.rs @@ -364,6 +364,7 @@ async fn capture_hidpp_settings( force_sensing, disable_keys, sidetone, + power_off_timeout: ProfileSetting::Unsupported, lighting: profile_support(capabilities.lighting), light: ProfileSupport::Unsupported, }) @@ -446,6 +447,7 @@ fn capture_standalone(source: &StandaloneDevice) -> Result force_sensing: ProfileSetting::Unsupported, disable_keys: ProfileSetting::Unsupported, sidetone: ProfileSetting::Unsupported, + power_off_timeout: ProfileSetting::Unsupported, lighting: ProfileSupport::Unsupported, light: profile_support(light_supported), }; diff --git a/crates/openlogi-device/src/replay/tests.rs b/crates/openlogi-device/src/replay/tests.rs index 15eb0f63e0..8c9be9d632 100644 --- a/crates/openlogi-device/src/replay/tests.rs +++ b/crates/openlogi-device/src/replay/tests.rs @@ -903,6 +903,7 @@ fn dpi_settings(route: DeviceRoute, current: u16, supported: Vec) -> Profil force_sensing: ProfileSetting::Unsupported, disable_keys: ProfileSetting::Unsupported, sidetone: ProfileSetting::Unsupported, + power_off_timeout: ProfileSetting::Unsupported, lighting: ProfileSupport::Unsupported, light: ProfileSupport::Unsupported, } diff --git a/crates/openlogi-fixture/src/fs/tests.rs b/crates/openlogi-fixture/src/fs/tests.rs index 6782ce4a91..2c74ccac5f 100644 --- a/crates/openlogi-fixture/src/fs/tests.rs +++ b/crates/openlogi-fixture/src/fs/tests.rs @@ -163,6 +163,46 @@ fn rejects_easy_switch_hosts_the_inventory_capabilities_do_not_advertise() { ); } +#[test] +fn rejects_a_power_off_timeout_the_inventory_capabilities_do_not_advertise() { + let (_temp, fixture) = copied_canonical_fixture(); + let mut profile: serde_json::Value = + serde_json::from_str(CANONICAL_DEVICE_PROFILE_JSON).expect("canonical profile JSON"); + // Slot 1 is an online mouse whose measured capabilities have no `0x1F20`. + profile["settings"][0]["power_off_timeout"] = serde_json::json!({ + "support": "supported", + "value": 15 + }); + std::fs::write( + fixture.join(PROFILE_FILE), + serde_json::to_vec_pretty(&profile).expect("serialize profile"), + ) + .expect("write contradicting power-off timeout"); + let error = Fixture::load(&fixture).expect_err("a contradicting timeout must fail"); + assert!( + format!("{error:#}") + .contains("power-off timeout support does not match inventory capabilities"), + "{error:#}" + ); +} + +#[test] +fn accepts_an_advertised_power_off_timeout_the_device_refused() { + let (_temp, fixture) = copied_canonical_fixture(); + let mut profile: serde_json::Value = + serde_json::from_str(CANONICAL_DEVICE_PROFILE_JSON).expect("canonical profile JSON"); + // `0x1F20` is listed for the battery, but the device refused function 1, + // so the recorder wrote the timeout as unsupported. + profile["inventories"][0]["paired"][0]["capabilities"]["power_off_timeout"] = true.into(); + profile["settings"][0]["power_off_timeout"] = serde_json::json!({ "support": "unsupported" }); + std::fs::write( + fixture.join(PROFILE_FILE), + serde_json::to_vec_pretty(&profile).expect("serialize profile"), + ) + .expect("write refused power-off timeout"); + Fixture::load(&fixture).expect("a refused read is not a contradiction"); +} + #[test] fn rejects_unknown_fields_as_schema_failures() { let (_temp, fixture) = copied_canonical_fixture(); diff --git a/crates/openlogi-fixture/src/schema.rs b/crates/openlogi-fixture/src/schema.rs index 9a40020585..946e63bf21 100644 --- a/crates/openlogi-fixture/src/schema.rs +++ b/crates/openlogi-fixture/src/schema.rs @@ -5,8 +5,8 @@ use std::collections::HashSet; use openlogi_core::device::{Capabilities, DeviceInventory, LightCapabilities, StandaloneDevice}; use openlogi_core::hid::{ BacklightState, BacklightStatus, DIRECT_DEVICE_INDEX, DeviceRoute, DisableKeysState, DpiInfo, - EasySwitchHosts, FnLockState, ForceSensingInfo, PointerSpeed, ReportRateInfo, ScrollWheelMode, - SidetoneLevel, SmartShiftStatus, + EasySwitchHosts, FnLockState, ForceSensingInfo, PointerSpeed, PowerOffTimeout, ReportRateInfo, + ScrollWheelMode, SidetoneLevel, SmartShiftStatus, }; use serde::{Deserialize, Deserializer, Serialize, de}; use thiserror::Error; @@ -213,6 +213,11 @@ pub struct ProfileDeviceSettings { /// profiles recorded before it existed keep loading. #[serde(default = "ProfileSetting::unsupported")] pub sidetone: ProfileSetting, + /// Headset automatic power-off timeout (`0x1F20` functions `1`/`2`) read + /// state. Defaults to unsupported so profiles recorded before it existed + /// keep loading. + #[serde(default = "ProfileSetting::unsupported")] + pub power_off_timeout: ProfileSetting, /// RGB keyboard-lighting write support. pub lighting: ProfileSupport, /// Standalone-light command support. @@ -663,6 +668,7 @@ fn validate_setting_support( || settings.force_sensing.supports_feature() || settings.disable_keys.supports_feature() || settings.sidetone.supports_feature() + || settings.power_off_timeout.supports_feature() || settings.lighting.is_supported() { return Err(FixtureError::invalid( @@ -746,11 +752,31 @@ fn validate_setting_support( for (family, declared, advertised) in families { validate_capability_support(settings, family, declared, advertised)?; } + validate_power_off_timeout_support(settings, &capabilities)?; } } Ok(()) } +/// `0x1F20` is advertised for the battery too, and a headset that refuses +/// function `1` reads as unsupported, so only a timeout without the advertised +/// feature contradicts the inventory. +fn validate_power_off_timeout_support( + settings: &ProfileDeviceSettings, + capabilities: &Capabilities, +) -> Result<(), FixtureError> { + if settings.power_off_timeout.supports_feature() { + validate_capability_support( + settings, + "power-off timeout", + true, + capabilities.power_off_timeout, + ) + } else { + Ok(()) + } +} + fn validate_capability_support( settings: &ProfileDeviceSettings, family: &str, From c62b7b903d8e7499eebaa2714ec8fb9ef74926c7 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:57:01 +0100 Subject: [PATCH 08/28] feat(ipc,agent): serve a headset's power-off timeout over IPC Agent::{read_power_off_timeout, set_power_off_timeout} are appended after action_ring_unhover, under protocol v47. The agent answers them through SharedHandles; the mock agent answers from the profile's power_off_timeout setting. --- crates/openlogi-agent/src/bin/mock_agent.rs | 31 ++++++++++++++-- crates/openlogi-agent/src/server.rs | 21 +++++++++-- .../src/cmd/fixture/record_profile/tests.rs | 27 ++++++++++++-- crates/openlogi-ipc/src/ipc.rs | 23 ++++++++++-- crates/openlogi-ipc/tests/wire_format.rs | 35 ++++++++++++++++--- 5 files changed, 124 insertions(+), 13 deletions(-) diff --git a/crates/openlogi-agent/src/bin/mock_agent.rs b/crates/openlogi-agent/src/bin/mock_agent.rs index 2ae02e9c53..335e6af947 100644 --- a/crates/openlogi-agent/src/bin/mock_agent.rs +++ b/crates/openlogi-agent/src/bin/mock_agent.rs @@ -68,8 +68,9 @@ use openlogi_core::single_instance::{self, InstanceError, Role}; use openlogi_fixture::{DeviceProfile, FixtureError, ProfileDeviceSettings, ProfileSetting}; use openlogi_hid::{ BacklightChange, BacklightState, DeviceRoute, Dpi, DpiInfo, EasySwitchHosts, FnLockState, - ForceSensingInfo, LightCommand, OnboardState, PasskeyMethod, PointerSpeed, ReceiverSelector, - ReportRate, ReportRateInfo, ScrollWheelMode, SidetoneLevel, SmartShiftStatus, WriteError, + ForceSensingInfo, LightCommand, OnboardState, PasskeyMethod, PointerSpeed, PowerOffTimeout, + ReceiverSelector, ReportRate, ReportRateInfo, ScrollWheelMode, SidetoneLevel, SmartShiftStatus, + WriteError, }; use openlogi_ipc::transport; use openlogi_ipc::{ @@ -1603,6 +1604,32 @@ impl Agent for MockAgent { ) -> Result<(), ActionRingCommandError> { Err(ActionRingCommandError::SessionNotFound) } + async fn read_power_off_timeout( + self, + _: Context, + route: DeviceRoute, + ) -> Result { + let state = self.state.lock().await; + profile_value( + &state.settings_for(&route)?.power_off_timeout, + &route, + 0x1f20, + ) + .copied() + } + async fn set_power_off_timeout( + self, + _: Context, + route: DeviceRoute, + timeout: PowerOffTimeout, + ) -> Result { + let mut state = self.state.lock().await; + let settings = state.settings_for_mut(&route)?; + let stored = profile_value_mut(&mut settings.power_off_timeout, &route, 0x1f20)?; + *stored = timeout; + info!(%route, %timeout, "set_power_off_timeout"); + Ok(timeout) + } } #[cfg(test)] diff --git a/crates/openlogi-agent/src/server.rs b/crates/openlogi-agent/src/server.rs index 366284c465..6483e304b7 100644 --- a/crates/openlogi-agent/src/server.rs +++ b/crates/openlogi-agent/src/server.rs @@ -25,8 +25,8 @@ use openlogi_core::device::DeviceInventory; use openlogi_hid::{ BacklightChange, BacklightState, DeviceRoute, Dpi, DpiInfo, EasySwitchHosts, FnLockState, ForceSensingInfo, HapticRestore, HapticRestoreOutcome, HapticWaveform, HidppOperation, - LightCommand, OnboardState, PointerSpeed, ReceiverSelector, ReportRate, ReportRateInfo, - ScrollWheelMode, SidetoneLevel, SmartShiftStatus, WriteError, + LightCommand, OnboardState, PointerSpeed, PowerOffTimeout, ReceiverSelector, ReportRate, + ReportRateInfo, ScrollWheelMode, SidetoneLevel, SmartShiftStatus, WriteError, }; use openlogi_ipc::transport; use openlogi_ipc::{ @@ -599,6 +599,23 @@ impl Agent for AgentServer { ) -> Result<(), ActionRingCommandError> { self.action_ring.unhover(session_id) } + + async fn read_power_off_timeout( + self, + _: Context, + route: DeviceRoute, + ) -> Result { + self.shared.read_power_off_timeout(&route).await + } + + async fn set_power_off_timeout( + self, + _: Context, + route: DeviceRoute, + timeout: PowerOffTimeout, + ) -> Result { + self.shared.set_power_off_timeout(&route, timeout).await + } } /// Run the action a ring session closed on, whether a click on the overlay diff --git a/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs b/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs index 9fc4d8045c..8df6a7d553 100644 --- a/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs +++ b/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs @@ -10,8 +10,8 @@ use openlogi_core::device::DeviceInventory; use openlogi_core::hid::{ BacklightChange, BacklightControls, BacklightMode, BacklightState, BacklightStatus, DisableKeysMask, DisableKeysState, Dpi, DpiInfo, EasySwitchHosts, EasySwitchSlot, FnLockState, - ForceSensingInfo, HostConnection, LightCommand, PasskeyMethod, PointerSpeed, ReceiverSelector, - ReportRate, ReportRateInfo, ScrollWheelMode, SidetoneLevel, SmartShiftStatus, + ForceSensingInfo, HostConnection, LightCommand, PasskeyMethod, PointerSpeed, PowerOffTimeout, + ReceiverSelector, ReportRate, ReportRateInfo, ScrollWheelMode, SidetoneLevel, SmartShiftStatus, }; use openlogi_fixture::{ CANONICAL_DEVICE_PROFILE_JSON, SyntheticIdentityKind, classify_synthetic_identity_bytes, @@ -49,6 +49,7 @@ enum ReadFamily { ForceSensing, DisableKeys, Sidetone, + PowerOffTimeout, } #[derive(Clone)] @@ -527,6 +528,28 @@ impl Agent for TestAgent { unreachable!("profile capture must never write the sidetone") } + async fn read_power_off_timeout( + self, + _: TarpcContext, + route: DeviceRoute, + ) -> Result { + self.read( + ReadFamily::PowerOffTimeout, + &route, + |settings| &settings.power_off_timeout, + 0x1f20, + ) + } + + async fn set_power_off_timeout( + self, + _: TarpcContext, + _route: DeviceRoute, + _timeout: PowerOffTimeout, + ) -> Result { + unreachable!("profile capture must never write the power-off timeout") + } + async fn read_disable_keys( self, _: TarpcContext, diff --git a/crates/openlogi-ipc/src/ipc.rs b/crates/openlogi-ipc/src/ipc.rs index 97a745d242..770393b35a 100644 --- a/crates/openlogi-ipc/src/ipc.rs +++ b/crates/openlogi-ipc/src/ipc.rs @@ -21,8 +21,8 @@ use openlogi_core::device::{ use openlogi_core::hid::{ BacklightChange, BacklightState, DeviceRoute, DisableKeysMask, DisableKeysState, Dpi, DpiInfo, EasySwitchHosts, FnLockState, ForceSensingInfo, LightCommand, OnboardState, PairingError, - PasskeyMethod, PointerSpeed, ReceiverSelector, ReportRate, ReportRateInfo, ScrollWheelMode, - SidetoneLevel, SmartShiftStatus, WriteError, + PasskeyMethod, PointerSpeed, PowerOffTimeout, ReceiverSelector, ReportRate, ReportRateInfo, + ScrollWheelMode, SidetoneLevel, SmartShiftStatus, WriteError, }; use serde::{Deserialize, Serialize}; pub use succession::Identity; @@ -194,7 +194,12 @@ pub use succession::Identity; /// and `ActionRingIcon::{Channel1, Channel2, Channel3}` appended after /// them — a device's move to another Easy-Switch channel, bound to a /// button or an Actions Ring slot. -pub const PROTOCOL_VERSION: u32 = 46; +/// v47: `Capabilities::power_off_timeout`, +/// `HidppOperation::{ReadPowerOffTimeout, WritePowerOffTimeout}` and +/// `Agent::{read_power_off_timeout, set_power_off_timeout}` appended — a +/// headset's HID++ `0x1F20` automatic power-off timeout, as a +/// [`PowerOffTimeout`]. +pub const PROTOCOL_VERSION: u32 = 47; /// Environment variable through which the agent hands a supervised helper the /// run token it will serve, so the helper knows which agent it belongs to @@ -1263,4 +1268,16 @@ pub trait Agent { /// held trigger cancels instead of choosing the slot last reported by /// [`Agent::action_ring_hover`]. async fn action_ring_unhover(session_id: u64) -> Result<(), ActionRingCommandError>; + + /// Read the automatic power-off timeout of the headset on `route` (HID++ + /// `0x1F20` function `1`). A headset that refuses the read answers + /// [`WriteError::FeatureUnsupported`]. + async fn read_power_off_timeout(route: DeviceRoute) -> Result; + /// Write the automatic power-off timeout of the headset on `route` now and + /// answer with the timeout the headset confirms. The headset keeps it + /// across power cycles, so nothing is saved to the config. + async fn set_power_off_timeout( + route: DeviceRoute, + timeout: PowerOffTimeout, + ) -> Result; } diff --git a/crates/openlogi-ipc/tests/wire_format.rs b/crates/openlogi-ipc/tests/wire_format.rs index 5e11fe19d5..ea1b621e73 100644 --- a/crates/openlogi-ipc/tests/wire_format.rs +++ b/crates/openlogi-ipc/tests/wire_format.rs @@ -50,9 +50,10 @@ use openlogi_core::hid::{ BacklightStatus, Click, DeviceRoute, DisableKeysMask, DisableKeysState, Dpi, DpiCapabilities, DpiInfo, EasySwitchHosts, EasySwitchSlot, FnLockState, ForceSensingInfo, HidppFeatureErrorKind, HidppOperation, HostConnection, HostOsInfo, HostOsKind, LightCommand, OnboardMode, - OnboardProfile, OnboardState, PasskeyMethod, ProfileIndex, ReceiverSelector, ReportRate, - ReportRateInfo, ScrollReportingTarget, ScrollWheelMode, SidetoneLevel, SmartShiftAutoDisengage, - SmartShiftMode, SmartShiftStatus, SmartShiftThreshold, TunableTorque, WriteError, + OnboardProfile, OnboardState, PasskeyMethod, PowerOffTimeout, ProfileIndex, ReceiverSelector, + ReportRate, ReportRateInfo, ScrollReportingTarget, ScrollWheelMode, SidetoneLevel, + SmartShiftAutoDisengage, SmartShiftMode, SmartShiftStatus, SmartShiftThreshold, TunableTorque, + WriteError, }; use openlogi_ipc::{ ActionRingCommandError, ActionRingInvocation, ActionRingPresentation, AgentRequest, @@ -119,7 +120,7 @@ fn representative_smartshift_status() -> SmartShiftStatus { /// unreleased version and leave this pin alone (`crates/openlogi-ipc/AGENTS.md`). #[test] fn protocol_version_is_pinned() { - assert_eq!(PROTOCOL_VERSION, 46); + assert_eq!(PROTOCOL_VERSION, 47); } #[test] @@ -406,6 +407,32 @@ fn sidetone_calls() { assert_wire(&AgentResponse::SetSidetone(Ok(level)), "320028"); } +/// The power-off timeout calls are appended last, and carry the timeout in +/// minutes as one byte. +#[test] +fn power_off_timeout_calls() { + let route = DeviceRoute::Direct { + vendor_id: 0x046d, + product_id: 0x0a5b, + }; + let timeout = PowerOffTimeout::try_new(30).expect("a timeout in range"); + assert_wire(&HidppOperation::ReadPowerOffTimeout, "21"); + assert_wire(&HidppOperation::WritePowerOffTimeout, "22"); + assert_wire(&timeout, "1e"); + assert_wire(&Ok::(timeout), "001e"); + assert_wire( + &AgentRequest::ReadPowerOffTimeout { + route: route.clone(), + }, + "3a02fb6d04fb5b0a", + ); + assert_wire( + &AgentRequest::SetPowerOffTimeout { route, timeout }, + "3b02fb6d04fb5b0a1e", + ); + assert_wire(&AgentResponse::SetPowerOffTimeout(Ok(timeout)), "3b001e"); +} + /// The overlay long-polls the backlight indicator by generation, like /// the other observe calls. #[test] From 524c1953edd2af0525c710b069973a3f69867973 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:57:01 +0100 Subject: [PATCH 09/28] feat(cli): record a headset's power-off timeout in device profiles record-profile reads the timeout when the inventory advertises it, and records a refused read as unsupported. --- .../src/cmd/fixture/record_profile.rs | 9 ++- .../src/cmd/fixture/record_profile/tests.rs | 77 +++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/openlogi-cli/src/cmd/fixture/record_profile.rs b/crates/openlogi-cli/src/cmd/fixture/record_profile.rs index a4dcc6cab5..4e8fcb1773 100644 --- a/crates/openlogi-cli/src/cmd/fixture/record_profile.rs +++ b/crates/openlogi-cli/src/cmd/fixture/record_profile.rs @@ -350,6 +350,13 @@ async fn capture_hidpp_settings( agent::call(client.read_sidetone(context::current(), source_route.clone())) }) .await?; + let power_off_timeout = gated_read( + "power-off timeout", + device.online, + capabilities.power_off_timeout, + || agent::call(client.read_power_off_timeout(context::current(), source_route.clone())), + ) + .await?; Ok(ProfileDeviceSettings { route: profile_route, @@ -364,7 +371,7 @@ async fn capture_hidpp_settings( force_sensing, disable_keys, sidetone, - power_off_timeout: ProfileSetting::Unsupported, + power_off_timeout, lighting: profile_support(capabilities.lighting), light: ProfileSupport::Unsupported, }) diff --git a/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs b/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs index 8df6a7d553..6f6b947281 100644 --- a/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs +++ b/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs @@ -1203,6 +1203,83 @@ async fn capture_reads_the_press_force_of_a_force_sensing_mouse() { assert_eq!(*captured, force); } +/// Advertise `0x1F20` on the synthetic mouse and give it `timeout` as its +/// power-off setting. +fn power_off_agent(timeout: ProfileSetting) -> TestAgent { + fixture_agent_with(move |profile| { + let mouse = profile.inventories[0] + .paired + .iter_mut() + .find(|device| device.slot == 1) + .expect("mouse"); + mouse + .capabilities + .as_mut() + .expect("mouse capabilities") + .power_off_timeout = true; + let settings = profile + .settings + .iter_mut() + .find(|settings| matches!(settings.route, DeviceRoute::Bolt { slot: 1, .. })) + .expect("mouse settings"); + settings.power_off_timeout = timeout; + }) +} + +async fn captured_power_off_timeout( + agent: TestAgent, +) -> (ProfileSetting, Vec) { + let directory = tempfile::tempdir().expect("tempdir"); + let output = directory.path().join("profile.json"); + let inspection = agent.clone(); + capture_connected( + args(output.clone(), Some("synthetic performance mouse")), + test_client(agent), + ) + .await + .expect("semantic capture succeeds"); + let profile: DeviceProfile = + serde_json::from_slice(&std::fs::read(output).expect("profile output")) + .expect("typed profile"); + profile.validate().expect("published profile validates"); + let setting = profile + .settings + .iter() + .find(|settings| matches!(settings.route, DeviceRoute::Bolt { slot: 1, .. })) + .expect("mouse settings") + .power_off_timeout + .clone(); + let families = inspection + .calls + .lock() + .expect("calls lock") + .iter() + .map(|(family, _)| *family) + .collect(); + (setting, families) +} + +#[tokio::test] +async fn capture_reads_the_power_off_timeout_of_a_headset() { + let timeout = PowerOffTimeout::try_new(15).expect("a timeout in range"); + let (setting, families) = + captured_power_off_timeout(power_off_agent(ProfileSetting::Supported(timeout))).await; + + assert!(families.contains(&ReadFamily::PowerOffTimeout)); + assert_eq!(setting, ProfileSetting::Supported(timeout)); +} + +#[tokio::test] +async fn a_refused_power_off_read_is_recorded_unsupported() { + // `0x1F20` is listed for the battery, but the device refuses function 1, + // which the agent answers as an unsupported feature. + let (setting, families) = + captured_power_off_timeout(power_off_agent(ProfileSetting::Unsupported)).await; + + assert!(families.contains(&ReadFamily::PowerOffTimeout)); + assert_eq!(setting, ProfileSetting::Unsupported); +} + #[tokio::test] async fn receiver_capture_drops_a_sibling_device_with_no_identity() { let directory = tempfile::tempdir().expect("tempdir"); From d42f986ebe3c076f417d86c96758124d2cc34769 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:57:46 +0100 Subject: [PATCH 10/28] feat(i18n): add the headset automatic power-off strings Eight audio.* keys for the Audio tab row and the menu-bar submenu, English in every catalog until translated. --- crates/openlogi-ui/locales/be.toml | 8 ++++++++ crates/openlogi-ui/locales/cs.toml | 8 ++++++++ crates/openlogi-ui/locales/da.toml | 8 ++++++++ crates/openlogi-ui/locales/de.toml | 8 ++++++++ crates/openlogi-ui/locales/el.toml | 8 ++++++++ crates/openlogi-ui/locales/en.toml | 8 ++++++++ crates/openlogi-ui/locales/es.toml | 8 ++++++++ crates/openlogi-ui/locales/fi.toml | 8 ++++++++ crates/openlogi-ui/locales/fr.toml | 8 ++++++++ crates/openlogi-ui/locales/it.toml | 8 ++++++++ crates/openlogi-ui/locales/ja.toml | 8 ++++++++ crates/openlogi-ui/locales/ko.toml | 8 ++++++++ crates/openlogi-ui/locales/nb.toml | 8 ++++++++ crates/openlogi-ui/locales/nl.toml | 8 ++++++++ crates/openlogi-ui/locales/pl.toml | 8 ++++++++ crates/openlogi-ui/locales/pt-BR.toml | 8 ++++++++ crates/openlogi-ui/locales/pt-PT.toml | 8 ++++++++ crates/openlogi-ui/locales/ru.toml | 8 ++++++++ crates/openlogi-ui/locales/sv.toml | 8 ++++++++ crates/openlogi-ui/locales/tr.toml | 8 ++++++++ crates/openlogi-ui/locales/uk.toml | 8 ++++++++ crates/openlogi-ui/locales/zh-CN.toml | 8 ++++++++ crates/openlogi-ui/locales/zh-HK.toml | 8 ++++++++ crates/openlogi-ui/locales/zh-TW.toml | 8 ++++++++ 24 files changed, 192 insertions(+) diff --git a/crates/openlogi-ui/locales/be.toml b/crates/openlogi-ui/locales/be.toml index 942dbe53b2..bbbfe34c33 100644 --- a/crates/openlogi-ui/locales/be.toml +++ b/crates/openlogi-ui/locales/be.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Чытанне самапраслухоўвання…" couldnt_read_sidetone_click_to_retry = "Не ўдалося прачытаць самапраслухоўванне. Націсніце, каб паўтарыць." device_offline_sidetone_is_unavailable = "Гарнітура па-за сеткай. Самапраслухоўванне недаступнае." sidetone_unsupported = "Гарнітура не паведамляе пра падтрымку рэгуляванага самапраслухоўвання." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Патрэбны дазвол «Універсальны доступ»" diff --git a/crates/openlogi-ui/locales/cs.toml b/crates/openlogi-ui/locales/cs.toml index 4205c27a7b..7d6c069a6c 100644 --- a/crates/openlogi-ui/locales/cs.toml +++ b/crates/openlogi-ui/locales/cs.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Načítání příposlechu…" couldnt_read_sidetone_click_to_retry = "Příposlech se nepodařilo načíst. Kliknutím to zkuste znovu." device_offline_sidetone_is_unavailable = "Příposlech není dostupný, když jsou sluchátka odpojená." sidetone_unsupported = "Tato sluchátka nehlásí podporu nastavitelného příposlechu." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Je potřeba oprávnění Zpřístupnění" diff --git a/crates/openlogi-ui/locales/da.toml b/crates/openlogi-ui/locales/da.toml index 95f1836dff..c9137ff9e3 100644 --- a/crates/openlogi-ui/locales/da.toml +++ b/crates/openlogi-ui/locales/da.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Aflæser sidetone…" couldnt_read_sidetone_click_to_retry = "Sidetonen kunne ikke aflæses. Klik for at prøve igen." device_offline_sidetone_is_unavailable = "Sidetone er ikke tilgængelig, mens headsettet er offline." sidetone_unsupported = "Dette headset oplyser ikke, at justerbar sidetone understøttes." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Tilladelse til Tilgængelighed kræves" diff --git a/crates/openlogi-ui/locales/de.toml b/crates/openlogi-ui/locales/de.toml index ed69adb521..df9e9ec06d 100644 --- a/crates/openlogi-ui/locales/de.toml +++ b/crates/openlogi-ui/locales/de.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Mithörton wird gelesen…" couldnt_read_sidetone_click_to_retry = "Mithörton konnte nicht gelesen werden. Zum Wiederholen klicken." device_offline_sidetone_is_unavailable = "Der Mithörton ist nicht verfügbar, solange das Headset offline ist." sidetone_unsupported = "Dieses Headset meldet keinen einstellbaren Mithörton." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Bedienungshilfen-Berechtigung erforderlich" diff --git a/crates/openlogi-ui/locales/el.toml b/crates/openlogi-ui/locales/el.toml index 4c64d289d7..afa45fdc3d 100644 --- a/crates/openlogi-ui/locales/el.toml +++ b/crates/openlogi-ui/locales/el.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Ανάγνωση sidetone…" couldnt_read_sidetone_click_to_retry = "Δεν ήταν δυνατή η ανάγνωση του sidetone. Πατήστε για νέα προσπάθεια." device_offline_sidetone_is_unavailable = "Τα ακουστικά είναι εκτός σύνδεσης. Το sidetone δεν είναι διαθέσιμο." sidetone_unsupported = "Τα ακουστικά δεν ανέφεραν υποστήριξη ρυθμιζόμενου sidetone." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Απαιτείται η άδεια «Προσβασιμότητα»" diff --git a/crates/openlogi-ui/locales/en.toml b/crates/openlogi-ui/locales/en.toml index 4c65b41a47..08b9c67d85 100644 --- a/crates/openlogi-ui/locales/en.toml +++ b/crates/openlogi-ui/locales/en.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Reading sidetone…" couldnt_read_sidetone_click_to_retry = "Couldn't read the sidetone. Click to retry." device_offline_sidetone_is_unavailable = "Sidetone is unavailable while the headset is offline." sidetone_unsupported = "This headset does not report an adjustable sidetone." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Accessibility permission needed" diff --git a/crates/openlogi-ui/locales/es.toml b/crates/openlogi-ui/locales/es.toml index f6d1188f79..91a9b23a35 100644 --- a/crates/openlogi-ui/locales/es.toml +++ b/crates/openlogi-ui/locales/es.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Leyendo el efecto local…" couldnt_read_sidetone_click_to_retry = "No se pudo leer el efecto local. Haz clic para reintentar." device_offline_sidetone_is_unavailable = "El efecto local no está disponible mientras los auriculares estén sin conexión." sidetone_unsupported = "Estos auriculares no indican que admitan efecto local ajustable." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Se necesita el permiso de Accesibilidad" diff --git a/crates/openlogi-ui/locales/fi.toml b/crates/openlogi-ui/locales/fi.toml index 15d30fefe2..46094fc215 100644 --- a/crates/openlogi-ui/locales/fi.toml +++ b/crates/openlogi-ui/locales/fi.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Luetaan sivuääntä…" couldnt_read_sidetone_click_to_retry = "Sivuääntä ei voitu lukea. Yritä uudelleen napsauttamalla." device_offline_sidetone_is_unavailable = "Kuulokkeet eivät ole yhteydessä. Sivuääni ei ole käytettävissä." sidetone_unsupported = "Kuulokkeet eivät ilmoittaneet tukevansa säädettävää sivuääntä." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Käyttöapu-lupa tarvitaan" diff --git a/crates/openlogi-ui/locales/fr.toml b/crates/openlogi-ui/locales/fr.toml index 840355aab7..28ae8a8c6f 100644 --- a/crates/openlogi-ui/locales/fr.toml +++ b/crates/openlogi-ui/locales/fr.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Lecture de l'effet local…" couldnt_read_sidetone_click_to_retry = "Impossible de lire l'effet local. Cliquez pour réessayer." device_offline_sidetone_is_unavailable = "L'effet local est indisponible tant que le casque est hors ligne." sidetone_unsupported = "Ce casque n'indique pas prendre en charge le réglage de l'effet local." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Autorisation Accessibilité requise" diff --git a/crates/openlogi-ui/locales/it.toml b/crates/openlogi-ui/locales/it.toml index a0db0a4049..90af504e37 100644 --- a/crates/openlogi-ui/locales/it.toml +++ b/crates/openlogi-ui/locales/it.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Lettura effetto locale…" couldnt_read_sidetone_click_to_retry = "Impossibile leggere l'effetto locale. Clicca per riprovare." device_offline_sidetone_is_unavailable = "L'effetto locale non è disponibile mentre le cuffie sono offline." sidetone_unsupported = "Le cuffie non segnalano il supporto dell'effetto locale regolabile." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Serve il permesso Accessibilità" diff --git a/crates/openlogi-ui/locales/ja.toml b/crates/openlogi-ui/locales/ja.toml index 1c9ca01d96..e7df06ae11 100644 --- a/crates/openlogi-ui/locales/ja.toml +++ b/crates/openlogi-ui/locales/ja.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "サイドトーンを読み取り中…" couldnt_read_sidetone_click_to_retry = "サイドトーンを読み取れませんでした。クリックして再試行してください。" device_offline_sidetone_is_unavailable = "ヘッドセットがオフラインのため、サイドトーンを利用できません。" sidetone_unsupported = "このヘッドセットはサイドトーン調整への対応を報告していません。" +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "「アクセシビリティ」の許可が必要です" diff --git a/crates/openlogi-ui/locales/ko.toml b/crates/openlogi-ui/locales/ko.toml index d78ebab981..05980fd434 100644 --- a/crates/openlogi-ui/locales/ko.toml +++ b/crates/openlogi-ui/locales/ko.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "측음 읽는 중…" couldnt_read_sidetone_click_to_retry = "측음을 읽지 못했습니다. 클릭하여 다시 시도하세요." device_offline_sidetone_is_unavailable = "헤드셋이 오프라인이어서 측음을 사용할 수 없습니다." sidetone_unsupported = "이 헤드셋은 측음 조절 지원 여부를 보고하지 않았습니다." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "손쉬운 사용 권한이 필요합니다" diff --git a/crates/openlogi-ui/locales/nb.toml b/crates/openlogi-ui/locales/nb.toml index 4e3232ba57..4b16a21788 100644 --- a/crates/openlogi-ui/locales/nb.toml +++ b/crates/openlogi-ui/locales/nb.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Leser sidetone…" couldnt_read_sidetone_click_to_retry = "Kunne ikke lese sidetone. Klikk for å prøve igjen." device_offline_sidetone_is_unavailable = "Sidetone er utilgjengelig mens headsettet er frakoblet." sidetone_unsupported = "Dette headsettet oppgir ikke støtte for justerbar sidetone." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Tillatelse for Tilgjengelighet kreves" diff --git a/crates/openlogi-ui/locales/nl.toml b/crates/openlogi-ui/locales/nl.toml index 1e3fd284b6..91725ca40c 100644 --- a/crates/openlogi-ui/locales/nl.toml +++ b/crates/openlogi-ui/locales/nl.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Sidetone lezen…" couldnt_read_sidetone_click_to_retry = "Sidetone kan niet worden gelezen. Klik om het opnieuw te proberen." device_offline_sidetone_is_unavailable = "Sidetone is niet beschikbaar zolang de headset offline is." sidetone_unsupported = "Deze headset meldt geen ondersteuning voor instelbare sidetone." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Toegankelijkheidstoestemming nodig" diff --git a/crates/openlogi-ui/locales/pl.toml b/crates/openlogi-ui/locales/pl.toml index 5467b90623..eb4f939ac2 100644 --- a/crates/openlogi-ui/locales/pl.toml +++ b/crates/openlogi-ui/locales/pl.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Odczytywanie sidetone…" couldnt_read_sidetone_click_to_retry = "Nie udało się odczytać sidetone. Kliknij, aby spróbować ponownie." device_offline_sidetone_is_unavailable = "Zestaw słuchawkowy jest offline. Sidetone jest niedostępny." sidetone_unsupported = "Ten zestaw słuchawkowy nie zgłosił obsługi regulowanego sidetone." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Wymagane uprawnienie Dostępność" diff --git a/crates/openlogi-ui/locales/pt-BR.toml b/crates/openlogi-ui/locales/pt-BR.toml index 9869ef834e..5aaf752254 100644 --- a/crates/openlogi-ui/locales/pt-BR.toml +++ b/crates/openlogi-ui/locales/pt-BR.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Lendo o tom lateral…" couldnt_read_sidetone_click_to_retry = "Não foi possível ler o tom lateral. Clique para tentar novamente." device_offline_sidetone_is_unavailable = "O tom lateral fica indisponível enquanto o headset está off-line." sidetone_unsupported = "O headset não informa suporte a tom lateral ajustável." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Permissão de Acessibilidade necessária" diff --git a/crates/openlogi-ui/locales/pt-PT.toml b/crates/openlogi-ui/locales/pt-PT.toml index 3373ca0edd..e58ca3948e 100644 --- a/crates/openlogi-ui/locales/pt-PT.toml +++ b/crates/openlogi-ui/locales/pt-PT.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "A ler o tom lateral…" couldnt_read_sidetone_click_to_retry = "Não foi possível ler o tom lateral. Clique para tentar novamente." device_offline_sidetone_is_unavailable = "O tom lateral está indisponível enquanto os auscultadores estiverem desligados." sidetone_unsupported = "Os auscultadores não indicam suporte para tom lateral ajustável." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "É necessária a permissão de Acessibilidade" diff --git a/crates/openlogi-ui/locales/ru.toml b/crates/openlogi-ui/locales/ru.toml index 26f4d07141..85ccc90c84 100644 --- a/crates/openlogi-ui/locales/ru.toml +++ b/crates/openlogi-ui/locales/ru.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Чтение местного эффекта…" couldnt_read_sidetone_click_to_retry = "Не удалось прочитать местный эффект. Нажмите, чтобы повторить." device_offline_sidetone_is_unavailable = "Местный эффект недоступен, пока гарнитура не в сети." sidetone_unsupported = "Гарнитура не сообщает о поддержке регулируемого местного эффекта." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Нужно разрешение «Универсальный доступ»" diff --git a/crates/openlogi-ui/locales/sv.toml b/crates/openlogi-ui/locales/sv.toml index 017bb0977e..820ea8233a 100644 --- a/crates/openlogi-ui/locales/sv.toml +++ b/crates/openlogi-ui/locales/sv.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Läser sidoton…" couldnt_read_sidetone_click_to_retry = "Kunde inte läsa sidotonen. Klicka för att försöka igen." device_offline_sidetone_is_unavailable = "Sidoton är inte tillgänglig när headsetet är frånkopplat." sidetone_unsupported = "Headsetet uppger inte stöd för justerbar sidoton." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Behörighet för Hjälpmedel krävs" diff --git a/crates/openlogi-ui/locales/tr.toml b/crates/openlogi-ui/locales/tr.toml index f023f8c0b5..03f4bc9cc6 100644 --- a/crates/openlogi-ui/locales/tr.toml +++ b/crates/openlogi-ui/locales/tr.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Yan ton okunuyor…" couldnt_read_sidetone_click_to_retry = "Yan ton okunamadı. Yeniden denemek için tıklayın." device_offline_sidetone_is_unavailable = "Kulaklık çevrimdışı olduğundan yan ton kullanılamıyor." sidetone_unsupported = "Bu kulaklık ayarlanabilir yan ton desteği bildirmiyor." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Erişilebilirlik izni gerekli" diff --git a/crates/openlogi-ui/locales/uk.toml b/crates/openlogi-ui/locales/uk.toml index e092780acb..fc06073cc6 100644 --- a/crates/openlogi-ui/locales/uk.toml +++ b/crates/openlogi-ui/locales/uk.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "Читання самопрослуховування…" couldnt_read_sidetone_click_to_retry = "Не вдалося прочитати самопрослуховування. Натисніть, щоб повторити." device_offline_sidetone_is_unavailable = "Самопрослуховування недоступне, поки гарнітура не в мережі." sidetone_unsupported = "Ця гарнітура не повідомила про підтримку регульованого самопрослуховування." +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "Потрібен дозвіл «Доступність»" diff --git a/crates/openlogi-ui/locales/zh-CN.toml b/crates/openlogi-ui/locales/zh-CN.toml index 53008f036b..07a50b01e6 100644 --- a/crates/openlogi-ui/locales/zh-CN.toml +++ b/crates/openlogi-ui/locales/zh-CN.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "正在读取侧音…" couldnt_read_sidetone_click_to_retry = "无法读取侧音,请点击重试。" device_offline_sidetone_is_unavailable = "耳机离线,侧音不可用。" sidetone_unsupported = "此耳机未报告可调侧音支持。" +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "需要“辅助功能”权限" diff --git a/crates/openlogi-ui/locales/zh-HK.toml b/crates/openlogi-ui/locales/zh-HK.toml index b6a745ab89..c5d9d55a84 100644 --- a/crates/openlogi-ui/locales/zh-HK.toml +++ b/crates/openlogi-ui/locales/zh-HK.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "正在讀取側音…" couldnt_read_sidetone_click_to_retry = "無法讀取側音,請點擊重試。" device_offline_sidetone_is_unavailable = "耳機離線,側音無法使用。" sidetone_unsupported = "此耳機未回報可調整側音支援。" +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "需要「輔助使用」權限" diff --git a/crates/openlogi-ui/locales/zh-TW.toml b/crates/openlogi-ui/locales/zh-TW.toml index c08a6671cd..523e4d85a1 100644 --- a/crates/openlogi-ui/locales/zh-TW.toml +++ b/crates/openlogi-ui/locales/zh-TW.toml @@ -1014,6 +1014,14 @@ reading_sidetone = "正在讀取側音…" couldnt_read_sidetone_click_to_retry = "無法讀取側音,請按一下重試。" device_offline_sidetone_is_unavailable = "耳機離線,側音無法使用。" sidetone_unsupported = "此耳機未回報可調整側音支援。" +power_off = "Automatic power-off" +power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." +power_off_never = "Never" +power_off_minutes = "%{minutes} min" +reading_power_off = "Reading automatic power-off…" +couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." +device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." +power_off_unsupported = "This headset does not report an adjustable automatic power-off." [tray] accessibility_needed = "需要「輔助使用」權限" From e2383dfef92a3365b087ef337713742a7849b814 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:04:38 +0100 Subject: [PATCH 11/28] feat(cli): add openlogi diag power-off Read a headset's HID++ 0x1F20 automatic power-off timeout, or set it in minutes (0 is never) and fail when the headset's echo differs. The range comes from PowerOffTimeout, so an out-of-range value is rejected before any device is opened. --- crates/openlogi-cli/src/cmd/diag.rs | 4 + crates/openlogi-cli/src/cmd/diag/power_off.rs | 95 +++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 crates/openlogi-cli/src/cmd/diag/power_off.rs diff --git a/crates/openlogi-cli/src/cmd/diag.rs b/crates/openlogi-cli/src/cmd/diag.rs index 72b78d2e49..cfcfef056f 100644 --- a/crates/openlogi-cli/src/cmd/diag.rs +++ b/crates/openlogi-cli/src/cmd/diag.rs @@ -23,6 +23,7 @@ pub mod lighting; pub mod mouse_buttons; pub mod onboard; pub mod pointer_speed; +pub mod power_off; pub mod sidetone; pub mod smartshift; pub mod wheel; @@ -56,6 +57,8 @@ pub enum DiagCmd { HostSwitch(host_switch::HostSwitchArgs), /// Read a headset's HID++ 0x8300 sidetone level, or set it. Sidetone(sidetone::SidetoneArgs), + /// Read a headset's HID++ 0x1F20 automatic power-off timeout, or set it. + PowerOff(power_off::PowerOffArgs), /// Light each HID++ 0x8081 zone of a keyboard alone and record its key. Zones(zones::ZonesArgs), } @@ -81,6 +84,7 @@ impl DiagCmd { Self::MouseButtons(args) => mouse_buttons::run(args).await, Self::HostSwitch(args) => host_switch::run(args).await, Self::Sidetone(args) => sidetone::run(args).await, + Self::PowerOff(args) => power_off::run(args).await, Self::Zones(args) => zones::run(args).await, } } diff --git a/crates/openlogi-cli/src/cmd/diag/power_off.rs b/crates/openlogi-cli/src/cmd/diag/power_off.rs new file mode 100644 index 0000000000..8c602706dc --- /dev/null +++ b/crates/openlogi-cli/src/cmd/diag/power_off.rs @@ -0,0 +1,95 @@ +//! `openlogi diag power-off` — read or set a headset's HID++ 0x1F20 +//! automatic power-off timeout. + +use std::fmt; + +use anyhow::{Context, Result, bail}; +use clap::Args; +use openlogi_hid::PowerOffTimeout; + +use crate::cmd::diag::select_device; + +#[derive(Debug, Args)] +pub struct PowerOffArgs { + /// Timeout to write, in idle minutes (0 is never, 90 the longest). The + /// headset stores it; nothing is written to config.toml. + #[arg(value_parser = parse_minutes)] + pub minutes: Option, + + /// Run against the device whose name contains this string + /// (case-insensitive) instead of auto-selecting. + #[arg(long, value_name = "NAME")] + pub device: Option, +} + +pub async fn run(args: PowerOffArgs) -> Result<()> { + let (route, name) = select_device(args.device.as_deref(), &[0x1f20]).await?; + println!("device: {name} ({route})"); + + let before = openlogi_hid::get_power_off_timeout(&route) + .await + .context("read power-off timeout")?; + println!(" current power-off: {}", Minutes(before)); + + let Some(requested) = args.minutes else { + return Ok(()); + }; + let applied = openlogi_hid::set_power_off_timeout(&route, requested) + .await + .context("set power-off timeout")?; + println!(" confirmed: {}", Minutes(applied)); + if applied != requested { + bail!( + "power-off write not applied: requested {}, device confirms {}", + Minutes(requested), + Minutes(applied) + ); + } + println!("✓ power-off set to {}", Minutes(applied)); + Ok(()) +} + +/// Parses the minutes argument, leaving the range to [`PowerOffTimeout`]. +fn parse_minutes(raw: &str) -> Result { + let minutes: u8 = raw.parse().map_err(|err| format!("{err}"))?; + PowerOffTimeout::try_new(minutes).map_err(|err| err.to_string()) +} + +/// A timeout as the user reads it: `0` is "never", not "0 min". +struct Minutes(PowerOffTimeout); + +impl fmt::Display for Minutes { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.0 == PowerOffTimeout::NEVER { + f.write_str("never") + } else { + write!(f, "{} min", self.0.minutes()) + } + } +} + +#[cfg(test)] +mod tests { + use openlogi_hid::PowerOffTimeout; + + use super::{Minutes, parse_minutes}; + + #[test] + fn parses_the_whole_range_the_headset_accepts() { + assert_eq!(parse_minutes("0"), Ok(PowerOffTimeout::NEVER)); + assert_eq!(parse_minutes("90"), Ok(PowerOffTimeout::MAX)); + } + + #[test] + fn rejects_a_timeout_the_headset_would_not_take_before_writing() { + assert!(parse_minutes("91").is_err(), "91 is above the range"); + assert!(parse_minutes("256").is_err(), "256 does not fit a byte"); + assert!(parse_minutes("-1").is_err(), "minutes are not negative"); + } + + #[test] + fn zero_reads_as_never_rather_than_zero_minutes() { + assert_eq!(Minutes(PowerOffTimeout::NEVER).to_string(), "never"); + assert_eq!(Minutes(PowerOffTimeout::clamped(15)).to_string(), "15 min"); + } +} From a4d8993a367fddae2dcaa3f2aee6f6633b763389 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:09:39 +0100 Subject: [PATCH 12/28] feat(gui): let a slider rest on a headset power-off timeout --- crates/openlogi-desktop/src/ui/commit_slider.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/openlogi-desktop/src/ui/commit_slider.rs b/crates/openlogi-desktop/src/ui/commit_slider.rs index d29dbd758e..175a76bf96 100644 --- a/crates/openlogi-desktop/src/ui/commit_slider.rs +++ b/crates/openlogi-desktop/src/ui/commit_slider.rs @@ -13,7 +13,9 @@ use std::rc::Rc; use gpui::{App, AppContext as _, Context, Entity, Subscription, Window}; use gpui_kit::component::slider::{SliderEvent, SliderState}; use openlogi_core::config::{ThumbwheelSensitivity, VerticalScrollSensitivity}; -use openlogi_core::hid::{Dpi, PointerSpeed, SidetoneLevel, SmartShiftThreshold, TunableTorque}; +use openlogi_core::hid::{ + Dpi, PointerSpeed, PowerOffTimeout, SidetoneLevel, SmartShiftThreshold, TunableTorque, +}; /// A value a slider thumb can rest on. pub(crate) trait SliderUnit: Copy + PartialEq + 'static { @@ -95,6 +97,17 @@ impl SliderUnit for SidetoneLevel { } } +/// An automatic power-off timeout rests on whole minutes, `0` being never. +impl SliderUnit for PowerOffTimeout { + fn to_slider(self) -> f32 { + f32::from(self.minutes()) + } + + fn from_slider(raw: f32) -> Self { + Self::clamped(u8::from_slider(raw)) + } +} + /// Domain values that already round a control position into their own range. macro_rules! rounded_slider_unit { ($($unit:ty),+ $(,)?) => {$( From b7d417b5fbd473719bc162dee85578b72f768730 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:09:42 +0100 Subject: [PATCH 13/28] feat(gui): add the automatic power-off row to the Audio tab A headset that lists HID++ 0x1F20 gets a second Audio row: a slider in minutes from 0 (never) to 90. A release writes the headset through the agent and nothing is saved; a refusal reads the headset again. A headset that refuses the timeout read shows as unsupported. --- crates/openlogi-desktop/src/app.rs | 1 + crates/openlogi-desktop/src/features/audio.rs | 196 ++++++++++++++- crates/openlogi-desktop/src/runtime.rs | 7 + .../src/services/device_reads.rs | 165 ++++++++++++- crates/openlogi-desktop/src/services/ipc.rs | 22 +- .../src/services/ipc/request.rs | 51 +++- crates/openlogi-desktop/src/state.rs | 5 +- crates/openlogi-desktop/src/state/events.rs | 4 + .../openlogi-desktop/src/state/inventory.rs | 1 + crates/openlogi-desktop/src/state/load.rs | 5 +- .../src/state/power_off_timeout.rs | 136 +++++++++++ crates/openlogi-desktop/src/state/tests.rs | 1 + .../src/state/tests/power_off_timeout.rs | 224 ++++++++++++++++++ 13 files changed, 788 insertions(+), 30 deletions(-) create mode 100644 crates/openlogi-desktop/src/state/power_off_timeout.rs create mode 100644 crates/openlogi-desktop/src/state/tests/power_off_timeout.rs diff --git a/crates/openlogi-desktop/src/app.rs b/crates/openlogi-desktop/src/app.rs index 4da8bacab1..13b760e71f 100644 --- a/crates/openlogi-desktop/src/app.rs +++ b/crates/openlogi-desktop/src/app.rs @@ -428,6 +428,7 @@ impl AppView { | StateEvent::ReportRateChanged(_) | StateEvent::PointerSpeedChanged(_) | StateEvent::SidetoneChanged(_) + | StateEvent::PowerOffTimeoutChanged(_) | StateEvent::ForceSensingChanged(_) | StateEvent::DeviceRemovalFailed { .. } | StateEvent::StalePairingRemovalFailed { .. } diff --git a/crates/openlogi-desktop/src/features/audio.rs b/crates/openlogi-desktop/src/features/audio.rs index 6e8d41ddbc..37ad7a397a 100644 --- a/crates/openlogi-desktop/src/features/audio.rs +++ b/crates/openlogi-desktop/src/features/audio.rs @@ -1,4 +1,5 @@ -//! The Audio tab of a headset: its sidetone level. +//! The Audio tab of a headset: its sidetone level and its automatic +//! power-off. //! //! Sidetone plays the microphone back into the earcups, so the wearer hears //! their own voice. The slider runs from 0 % (off) to 100 %, as HID++ @@ -6,14 +7,19 @@ //! which writes the headset; the headset keeps the level across power //! cycles, so nothing is saved. When the headset refuses the write, the //! slider returns to the level the headset reads back. +//! +//! The automatic power-off row works the same way over HID++ `0x1F20`: a +//! slider in minutes from 0 (never) to 90, written through +//! [`AppState::commit_power_off_timeout`] and kept by the headset. use gpui::{ - AnyElement, App, Context, IntoElement, ParentElement, Render, Styled, Subscription, Window, div, + AnyElement, App, Context, IntoElement, ParentElement, Render, SharedString, Styled, + Subscription, Window, div, prelude::FluentBuilder as _, px, }; use gpui_kit::component::{h_flex, slider::Slider, v_flex}; -use openlogi_core::hid::SidetoneLevel; +use openlogi_core::hid::{PowerOffTimeout, SidetoneLevel}; -use crate::state::{AppState, DeviceKey, SidetoneLoad, StateEvent}; +use crate::state::{AppState, DeviceKey, PowerOffTimeoutLoad, SidetoneLoad, StateEvent}; use crate::ui::commit_slider::{CommitSlider, SliderRange}; use crate::ui::status::{retry_line, status_line}; use crate::ui::theme::{self, Palette, Typography as _}; @@ -21,18 +27,24 @@ use crate::ui::theme::{self, Palette, Typography as _}; /// The Audio tab's icon, from the shared action-icon set. pub const AUDIO_ICON: &str = "action-icons/volume-2.svg"; -/// The Audio tab's body, kept across frames for its slider. +/// The Audio tab's body, kept across frames for its sliders. pub struct AudioPanel { sidetone: Option, + power_off: Option, _state_obs: Subscription, } impl AudioPanel { pub fn new(cx: &mut Context) -> Self { - let state_obs = - AppState::repaint_on(cx, |event| matches!(event, StateEvent::SidetoneChanged(_))); + let state_obs = AppState::repaint_on(cx, |event| { + matches!( + event, + StateEvent::SidetoneChanged(_) | StateEvent::PowerOffTimeoutChanged(_) + ) + }); Self { sidetone: None, + power_off: None, _state_obs: state_obs, } } @@ -41,14 +53,25 @@ impl AudioPanel { impl Render for AudioPanel { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let pal = theme::palette(cx); - let Some(facts) = SidetoneFacts::current(cx) else { - self.sidetone = None; - return v_flex().w_full(); - }; - SidetoneSlider::sync(&mut self.sidetone, &facts, window, cx); + let sidetone = SidetoneFacts::current(cx); + match &sidetone { + Some(facts) => SidetoneSlider::sync(&mut self.sidetone, facts, window, cx), + None => self.sidetone = None, + } + let power_off = PowerOffFacts::current(cx); + match &power_off { + Some(facts) => PowerOffSlider::sync(&mut self.power_off, facts, window, cx), + None => self.power_off = None, + } + let both = sidetone.is_some() && power_off.is_some(); v_flex() .w_full() - .child(sidetone_section(facts, self.sidetone.as_ref(), pal)) + .gap_4() + .children(sidetone.map(|facts| sidetone_section(facts, self.sidetone.as_ref(), pal))) + .when(both, |this| { + this.child(div().h(px(1.)).w_full().bg(pal.border)) + }) + .children(power_off.map(|facts| power_off_section(facts, self.power_off.as_ref(), pal))) } } @@ -192,3 +215,150 @@ fn sidetone_section( ) .into_any_element() } + +/// What the automatic power-off row needs about the selected headset. +struct PowerOffFacts { + key: DeviceKey, + load: PowerOffTimeoutLoad, + reachable: bool, +} + +impl PowerOffFacts { + /// The selected headset's facts, or `None` when nothing is selected or + /// the device has no `0x1F20`. + fn current(cx: &App) -> Option { + let state = AppState::try_read(cx)?; + if !state.current_power_off_timeout_supported() { + return None; + } + let record = state.current_record()?; + Some(Self { + key: record.device_key(), + load: state.current_power_off_timeout_load(), + reachable: state.current_power_off_timeout_route().is_some(), + }) + } + + /// The timeout to put the slider on, or `None` while the slider must not + /// show: the headset is offline, or its reading has not landed. + fn slider_timeout(&self) -> Option { + match &self.load { + PowerOffTimeoutLoad::Ready(timeout) if self.reachable => Some(**timeout), + _ => None, + } + } +} + +/// The power-off slider, kept across frames, with the headset it was built +/// for. +struct PowerOffSlider { + key: DeviceKey, + slider: CommitSlider, +} + +impl PowerOffSlider { + /// Keep `current` in step with `facts`, as [`SidetoneSlider::sync`] does. + fn sync( + current: &mut Option, + facts: &PowerOffFacts, + window: &mut Window, + cx: &mut Context, + ) { + let Some(timeout) = facts.slider_timeout() else { + *current = None; + return; + }; + if let Some(existing) = current + .as_ref() + .filter(|existing| existing.key == facts.key) + { + existing.slider.sync(timeout, window, cx); + return; + } + let slider = CommitSlider::new( + SliderRange::new(PowerOffTimeout::NEVER, PowerOffTimeout::MAX), + timeout, + cx, + // Resolved on release, like the sidetone slider, so a device + // switch mid-drag writes the headset now on screen. + |_, timeout, cx| AppState::apply(cx, |state| state.commit_power_off_timeout(timeout)), + ); + *current = Some(Self { + key: facts.key.clone(), + slider, + }); + } +} + +/// The timeout as the header shows it: "Never" for 0, minutes otherwise. +fn power_off_label(timeout: PowerOffTimeout) -> SharedString { + match timeout.minutes() { + 0 => tr!("audio.power_off_never"), + minutes => tr!("audio.power_off_minutes", minutes => minutes), + } +} + +/// The row: a header with the timeout, the slider or a status line, and what +/// the setting does. +fn power_off_section( + facts: PowerOffFacts, + slider: Option<&PowerOffSlider>, + pal: Palette, +) -> AnyElement { + let shown = facts + .slider_timeout() + .map(|timeout| slider.map_or(timeout, |slider| slider.slider.shown(timeout))); + let PowerOffFacts { + key, + load, + reachable, + } = facts; + let body: AnyElement = match (load, slider) { + _ if !reachable => status_line(tr!("audio.device_offline_power_off_is_unavailable"), pal) + .into_any_element(), + (PowerOffTimeoutLoad::Ready(_), Some(slider)) => Slider::new(slider.slider.slider()) + .horizontal() + .into_any_element(), + (PowerOffTimeoutLoad::Ready(_), None) + | (PowerOffTimeoutLoad::Unknown | PowerOffTimeoutLoad::Loading, _) => { + status_line(tr!("audio.reading_power_off"), pal).into_any_element() + } + (PowerOffTimeoutLoad::Failed(_), _) => retry_line( + "power-off-retry", + tr!("audio.couldnt_read_power_off_click_to_retry"), + move |cx| AppState::apply(cx, |state| state.retry_power_off_timeout_read(&key)), + ) + .into_any_element(), + (PowerOffTimeoutLoad::Unsupported(_), _) => { + status_line(tr!("audio.power_off_unsupported"), pal).into_any_element() + } + }; + v_flex() + .gap_3() + .w_full() + .child( + h_flex() + .justify_between() + .items_baseline() + .child( + div() + .text_body() + .text_color(pal.text_muted) + .child(tr!("audio.power_off")), + ) + .children(shown.map(|timeout| { + div() + .text_body() + .text_color(pal.text_primary) + .child(power_off_label(timeout)) + })), + ) + .child(body) + .child( + div() + .text_caption() + .text_color(pal.text_muted) + .child(tr!("audio.power_off_description")), + ) + .into_any_element() +} diff --git a/crates/openlogi-desktop/src/runtime.rs b/crates/openlogi-desktop/src/runtime.rs index 630832b395..107c3852c6 100644 --- a/crates/openlogi-desktop/src/runtime.rs +++ b/crates/openlogi-desktop/src/runtime.rs @@ -375,6 +375,13 @@ impl Runtime { AppState::apply(cx, |state| state.apply_sidetone_written(&key, result)); }); } + ipc::GuiUpdate::PowerOffTimeoutWritten { key, result } => { + cx.update(|cx| { + AppState::apply(cx, |state| { + state.apply_power_off_timeout_written(&key, result) + }); + }); + } ipc::GuiUpdate::ForceSensingWritten { key, write, diff --git a/crates/openlogi-desktop/src/services/device_reads.rs b/crates/openlogi-desktop/src/services/device_reads.rs index dae050e9a9..090756b660 100644 --- a/crates/openlogi-desktop/src/services/device_reads.rs +++ b/crates/openlogi-desktop/src/services/device_reads.rs @@ -1,6 +1,6 @@ //! SWR-backed device-setting reads (DPI, SmartShift, Fn lock, report rate, -//! pointer speed, sidetone, press force, backlight, Easy-Switch hosts) keyed by device -//! identity. +//! pointer speed, sidetone, automatic power-off, press force, backlight, +//! Easy-Switch hosts) keyed by device identity. use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; @@ -9,8 +9,8 @@ use std::time::Duration; use gpui::{Context, Subscription}; use openlogi_core::hid::{ BacklightChange, BacklightState, DeviceRoute, Dpi, DpiInfo, EasySwitchHosts, FnLockState, - ForceSensingInfo, OnboardState, PointerSpeed, ReportRateInfo, SidetoneLevel, SmartShiftStatus, - WriteError, + ForceSensingInfo, OnboardState, PointerSpeed, PowerOffTimeout, ReportRateInfo, SidetoneLevel, + SmartShiftStatus, WriteError, }; use swr_core::{ MaybeSend, MaybeSync, QueryHandle, QueryOptions, QueryState, Retry, RetryPolicy, Runtime, @@ -21,12 +21,13 @@ use tokio::sync::mpsc; use super::ipc::{ Command, ReadBacklight, ReadDpi, ReadEasySwitchHosts, ReadFnLock, ReadForceSensing, - ReadOnboard, ReadPointerSpeed, ReadReportRate, ReadSidetone, ReadSmartShift, + ReadOnboard, ReadPointerSpeed, ReadPowerOffTimeout, ReadReportRate, ReadSidetone, + ReadSmartShift, }; use crate::state::{ AppState, BacklightLoad, DeviceKey, DpiLoad, EasySwitchLoad, FnLockLoad, ForceSensingLoad, - HostRenameRefusal, Load, OnboardLoad, PointerSpeedLoad, ReportRateLoad, SidetoneLoad, - SmartShiftLoad, StateEvent, + HostRenameRefusal, Load, OnboardLoad, PointerSpeedLoad, PowerOffTimeoutLoad, ReportRateLoad, + SidetoneLoad, SmartShiftLoad, StateEvent, }; const ROOT: &str = "device-read"; @@ -36,6 +37,7 @@ const FN_LOCK: &str = "fn-lock"; const REPORT_RATE: &str = "report-rate"; const POINTER_SPEED: &str = "pointer-speed"; const SIDETONE: &str = "sidetone"; +const POWER_OFF_TIMEOUT: &str = "power-off-timeout"; const FORCE_SENSING: &str = "force-sensing"; const BACKLIGHT: &str = "backlight"; const EASY_SWITCH: &str = "easy-switch"; @@ -77,6 +79,7 @@ pub(crate) struct DeviceReads { report_rate: BTreeMap>, pointer_speed: BTreeMap>, sidetone: BTreeMap>, + power_off_timeout: BTreeMap>, force_sensing: BTreeMap>, backlight: BTreeMap>, /// The backlight changes sent per keyboard, for the read on the route @@ -839,6 +842,122 @@ impl DeviceReads { self.sidetone.get(key).map(|read| &read.load) } + /// Start the automatic power-off query unless the same headset route is + /// already subscribed. A write answers through + /// [`Self::set_power_off_timeout_ready`], or + /// [`Self::refresh_power_off_timeout`] when the headset refused it. + pub(crate) fn ensure_power_off_timeout( + &mut self, + key: DeviceKey, + route: DeviceRoute, + commands: mpsc::UnboundedSender, + cx: &mut Context, + ) { + if self + .power_off_timeout + .get(&key) + .is_some_and(|read| read.route == route) + { + return; + } + self.remove_power_off_timeout(&key); + let Some((client, runtime)) = self.cache() else { + return; + }; + let flight = self.take_flight(); + let fetch_route = route.clone(); + let fetcher = Retry::new( + runtime, + move |_| { + let commands = commands.clone(); + let route = fetch_route.clone(); + read_ipc( + move |reply| ReadPowerOffTimeout { route, reply }.into(), + commands, + ) + }, + READ_RETRY_POLICY, + ) + .retry_if(|error| !unsupported_error_is_permanent(error)); + let handle = client.subscribe( + query_key(POWER_OFF_TIMEOUT, &key), + fetcher, + QueryOptions::immutable(), + ); + read_through(&client, POWER_OFF_TIMEOUT, &key, &handle); + let query = Query::new(&client, handle, cx); + let load = project_load(query.read(cx), unsupported_error_is_permanent); + let observed_key = key.clone(); + let observer = cx.observe(query.state(), move |state, query_state, cx| { + let load = project_load(query_state.read(cx), unsupported_error_is_permanent); + if state + .device_reads_mut() + .update_power_off_timeout(&observed_key, flight, load) + { + cx.emit(StateEvent::PowerOffTimeoutChanged(observed_key.clone())); + } + }); + self.power_off_timeout.insert( + key, + DeviceRead { + route, + flight, + load, + query, + _observer: observer, + }, + ); + } + + /// Show `timeout` as `key`'s automatic power-off reading now: the timeout + /// the GUI just asked for, then what the headset read back. Like + /// [`Self::set_sidetone_ready`], a local write supersedes a fetch still in + /// flight, and an answer from a route the headset has since left still + /// holds. + pub(crate) fn set_power_off_timeout_ready( + &mut self, + key: &DeviceKey, + timeout: PowerOffTimeout, + ) { + let value = Arc::new(timeout); + if let Some(client) = &self.client { + client.set::<_, Cached, WriteError>( + query_key(POWER_OFF_TIMEOUT, key), + Some(value.clone()), + ); + } + if let Some(read) = self.power_off_timeout.get_mut(key) { + read.load = Load::Ready(value); + } + } + + /// Re-read `key`'s automatic power-off timeout from the headset, keeping + /// the last value on screen while it answers. The fallback after a write + /// the headset refused. + pub(crate) fn refresh_power_off_timeout(&mut self, key: &DeviceKey) { + if let Some(read) = self.power_off_timeout.get_mut(key) { + read.query.revalidate(); + } + } + + /// Retry an exhausted automatic power-off query. + pub(crate) fn retry_power_off_timeout(&mut self, key: &DeviceKey) { + let Some(read) = self.power_off_timeout.get_mut(key) else { + return; + }; + if !matches!(read.load, Load::Ready(_)) { + read.load = Load::Loading; + } + read.query.revalidate(); + } + + /// `key`'s automatic power-off load, or `None` while nothing has + /// subscribed to it. + #[must_use] + pub(crate) fn power_off_timeout_load(&self, key: &DeviceKey) -> Option<&PowerOffTimeoutLoad> { + self.power_off_timeout.get(key).map(|read| &read.load) + } + /// Start the press-force query unless the same device route is already /// subscribed. A write answers through [`Self::set_force_sensing_ready`], /// or [`Self::refresh_force_sensing`] when the device refused it. @@ -1311,7 +1430,7 @@ impl DeviceReads { /// Re-read `key`'s settings after the device or agent announced a change, /// keeping the shown values while it answers. Covers the settings /// such a report can concern — DPI, Fn lock, report rate, backlight, - /// sidetone and the SmartShift wheel mode (see + /// sidetone, automatic power-off and the SmartShift wheel mode (see /// [`PairedDevice::settings_revision`]); a read nothing subscribed to /// stays unsubscribed. /// @@ -1330,6 +1449,7 @@ impl DeviceReads { } self.refresh_fn_lock(key); self.refresh_sidetone(key); + self.refresh_power_off_timeout(key); if let Some(read) = self.report_rate.get_mut(key) { read.query.revalidate(); } @@ -1439,6 +1559,7 @@ impl DeviceReads { self.remove_report_rate(key); self.remove_pointer_speed(key); self.remove_sidetone(key); + self.remove_power_off_timeout(key); self.remove_force_sensing(key); self.remove_backlight(key); self.remove_easy_switch(key); @@ -1494,6 +1615,13 @@ impl DeviceReads { } } + fn remove_power_off_timeout(&mut self, key: &DeviceKey) { + if let Some(read) = self.power_off_timeout.remove(key) { + drop(read); + self.clear::(POWER_OFF_TIMEOUT, key); + } + } + fn remove_force_sensing(&mut self, key: &DeviceKey) { if let Some(read) = self.force_sensing.remove(key) { drop(read); @@ -1527,6 +1655,7 @@ impl DeviceReads { .chain(self.report_rate.keys()) .chain(self.pointer_speed.keys()) .chain(self.sidetone.keys()) + .chain(self.power_off_timeout.keys()) .chain(self.force_sensing.keys()) .chain(self.backlight.keys()) .chain(self.easy_switch.keys()) @@ -1643,6 +1772,26 @@ impl DeviceReads { true } + fn update_power_off_timeout( + &mut self, + key: &DeviceKey, + flight: u64, + load: PowerOffTimeoutLoad, + ) -> bool { + let Some(read) = self + .power_off_timeout + .get_mut(key) + .filter(|read| read.flight == flight) + else { + return false; + }; + if read.load == load { + return false; + } + read.load = load; + true + } + fn update_force_sensing( &mut self, key: &DeviceKey, diff --git a/crates/openlogi-desktop/src/services/ipc.rs b/crates/openlogi-desktop/src/services/ipc.rs index 29149c3cd4..a5f12d00d4 100644 --- a/crates/openlogi-desktop/src/services/ipc.rs +++ b/crates/openlogi-desktop/src/services/ipc.rs @@ -44,7 +44,8 @@ use std::time::{Duration, Instant}; use openlogi_core::hid::{ BacklightState, DeviceRoute, DisableKeysState, Dpi, EasySwitchHosts, FnLockState, - ForceSensingInfo, LightCommand, PointerSpeed, ReportRateInfo, SidetoneLevel, WriteError, + ForceSensingInfo, LightCommand, PointerSpeed, PowerOffTimeout, ReportRateInfo, SidetoneLevel, + WriteError, }; use openlogi_ipc::client::{self, ConnectError}; use openlogi_ipc::{ @@ -73,11 +74,11 @@ pub use request::PollEventMonitor; pub use request::{ CancelFlowPairing, CancelPairing, Command, ConfirmFlowPairing, LoadConfig, PairDevice, PairFlowPeer, ReadBacklight, ReadDisableKeys, ReadDpi, ReadEasySwitchHosts, ReadFnLock, - ReadForceSensing, ReadOnboard, ReadPointerSpeed, ReadReportRate, ReadSidetone, ReadSmartShift, - ReloadConfig, RenameEasySwitchHost, RequestAccessibilityPrompt, RetryConnection, SetBacklight, - SetDisableKeys, SetDpi, SetFnLock, SetForceSensing, SetLight, SetLightManualPower, SetLighting, - SetPointerSpeed, SetReportRate, SetSidetone, SetSmartShift, StartFlowPairing, StartPairing, - StopFlowPairing, UnpairDevice, + ReadForceSensing, ReadOnboard, ReadPointerSpeed, ReadPowerOffTimeout, ReadReportRate, + ReadSidetone, ReadSmartShift, ReloadConfig, RenameEasySwitchHost, RequestAccessibilityPrompt, + RetryConnection, SetBacklight, SetDisableKeys, SetDpi, SetFnLock, SetForceSensing, SetLight, + SetLightManualPower, SetLighting, SetPointerSpeed, SetPowerOffTimeout, SetReportRate, + SetSidetone, SetSmartShift, StartFlowPairing, StartPairing, StopFlowPairing, UnpairDevice, }; /// Complete identity of one Disable Keys write/reload transaction. @@ -196,6 +197,15 @@ pub enum GuiUpdate { /// The confirmed level, or why the write did not land. result: Result, }, + /// What a headset confirms after an automatic power-off write the GUI + /// asked for: the timeout it took, or the typed refusal. Answers + /// [`SetPowerOffTimeout`]. + PowerOffTimeoutWritten { + /// The headset that was written. + key: DeviceKey, + /// The confirmed timeout, or why the write did not land. + result: Result, + }, /// What a force-sensing button reports after a press-force write the GUI /// asked for: the force it took, or the typed refusal. Answers /// [`SetForceSensing`]. diff --git a/crates/openlogi-desktop/src/services/ipc/request.rs b/crates/openlogi-desktop/src/services/ipc/request.rs index f7de04ef4c..f41bb14f42 100644 --- a/crates/openlogi-desktop/src/services/ipc/request.rs +++ b/crates/openlogi-desktop/src/services/ipc/request.rs @@ -20,7 +20,8 @@ use openlogi_core::config::{ConfigRevision, Lighting}; use openlogi_core::hid::{ BacklightChange, BacklightState, DeviceRoute, DisableKeysMask, DisableKeysState, Dpi, DpiInfo, EasySwitchHosts, FnLockState, ForceSensingInfo, LightCommand, OnboardState, PointerSpeed, - ReceiverSelector, ReportRate, ReportRateInfo, SidetoneLevel, SmartShiftStatus, WriteError, + PowerOffTimeout, ReceiverSelector, ReportRate, ReportRateInfo, SidetoneLevel, SmartShiftStatus, + WriteError, }; use openlogi_ipc::{ AgentClient, ChosenLight, ConfigReloadError, FlowPairTarget, FlowPairingCommandError, @@ -259,6 +260,31 @@ impl Request for SetSidetone { } } +/// Write a headset's automatic power-off timeout now, answered as +/// [`GuiUpdate::PowerOffTimeoutWritten`] with the timeout the headset confirms. +pub struct SetPowerOffTimeout { + pub route: DeviceRoute, + pub timeout: PowerOffTimeout, + pub key: DeviceKey, +} + +impl Request for SetPowerOffTimeout { + type Answer = Result; + + async fn call(&self, client: &AgentClient) -> Result { + client + .set_power_off_timeout(context::current(), self.route.clone(), self.timeout) + .await + } + + fn deliver(self, outcome: Result, updates: &UpdateSender) { + let _ = updates.send(GuiUpdate::PowerOffTimeoutWritten { + key: self.key, + result: or_unavailable(outcome), + }); + } +} + /// Write the press force of a force-sensing button now, answered as /// [`GuiUpdate::ForceSensingWritten`] with what the device reads back. pub struct SetForceSensing { @@ -590,6 +616,27 @@ impl Request for ReadSidetone { } } +/// Read a headset's automatic power-off timeout; the answer goes back over +/// `reply`. +pub struct ReadPowerOffTimeout { + pub route: DeviceRoute, + pub reply: oneshot::Sender>, +} + +impl Request for ReadPowerOffTimeout { + type Answer = Result; + + async fn call(&self, client: &AgentClient) -> Result { + client + .read_power_off_timeout(context::current(), self.route.clone()) + .await + } + + fn deliver(self, outcome: Result, _: &UpdateSender) { + let _ = self.reply.send(or_unavailable(outcome)); + } +} + /// Read the press force of a force-sensing button, with the range the device /// accepts; the answer goes back over `reply`. pub struct ReadForceSensing { @@ -1150,6 +1197,7 @@ commands! { SetReportRate, SetPointerSpeed, SetSidetone, + SetPowerOffTimeout, SetForceSensing, SetBacklight, RenameEasySwitchHost, @@ -1159,6 +1207,7 @@ commands! { ReadReportRate, ReadPointerSpeed, ReadSidetone, + ReadPowerOffTimeout, ReadForceSensing, ReadBacklight, ReadEasySwitchHosts, diff --git a/crates/openlogi-desktop/src/state.rs b/crates/openlogi-desktop/src/state.rs index 762ba83b95..9ccb1e284a 100644 --- a/crates/openlogi-desktop/src/state.rs +++ b/crates/openlogi-desktop/src/state.rs @@ -42,7 +42,8 @@ pub use light::LightCommandStatus; pub(crate) use load::Load; pub use load::{ BacklightLoad, DisableKeysLoad, DpiLoad, EasySwitchLoad, FnLockLoad, ForceSensingLoad, - OnboardLoad, PointerSpeedLoad, ReportRateLoad, SidetoneLoad, SmartShiftLoad, + OnboardLoad, PointerSpeedLoad, PowerOffTimeoutLoad, ReportRateLoad, SidetoneLoad, + SmartShiftLoad, }; /// Result of confirming a SmartShift write by reading the value back. @@ -104,6 +105,7 @@ mod onboard; mod os_layout; mod pointer; mod pointer_speed; +mod power_off_timeout; mod reconciliation; mod report_rate; mod scroll; @@ -260,6 +262,7 @@ impl AppState { state.load_current_report_rate(cx); state.load_current_pointer_speed(cx); state.load_current_sidetone(cx); + state.load_current_power_off_timeout(cx); state.load_current_force_sensing(cx); state.load_current_backlight(cx); state.load_current_easy_switch(cx); diff --git a/crates/openlogi-desktop/src/state/events.rs b/crates/openlogi-desktop/src/state/events.rs index 708998583a..4f8be7a2df 100644 --- a/crates/openlogi-desktop/src/state/events.rs +++ b/crates/openlogi-desktop/src/state/events.rs @@ -59,6 +59,8 @@ pub(crate) enum StateEvent { PointerSpeedChanged(DeviceKey), /// The headset's sidetone read landed or changed. SidetoneChanged(DeviceKey), + /// The headset's automatic power-off read landed or changed. + PowerOffTimeoutChanged(DeviceKey), /// The device's press-force read landed or changed. ForceSensingChanged(DeviceKey), /// The keyboard's backlight read landed or changed. @@ -106,6 +108,7 @@ impl StateEvent { | Self::ReportRateChanged(key) | Self::PointerSpeedChanged(key) | Self::SidetoneChanged(key) + | Self::PowerOffTimeoutChanged(key) | Self::ForceSensingChanged(key) | Self::BacklightChanged(key) | Self::EasySwitchChanged(key) @@ -267,6 +270,7 @@ impl AppState { | StateEvent::ReportRateChanged(_) | StateEvent::PointerSpeedChanged(_) | StateEvent::SidetoneChanged(_) + | StateEvent::PowerOffTimeoutChanged(_) | StateEvent::ForceSensingChanged(_) | StateEvent::BacklightChanged(_) | StateEvent::EasySwitchChanged(_) diff --git a/crates/openlogi-desktop/src/state/inventory.rs b/crates/openlogi-desktop/src/state/inventory.rs index 0dcef44084..33e7b18518 100644 --- a/crates/openlogi-desktop/src/state/inventory.rs +++ b/crates/openlogi-desktop/src/state/inventory.rs @@ -189,6 +189,7 @@ impl AppState { for key in &reconnected { self.pointer_speed_reconnected(key); self.sidetone_reconnected(key); + self.power_off_timeout_reconnected(key); self.force_sensing_reconnected(key); } for key in &disable_keys_invalidated { diff --git a/crates/openlogi-desktop/src/state/load.rs b/crates/openlogi-desktop/src/state/load.rs index 3177ff53ac..2b132ce0d1 100644 --- a/crates/openlogi-desktop/src/state/load.rs +++ b/crates/openlogi-desktop/src/state/load.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use openlogi_core::hid::{ BacklightState, DisableKeysState, DpiInfo, EasySwitchHosts, FnLockState, ForceSensingInfo, - OnboardState, PointerSpeed, ReportRateInfo, SidetoneLevel, SmartShiftStatus, + OnboardState, PointerSpeed, PowerOffTimeout, ReportRateInfo, SidetoneLevel, SmartShiftStatus, }; /// State projected from an swr-backed device query: unqueried, in flight, @@ -53,6 +53,9 @@ pub type PointerSpeedLoad = Load>; /// Per-headset sidetone (`0x8300`) load state. See [`Load`]. The headset /// stores the level itself, so the read is the only record. pub type SidetoneLoad = Load>; +/// Per-headset automatic power-off (`0x1F20`) load state. See [`Load`]. The +/// headset stores the timeout itself, so the read is the only record. +pub type PowerOffTimeoutLoad = Load>; /// Per-device press-force (`0x19c0`) load state. See [`Load`]. The read is /// the force the button clicks at now, the range the device accepts, and /// whether software may change it. diff --git a/crates/openlogi-desktop/src/state/power_off_timeout.rs b/crates/openlogi-desktop/src/state/power_off_timeout.rs new file mode 100644 index 0000000000..26bcdd9005 --- /dev/null +++ b/crates/openlogi-desktop/src/state/power_off_timeout.rs @@ -0,0 +1,136 @@ +//! Headset automatic power-off: how long the headset idles before it switches +//! itself off. +//! +//! The headset stores the timeout itself and keeps it when it turns off, so +//! nothing is persisted here. The reading is the swr-backed device query the +//! device-read service owns, and the slider shows it. +//! +//! A release of the slider writes the headset. Its answer is the timeout the +//! headset confirms. A refusal reads the headset again, so the slider returns +//! to the headset's own timeout, as for sidetone. + +use openlogi_core::hid::{DeviceRoute, PowerOffTimeout, WriteError}; +use tracing::{debug, warn}; + +use super::device_key::DeviceKey; +use super::devices::DeviceRecord; +use super::events::StateEvents; +use super::load::PowerOffTimeoutLoad; +use super::{AppState, StateEvent}; + +impl AppState { + /// Whether the active device reports HID++ `0x1F20`, which carries the + /// automatic power-off timeout. + #[must_use] + pub fn current_power_off_timeout_supported(&self) -> bool { + self.current_record().is_some_and(has_power_off_timeout) + } + + /// The route to write the active headset's automatic power-off on, or + /// `None` when it has no `0x1F20` or is offline. A wireless headset that + /// is switched off keeps its dongle's route, so the route alone does not + /// say it answers. + #[must_use] + pub fn current_power_off_timeout_route(&self) -> Option<&DeviceRoute> { + self.writable_power_off_timeout().map(|(_, route)| route) + } + + fn writable_power_off_timeout(&self) -> Option<(&DeviceRecord, &DeviceRoute)> { + let record = self + .current_record() + .filter(|record| has_power_off_timeout(record))?; + Some((record, record.addressable_route()?)) + } + + /// What is known of the active headset's automatic power-off reading. + #[must_use] + pub fn current_power_off_timeout_load(&self) -> PowerOffTimeoutLoad { + self.current_record() + .and_then(|record| { + self.pointer + .reads + .power_off_timeout_load(&record.device_key()) + }) + .cloned() + .unwrap_or_default() + } + + /// Write `timeout` to the active headset through the agent. The slider + /// shows `timeout` at once; the headset's confirmation arrives as + /// [`Self::apply_power_off_timeout_written`]. No-op when no device is + /// selected, it has no `0x1F20`, or it is offline. + pub fn commit_power_off_timeout(&mut self, timeout: PowerOffTimeout) -> StateEvents { + let events = self.for_current_device(StateEvent::PowerOffTimeoutChanged); + let Some((key, route)) = self + .writable_power_off_timeout() + .map(|(record, route)| (record.device_key(), route.clone())) + else { + return events; + }; + self.pointer + .reads + .set_power_off_timeout_ready(&key, timeout); + self.send_ipc(crate::services::ipc::SetPowerOffTimeout { + route, + timeout, + key, + }); + events + } + + /// The headset's answer to a [`Self::commit_power_off_timeout`] write: + /// show the confirmed timeout, or — when the headset refused or could not + /// be reached — read it again so the optimistic value does not stand in + /// for its own. + pub fn apply_power_off_timeout_written( + &mut self, + key: &DeviceKey, + result: Result, + ) -> StateEvents { + match result { + Ok(timeout) => self.pointer.reads.set_power_off_timeout_ready(key, timeout), + Err(error) => { + warn!( + %error, + key = %key, + "power-off timeout write did not land — re-reading the headset" + ); + self.pointer.reads.refresh_power_off_timeout(key); + } + } + StateEvent::PowerOffTimeoutChanged(key.clone()).into() + } + + /// Re-run `key`'s exhausted automatic power-off read — the "click to + /// retry" affordance on a [`PowerOffTimeoutLoad::Failed`] headset. + pub(crate) fn retry_power_off_timeout_read(&mut self, key: &DeviceKey) -> StateEvents { + self.pointer.reads.retry_power_off_timeout(key); + StateEvent::PowerOffTimeoutChanged(key.clone()).into() + } + + /// `key`'s headset came back online: read it again in case another host + /// changed its timeout. + pub(super) fn power_off_timeout_reconnected(&mut self, key: &DeviceKey) { + self.pointer.reads.refresh_power_off_timeout(key); + } + + pub(super) fn load_current_power_off_timeout(&mut self, cx: &mut gpui::Context) { + let Some((key, route)) = self + .current_record() + .filter(|record| has_power_off_timeout(record)) + .and_then(|record| Some((record.device_key(), record.route.clone()?))) + else { + return; + }; + debug!(key = %key, "reading the headset's automatic power-off"); + self.pointer + .reads + .ensure_power_off_timeout(key, route, self.ipc_sender(), cx); + } +} + +fn has_power_off_timeout(record: &DeviceRecord) -> bool { + record + .capabilities + .is_some_and(|capabilities| capabilities.power_off_timeout) +} diff --git a/crates/openlogi-desktop/src/state/tests.rs b/crates/openlogi-desktop/src/state/tests.rs index 6196d8f66e..ec04e4d8a2 100644 --- a/crates/openlogi-desktop/src/state/tests.rs +++ b/crates/openlogi-desktop/src/state/tests.rs @@ -62,6 +62,7 @@ mod light_adoption; mod lighting; mod os_layout; mod pointer_speed; +mod power_off_timeout; mod profile_scope; mod reload; mod report_rate; diff --git a/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs b/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs new file mode 100644 index 0000000000..2355c8617c --- /dev/null +++ b/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs @@ -0,0 +1,224 @@ +//! Automatic power-off: a release writes the headset through the agent, +//! nothing is saved, and the slider shows the headset's own reading. A +//! headset that lists `0x1F20` but refuses the timeout read shows as +//! unsupported instead of retrying forever. + +use super::fn_lock::drain; +use super::pointer_speed::install; +use super::*; +use crate::services::ipc::{Command, ReadPowerOffTimeout, SetPowerOffTimeout}; +use crate::state::PowerOffTimeoutLoad; +use openlogi_core::hid::{DeviceRoute, PowerOffTimeout}; + +fn minutes(raw: u8) -> PowerOffTimeout { + PowerOffTimeout::try_new(raw).expect("a timeout in range") +} + +/// A direct headset that lists `0x1F20`, or one that does not. +fn headset_inventory(power_off_timeout: bool) -> DeviceInventory { + let mut inventory = direct_inventory([0x0a, 0x5b, 0x00, 0x01]); + inventory.paired[0].kind = DeviceKind::Headset; + inventory.paired[0].capabilities = Some(Capabilities { + power_off_timeout, + ..Capabilities::default() + }); + inventory +} + +fn headset_state( + power_off_timeout: bool, +) -> (AppState, tokio::sync::mpsc::UnboundedReceiver) { + let resolver = AssetResolver::new(); + let (commands, receiver) = tokio::sync::mpsc::unbounded_channel(); + let state = AppState::new(Sources { + inventories: &[headset_inventory(power_off_timeout)], + ..Sources::in_memory(Config::ephemeral(), &resolver, commands) + }); + (state, receiver) +} + +/// Answer the power-off read the state has queued with `answer`, returning +/// the route it was asked on. Every other read is left unanswered. +fn answer_read( + receiver: &mut tokio::sync::mpsc::UnboundedReceiver, + answer: &Result, +) -> DeviceRoute { + let mut answered = None; + for command in drain(receiver) { + if let Command::ReadPowerOffTimeout(ReadPowerOffTimeout { route, reply }) = command { + assert!(answered.is_none(), "one power-off read at a time"); + let _ = reply.send(answer.clone()); + answered = Some(route); + } + } + answered.expect("the state asked the headset for its power-off timeout") +} + +fn current_load(cx: &gpui::TestAppContext) -> PowerOffTimeoutLoad { + cx.read(|cx| { + AppState::try_read(cx) + .expect("state installed") + .current_power_off_timeout_load() + }) +} + +#[test] +fn a_release_writes_the_headset_and_saves_nothing() { + let (mut state, mut receiver) = headset_state(true); + drain(&mut receiver); + let record = state.current_record().expect("the headset is selected"); + let key = record.device_key(); + let route = record.route.clone().expect("a direct route"); + + let events = state.commit_power_off_timeout(minutes(30)); + + assert_eq!(events, [StateEvent::PowerOffTimeoutChanged(key.clone())]); + let commands = drain(&mut receiver); + let [ + Command::SetPowerOffTimeout(SetPowerOffTimeout { + route: written_route, + timeout: written, + key: written_key, + }), + ] = commands.as_slice() + else { + panic!("expected one power-off write and no config reload: the headset keeps the timeout"); + }; + assert_eq!(*written_route, route); + assert_eq!(*written, minutes(30)); + assert_eq!(*written_key, key); +} + +/// "Never" is a timeout like any other: 0 reaches the headset instead of +/// being dropped as an empty value. +#[test] +fn never_is_written_as_zero_minutes() { + let (mut state, mut receiver) = headset_state(true); + drain(&mut receiver); + + let _ = state.commit_power_off_timeout(PowerOffTimeout::NEVER); + + let commands = drain(&mut receiver); + let [Command::SetPowerOffTimeout(SetPowerOffTimeout { timeout, .. })] = commands.as_slice() + else { + panic!("expected one power-off write"); + }; + assert_eq!(timeout.minutes(), 0); +} + +#[test] +fn a_release_is_inert_on_a_device_without_power_off() { + let (mut state, mut receiver) = headset_state(false); + drain(&mut receiver); + assert!(!state.current_power_off_timeout_supported()); + + let _ = state.commit_power_off_timeout(minutes(30)); + + assert!(drain(&mut receiver).is_empty()); +} + +/// A wireless headset that is switched off keeps its dongle's route: the +/// slider hides and a release writes nothing. +#[test] +fn an_offline_headset_is_not_written() { + let mut inventory = headset_inventory(true); + inventory.paired[0].online = false; + let resolver = AssetResolver::new(); + let (commands, mut receiver) = tokio::sync::mpsc::unbounded_channel(); + let mut state = AppState::new(Sources { + inventories: &[inventory], + ..Sources::in_memory(Config::ephemeral(), &resolver, commands) + }); + drain(&mut receiver); + let record = state.current_record().expect("the headset is selected"); + assert!(!record.is_online() && record.route.is_some()); + assert!(state.current_power_off_timeout_supported()); + assert_eq!(state.current_power_off_timeout_route(), None); + + let _ = state.commit_power_off_timeout(minutes(30)); + + assert!(drain(&mut receiver).is_empty()); +} + +#[gpui::test] +fn the_reading_lands_and_a_refusal_reads_the_headset_again(cx: &mut gpui::TestAppContext) { + let (state, mut receiver) = headset_state(true); + let key = state.current_record().expect("headset").device_key(); + install(state, cx); + let route = answer_read(&mut receiver, &Ok(minutes(15))); + cx.run_until_parked(); + assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(15)))); + + let events = cx.update(|cx| { + AppState::update(cx, |state, _| { + state.apply_power_off_timeout_written(&key, Ok(minutes(30))) + }) + }); + assert_eq!(events, [StateEvent::PowerOffTimeoutChanged(key.clone())]); + assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(30)))); + + let events = cx.update(|cx| { + AppState::update(cx, |state, _| { + state.apply_power_off_timeout_written(&key, Err(WriteError::AgentUnavailable)) + }) + }); + assert_eq!(events, [StateEvent::PowerOffTimeoutChanged(key)]); + cx.run_until_parked(); + assert_eq!( + answer_read(&mut receiver, &Ok(minutes(30))), + route, + "the refusal sends the read back to the headset" + ); + cx.run_until_parked(); + assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(30)))); +} + +/// Some headsets list `0x1F20` for the battery but refuse the timeout +/// functions. That answer is final: the row says so instead of offering a +/// retry that can never succeed. +#[gpui::test] +fn a_headset_that_refuses_the_read_is_unsupported(cx: &mut gpui::TestAppContext) { + let (state, mut receiver) = headset_state(true); + install(state, cx); + answer_read( + &mut receiver, + &Err(WriteError::FeatureUnsupported { + feature_hex: 0x1f20, + }), + ); + cx.run_until_parked(); + + let load = current_load(cx); + assert!( + matches!(load, Load::Unsupported(_)), + "expected Unsupported, got {load:?}" + ); + assert!( + drain(&mut receiver) + .iter() + .all(|command| !matches!(command, Command::ReadPowerOffTimeout(_))), + "an unsupported answer is not retried" + ); +} + +/// The agent changed the timeout itself — from the menu-bar menu — and +/// moved the headset's settings revision, so the slider reads it again. +#[gpui::test] +fn a_moved_settings_revision_reads_the_headset_again(cx: &mut gpui::TestAppContext) { + let (state, mut receiver) = headset_state(true); + install(state, cx); + let route = answer_read(&mut receiver, &Ok(minutes(15))); + cx.run_until_parked(); + + let mut moved = headset_inventory(true); + moved.paired[0].settings_revision = 1; + let _ = cx.update(|cx| { + AppState::update(cx, |state, _| { + state.refresh_inventories(&[moved], &[], &AssetResolver::new(), &[]) + }) + }); + cx.run_until_parked(); + assert_eq!(answer_read(&mut receiver, &Ok(minutes(60))), route); + cx.run_until_parked(); + assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(60)))); +} From addfaf6a4676f396bf9d852035be1ef35e3fa539 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:10:49 +0100 Subject: [PATCH 14/28] feat(gui): show the Audio tab for a headset with automatic power-off --- crates/openlogi-desktop/src/app.rs | 4 +-- crates/openlogi-desktop/src/app/detail.rs | 4 +-- crates/openlogi-desktop/src/app/tests.rs | 32 +++++++++++++++++++++++ 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/crates/openlogi-desktop/src/app.rs b/crates/openlogi-desktop/src/app.rs index 13b760e71f..b789ede19f 100644 --- a/crates/openlogi-desktop/src/app.rs +++ b/crates/openlogi-desktop/src/app.rs @@ -88,7 +88,7 @@ enum DetailTab { Camera, /// Standalone light controls driven by a raw-HID device driver. Light, - /// Headset audio — sidetone. + /// Headset audio — sidetone and automatic power-off. Audio, /// Device info and configuration. Device, @@ -188,7 +188,7 @@ impl DetailTab { if record.light_capabilities.is_some() { tabs.push(Self::Light); } - if caps.sidetone { + if caps.sidetone || caps.power_off_timeout { tabs.push(Self::Audio); } tabs.push(Self::Device); diff --git a/crates/openlogi-desktop/src/app/detail.rs b/crates/openlogi-desktop/src/app/detail.rs index f861597921..a555e70734 100644 --- a/crates/openlogi-desktop/src/app/detail.rs +++ b/crates/openlogi-desktop/src/app/detail.rs @@ -814,8 +814,8 @@ fn wheel_resolution_control( }) } -/// Audio tab: the headset's sidetone in one untitled card — the rail already -/// names the page "Audio", as with Lighting. +/// Audio tab: the headset's sidetone and automatic power-off in one untitled +/// card — the rail already names the page "Audio", as with Lighting. fn audio_tab(audio_panel: &gpui::Entity) -> impl IntoElement { tab_body( DetailTab::Audio, diff --git a/crates/openlogi-desktop/src/app/tests.rs b/crates/openlogi-desktop/src/app/tests.rs index 888e9af116..7db24dfd5b 100644 --- a/crates/openlogi-desktop/src/app/tests.rs +++ b/crates/openlogi-desktop/src/app/tests.rs @@ -1586,6 +1586,38 @@ fn a_sidetone_headset_opens_on_the_audio_tab() { assert_eq!(DetailTab::default_for(&headset), DetailTab::Audio); } +/// A headset with an automatic power-off but no sidetone still needs the +/// Audio tab: the power-off row lives there. +#[test] +fn a_power_off_only_headset_opens_on_the_audio_tab() { + let caps = Some(Capabilities { + power_off_timeout: true, + ..Capabilities::default() + }); + let headset = record(DeviceKind::Headset, caps); + assert_eq!( + DetailTab::tabs_for(&headset), + vec![DetailTab::Audio, DetailTab::Device] + ); + assert_eq!(DetailTab::default_for(&headset), DetailTab::Audio); +} + +/// A G933 has both settings; they share one Audio tab rather than adding a +/// second. +#[test] +fn a_headset_with_sidetone_and_power_off_has_one_audio_tab() { + let caps = Some(Capabilities { + sidetone: true, + power_off_timeout: true, + ..Capabilities::default() + }); + let headset = record(DeviceKind::Headset, caps); + assert_eq!( + DetailTab::tabs_for(&headset), + vec![DetailTab::Audio, DetailTab::Device] + ); +} + /// An unprobed (offline) device has no measured capabilities and falls back /// to a kind presumption, so a sleeping mouse keeps its button/pointer tabs. #[test] From 1548082b16d60830942f19f25028ac3c078fcf3a Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:07:22 +0100 Subject: [PATCH 15/28] feat(tray): offer the headset automatic power-off in the menu-bar item A headset that lists 0x1F20 gets an automatic power-off submenu group with Never, 5, 15, 30, 60 and 90 minutes, read when the submenu opens and written on the device alone, as sidetone is. A headset that refuses the read hides the group. --- crates/openlogi-agent/src/tray.rs | 35 +++++++++++-- crates/openlogi-agent/src/tray_model.rs | 1 + .../openlogi-agent/src/tray_model/controls.rs | 50 ++++++++++++++++++- 3 files changed, 81 insertions(+), 5 deletions(-) diff --git a/crates/openlogi-agent/src/tray.rs b/crates/openlogi-agent/src/tray.rs index cfc1f0625f..994dc66960 100644 --- a/crates/openlogi-agent/src/tray.rs +++ b/crates/openlogi-agent/src/tray.rs @@ -469,7 +469,7 @@ async fn read_device(shared: &SharedHandles, route: &DeviceRoute, reads: Reads) Read::Unread } } - let (dpi, wheel, fn_lock, backlight, disabled_keys, sidetone) = tokio::join!( + let (dpi, wheel, fn_lock, backlight, disabled_keys, sidetone, power_off_timeout) = tokio::join!( when(reads.dpi, async { shared.read_dpi(route).await.map(|info| info.current) }), @@ -480,6 +480,10 @@ async fn read_device(shared: &SharedHandles, route: &DeviceRoute, reads: Reads) when(reads.backlight, shared.read_backlight(route)), when(reads.disabled_keys, shared.read_disable_keys(route)), when(reads.sidetone, shared.read_sidetone(route)), + when( + reads.power_off_timeout, + shared.read_power_off_timeout(route) + ), ); Reading { dpi, @@ -488,13 +492,15 @@ async fn read_device(shared: &SharedHandles, route: &DeviceRoute, reads: Reads) backlight, disabled_keys, sidetone, + power_off_timeout, } } /// Make `change` to `device` as the settings app would: saved settings -/// through the agent's device settings, the backlight and sidetone, which -/// the device keeps itself, on the device alone. Answers the change the -/// device took, or `None` when a newer write superseded it. A change reaches +/// through the agent's device settings, the backlight, sidetone and +/// automatic power-off, which the device keeps itself, on the device alone. +/// Answers the change the device took, or `None` when a newer write +/// superseded it. A change reaches /// only `device`: another device the agent knows on its route, or that /// answers there when the change is written, such as one paired into the /// receiver slot since the menu listed `device`, takes none of it. @@ -548,6 +554,27 @@ async fn apply( Failure::Device }); } + Change::PowerOffTimeout(timeout) => { + let written = server + .shared + .reaching(device.unit) + .set_power_off_timeout(route, timeout) + .await; + // The settings app re-reads it, as it does after a backlight + // change the agent made. + server + .orchestrator + .lock() + .await + .announce_settings_changed(route); + // A superseded write answers the timeout the headset kept. + return written + .map(|timeout| Some(Change::PowerOffTimeout(timeout))) + .map_err(|error| { + warn!(%route, %error, "menu-bar power-off change failed"); + Failure::Device + }); + } }; match saved { Ok(()) => Ok(Some(change)), diff --git a/crates/openlogi-agent/src/tray_model.rs b/crates/openlogi-agent/src/tray_model.rs index 8552ab107e..6a82c137d2 100644 --- a/crates/openlogi-agent/src/tray_model.rs +++ b/crates/openlogi-agent/src/tray_model.rs @@ -576,6 +576,7 @@ impl Known { backlight: capabilities.backlight, disable_keys: capabilities.disable_keys, sidetone: capabilities.sidetone, + power_off_timeout: capabilities.power_off_timeout, light: None, } } diff --git a/crates/openlogi-agent/src/tray_model/controls.rs b/crates/openlogi-agent/src/tray_model/controls.rs index ee2c5ba9bc..99df966e57 100644 --- a/crates/openlogi-agent/src/tray_model/controls.rs +++ b/crates/openlogi-agent/src/tray_model/controls.rs @@ -19,7 +19,8 @@ use openlogi_core::config::{ use openlogi_core::device::LightCapabilities; use openlogi_core::hid::{ BacklightChange, BacklightState, DisableKeysMask, DisableKeysState, Dpi, LightCommand, - SidetoneLevel, SmartShiftAutoDisengage, SmartShiftMode, SmartShiftStatus, WriteError, + PowerOffTimeout, SidetoneLevel, SmartShiftAutoDisengage, SmartShiftMode, SmartShiftStatus, + WriteError, }; use rust_i18n::t; @@ -27,6 +28,9 @@ use super::{DeviceRow, DeviceState}; /// The sidetone levels the submenu offers, in percent. const SIDETONE_LEVELS: [u8; 5] = [0, 25, 50, 75, 100]; +/// The automatic power-off timeouts the submenu offers, in minutes; 0 is +/// never. +const POWER_OFF_TIMEOUTS: [u8; 6] = [0, 5, 15, 30, 60, 90]; /// The brightness levels the submenu offers a light, in percent of its range. const LIGHT_BRIGHTNESS_LEVELS: [u8; 4] = [25, 50, 75, 100]; @@ -57,6 +61,9 @@ pub struct Controls { pub disable_keys: bool, /// Whether the headset plays the microphone back. pub sidetone: bool, + /// Whether the headset switches itself off after an adjustable idle + /// time. + pub power_off_timeout: bool, /// The controls of a standalone light. pub light: Option, } @@ -160,6 +167,8 @@ pub struct Reading { pub disabled_keys: Read, /// Its sidetone. pub sidetone: Read, + /// Its automatic power-off timeout. + pub power_off_timeout: Read, } impl Reading { @@ -180,6 +189,11 @@ impl Reading { fresh.disabled_keys, ); take(reads.sidetone, &mut self.sidetone, fresh.sidetone); + take( + reads.power_off_timeout, + &mut self.power_off_timeout, + fresh.power_off_timeout, + ); } /// Take a change the device and config just took, so the next opening @@ -200,6 +214,7 @@ impl Reading { } } Change::Sidetone(level) => self.sidetone = Read::Value(level), + Change::PowerOffTimeout(timeout) => self.power_off_timeout = Read::Value(timeout), // The snapshot and the reloaded config carry these. Change::Managed(_) | Change::Light(_) => {} } @@ -268,6 +283,8 @@ pub struct Reads { pub disabled_keys: bool, /// Its sidetone. pub sidetone: bool, + /// Its automatic power-off timeout. + pub power_off_timeout: bool, } impl Reads { @@ -280,6 +297,7 @@ impl Reads { || self.backlight || self.disabled_keys || self.sidetone + || self.power_off_timeout } /// The reads in either. @@ -291,6 +309,7 @@ impl Reads { backlight: self.backlight || other.backlight, disabled_keys: self.disabled_keys || other.disabled_keys, sidetone: self.sidetone || other.sidetone, + power_off_timeout: self.power_off_timeout || other.power_off_timeout, } } @@ -303,6 +322,7 @@ impl Reads { backlight: self.backlight && !other.backlight, disabled_keys: self.disabled_keys && !other.disabled_keys, sidetone: self.sidetone && !other.sidetone, + power_off_timeout: self.power_off_timeout && !other.power_off_timeout, } } } @@ -318,6 +338,7 @@ impl Change { Self::Backlight(_) => reads.backlight = true, Self::DisabledKeys(_) => reads.disabled_keys = true, Self::Sidetone(_) => reads.sidetone = true, + Self::PowerOffTimeout(_) => reads.power_off_timeout = true, Self::Managed(_) | Self::Light(_) => {} } reads @@ -341,6 +362,8 @@ pub enum Change { DisabledKeys(DisableKeysMask), /// Set the sidetone. Sidetone(SidetoneLevel), + /// Set the automatic power-off timeout. + PowerOffTimeout(PowerOffTimeout), /// Have the light take the command and save it. Light(LightCommand), } @@ -516,6 +539,7 @@ impl DeviceRow { backlight: controls.backlight, disabled_keys: controls.disable_keys, sidetone: controls.sidetone, + power_off_timeout: controls.power_off_timeout, } } @@ -539,6 +563,7 @@ impl DeviceRow { groups.push(self.keyboard_group(reading)); groups.push(self.disabled_keys_group(reading)); groups.push(self.sidetone_group(reading)); + groups.push(self.power_off_group(reading)); if let Some(capabilities) = self.controls.light { groups.extend(self.light_groups(capabilities)); } @@ -584,6 +609,7 @@ impl DeviceRow { (reads.backlight, reading.backlight.state()), (reads.disabled_keys, reading.disabled_keys.state()), (reads.sidetone, reading.sidetone.state()), + (reads.power_off_timeout, reading.power_off_timeout.state()), ]; if memory.reading_now() && answers.contains(&(true, Read::Unread)) { status.push(Entry::Note(t!("tray.reading").into_owned())); @@ -735,6 +761,28 @@ impl DeviceRow { group } + fn power_off_group(&self, reading: &Reading) -> Vec { + if !self.controls.power_off_timeout + || reading.power_off_timeout.state() == Read::Unsupported + { + return Vec::new(); + } + let read = reading.power_off_timeout.value(); + let mut group = vec![Entry::Header(t!("audio.power_off").into_owned())]; + group.extend(POWER_OFF_TIMEOUTS.map(|minutes| Entry::Choice { + title: if minutes == 0 { + t!("audio.power_off_never").into_owned() + } else { + t!("audio.power_off_minutes", minutes => minutes).into_owned() + }, + checked: read.is_some_and(|timeout| timeout.minutes() == minutes), + change: read.and_then(|_| { + self.live(Change::PowerOffTimeout(PowerOffTimeout::clamped(minutes))) + }), + })); + group + } + /// A light's power, brightness and colour temperature, which change only /// while it is online and read back. fn light_groups(&self, capabilities: LightCapabilities) -> Vec> { From cbaeb34f4c81cf38a30593c9357ac00078157517 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:57:53 +0100 Subject: [PATCH 16/28] docs: note the headset automatic power-off setting --- README.md | 2 +- docs/CONFIGURATION.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0ee953710c..a8fb973575 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ Things OpenLogi does that Options+ won't: - Logi Bolt and Unifying receivers, Bluetooth, and wired connections, with battery level and charge state - Low-battery notices at the bottom of the screen, once per discharge, with no OS notification permission - An on-screen indicator when a keyboard turns Caps Lock on or off, plus Num Lock and Scroll Lock on Windows and Linux -- On macOS, a menu-bar menu that lists each device with its battery or light state, flags a missing permission, and changes the settings you reach for most without opening the app: DPI preset, wheel mode, Fn lock, backlight, disabled keys, headset sidetone, and a light's power, brightness, and color temperature. Hold ⌥ to see how each device connects +- On macOS, a menu-bar menu that lists each device with its battery or light state, flags a missing permission, and changes the settings you reach for most without opening the app: DPI preset, wheel mode, Fn lock, backlight, disabled keys, headset sidetone and automatic power-off, and a light's power, brightness, and color temperature. Hold ⌥ to see how each device connects diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 6679e85317..60b36df0db 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -39,8 +39,8 @@ is saved and the device's submenu says so; choose the change again. The agent then reloads the file, and an open GUI picks up the change without a relaunch. A sleeping mouse's DPI preset and wheel mode, and whether OpenLogi manages a device, are saved and applied when the device reconnects; the other menu -controls need the device online. The backlight and sidetone stay on the device -and are not saved. +controls need the device online. The backlight, the sidetone and a headset's +automatic power-off timeout stay on the device and are not saved. Schema versions newer than the running build are rejected before their fields are parsed. v1 binding maps and the v2–v3 gesture-owner layout migrate on load. From 5fa0be210e7d64799570ba3aeea33515e9fa8bfd Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:07:22 +0100 Subject: [PATCH 17/28] test(tray): cover the headset automatic power-off submenu The group offers its six timeouts only once the headset answered, shows a change the headset echoed, greys out after a failed read and disappears when the headset refuses the feature. --- crates/openlogi-agent/src/tray_model/tests.rs | 61 ++++++++++++++++++- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/openlogi-agent/src/tray_model/tests.rs b/crates/openlogi-agent/src/tray_model/tests.rs index 675a100e07..8084925d89 100644 --- a/crates/openlogi-agent/src/tray_model/tests.rs +++ b/crates/openlogi-agent/src/tray_model/tests.rs @@ -573,9 +573,9 @@ mod controls { use openlogi_core::device_order::{DeviceStableId, PhysicalDeviceKey}; use openlogi_core::hid::{ BacklightChange, BacklightControls, BacklightMode, BacklightState, BacklightStatus, - DeviceRoute, DisableKeysMask, DisableKeysState, Dpi, LightCommand, SidetoneLevel, - SmartShiftAutoDisengage, SmartShiftMode, SmartShiftStatus, SmartShiftThreshold, - TunableTorque, WriteError, + DeviceRoute, DisableKeysMask, DisableKeysState, Dpi, LightCommand, PowerOffTimeout, + SidetoneLevel, SmartShiftAutoDisengage, SmartShiftMode, SmartShiftStatus, + SmartShiftThreshold, TunableTorque, WriteError, }; use openlogi_ipc::{AgentSnapshot, ObservedLight}; @@ -1114,6 +1114,61 @@ mod controls { ); } + #[test] + fn a_headset_offers_six_power_off_timeouts_while_it_answers() { + let capabilities = Capabilities { + power_off_timeout: true, + ..Capabilities::default() + }; + let headset = bolt_device(DeviceKind::Headset, capabilities, true); + let row = row(headset, &Config::default()); + assert_eq!( + row.reads(), + Reads { + power_off_timeout: true, + ..Reads::default() + }, + "opening the submenu reads the timeout" + ); + let mut memory = DeviceMemory::default(); + memory.reading.power_off_timeout = Read::Value(PowerOffTimeout::clamped(15)); + let entries = row.entries(&memory); + assert_eq!(headers(&entries), ["Automatic power-off"]); + let timeout = |minutes| Some(Change::PowerOffTimeout(PowerOffTimeout::clamped(minutes))); + assert_eq!( + choices(&entries), + [ + ("Never".to_owned(), false, timeout(0)), + ("5 min".to_owned(), false, timeout(5)), + ("15 min".to_owned(), true, timeout(15)), + ("30 min".to_owned(), false, timeout(30)), + ("60 min".to_owned(), false, timeout(60)), + ("90 min".to_owned(), false, timeout(90)), + ], + "a headset is not managed, so the timeout is all it offers" + ); + + // A change the headset echoed shows at the next opening. + memory.changed(Ok(Some(Change::PowerOffTimeout(PowerOffTimeout::NEVER)))); + let entries = row.entries(&memory); + assert_eq!(choice(&entries, "Never"), (true, timeout(0))); + + // Unread or unanswered, nothing can be changed: there is no saved + // timeout to fall back on. + memory.reading.power_off_timeout = Read::Failed; + let entries = row.entries(&memory); + assert_eq!(notes(&entries), ["Couldn't read the device."]); + assert!( + choices(&entries) + .iter() + .all(|(_, checked, change)| !checked && change.is_none()) + ); + + // A headset that lists the feature but refuses the read hides it. + memory.reading.power_off_timeout = Read::Unsupported; + assert!(row.entries(&memory).is_empty()); + } + /// A Litra Glow, plugged in. fn litra() -> StandaloneDevice { StandaloneDevice { From 66f6546c349ca7da908037a9e6c6a9a9d0207f72 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:23:29 +0100 Subject: [PATCH 18/28] fix(gui): hide a refused power-off row beside a working sidetone A headset can list 0x1F20 for its battery alone and refuse the timeout read, as the G535 may. Its Audio tab then showed a permanent "unsupported" line under the working sidetone slider, while the menu-bar menu hides the group. The row now disappears in that case and keeps the unsupported line only when the tab would otherwise be empty. --- crates/openlogi-desktop/src/features/audio.rs | 21 ++++- .../src/features/audio/tests.rs | 93 +++++++++++++++++++ crates/openlogi-desktop/src/state/tests.rs | 2 +- 3 files changed, 112 insertions(+), 4 deletions(-) create mode 100644 crates/openlogi-desktop/src/features/audio/tests.rs diff --git a/crates/openlogi-desktop/src/features/audio.rs b/crates/openlogi-desktop/src/features/audio.rs index 37ad7a397a..6d2b4184f8 100644 --- a/crates/openlogi-desktop/src/features/audio.rs +++ b/crates/openlogi-desktop/src/features/audio.rs @@ -224,17 +224,29 @@ struct PowerOffFacts { } impl PowerOffFacts { - /// The selected headset's facts, or `None` when nothing is selected or - /// the device has no `0x1F20`. + /// The selected headset's facts, or `None` when nothing is selected, the + /// device has no `0x1F20`, or it refused the timeout read while the + /// sidetone row still has something to show. + /// + /// A headset can list `0x1F20` for its battery alone. Its refusal hides + /// the row, as the menu-bar menu hides the group, so a working sidetone + /// slider is not followed by a permanent "unsupported" line. The line + /// stays when the tab would otherwise be empty. fn current(cx: &App) -> Option { let state = AppState::try_read(cx)?; if !state.current_power_off_timeout_supported() { return None; } + let load = state.current_power_off_timeout_load(); + let sidetone_shown = state.current_sidetone_supported() + && !matches!(state.current_sidetone_load(), SidetoneLoad::Unsupported(_)); + if matches!(load, PowerOffTimeoutLoad::Unsupported(_)) && sidetone_shown { + return None; + } let record = state.current_record()?; Some(Self { key: record.device_key(), - load: state.current_power_off_timeout_load(), + load, reachable: state.current_power_off_timeout_route().is_some(), }) } @@ -362,3 +374,6 @@ fn power_off_section( ) .into_any_element() } + +#[cfg(test)] +mod tests; diff --git a/crates/openlogi-desktop/src/features/audio/tests.rs b/crates/openlogi-desktop/src/features/audio/tests.rs new file mode 100644 index 0000000000..855e3bd45f --- /dev/null +++ b/crates/openlogi-desktop/src/features/audio/tests.rs @@ -0,0 +1,93 @@ +//! Which Audio rows a headset that refuses the power-off read shows. + +use openlogi_core::config::Config; +use openlogi_core::device::{Capabilities, DeviceInventory, DeviceKind}; +use openlogi_core::hid::{SidetoneLevel, WriteError}; + +use super::{PowerOffFacts, SidetoneFacts}; +use crate::services::assets::AssetResolver; +use crate::services::ipc::{Command, ReadPowerOffTimeout, ReadSidetone}; +use crate::state::tests::direct_inventory; +use crate::state::tests::pointer_speed::install; +use crate::state::{AppState, PowerOffTimeoutLoad, Sources}; + +/// A direct headset that lists `0x1F20`, with or without `0x8300`. +fn headset_inventory(sidetone: bool) -> DeviceInventory { + let mut inventory = direct_inventory([0x0a, 0xc4, 0x00, 0x01]); + inventory.paired[0].kind = DeviceKind::Headset; + inventory.paired[0].capabilities = Some(Capabilities { + sidetone, + power_off_timeout: true, + ..Capabilities::default() + }); + inventory +} + +/// Install the headset, answer its sidetone read with a level and refuse +/// its power-off read, as a headset that lists `0x1F20` only for its +/// battery does. +fn refusing_headset(sidetone: bool, cx: &mut gpui::TestAppContext) { + let resolver = AssetResolver::new(); + let (commands, mut receiver) = tokio::sync::mpsc::unbounded_channel(); + let state = AppState::new(Sources { + inventories: &[headset_inventory(sidetone)], + ..Sources::in_memory(Config::ephemeral(), &resolver, commands) + }); + install(state, cx); + let mut refused = false; + while let Ok(command) = receiver.try_recv() { + match command { + Command::ReadSidetone(ReadSidetone { reply, .. }) => { + let _ = reply.send(Ok(SidetoneLevel::try_new(40).expect("a level in range"))); + } + Command::ReadPowerOffTimeout(ReadPowerOffTimeout { reply, .. }) => { + let _ = reply.send(Err(WriteError::FeatureUnsupported { + feature_hex: 0x1f20, + })); + refused = true; + } + _ => {} + } + } + assert!( + refused, + "the state asked the headset for its power-off timeout" + ); + cx.run_until_parked(); +} + +/// A G535-style headset: sidetone works, and its `0x1F20` is the battery +/// only. The tab shows the sidetone slider and no power-off row, as the +/// menu-bar menu hides the group, instead of a permanent "unsupported" +/// line under a working control. +#[gpui::test] +fn a_refused_power_off_read_beside_sidetone_shows_no_row(cx: &mut gpui::TestAppContext) { + refusing_headset(true, cx); + + cx.read(|cx| { + assert!( + SidetoneFacts::current(cx).is_some(), + "the sidetone row stays" + ); + assert!( + PowerOffFacts::current(cx).is_none(), + "the refused power-off row is hidden" + ); + }); +} + +/// Without sidetone the power-off row is all the tab has, so it stays and +/// says the setting is unsupported rather than leaving the tab blank. +#[gpui::test] +fn a_refused_power_off_read_alone_says_unsupported(cx: &mut gpui::TestAppContext) { + refusing_headset(false, cx); + + cx.read(|cx| { + assert!(SidetoneFacts::current(cx).is_none()); + let facts = PowerOffFacts::current(cx).expect("the power-off row stays"); + assert!( + matches!(facts.load, PowerOffTimeoutLoad::Unsupported(_)), + "the row says unsupported" + ); + }); +} diff --git a/crates/openlogi-desktop/src/state/tests.rs b/crates/openlogi-desktop/src/state/tests.rs index ec04e4d8a2..fceac54eca 100644 --- a/crates/openlogi-desktop/src/state/tests.rs +++ b/crates/openlogi-desktop/src/state/tests.rs @@ -61,7 +61,7 @@ pub(crate) mod keypad_pages; mod light_adoption; mod lighting; mod os_layout; -mod pointer_speed; +pub(crate) mod pointer_speed; mod power_off_timeout; mod profile_scope; mod reload; From c8641151c890173a0fccedb4970d9fe0c034a197 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:24:14 +0100 Subject: [PATCH 19/28] fix(device): read only a refusal of the power-off timeout as unsupported Only InvalidFunctionId, InvalidArgument and Unsupported on function 1 now mean the headset lacks the timeout. HwError, Unknown, LogitechInternal and the other HID++ errors stay retryable read errors, so one transient fault no longer hides the setting until the headset reconnects. --- .../src/write/power_off_timeout.rs | 16 ++++--- .../src/write/power_off_timeout/tests.rs | 44 ++++++++++++++++--- 2 files changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/openlogi-device/src/write/power_off_timeout.rs b/crates/openlogi-device/src/write/power_off_timeout.rs index 732a006918..5f4c823b05 100644 --- a/crates/openlogi-device/src/write/power_off_timeout.rs +++ b/crates/openlogi-device/src/write/power_off_timeout.rs @@ -70,18 +70,20 @@ pub async fn set_power_off_timeout_on( } /// A device can list `0x1F20` for its battery without answering function -/// `1`, and it refuses the call with a HID++ error, so a refused read is the -/// feature being unsupported. `Busy` is a transient answer, not a refusal. +/// `1`, and it refuses the call, so a refusal is the feature being +/// unsupported: `InvalidFunctionId`, `InvalidArgument` or `Unsupported`. +/// Every other HID++ error, `Busy` or `HwError` among them, may pass and +/// stays a retryable read error. async fn read(feature: &AdcMeasurementFeature) -> Result { let raw = feature .get_power_off_timeout() .await .map_err(|error| match error { - Hidpp20Error::Feature(kind) if kind != ErrorType::Busy => { - WriteError::FeatureUnsupported { - feature_hex: AdcMeasurementFeature::ID, - } - } + Hidpp20Error::Feature( + ErrorType::InvalidFunctionId | ErrorType::InvalidArgument | ErrorType::Unsupported, + ) => WriteError::FeatureUnsupported { + feature_hex: AdcMeasurementFeature::ID, + }, error => classify(error, HidppOperation::ReadPowerOffTimeout), })?; parse(raw, HidppOperation::ReadPowerOffTimeout) diff --git a/crates/openlogi-device/src/write/power_off_timeout/tests.rs b/crates/openlogi-device/src/write/power_off_timeout/tests.rs index 4ac80b7ec7..2357899b5a 100644 --- a/crates/openlogi-device/src/write/power_off_timeout/tests.rs +++ b/crates/openlogi-device/src/write/power_off_timeout/tests.rs @@ -6,14 +6,19 @@ use std::sync::{Arc, Mutex}; use super::*; use crate::channel::route::DeviceRoute; use crate::channel::scripted::{ScriptedRawHidChannel, feature_error, scripted_channel}; +use crate::write::HidppFeatureErrorKind; /// The `0x1F20` feature index on a G933. const ADC_INDEX: u8 = 0x08; /// HID++ 2.0 `InvalidFunctionId`, what a device without functions `1`/`2` /// answers. const INVALID_FUNCTION_ID: u8 = 0x07; +/// HID++ 2.0 `HwError`. +const HW_ERROR: u8 = 0x04; /// HID++ 2.0 `Busy`. const BUSY: u8 = 0x08; +/// HID++ 2.0 `Unsupported`. +const UNSUPPORTED: u8 = 0x09; /// A G933 as measured: it echoes each write and reads the new timeout back. struct Headset { @@ -149,23 +154,50 @@ async fn a_refused_read_means_the_device_does_not_support_the_timeout() { } #[tokio::test] -async fn a_busy_read_stays_a_retryable_error() { +async fn an_unsupported_answer_means_the_device_does_not_support_the_timeout() { let headset = Arc::new(Mutex::new(Headset { - read_error: Some(BUSY), + read_error: Some(UNSUPPORTED), ..Headset::g933(0) })); let shared = headset_channel(&headset).await; assert_matches!( get_power_off_timeout_on(&shared).await, - Err(WriteError::HidppFeature { - operation: HidppOperation::ReadPowerOffTimeout, - feature_hex: 0x1f20, - .. + Err(WriteError::FeatureUnsupported { + feature_hex: 0x1f20 }) ); } +/// A busy or faulting headset may answer next time. Reading it as +/// unsupported would hide the setting until it reconnects. +#[tokio::test] +async fn a_busy_or_faulting_read_stays_a_retryable_error() { + for (code, kind) in [ + (BUSY, HidppFeatureErrorKind::Busy), + (HW_ERROR, HidppFeatureErrorKind::HwError), + ] { + let headset = Arc::new(Mutex::new(Headset { + read_error: Some(code), + ..Headset::g933(0) + })); + let shared = headset_channel(&headset).await; + + let result = get_power_off_timeout_on(&shared).await; + assert!( + matches!( + result, + Err(WriteError::HidppFeature { + operation: HidppOperation::ReadPowerOffTimeout, + feature_hex: 0x1f20, + kind: found, + }) if found == kind + ), + "error {code:#04x} gave {result:?}" + ); + } +} + #[tokio::test] async fn a_timeout_above_the_range_is_an_unsupported_response() { let headset = Arc::new(Mutex::new(Headset::g933(120))); From bdf937436e903cc1f6436d34c966d1eeb495e975 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:25:19 +0100 Subject: [PATCH 20/28] test(gui): cover the power-off re-read on reconnect A headset that comes back online is read again. The unsupported test now advances the clock past any retry before it checks that a refusal is not read again. --- .../src/state/tests/power_off_timeout.rs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs b/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs index 2355c8617c..5153dd66ee 100644 --- a/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs +++ b/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs @@ -9,6 +9,7 @@ use super::*; use crate::services::ipc::{Command, ReadPowerOffTimeout, SetPowerOffTimeout}; use crate::state::PowerOffTimeoutLoad; use openlogi_core::hid::{DeviceRoute, PowerOffTimeout}; +use std::time::Duration; fn minutes(raw: u8) -> PowerOffTimeout { PowerOffTimeout::try_new(raw).expect("a timeout in range") @@ -186,6 +187,8 @@ fn a_headset_that_refuses_the_read_is_unsupported(cx: &mut gpui::TestAppContext) feature_hex: 0x1f20, }), ); + // Let any retry the read policy would schedule come due. + cx.executor().advance_clock(Duration::from_secs(60)); cx.run_until_parked(); let load = current_load(cx); @@ -222,3 +225,31 @@ fn a_moved_settings_revision_reads_the_headset_again(cx: &mut gpui::TestAppConte cx.run_until_parked(); assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(60)))); } + +/// The headset switched itself off after its own timeout and came back. +/// The reading from before may be stale, so the slider reads it again. +#[gpui::test] +fn a_reconnect_reads_the_headset_again(cx: &mut gpui::TestAppContext) { + let (state, mut receiver) = headset_state(true); + install(state, cx); + let route = answer_read(&mut receiver, &Ok(minutes(15))); + cx.run_until_parked(); + + let mut offline = headset_inventory(true); + offline.paired[0].online = false; + for inventory in [offline, headset_inventory(true)] { + let _ = cx.update(|cx| { + AppState::update(cx, |state, _| { + state.refresh_inventories(&[inventory], &[], &AssetResolver::new(), &[]) + }) + }); + cx.run_until_parked(); + } + assert_eq!( + answer_read(&mut receiver, &Ok(minutes(30))), + route, + "the reconnect reads the headset again" + ); + cx.run_until_parked(); + assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(30)))); +} From 91f398db09f311872880aeac0989e6f4a5e8251d Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:25:19 +0100 Subject: [PATCH 21/28] docs(gui): name every caller of the power-off re-read --- crates/openlogi-desktop/src/services/device_reads.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/openlogi-desktop/src/services/device_reads.rs b/crates/openlogi-desktop/src/services/device_reads.rs index 090756b660..bd60409908 100644 --- a/crates/openlogi-desktop/src/services/device_reads.rs +++ b/crates/openlogi-desktop/src/services/device_reads.rs @@ -932,8 +932,9 @@ impl DeviceReads { } /// Re-read `key`'s automatic power-off timeout from the headset, keeping - /// the last value on screen while it answers. The fallback after a write - /// the headset refused. + /// the last value on screen while it answers: after a write the headset + /// refused, or a change the agent announced, when the shown value is no + /// longer known to be its own. pub(crate) fn refresh_power_off_timeout(&mut self, key: &DeviceKey) { if let Some(read) = self.power_off_timeout.get_mut(key) { read.query.revalidate(); From de7c373463d216d4248cab1b902c2e1ce7814624 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:25:32 +0100 Subject: [PATCH 22/28] test(cli): name the power-off capture test after its gate --- .../openlogi-cli/src/cmd/fixture/record_profile/tests.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs b/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs index 6f6b947281..aadcdf5e97 100644 --- a/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs +++ b/crates/openlogi-cli/src/cmd/fixture/record_profile/tests.rs @@ -1203,8 +1203,9 @@ async fn capture_reads_the_press_force_of_a_force_sensing_mouse() { assert_eq!(*captured, force); } -/// Advertise `0x1F20` on the synthetic mouse and give it `timeout` as its -/// power-off setting. +/// Advertise `0x1F20` on the synthetic mouse, which stands in for a headset: +/// the capture keys on the capability, not the kind. Give it `timeout` as +/// its power-off setting. fn power_off_agent(timeout: ProfileSetting) -> TestAgent { fixture_agent_with(move |profile| { let mouse = profile.inventories[0] @@ -1260,7 +1261,7 @@ async fn captured_power_off_timeout( } #[tokio::test] -async fn capture_reads_the_power_off_timeout_of_a_headset() { +async fn capture_reads_the_power_off_timeout_when_advertised() { let timeout = PowerOffTimeout::try_new(15).expect("a timeout in range"); let (setting, families) = captured_power_off_timeout(power_off_agent(ProfileSetting::Supported(timeout))).await; From 8157f4e3153eca281acf5d35c0dd9477e5a63926 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:25:54 +0100 Subject: [PATCH 23/28] feat(i18n): translate the headset automatic power-off strings into German --- crates/openlogi-ui/locales/de.toml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/openlogi-ui/locales/de.toml b/crates/openlogi-ui/locales/de.toml index df9e9ec06d..8a87d6a6be 100644 --- a/crates/openlogi-ui/locales/de.toml +++ b/crates/openlogi-ui/locales/de.toml @@ -1014,14 +1014,14 @@ reading_sidetone = "Mithörton wird gelesen…" couldnt_read_sidetone_click_to_retry = "Mithörton konnte nicht gelesen werden. Zum Wiederholen klicken." device_offline_sidetone_is_unavailable = "Der Mithörton ist nicht verfügbar, solange das Headset offline ist." sidetone_unsupported = "Dieses Headset meldet keinen einstellbaren Mithörton." -power_off = "Automatic power-off" -power_off_description = "Switches the headset off after it has been idle this long. The headset keeps the setting when it turns off." -power_off_never = "Never" -power_off_minutes = "%{minutes} min" -reading_power_off = "Reading automatic power-off…" -couldnt_read_power_off_click_to_retry = "Couldn't read the automatic power-off. Click to retry." -device_offline_power_off_is_unavailable = "Automatic power-off is unavailable while the headset is offline." -power_off_unsupported = "This headset does not report an adjustable automatic power-off." +power_off = "Automatische Abschaltung" +power_off_description = "Schaltet das Headset aus, wenn es so lange nicht benutzt wurde. Das Headset behält die Einstellung, wenn es sich ausschaltet." +power_off_never = "Nie" +power_off_minutes = "%{minutes} Min." +reading_power_off = "Automatische Abschaltung wird gelesen…" +couldnt_read_power_off_click_to_retry = "Automatische Abschaltung konnte nicht gelesen werden. Zum Wiederholen klicken." +device_offline_power_off_is_unavailable = "Die automatische Abschaltung ist nicht verfügbar, solange das Headset offline ist." +power_off_unsupported = "Dieses Headset meldet keine einstellbare automatische Abschaltung." [tray] accessibility_needed = "Bedienungshilfen-Berechtigung erforderlich" From 51d14223f86c473108c8d8f6e726b159f93cb8f7 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:36:04 +0100 Subject: [PATCH 24/28] feat(tray): show a power-off timeout between the steps The settings app sets any minute from 0 to 90, while the tray offers six steps. A timeout between them left the submenu without a checkmark. It now joins the steps in its place, checked and greyed out, so the tray always shows what the headset holds. --- .../openlogi-agent/src/tray_model/controls.rs | 14 ++++++++++++-- crates/openlogi-agent/src/tray_model/tests.rs | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/openlogi-agent/src/tray_model/controls.rs b/crates/openlogi-agent/src/tray_model/controls.rs index 99df966e57..e0a8cfa92a 100644 --- a/crates/openlogi-agent/src/tray_model/controls.rs +++ b/crates/openlogi-agent/src/tray_model/controls.rs @@ -768,15 +768,25 @@ impl DeviceRow { return Vec::new(); } let read = reading.power_off_timeout.value(); + // The settings app sets any minute; one between the steps joins them + // in its place, so the checkmark always shows what the headset holds. + let between = read + .map(PowerOffTimeout::minutes) + .filter(|minutes| !POWER_OFF_TIMEOUTS.contains(minutes)); + let mut steps = POWER_OFF_TIMEOUTS.to_vec(); + if let Some(minutes) = between { + steps.insert(steps.partition_point(|&step| step < minutes), minutes); + } let mut group = vec![Entry::Header(t!("audio.power_off").into_owned())]; - group.extend(POWER_OFF_TIMEOUTS.map(|minutes| Entry::Choice { + group.extend(steps.into_iter().map(|minutes| Entry::Choice { title: if minutes == 0 { t!("audio.power_off_never").into_owned() } else { t!("audio.power_off_minutes", minutes => minutes).into_owned() }, checked: read.is_some_and(|timeout| timeout.minutes() == minutes), - change: read.and_then(|_| { + // Picking the timeout between the steps again would change nothing. + change: read.filter(|_| between != Some(minutes)).and_then(|_| { self.live(Change::PowerOffTimeout(PowerOffTimeout::clamped(minutes))) }), })); diff --git a/crates/openlogi-agent/src/tray_model/tests.rs b/crates/openlogi-agent/src/tray_model/tests.rs index 8084925d89..b8c614155f 100644 --- a/crates/openlogi-agent/src/tray_model/tests.rs +++ b/crates/openlogi-agent/src/tray_model/tests.rs @@ -1153,6 +1153,25 @@ mod controls { let entries = row.entries(&memory); assert_eq!(choice(&entries, "Never"), (true, timeout(0))); + // The settings app sets any minute. A timeout between the steps still + // shows, checked in its place, so the menu never hides what the + // headset holds; picking it again would change nothing, so it is + // greyed out. + memory.reading.power_off_timeout = Read::Value(PowerOffTimeout::clamped(20)); + let entries = row.entries(&memory); + assert_eq!( + choices(&entries), + [ + ("Never".to_owned(), false, timeout(0)), + ("5 min".to_owned(), false, timeout(5)), + ("15 min".to_owned(), false, timeout(15)), + ("20 min".to_owned(), true, None), + ("30 min".to_owned(), false, timeout(30)), + ("60 min".to_owned(), false, timeout(60)), + ("90 min".to_owned(), false, timeout(90)), + ] + ); + // Unread or unanswered, nothing can be changed: there is no saved // timeout to fall back on. memory.reading.power_off_timeout = Read::Failed; From 3418b25cd8115aac177ff8594b675cbd5618336b Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:40:42 +0100 Subject: [PATCH 25/28] fix(device): log a confirmed power-off timeout change at info A confirmed write changes when the headset switches itself off, so it is a device change and belongs at info, not debug. The new test installs a subscriber at info and checks that the write is logged. --- Cargo.lock | 1 + crates/openlogi-device/Cargo.toml | 1 + .../src/write/power_off_timeout.rs | 5 +- .../src/write/power_off_timeout/tests.rs | 50 +++++++++++++++++++ 4 files changed, 55 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2471721edb..f8356688ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6179,6 +6179,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tracing", + "tracing-subscriber", ] [[package]] diff --git a/crates/openlogi-device/Cargo.toml b/crates/openlogi-device/Cargo.toml index ff5d826a6b..b9790a332b 100644 --- a/crates/openlogi-device/Cargo.toml +++ b/crates/openlogi-device/Cargo.toml @@ -34,6 +34,7 @@ tracing = { workspace = true } serde_json.workspace = true tempfile = "3" tokio = { workspace = true, features = ["test-util"] } +tracing-subscriber = { workspace = true } [lints] workspace = true diff --git a/crates/openlogi-device/src/write/power_off_timeout.rs b/crates/openlogi-device/src/write/power_off_timeout.rs index 5f4c823b05..9746ffd98e 100644 --- a/crates/openlogi-device/src/write/power_off_timeout.rs +++ b/crates/openlogi-device/src/write/power_off_timeout.rs @@ -14,7 +14,7 @@ use hidpp::{ protocol::v20::{ErrorType, Hidpp20Error}, }; use openlogi_core::hid::PowerOffTimeout; -use tracing::debug; +use tracing::info; use super::{HidppOperation, WriteError, classify_hidpp_error, open_feature, with_route}; use crate::SharedChannel; @@ -100,7 +100,8 @@ async fn write( .await .map_err(|error| classify(error, HidppOperation::WritePowerOffTimeout))?; let applied = parse(raw, HidppOperation::WritePowerOffTimeout)?; - debug!(index, %timeout, %applied, "power-off timeout written"); + // The headset now powers off on another timeout: a change, not a refresh. + info!(index, %timeout, %applied, "power-off timeout written"); Ok(applied) } diff --git a/crates/openlogi-device/src/write/power_off_timeout/tests.rs b/crates/openlogi-device/src/write/power_off_timeout/tests.rs index 2357899b5a..e81677282e 100644 --- a/crates/openlogi-device/src/write/power_off_timeout/tests.rs +++ b/crates/openlogi-device/src/write/power_off_timeout/tests.rs @@ -211,3 +211,53 @@ async fn a_timeout_above_the_range_is_an_unsupported_response() { }) ); } + +thread_local! { + /// What the test subscriber logged on this thread. + static LOGGED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Writes a log line into [`LOGGED`] of the thread that emitted it. +struct ThreadLog; + +impl std::io::Write for ThreadLog { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + LOGGED.with_borrow_mut(|logged| logged.extend_from_slice(bytes)); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// A confirmed write changes when the headset switches itself off, so it is +/// logged at `info`, the level a user's log keeps; a refresh stays below it. +#[tokio::test] +async fn a_confirmed_write_is_logged_at_info() { + // Global, not `set_default`: with a single dispatcher `tracing` caches a + // callsite's interest from whichever thread reaches it first, so a + // parallel test writing the timeout would switch this line off here. + static INSTALL: std::sync::Once = std::sync::Once::new(); + INSTALL.call_once(|| { + let subscriber = tracing_subscriber::fmt() + .with_max_level(tracing::Level::INFO) + .with_writer(|| ThreadLog) + .finish(); + tracing::subscriber::set_global_default(subscriber) + .expect("no other test in this binary installs a global subscriber"); + }); + LOGGED.with_borrow_mut(Vec::clear); + let headset = Arc::new(Mutex::new(Headset::g933(15))); + let shared = headset_channel(&headset).await; + + set_power_off_timeout_on(&shared, minutes(30)) + .await + .unwrap(); + + let logged = String::from_utf8(LOGGED.take()).unwrap(); + assert!( + logged.contains("INFO") && logged.contains("power-off timeout written"), + "expected the confirmed write at info, got: {logged:?}" + ); +} From 1256e44f36e0008f8d7f97f722d7e14d814dfe38 Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:44:20 +0100 Subject: [PATCH 26/28] fix(gui): ignore the answer to a superseded power-off timeout write The agent answers a power-off write that a newer one superseded before its turn with a plain read, which still holds the old timeout. Two releases before the first answer moved the slider back to that old timeout until the second answer came. Each write now carries a number, as press-force writes do, and only the newest write's answer counts. --- crates/openlogi-desktop/src/runtime.rs | 4 +- crates/openlogi-desktop/src/services/ipc.rs | 5 +- .../src/services/ipc/request.rs | 4 + crates/openlogi-desktop/src/state/pointer.rs | 7 ++ .../src/state/power_off_timeout.rs | 30 ++++-- .../src/state/tests/power_off_timeout.rs | 94 +++++++++++++++++-- 6 files changed, 126 insertions(+), 18 deletions(-) diff --git a/crates/openlogi-desktop/src/runtime.rs b/crates/openlogi-desktop/src/runtime.rs index 107c3852c6..001b04a149 100644 --- a/crates/openlogi-desktop/src/runtime.rs +++ b/crates/openlogi-desktop/src/runtime.rs @@ -375,10 +375,10 @@ impl Runtime { AppState::apply(cx, |state| state.apply_sidetone_written(&key, result)); }); } - ipc::GuiUpdate::PowerOffTimeoutWritten { key, result } => { + ipc::GuiUpdate::PowerOffTimeoutWritten { key, write, result } => { cx.update(|cx| { AppState::apply(cx, |state| { - state.apply_power_off_timeout_written(&key, result) + state.apply_power_off_timeout_written(&key, write, result) }); }); } diff --git a/crates/openlogi-desktop/src/services/ipc.rs b/crates/openlogi-desktop/src/services/ipc.rs index a5f12d00d4..a8acfd9268 100644 --- a/crates/openlogi-desktop/src/services/ipc.rs +++ b/crates/openlogi-desktop/src/services/ipc.rs @@ -203,7 +203,10 @@ pub enum GuiUpdate { PowerOffTimeoutWritten { /// The headset that was written. key: DeviceKey, - /// The confirmed timeout, or why the write did not land. + /// Which write this answers: [`SetPowerOffTimeout::write`]. + write: u64, + /// The confirmed timeout, or why the write did not land. A write the + /// agent superseded before its turn answers with a plain read. result: Result, }, /// What a force-sensing button reports after a press-force write the GUI diff --git a/crates/openlogi-desktop/src/services/ipc/request.rs b/crates/openlogi-desktop/src/services/ipc/request.rs index f41bb14f42..8ab1c3ea3c 100644 --- a/crates/openlogi-desktop/src/services/ipc/request.rs +++ b/crates/openlogi-desktop/src/services/ipc/request.rs @@ -266,6 +266,9 @@ pub struct SetPowerOffTimeout { pub route: DeviceRoute, pub timeout: PowerOffTimeout, pub key: DeviceKey, + /// The number the state gave this write, returned with the answer so it + /// is matched to the write it answers. + pub write: u64, } impl Request for SetPowerOffTimeout { @@ -280,6 +283,7 @@ impl Request for SetPowerOffTimeout { fn deliver(self, outcome: Result, updates: &UpdateSender) { let _ = updates.send(GuiUpdate::PowerOffTimeoutWritten { key: self.key, + write: self.write, result: or_unavailable(outcome), }); } diff --git a/crates/openlogi-desktop/src/state/pointer.rs b/crates/openlogi-desktop/src/state/pointer.rs index 500a02f311..46ab5ad154 100644 --- a/crates/openlogi-desktop/src/state/pointer.rs +++ b/crates/openlogi-desktop/src/state/pointer.rs @@ -29,6 +29,11 @@ pub(super) struct PointerState { /// save it. pub(super) pending_force_sensing_writes: HashMap, pub(super) next_force_sensing_write: u64, + /// The newest automatic power-off write sent to each headset whose answer + /// has not arrived yet. Only that write's answer may change the shown + /// timeout. + pub(super) pending_power_off_timeout_writes: HashMap, + pub(super) next_power_off_timeout_write: u64, } impl Default for PointerState { @@ -43,6 +48,8 @@ impl Default for PointerState { refused_force_sensing: HashSet::new(), pending_force_sensing_writes: HashMap::new(), next_force_sensing_write: 0, + pending_power_off_timeout_writes: HashMap::new(), + next_power_off_timeout_write: 0, } } } diff --git a/crates/openlogi-desktop/src/state/power_off_timeout.rs b/crates/openlogi-desktop/src/state/power_off_timeout.rs index 26bcdd9005..b492e5e73d 100644 --- a/crates/openlogi-desktop/src/state/power_off_timeout.rs +++ b/crates/openlogi-desktop/src/state/power_off_timeout.rs @@ -5,9 +5,11 @@ //! nothing is persisted here. The reading is the swr-backed device query the //! device-read service owns, and the slider shows it. //! -//! A release of the slider writes the headset. Its answer is the timeout the -//! headset confirms. A refusal reads the headset again, so the slider returns -//! to the headset's own timeout, as for sidetone. +//! A release of the slider writes the headset. Only the answer to the newest +//! write counts: the agent answers a write that a newer one superseded with a +//! plain read, which would move the slider back off the newer release. Its +//! answer is the timeout the headset confirms. A refusal reads the headset +//! again, so the slider returns to the headset's own timeout. use openlogi_core::hid::{DeviceRoute, PowerOffTimeout, WriteError}; use tracing::{debug, warn}; @@ -70,23 +72,37 @@ impl AppState { self.pointer .reads .set_power_off_timeout_ready(&key, timeout); + let write = self.pointer.next_power_off_timeout_write; + self.pointer.next_power_off_timeout_write = write.saturating_add(1); + self.pointer + .pending_power_off_timeout_writes + .insert(key.clone(), write); self.send_ipc(crate::services::ipc::SetPowerOffTimeout { route, timeout, key, + write, }); events } - /// The headset's answer to a [`Self::commit_power_off_timeout`] write: - /// show the confirmed timeout, or — when the headset refused or could not - /// be reached — read it again so the optimistic value does not stand in - /// for its own. + /// The headset's answer to the [`Self::commit_power_off_timeout`] write + /// numbered `write`: show the confirmed timeout, or — when the headset + /// refused or could not be reached — read it again so the optimistic + /// value does not stand in for its own. Only the newest write's answer + /// counts; an older one changes nothing, so the slider stays on the newer + /// release. pub fn apply_power_off_timeout_written( &mut self, key: &DeviceKey, + write: u64, result: Result, ) -> StateEvents { + if self.pointer.pending_power_off_timeout_writes.get(key) != Some(&write) { + debug!(key = %key, write, "a newer power-off timeout write is pending — ignoring this answer"); + return StateEvents::none(); + } + self.pointer.pending_power_off_timeout_writes.remove(key); match result { Ok(timeout) => self.pointer.reads.set_power_off_timeout_ready(key, timeout), Err(error) => { diff --git a/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs b/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs index 5153dd66ee..ce2b4829f7 100644 --- a/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs +++ b/crates/openlogi-desktop/src/state/tests/power_off_timeout.rs @@ -55,6 +55,31 @@ fn answer_read( answered.expect("the state asked the headset for its power-off timeout") } +fn with_state(cx: &mut gpui::TestAppContext, f: impl FnOnce(&mut AppState) -> R) -> R { + cx.update(|cx| AppState::update(cx, |state, _| f(state))) +} + +/// Release the slider at `timeout` and return the number of the write it +/// sent. +fn release( + cx: &mut gpui::TestAppContext, + receiver: &mut tokio::sync::mpsc::UnboundedReceiver, + timeout: PowerOffTimeout, +) -> u64 { + let _ = with_state(cx, |state| state.commit_power_off_timeout(timeout)); + let writes: Vec = drain(receiver) + .into_iter() + .filter_map(|command| match command { + Command::SetPowerOffTimeout(SetPowerOffTimeout { write, .. }) => Some(write), + _ => None, + }) + .collect(); + let [write] = writes[..] else { + panic!("expected one power-off write, got {writes:?}"); + }; + write +} + fn current_load(cx: &gpui::TestAppContext) -> PowerOffTimeoutLoad { cx.read(|cx| { AppState::try_read(cx) @@ -80,6 +105,7 @@ fn a_release_writes_the_headset_and_saves_nothing() { route: written_route, timeout: written, key: written_key, + .. }), ] = commands.as_slice() else { @@ -150,18 +176,16 @@ fn the_reading_lands_and_a_refusal_reads_the_headset_again(cx: &mut gpui::TestAp cx.run_until_parked(); assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(15)))); - let events = cx.update(|cx| { - AppState::update(cx, |state, _| { - state.apply_power_off_timeout_written(&key, Ok(minutes(30))) - }) + let write = release(cx, &mut receiver, minutes(30)); + let events = with_state(cx, |state| { + state.apply_power_off_timeout_written(&key, write, Ok(minutes(30))) }); assert_eq!(events, [StateEvent::PowerOffTimeoutChanged(key.clone())]); assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(30)))); - let events = cx.update(|cx| { - AppState::update(cx, |state, _| { - state.apply_power_off_timeout_written(&key, Err(WriteError::AgentUnavailable)) - }) + let write = release(cx, &mut receiver, minutes(45)); + let events = with_state(cx, |state| { + state.apply_power_off_timeout_written(&key, write, Err(WriteError::AgentUnavailable)) }); assert_eq!(events, [StateEvent::PowerOffTimeoutChanged(key)]); cx.run_until_parked(); @@ -174,6 +198,60 @@ fn the_reading_lands_and_a_refusal_reads_the_headset_again(cx: &mut gpui::TestAp assert_eq!(current_load(cx), Load::Ready(Arc::new(minutes(30)))); } +/// The agent answers a write that a newer one superseded before its turn +/// with a plain read of the headset, which still holds its old timeout. That +/// answer must not move the slider off the newer release, and an older +/// failure must not send the read back to the headset; only the newest +/// write's answer counts. +#[gpui::test] +fn an_answer_to_a_superseded_write_does_not_move_the_slider(cx: &mut gpui::TestAppContext) { + let (state, mut receiver) = headset_state(true); + let key = state.current_record().expect("headset").device_key(); + install(state, cx); + answer_read(&mut receiver, &Ok(minutes(15))); + cx.run_until_parked(); + + let older = release(cx, &mut receiver, minutes(30)); + let newer = release(cx, &mut receiver, minutes(60)); + let pending = Load::Ready(Arc::new(minutes(60))); + + // The superseded write read the headset, which still ran 15 minutes. + let events = with_state(cx, |state| { + state.apply_power_off_timeout_written(&key, older, Ok(minutes(15))) + }); + assert!(events.is_empty(), "an older answer announces nothing"); + assert_eq!( + current_load(cx), + pending, + "the slider stays on the newer release" + ); + + // Even an older answer that happens to confirm its own timeout. + let _ = with_state(cx, |state| { + state.apply_power_off_timeout_written(&key, older, Ok(minutes(30))) + }); + assert_eq!(current_load(cx), pending); + + // Nor does an older failure read the headset again. + let _ = with_state(cx, |state| { + state.apply_power_off_timeout_written(&key, older, Err(WriteError::AgentUnavailable)) + }); + cx.run_until_parked(); + assert!( + drain(&mut receiver) + .iter() + .all(|command| !matches!(command, Command::ReadPowerOffTimeout(_))), + "an older failure sends no read" + ); + assert_eq!(current_load(cx), pending); + + let events = with_state(cx, |state| { + state.apply_power_off_timeout_written(&key, newer, Ok(minutes(60))) + }); + assert_eq!(events, [StateEvent::PowerOffTimeoutChanged(key)]); + assert_eq!(current_load(cx), pending, "the newest answer lands"); +} + /// Some headsets list `0x1F20` for the battery but refuse the timeout /// functions. That answer is final: the row says so instead of offering a /// retry that can never succeed. From 2577264e3ef071f7537cd0f133ecb3a4fb230d4c Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:45:59 +0100 Subject: [PATCH 27/28] fix(cli): keep diag power-off off the headset while an agent runs The agent writes the power-off timeout too, and diag power-off opened the headset without checking for it. It now takes the agent's instance lock for its whole run and refuses while an agent answers, as diag hidpp does. The check moves from diag hidpp into the diag module, so both commands share one copy. --- crates/openlogi-cli/src/cmd/diag.rs | 23 +++++- crates/openlogi-cli/src/cmd/diag/hidpp.rs | 19 +---- crates/openlogi-cli/src/cmd/diag/power_off.rs | 72 ++++++++++++++++++- 3 files changed, 96 insertions(+), 18 deletions(-) diff --git a/crates/openlogi-cli/src/cmd/diag.rs b/crates/openlogi-cli/src/cmd/diag.rs index cfcfef056f..5dbd731f18 100644 --- a/crates/openlogi-cli/src/cmd/diag.rs +++ b/crates/openlogi-cli/src/cmd/diag.rs @@ -8,10 +8,12 @@ //! the agent owns the device's HID channel and the device leaves this //! computer's radio link after the write. -use anyhow::{Result, anyhow}; +use anyhow::{Context, Result, anyhow, bail}; use clap::Subcommand; use openlogi_core::device::DeviceInventory; +use openlogi_core::single_instance::{self, InstanceGuard, Role}; use openlogi_hid::{DeviceRoute, dump_features}; +use openlogi_ipc::client::ConnectError; pub mod battery; pub mod controls; @@ -222,6 +224,25 @@ fn no_match_err(devices: &[Candidate], query: Option<&str>) -> anyhow::Error { /// Pick the device a diag should run against. /// +/// Keep the agent off the hardware for as long as the returned guard lives. +/// +/// The agent holds a device's channel and may write to it at any time. It +/// takes this lock before any HID I/O, so a caller that holds the guard to +/// the end of its run keeps one from starting; the endpoint check catches an +/// agent that is already up. +pub(crate) async fn exclude_agent() -> Result { + let agent_lock = single_instance::acquire(Role::Agent).context( + "could not take the agent's instance lock; quit the OpenLogi agent, then run this again", + )?; + if !matches!( + crate::agent::connect().await, + Err(ConnectError::Endpoint(_)) + ) { + bail!("the OpenLogi agent is running; quit it, then run this again"); + } + Ok(agent_lock) +} + /// Selection order: /// 1. If `query` is set, the one online device whose name contains it /// (case-insensitive), as [`select_named_device`] decides — ambiguous diff --git a/crates/openlogi-cli/src/cmd/diag/hidpp.rs b/crates/openlogi-cli/src/cmd/diag/hidpp.rs index d5ba258d23..827ae9973d 100644 --- a/crates/openlogi-cli/src/cmd/diag/hidpp.rs +++ b/crates/openlogi-cli/src/cmd/diag/hidpp.rs @@ -9,11 +9,9 @@ use std::io::Write as _; use anyhow::{Context, Result, bail}; use clap::Args; -use openlogi_core::single_instance::{self, Role}; use openlogi_hid::{RAW_FEATURE_PARAMS, RawFeatureCall, RawFeatureReply}; -use openlogi_ipc::client::ConnectError; -use crate::cmd::diag::select_device; +use crate::cmd::diag::{exclude_agent, select_device}; #[derive(Debug, Args)] pub struct HidppArgs { @@ -34,19 +32,8 @@ pub struct HidppArgs { } pub async fn run(args: HidppArgs) -> Result<()> { - // The agent holds the device's channel and may write to it at any time. - // It takes this lock before any HID I/O, so holding it to the end keeps - // one from starting while a prompt waits; the endpoint check catches an - // agent that is already up. - let _agent_lock = single_instance::acquire(Role::Agent).context( - "could not take the agent's instance lock; quit the OpenLogi agent, then run this again", - )?; - if !matches!( - crate::agent::connect().await, - Err(ConnectError::Endpoint(_)) - ) { - bail!("the OpenLogi agent is running; quit it, then run this again"); - } + // Held to the end, so no agent starts while a prompt waits. + let _agent_lock = exclude_agent().await?; let (route, name) = select_device(args.device.as_deref(), &[args.feature]).await?; println!("device: {name} ({route})"); diff --git a/crates/openlogi-cli/src/cmd/diag/power_off.rs b/crates/openlogi-cli/src/cmd/diag/power_off.rs index 8c602706dc..cc2e75ba56 100644 --- a/crates/openlogi-cli/src/cmd/diag/power_off.rs +++ b/crates/openlogi-cli/src/cmd/diag/power_off.rs @@ -7,7 +7,7 @@ use anyhow::{Context, Result, bail}; use clap::Args; use openlogi_hid::PowerOffTimeout; -use crate::cmd::diag::select_device; +use crate::cmd::diag::{exclude_agent, select_device}; #[derive(Debug, Args)] pub struct PowerOffArgs { @@ -23,6 +23,9 @@ pub struct PowerOffArgs { } pub async fn run(args: PowerOffArgs) -> Result<()> { + // The agent writes the timeout too; held to the end, so none starts + // between this read and the write. + let _agent_lock = exclude_agent().await?; let (route, name) = select_device(args.device.as_deref(), &[0x1f20]).await?; println!("device: {name} ({route})"); @@ -87,6 +90,73 @@ mod tests { assert!(parse_minutes("-1").is_err(), "minutes are not negative"); } + // Unix socket paths honor XDG_CONFIG_HOME; Windows uses a fixed pipe name + // and cannot isolate this endpoint test from a real agent that way. + #[cfg(unix)] + #[test] + fn a_running_agent_keeps_the_diagnostic_off_the_headset() { + use openlogi_core::single_instance::{self, InstanceError, Role}; + + use super::{PowerOffArgs, run}; + + const TEST: &str = + "cmd::diag::power_off::tests::a_running_agent_keeps_the_diagnostic_off_the_headset"; + const MODE: &str = "OPENLOGI_DIAG_POWER_OFF_OWNERSHIP_TEST"; + if std::env::var(MODE).as_deref() != Ok("exercise") { + // Run in a child with its own config home, so neither the lock + // nor the endpoint is a real agent's. + let home = tempfile::tempdir().unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", TEST, "--nocapture"]) + .env(MODE, "exercise") + .env("XDG_CONFIG_HOME", home.path()) + .env_remove("XDG_RUNTIME_DIR") + .env( + openlogi_core::env::PROFILE, + openlogi_core::paths::Profile::Production.env_value(), + ) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + return; + } + // Only reads: should the guard be missing, nothing is written. + let args = || PowerOffArgs { + minutes: None, + device: None, + }; + openlogi_core::worker::runtime().unwrap().block_on(async { + // An agent starting up holds its lock before its socket binds. + { + let _agent = single_instance::acquire(Role::Agent).unwrap(); + let error = run(args()) + .await + .expect_err("an agent holding its lock must exclude the diagnostic"); + assert!( + matches!( + error.downcast_ref::(), + Some(InstanceError::AlreadyRunning { .. }) + ), + "refused for another reason: {error:#}" + ); + } + // An endpoint that accepts connections is an agent, too. + let _listener = openlogi_ipc::transport::bind().unwrap(); + let error = run(args()) + .await + .expect_err("an answering endpoint must exclude the diagnostic"); + assert!( + error.to_string().contains("agent is running"), + "refused for another reason: {error:#}" + ); + }); + } + #[test] fn zero_reads_as_never_rather_than_zero_minutes() { assert_eq!(Minutes(PowerOffTimeout::NEVER).to_string(), "never"); From 48b3a011c94777e6b0ce52d7ed4955423b9b05ec Mon Sep 17 00:00:00 2001 From: Thomas Kroll <99196436+tkroll-ionos@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:51:23 +0100 Subject: [PATCH 28/28] test(gui): drag the power-off slider in the rendered Audio tab The Audio tab tests only looked at the facts behind the rows, so they passed even if the tab stopped drawing the slider. The new test renders the main window at 125 % in its minimum size, scrolls the Audio tab to its end, checks that the power-off row sits inside the window beside the sidetone row, and drags the slider with the mouse: the drag writes nothing, the release writes the headset once. --- crates/openlogi-desktop/src/app/tests.rs | 172 +++++++++++++++++- crates/openlogi-desktop/src/features/audio.rs | 14 +- .../src/windows/main_window.rs | 2 +- 3 files changed, 183 insertions(+), 5 deletions(-) diff --git a/crates/openlogi-desktop/src/app/tests.rs b/crates/openlogi-desktop/src/app/tests.rs index 7db24dfd5b..f837bb424f 100644 --- a/crates/openlogi-desktop/src/app/tests.rs +++ b/crates/openlogi-desktop/src/app/tests.rs @@ -181,6 +181,21 @@ fn open_device_detail( inventory: openlogi_core::device::DeviceInventory, config: openlogi_core::config::Config, ) -> (gpui::Entity, &mut gpui::VisualTestContext) { + let (app_view, cx, _commands) = open_device_detail_with_commands(cx, inventory, config); + (app_view, cx) +} + +/// [`open_device_detail`], keeping the commands the state sends the agent, +/// so a test can answer the device's reads and see its writes. +fn open_device_detail_with_commands( + cx: &mut gpui::TestAppContext, + inventory: openlogi_core::device::DeviceInventory, + config: openlogi_core::config::Config, +) -> ( + gpui::Entity, + &mut gpui::VisualTestContext, + tokio::sync::mpsc::UnboundedReceiver, +) { use std::{cell::RefCell, rc::Rc}; use gpui::AppContext as _; @@ -192,8 +207,8 @@ fn open_device_detail( rust_i18n::set_locale("en"); cx.update(gpui_kit::init); + let (commands, receiver) = tokio::sync::mpsc::unbounded_channel(); cx.update(|cx| { - let (commands, _receiver) = tokio::sync::mpsc::unbounded_channel(); let resolver = AssetResolver::new(); let state = cx.new(|_| { let mut state = AppState::new(Sources { @@ -227,7 +242,7 @@ fn open_device_detail( app_view.update(cx, |view, cx| view.open_device(record_key, cx)); window.draw(cx).clear(cx); }); - (app_view, cx) + (app_view, cx, receiver) } /// The Pointer tab's Scrolling card carries the smooth-wheel switch, shows the @@ -1618,6 +1633,159 @@ fn a_headset_with_sidetone_and_power_off_has_one_audio_tab() { ); } +/// Answer the headset reads the state has sent the agent — sidetone at 40 %, +/// power-off at 15 minutes — and return the power-off writes among them. +fn answer_headset( + commands: &mut tokio::sync::mpsc::UnboundedReceiver, +) -> Vec { + use openlogi_core::hid::{PowerOffTimeout, SidetoneLevel}; + + use crate::services::ipc::{Command, ReadPowerOffTimeout, ReadSidetone, SetPowerOffTimeout}; + + let mut written = Vec::new(); + while let Ok(command) = commands.try_recv() { + match command { + Command::ReadSidetone(ReadSidetone { reply, .. }) => { + let _ = reply.send(Ok(SidetoneLevel::try_new(40).expect("a level"))); + } + Command::ReadPowerOffTimeout(ReadPowerOffTimeout { reply, .. }) => { + let _ = reply.send(Ok(PowerOffTimeout::clamped(15))); + } + Command::SetPowerOffTimeout(SetPowerOffTimeout { timeout, .. }) => { + written.push(timeout); + } + _ => {} + } + } + written +} + +/// Open a G933 — sidetone and automatic power-off — at the largest +/// interface scale in the smallest main window, with its reads answered. +fn open_headset_at_125_percent( + cx: &mut gpui::TestAppContext, +) -> ( + gpui::Entity, + &mut gpui::VisualTestContext, + tokio::sync::mpsc::UnboundedReceiver, +) { + use openlogi_core::config::{Config, UiScale}; + + use crate::state::tests::direct_inventory; + use crate::windows::main_window::MIN_SIZE; + + let mut inventory = direct_inventory([0x0a, 0x5b, 0x00, 0x01]); + inventory.paired[0].kind = DeviceKind::Headset; + inventory.paired[0].capabilities = Some(Capabilities { + sidetone: true, + power_off_timeout: true, + ..Capabilities::default() + }); + let mut config = Config::ephemeral(); + config.app_settings.ui_scale = UiScale::ExtraLarge; + let (app_view, cx, mut commands) = open_device_detail_with_commands(cx, inventory, config); + // The settings app reads the headset through its device-read service. + cx.update(|_, cx| { + let runtime: std::sync::Arc = + std::sync::Arc::new(swr_gpui::GpuiRuntime::new(cx)); + let client = swr_core::SwrClient::builder().build(runtime.clone()); + crate::state::AppState::update(cx, |state, _| state.connect_device_reads(client, runtime)); + crate::state::AppState::load_current_device_reads(cx); + }); + // Answer the reads as they come. + for _ in 0..3 { + cx.run_until_parked(); + assert!( + answer_headset(&mut commands).is_empty(), + "opening the tab writes nothing" + ); + cx.update(|window, cx| window.draw(cx).clear(cx)); + } + cx.simulate_resize(MIN_SIZE); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert_eq!( + cx.update(|window, _| window.rem_size()), + crate::ui::theme::rem_size(UiScale::ExtraLarge), + "the window renders at 125 %" + ); + (app_view, cx, commands) +} + +/// A G933 at the largest interface scale in the smallest main window: with +/// the Audio tab scrolled to its end, the last row, the power-off slider, +/// sits inside the window with the sidetone row above it, and dragging the +/// slider writes the headset once, on release, not at every step. +#[gpui::test] +fn the_power_off_slider_is_reachable_and_writes_only_on_release(cx: &mut gpui::TestAppContext) { + use gpui::{Modifiers, MouseButton, ScrollDelta, ScrollEvent, point, px}; + use openlogi_core::hid::PowerOffTimeout; + + use crate::services::i18n::LOCALE_LOCK; + use crate::ui::commit_slider::SliderUnit as _; + use crate::windows::main_window::MIN_SIZE; + + let _locale = LOCALE_LOCK.lock().unwrap(); + let (app_view, cx, mut commands) = open_headset_at_125_percent(cx); + let body = cx + .debug_bounds("detail-tab-body") + .expect("a headset opens on the Audio tab"); + cx.simulate_event(ScrollEvent { + position: point(body.left() + px(8.), body.top() + px(8.)), + delta: ScrollDelta::Pixels(point(px(0.), px(-5000.))), + ..Default::default() + }); + cx.update(|window, cx| window.draw(cx).clear(cx)); + assert!( + cx.debug_bounds("audio-sidetone-row").is_some(), + "the sidetone row shows beside the power-off row" + ); + let row = cx + .debug_bounds("audio-power-off-row") + .expect("the power-off row shows"); + assert!( + row.bottom() <= MIN_SIZE.height, + "the power-off row {row:?} must end inside the {MIN_SIZE:?} window" + ); + + let slider = cx.update(|_, cx| { + app_view + .read(cx) + .audio_panel + .read(cx) + .power_off_slider() + .cloned() + .expect("a read timeout shows the slider") + }); + let bar = cx.update(|_, cx| slider.read(cx).bounds()); + assert!( + bar.bottom() <= MIN_SIZE.height, + "the slider {bar:?} must sit inside the {MIN_SIZE:?} window" + ); + let at = |fraction: f32| point(bar.left() + bar.size.width * fraction, bar.center().y); + cx.simulate_mouse_down(at(0.25), MouseButton::Left, Modifiers::none()); + cx.simulate_mouse_move(at(0.5), MouseButton::Left, Modifiers::none()); + cx.simulate_mouse_move(at(0.7), MouseButton::Left, Modifiers::none()); + cx.run_until_parked(); + assert!( + answer_headset(&mut commands).is_empty(), + "a drag writes nothing until it ends" + ); + + cx.simulate_mouse_up(at(0.7), MouseButton::Left, Modifiers::none()); + cx.run_until_parked(); + let released = cx.update(|_, cx| PowerOffTimeout::from_slider(slider.read(cx).value().end())); + assert_ne!( + released, + PowerOffTimeout::clamped(15), + "the drag moved the thumb" + ); + assert_eq!( + answer_headset(&mut commands), + [released], + "the release writes the headset once" + ); +} + /// An unprobed (offline) device has no measured capabilities and falls back /// to a kind presumption, so a sleeping mouse keeps its button/pointer tabs. #[test] diff --git a/crates/openlogi-desktop/src/features/audio.rs b/crates/openlogi-desktop/src/features/audio.rs index 6d2b4184f8..7847aa04dc 100644 --- a/crates/openlogi-desktop/src/features/audio.rs +++ b/crates/openlogi-desktop/src/features/audio.rs @@ -13,8 +13,8 @@ //! [`AppState::commit_power_off_timeout`] and kept by the headset. use gpui::{ - AnyElement, App, Context, IntoElement, ParentElement, Render, SharedString, Styled, - Subscription, Window, div, prelude::FluentBuilder as _, px, + AnyElement, App, Context, InteractiveElement as _, IntoElement, ParentElement, Render, + SharedString, Styled, Subscription, Window, div, prelude::FluentBuilder as _, px, }; use gpui_kit::component::{h_flex, slider::Slider, v_flex}; use openlogi_core::hid::{PowerOffTimeout, SidetoneLevel}; @@ -48,6 +48,14 @@ impl AudioPanel { _state_obs: state_obs, } } + + /// The power-off slider, while the row shows one. + #[cfg(test)] + pub(crate) fn power_off_slider( + &self, + ) -> Option<&gpui::Entity> { + self.power_off.as_ref().map(|row| row.slider.slider()) + } } impl Render for AudioPanel { @@ -187,6 +195,7 @@ fn sidetone_section( } }; v_flex() + .debug_selector(|| "audio-sidetone-row".into()) .gap_3() .w_full() .child( @@ -346,6 +355,7 @@ fn power_off_section( } }; v_flex() + .debug_selector(|| "audio-power-off-row".into()) .gap_3() .w_full() .child( diff --git a/crates/openlogi-desktop/src/windows/main_window.rs b/crates/openlogi-desktop/src/windows/main_window.rs index 7648b2f269..b8f6e2bba1 100644 --- a/crates/openlogi-desktop/src/windows/main_window.rs +++ b/crates/openlogi-desktop/src/windows/main_window.rs @@ -26,7 +26,7 @@ pub(super) const PREFERRED_SIZE: Size = Size { /// reserve) so its side labels never overlap; below this the model can't /// shrink further without crowding. [`WindowFit`] lowers it only on a work /// area too small to hold it. -pub(super) const MIN_SIZE: Size = Size { +pub(crate) const MIN_SIZE: Size = Size { width: px(720.), height: px(680.), };