//! Scanning, connecting to and writing to devices. use super::*; use futures::StreamExt as _; impl AppView { pub(super) fn hid_service(&mut self) -> crate::hid::HidService { self.hid.get_or_insert_with(crate::hid::HidService::start).clone() } /// The rescue shortcut (`crate::rescue_hotkey`): gives the selected mouse's /// left button its click back, in the running onboard profile or in an /// MX-style remap. Other connected mice are left alone. Goes through the /// ordinary write queue, so it lands after a write in flight and replaces a /// waiting edit of the same button, and the mouse is read back after. pub fn restore_left_click(&mut self, cx: &mut Context) { let mut writes = Vec::new(); if let Some(TileStatus::Connected(r)) = self.devices.tiles.get(self.devices.selected).map(|t| &t.status) { if r.onboard_profiles_writable && r.mode.as_deref() == Some("Onboard") { writes.push(("logi.button.primary.0", serde_json::json!("Left click"))); } // Not judged by the control's shown value: a remap still being // written shows the old one. if r.tabs.controls().any(|c| c.id == "logi.remap.80") { writes.push(("logi.remap.80", serde_json::json!(80))); } } if writes.is_empty() { self.show_toast("The selected mouse has no left button to restore.", false, cx); return; } for (id, value) in writes { match self.selected_key().filter(|_| self.devices.writing.is_some()) { Some(key) => self.queue(Queued::Control { key, id: id.to_string(), value, rescue: true }), None => self.write_control(id.to_string(), value, cx), } } } /// Lists supported devices, loads their artwork, and connects the first. /// Everything blocking runs on `crate::hid`'s threads or the background /// executor. pub(super) fn scan_devices(&mut self, cx: &mut Context) { if self.devices.scanning { self.devices.rescan = true; return; } self.devices.scanning = true; self.devices.error = None; cx.notify(); let service = self.hid_service(); cx.spawn(async move |view, cx| { let blocked = crate::hid_access::blocked_devices(); let _ = view.update(cx, |v: &mut Self, _| { v.hid_blocked = blocked; if v.hid_blocked.is_empty() && matches!(v.udev_fix, UdevFix::Failed { .. }) { v.udev_fix = UdevFix::Idle; } }); let listed = service.list_candidates().await; let candidates = match listed { Ok(Ok(list)) => list, other => { let message = match other { Ok(Err(error)) => error, _ => "device runtime stopped".to_string(), }; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.scanning = false; v.devices.error = Some(message); cx.notify(); if std::mem::take(&mut v.devices.rescan) { v.scan_devices(cx); } }); return; } }; let _ = view.update(cx, |v: &mut Self, cx| { // Keep what is already known about devices that are still here. let keep = v.selected_key(); let mut old: Vec = std::mem::take(&mut v.devices.tiles); v.devices.tiles = candidates .iter() .filter(|c| !v.devices.ignored_keys.contains(&c.info.key)) .map(|c| { match old.iter().position(|t| t.key == c.info.key) { Some(i) => old.swap_remove(i), None => v.new_tile(c), } }) .collect(); v.reselect(keep); v.devices.scanning = false; v.close_unplugged_page(&old, cx); cx.notify(); if std::mem::take(&mut v.devices.rescan) { v.scan_devices(cx); } }); for c in &candidates { // Use the name the tile carries now: a receiver that was // connected is known by its mouse's name, and resolving the // receiver's generic product string would swap the mouse's // artwork for the placeholder. let current = view .update(cx, |v: &mut Self, _| { v.devices .tiles .iter() .find(|t| t.key == c.info.key) .map(|t| (t.default_name.clone(), t.art.is_some())) }) .ok() .flatten(); let Some((name, has_art)) = current else { continue }; if has_art { continue; } Self::load_art(&service, &c.info.key, &name, &view, cx).await; } let _ = view.update(cx, |v: &mut Self, cx| { v.reconnect(cx); if let Some(key) = v.devices.wake_connect.take() { let waiting = v.devices.tiles.iter().any(|t| t.key == key && !matches!(t.status, TileStatus::Connected(_) | TileStatus::Connecting)); if waiting { let keep = v.selected_key(); let _ = v.connect_task(&key, false, cx).map(|task| task.detach()); if v.devices.open.is_some() { v.reselect(keep); } } } v.ensure_usb_topology(cx); v.check_conflicting_apps(cx); }); }) .detach(); } /// Looks again whenever a device is plugged in or removed. pub(super) fn watch_devices(&mut self, cx: &mut Context) { let changes = crate::hotplug::watch(); cx.spawn(async move |view, cx| { let executor = cx.background_executor().clone(); let Some(mut changes) = changes else { // Nothing reports plug-ins here, so check on a timer. loop { crate::activity::ACTIVITY .sleep(&executor, Duration::from_secs(3), Duration::from_secs(15)) .await; if view.update(cx, |v: &mut Self, cx| v.scan_devices(cx)).is_err() { return; } } }; while changes.next().await.is_some() { // A device arrives one interface at a time: wait until it is quiet. loop { executor.timer(Duration::from_millis(700)).await; let mut more = false; while changes.try_recv().is_ok() { more = true; } if !more { break; } } if view .update(cx, |v: &mut Self, cx| { v.scan_devices(cx); if v.page == Page::UsbMap { v.scan_usb_topology(cx); } }) .is_err() { return; } } }) .detach(); } /// Leaves the settings page of a device that is no longer there. `gone` /// holds the tiles the last scan did not find. fn close_unplugged_page(&mut self, gone: &[Tile], cx: &mut Context) { let Some(open) = self.devices.open.as_deref() else { return }; let Some(name) = gone.iter().find(|t| t.key == open).map(|t| t.name.clone()) else { return }; self.devices.open = None; self.devices.staged = Staged::default(); self.show_toast(format!("{name} was disconnected."), false, cx); } pub(super) async fn load_art( service: &crate::hid::HidService, key: &str, name: &str, view: &WeakEntity, cx: &mut AsyncApp, ) { let (is_keyboard, custom_path) = view .update(cx, |v: &mut Self, _| { let keyboard = v.devices.tiles.iter().find(|t| t.key == key).is_some_and(|t| t.keyboard); let path = v.settings.device_overrides.get(key).and_then(|o| o.image_path.clone()).map(std::path::PathBuf::from); (keyboard, path) }) .unwrap_or((false, None)); if let Some(path) = custom_path.filter(|p| p.is_file()) { let key = key.to_string(); let _ = view.update(cx, |v: &mut Self, cx| { if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key) { tile.art = Some(LoadedArt { path, placement: None }); cx.notify(); } }); return; } let Ok(Ok(mut art)) = service.device_image(key, name).await else { return }; if is_keyboard { // Keyboards keep their bundled `unknown-keyboard.png` placeholder // when no real photo is found, rather than the mouse silhouette. if art.filename == "unknown-device.png" { return; } art.fallbacks.retain(|c| c.filename != "unknown-device.png"); } let Some((path, placement)) = cx.background_executor().spawn(async move { art.fetch_placed() }).await else { return; }; let key = key.to_string(); let _ = view.update(cx, |v: &mut Self, cx| { if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key) { tile.art = Some(LoadedArt { path, placement }); cx.notify(); } }); } fn retry_receiver(&mut self, key: String, cx: &mut Context) { let service = self.hid_service(); cx.spawn(async move |view, cx| { let executor = cx.background_executor().clone(); loop { crate::activity::ACTIVITY.sleep(&executor, Duration::from_secs(5), Duration::from_secs(15)).await; let still = view.update(cx, |v: &mut Self, _| v.devices.ignored_keys.contains(&key)); if !matches!(still, Ok(true)) { return; } match service.connect(&key).await { Ok(Ok(_)) => { let _ = view.update(cx, |v: &mut Self, cx| { crate::logging::log(&format!("[device] a mouse woke up behind receiver {key}")); v.devices.ignored_keys.remove(&key); v.devices.wake_connect = Some(key.clone()); v.scan_devices(cx); }); return; } Ok(Err(error)) if error.to_ascii_lowercase().contains("is not a mouse") => continue, _ => return, } } }) .detach(); } pub(super) fn selected_key(&self) -> Option { self.devices.tiles.get(self.devices.selected).map(|t| t.key.clone()) } pub(super) fn onboard(&self) -> Option<&crate::hid::OnboardProfiles> { let selected = self.devices.tiles.get(self.devices.selected)?; self.devices.onboard.as_ref().filter(|_| self.devices.onboard_key.as_deref() == Some(selected.key.as_str())) } pub(super) fn sync_selected(&mut self) { if self.editing_profile().is_some() { return; } if let Some(i) = self.devices.open.as_ref().and_then(|k| self.devices.tiles.iter().position(|t| &t.key == k)) { self.devices.selected = i; } } fn reselect(&mut self, key: Option) { self.devices.selected = key .and_then(|k| self.devices.tiles.iter().position(|t| t.key == k)) .unwrap_or_else(|| self.devices.selected.min(self.devices.tiles.len().saturating_sub(1))); } /// Opens a device's settings page, connecting it first if needed. pub(super) fn open_device(&mut self, key: &str, cx: &mut Context) { let Some(index) = self.devices.tiles.iter().position(|t| t.key == key) else { return }; if self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.key != key) { self.flush_stages(cx); } self.remember_device(key); self.devices.open = Some(key.to_string()); self.devices.selected = index; self.devices.staged = Staged::default(); self.devices.unlinked_axes = false; self.devices.dpi_pending = None; self.devices.tab = DeviceTab::Overview; self.devices.expanded = None; self.devices.stage_picked = None; self.devices.stage_draft = None; self.stage_seq += 1; self.stage_sent = self.stage_seq; self.stage_unlinked.clear(); self.stage_sliders.clear(); self.stage_inputs.clear(); self.profile_name = None; self.devices.magnetic_both = None; self.keyboard.reset(); self.macros.reset(); self.devices.onboard = None; self.devices.write_error = None; self.devices.queued.retain(Queued::is_rescue); if matches!( self.devices.tiles[index].status, TileStatus::Idle | TileStatus::Failed(_) ) { self.connect_tile(key, false, cx); } cx.notify(); } /// Records the Y sensitivity of a confirmed unlinked write. pub(super) fn patch_dpi_y(&mut self, key: &str, y: f64) { if let Some(Tile { status: TileStatus::Connected(r), .. }) = self.devices.tiles.iter_mut().find(|t| t.key == key) { r.dpi_y = Some(y); } } /// Reflects a confirmed write in the page. The value is what the driver /// reports the mouse applied (it can clamp or round), and it is used /// instead of a re-read: a Logitech mouse answers its get-report-rate call /// with a stale value after a live change (the driver only knows the real /// rate from the change notification it saw), so re-reading would show the /// old rate straight after a successful write. The Tauri app patches its /// status the same way. pub(super) fn patch_readout(&mut self, key: &str, action: &str, applied: &serde_json::Value, cx: &mut Context) { let mut left_onboard = false; let Some(tile) = self.devices.tiles.iter_mut().find(|t| t.key == key) else { return }; let TileStatus::Connected(r) = &mut tile.status else { return }; let into_profile = matches!(action, "dpi" | "pollingRate" | "liftOff") && r.onboard_profiles_writable && r.mode.as_deref() == Some("Onboard"); if !into_profile && matches!(action, "dpi" | "pollingRate" | "liftOff") && r.onboard_profiles && r.connection.as_deref() == Some("Wireless") && r.mode.as_deref() == Some("Onboard") { r.mode = Some("Host".to_string()); left_onboard = true; } match action { "dpi" => { r.dpi = applied.as_f64().or(r.dpi); // Linked writes put Y on X as well; an unlinked pair sets Y after this. r.dpi_y = r.dpi; } "pollingRate" => r.polling_hz = applied.as_f64().or(r.polling_hz), "liftOff" => r.lod = applied.as_str().map(str::to_string).or_else(|| r.lod.take()), "surface" => r.surface = applied.as_str().map(str::to_string).or_else(|| r.surface.take()), "lighting" => { if let Some(l) = &mut r.tabs.lighting { if let Some(mode) = applied.get("mode").and_then(|v| v.as_str()) { l.mode = Some(mode.to_string()); } l.color = applied.get("color").and_then(|v| v.as_str()).map(str::to_string).or_else(|| l.color.take()); l.color2 = applied.get("color2").and_then(|v| v.as_str()).map(str::to_string).or_else(|| l.color2.take()); l.speed = applied.get("speed").and_then(|v| v.as_f64()).or(l.speed); } } _ => {} } if left_onboard { // Which profile is running is no longer what we last read. self.devices.onboard = None; } let selected = self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.key == key); if into_profile && selected && action == "dpi" { if let (Some(dpi), Some(draft)) = (applied.as_f64(), self.devices.stage_draft.as_mut()) { draft.set_default_dpi(dpi.round() as i64); } } if into_profile && selected && action == "liftOff" { let lod = match applied.as_str() { Some("Low") => Some(1), Some("Medium") => Some(2), Some("High") => Some(3), _ => None, }; if let (Some(lod), Some(draft)) = (lod, self.devices.stage_draft.as_mut()) { draft.set_lod(lod); } } if into_profile && matches!(action, "dpi" | "pollingRate" | "liftOff") { self.load_onboard_profiles(cx); } } /// Reads the open Logitech mouse's stored profiles. On demand: a full pass /// is dozens of HID++ round trips. pub(super) fn load_onboard_profiles(&mut self, cx: &mut Context) { if self.devices.onboard_loading { return; } let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; let key = tile.key.clone(); self.devices.onboard_loading = true; cx.notify(); let service = self.hid_service(); cx.spawn(async move |view, cx| { let result = service.onboard_profiles(&key).await; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.onboard_loading = false; let selected = v.devices.tiles.get(v.devices.selected); if selected.map(|t| t.key.as_str()) != Some(key.as_str()) { let wants = selected.is_some_and(|t| matches!(&t.status, TileStatus::Connected(r) if r.onboard_profiles)); if wants && v.onboard().is_none() { v.load_onboard_profiles(cx); } cx.notify(); return; } match result { Ok(Ok(list)) => { v.devices.onboard = Some(list); v.devices.onboard_key = Some(key.clone()); if v.stage_seq == v.stage_sent { v.devices.stage_draft = None; } } Ok(Err(error)) => v.write_failed(&key, &error, cx), Err(_) => v.write_failed(&key, "device runtime stopped", cx), } cx.notify(); }); }) .detach(); } /// `mode`: switch Onboard / Host. `useProfile`: run a stored profile (this /// also puts the mouse in Onboard mode, which is the only mode that runs /// them). Neither writes flash. pub(super) fn onboard_action(&mut self, action: &'static str, value: serde_json::Value, cx: &mut Context) { let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; self.onboard_action_for(tile.key.clone(), action, value, cx); } pub(super) fn onboard_action_for(&mut self, key: String, action: &'static str, value: serde_json::Value, cx: &mut Context) { if self.busy(cx) { return; } self.devices.writing = Some(action.to_string()); self.devices.write_error = None; cx.notify(); let service = self.hid_service(); cx.spawn(async move |view, cx| { let result = service.onboard_action(&key, action, value.clone()).await; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.writing = None; let failed = !matches!(result, Ok(Ok(_))); match result { Ok(Ok(applied)) => { if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key).filter(|_| !matches!(action, "enable" | "rename")) { if let TileStatus::Connected(r) = &mut tile.status { r.mode = Some(if action == "mode" { applied.as_str().unwrap_or("Host").to_string() } else { "Onboard".to_string() }); } } if action == "stages" { v.saved("DPI stages", cx); } if action == "rename" { v.profile_name = None; v.saved("Profile name", cx); } if action == "enable" { v.saved("Profile list", cx); } if action == "factory" { v.devices.stage_draft = None; v.show_toast("Factory profiles restored.", false, cx); } if action == "useProfile" { v.show_toast(format!("Now running profile {}.", value), false, cx); } // Which profile is running changed; read the list again. v.load_onboard_profiles(cx); } Ok(Err(error)) => v.write_failed(&key, &error, cx), Err(_) => v.write_failed(&key, "device runtime stopped", cx), } if action == "factory" && failed { v.devices.onboard = None; v.load_onboard_profiles(cx); } v.read_back(&key, Vec::new(), cx); v.next_write(cx); cx.notify(); }); }) .detach(); } /// Writes one Buttons/Advanced control (always immediate, as in the Tauri /// app) and shows the value that was sent once the mouse accepts it. pub(super) fn set_control(&mut self, id: String, value: serde_json::Value, cx: &mut Context) { if id.starts_with("x.lg.") && self.editing_profile().is_some() { self.show_toast("This acts on the mouse right away, so a game profile can't keep it.", true, cx); return; } if let Some((gid, dev)) = self.editing_profile() { self.edit_profile( &gid, &dev, |p| { // Writing a `mag..both` override supersedes per-button overrides for that field. if let Some(prefix) = id.strip_suffix(".both") { if prefix.starts_with("mag.") { p.controls.remove(&format!("{prefix}.0")); p.controls.remove(&format!("{prefix}.1")); } } p.controls.insert(id, value); }, cx, ); return; } if id.starts_with("perf.") && self.blocked_by_profile(cx) { return; } if !self.ask_before_control(&id, &value, cx) { self.write_control(id, value, cx); } } /// [`Self::set_control`] once nothing stands in the way. pub(super) fn write_control(&mut self, id: String, value: serde_json::Value, cx: &mut Context) { let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; let (key, brand) = (tile.key.clone(), tile.brand.clone()); if self.devices.writing.is_some() { self.queue(Queued::Control { key, id, value, rescue: false }); return; } // "Link left & right" is one preference for every device that has it. if id.ends_with(".link") { if let Some(linked) = value.as_bool() { self.settings.link_left_right = Some(linked); self.settings.save(); self.hid_service().set_prefs(Some(linked)); } } self.devices.writing = Some(id.clone()); self.devices.write_error = None; cx.notify(); let service = self.hid_service(); cx.spawn(async move |view, cx| { let result = service.write(&key, &brand, &format!("control:{id}"), value.clone()).await; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.writing = None; if !matches!(result, Ok(Ok(_))) { if let Some(entry) = v.text_controls.colours.get_mut(&format!("{key}/{id}")) { entry.0.clear(); } } let mut expected = Vec::new(); match result { Ok(Ok(applied)) => { // Keyboard profile edits return verified tabs with canonical values. // The typed expression may differ from the value stored by the device. let confirmed_tabs = id.starts_with("logi.keyboard.") || id.starts_with("via."); if !confirmed_tabs { expected.push(Expected { action: format!("control:{id}"), value: value.clone() }); } let name = v.control_name(&key, &id); v.saved(&name, cx); if id.starts_with("via.") && id != "via.file.save" { v.keyboard.drop_board(); if matches!(v.devices.tab, DeviceTab::Keys | DeviceTab::Actuation) { v.load_keyboard_tab(v.devices.tab, cx); } } // A control that reshapes the page (a switch gaining analog settings) returns the new layout. let new_tabs = applied.get("tabs").and_then(|t| serde_json::from_value::(t.clone()).ok()); if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key) { if let (Some(tabs), TileStatus::Connected(r)) = (new_tabs, &mut tile.status) { r.tabs = tabs; } } // A Logitech button: reflect it in the stored profile we hold. let ours = v.devices.onboard_key.as_deref() == Some(key.as_str()); if let Some(n) = id.strip_prefix("logi.button.primary.").and_then(|n| n.parse::().ok()).filter(|_| ours) { if let Some(running) = v .devices .onboard .as_mut() .and_then(|o| o.profiles.iter_mut().find(|p| p.is_current)) { if let Some(slot) = running.button_assignments.get_mut(n) { slot["action"] = value.clone(); } } } if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key).filter(|_| !confirmed_tabs) { if let TileStatus::Connected(r) = &mut tile.status { for section in r.tabs.buttons.iter_mut().chain(r.tabs.advanced.iter_mut()).chain(r.tabs.performance.iter_mut()).chain(r.tabs.receiver.iter_mut()) { for control in &mut section.controls { if control.id == id { control.current = value.clone(); } } } } } } Ok(Err(error)) => v.write_failed(&key, &error, cx), Err(_) => v.write_failed(&key, "device runtime stopped", cx), } v.read_back(&key, expected, cx); v.next_write(cx); cx.notify(); }); }) .detach(); } /// The lighting as it would be written now: staged fields over the device's. pub(super) fn effective_lighting(&self, spec: &crate::hid::LightingSpec) -> serde_json::Value { let e = &self.devices.staged.light; serde_json::json!({ "mode": e.mode.clone().or_else(|| spec.mode.clone()), "color": e.color.clone().or_else(|| spec.color.clone()), "color2": e.color2.clone().or_else(|| spec.color2.clone()), "speed": e.speed.or(spec.speed), }) } /// One lighting edit: written now with instant apply, staged otherwise. pub(super) fn edit_lighting( &mut self, apply: impl FnOnce(&mut LightEdit), spec: &crate::hid::LightingSpec, cx: &mut Context, ) { if let Some((gid, dev)) = self.editing_profile() { let mut light = self.profile_light_edit(&gid, &dev, spec); apply(&mut light); let mut obj = serde_json::Map::new(); if let Some(m) = light.mode.or_else(|| spec.mode.clone()) { obj.insert("mode".into(), serde_json::json!(m)); } if let Some(c) = light.color.or_else(|| spec.color.clone()) { obj.insert("color".into(), serde_json::json!(c)); } if let Some(c2) = light.color2.or_else(|| spec.color2.clone()) { obj.insert("color2".into(), serde_json::json!(c2)); } if let Some(s) = light.speed.or(spec.speed) { obj.insert("speed".into(), serde_json::json!(s)); } self.edit_profile(&gid, &dev, |p| p.lighting = Some(serde_json::Value::Object(obj)), cx); return; } apply(&mut self.devices.staged.light); if self.settings.instant_apply { let value = self.effective_lighting(spec); self.devices.staged.light = LightEdit::default(); self.write_setting("lighting", value, cx); } cx.notify(); } /// Writes one setting and shows the value the mouse confirmed. pub(super) fn write_setting(&mut self, action: &'static str, value: serde_json::Value, cx: &mut Context) { let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; let (key, brand) = (tile.key.clone(), tile.brand.clone()); if self.devices.writing.is_some() { self.queue(Queued::Setting { key, action, value }); return; } let requested_y = value.get("y").and_then(|y| y.as_f64()); self.devices.writing = Some(action.to_string()); self.devices.write_error = None; cx.notify(); let service = self.hid_service(); cx.spawn(async move |view, cx| { let result = service.write(&key, &brand, action, value).await; let _ = view.update(cx, |v: &mut Self, cx| { v.devices.writing = None; let mut expected = Vec::new(); match result { Ok(Ok(applied)) => { if action == "dpi" && !v.devices.queued.iter().any(|q| matches!(q, Queued::Setting { action: "dpi", .. })) { v.devices.dpi_pending = None; } v.patch_readout(&key, action, &applied, cx); if let Some(y) = requested_y { v.patch_dpi_y(&key, y); } v.refresh_presence(cx); expected.push(Expected { action: action.to_string(), value: applied }); v.saved(setting_name(action), cx); } Ok(Err(error)) => v.write_failed(&key, &error, cx), Err(_) => v.write_failed(&key, "device runtime stopped", cx), } v.read_back(&key, expected, cx); v.next_write(cx); cx.notify(); }); }) .detach(); } /// Writes every staged edit in order (one device session each) and shows /// what the mouse confirmed. Stops at the first failure and keeps the rest /// staged so nothing is silently dropped. pub(super) fn apply_staged(&mut self, cx: &mut Context) { if self.devices.staged.is_empty() { return; } let Some(tile) = self.devices.tiles.get(self.devices.selected) else { return }; let (key, brand) = (tile.key.clone(), tile.brand.clone()); if self.devices.writing.is_some() { self.queue(Queued::Apply { key }); return; } let staged = self.devices.staged.clone(); let mut jobs: Vec<(&'static str, serde_json::Value)> = Vec::new(); if staged.dpi.is_some() || staged.dpi_y.is_some() { let current_x = match self.devices.tiles.get(self.devices.selected).map(|t| &t.status) { Some(TileStatus::Connected(r)) => r.dpi, _ => None, }; let x = staged.dpi.or(current_x).unwrap_or(0.0); jobs.push(("dpi", match staged.dpi_y { Some(y) => serde_json::json!({ "x": x, "y": y }), None => serde_json::json!(x), })); } if let Some(v) = staged.polling { jobs.push(("pollingRate", serde_json::json!(v))); } if let Some(v) = staged.lod.clone() { jobs.push(("liftOff", serde_json::json!(v))); } if let Some(v) = staged.surface.clone() { jobs.push(("surface", serde_json::json!(v))); } let light_job = if staged.light == LightEdit::default() { None } else { match &self.devices.tiles.get(self.devices.selected).map(|t| &t.status) { Some(TileStatus::Connected(r)) => r.tabs.lighting.as_ref().map(|spec| self.effective_lighting(spec)), _ => None, } }; if let Some(value) = light_job { jobs.push(("lighting", value)); } self.devices.writing = Some("apply".into()); self.devices.write_error = None; cx.notify(); let service = self.hid_service(); cx.spawn(async move |view, cx| { let mut failure = None; let mut done = Staged::default(); let mut applied_values: Vec<(&'static str, serde_json::Value)> = Vec::new(); for (action, value) in jobs { match service.write(&key, &brand, action, value).await { Ok(Ok(applied)) => { applied_values.push((action, applied)); match action { "dpi" => { done.dpi = staged.dpi; done.dpi_y = staged.dpi_y; } "pollingRate" => done.polling = staged.polling, "liftOff" => done.lod = staged.lod.clone(), "lighting" => done.light = staged.light.clone(), _ => done.surface = staged.surface.clone(), } } Ok(Err(error)) => { failure = Some(error); break; } Err(_) => { failure = Some("device runtime stopped".to_string()); break; } } } let _ = view.update(cx, |v: &mut Self, cx| { v.devices.writing = None; if v.selected_key().as_deref() == Some(key.as_str()) { let s = &mut v.devices.staged; if done.dpi.is_some() && s.dpi == done.dpi { s.dpi = None; } if done.dpi_y.is_some() && s.dpi_y == done.dpi_y { s.dpi_y = None; } if done.polling.is_some() && s.polling == done.polling { s.polling = None; } if done.lod.is_some() && s.lod == done.lod { s.lod = None; } if done.surface.is_some() && s.surface == done.surface { s.surface = None; } if done.light != LightEdit::default() && s.light == done.light { s.light = LightEdit::default(); } } match &failure { Some(error) => v.write_failed(&key, error, cx), None => v.saved("Changes", cx), } for (action, applied) in &applied_values { v.patch_readout(&key, action, applied, cx); if *action == "dpi" { if let Some(y) = staged.dpi_y { v.patch_dpi_y(&key, y); } } } v.refresh_presence(cx); let expected = applied_values .into_iter() .map(|(action, value)| Expected { action: action.to_string(), value }) .collect(); v.read_back(&key, expected, cx); v.next_write(cx); cx.notify(); }); }) .detach(); } /// The game whose profile currently controls the open device, if any. While /// one does, the Performance tab is locked: its settings are the profile's /// until the game closes (the Tauri tab does the same). pub(super) fn locked_game(&self) -> Option { if self.editing_profile().is_some() { return None; } let key = &self.devices.tiles.get(self.devices.selected)?.key; self.profile_overrides.iter().find(|o| &o.device == key).map(|o| o.game_name.clone()) } /// Refuses an edit with a note when [`Self::locked_game`] applies. pub(super) fn blocked_by_profile(&mut self, cx: &mut Context) -> bool { match self.locked_game() { Some(game) => { self.show_toast(format!("Locked while {game} is running - your game profile is in control."), true, cx); true } None => false, } } /// A DPI edit. Linked (the default) writes one number for both axes; with the /// axes unlinked, X and Y go together as a pair. pub(super) fn edit_dpi(&mut self, x: f64, y: Option, cx: &mut Context) { if let Some((gid, dev)) = self.editing_profile() { let unlinked = self.devices.unlinked_axes; self.edit_profile( &gid, &dev, |p| { p.dpi = Some(x); p.dpi_y = unlinked.then(|| y.unwrap_or(x)); }, cx, ); return; } if self.blocked_by_profile(cx) { return; } let unlinked = self.devices.unlinked_axes; if self.settings.instant_apply { let value = if unlinked { serde_json::json!({ "x": x, "y": y.unwrap_or(x) }) } else { serde_json::json!(x) }; self.write_setting("dpi", value, cx); return; } self.devices.staged.dpi = Some(x); self.devices.staged.dpi_y = unlinked.then(|| y.unwrap_or(x)); cx.notify(); } /// Records an edit: written now with instant apply, staged otherwise. pub(super) fn edit(&mut self, action: &'static str, value: serde_json::Value, cx: &mut Context) { if let Some((gid, dev)) = self.editing_profile() { self.edit_profile( &gid, &dev, |p| match action { "dpi" => p.dpi = value.as_f64(), "pollingRate" => p.polling = value.as_u64().map(|n| n as u32), "liftOff" => p.lod = value.as_str().map(str::to_string), _ => p.surface = value.as_str().map(str::to_string), }, cx, ); return; } if self.blocked_by_profile(cx) { return; } if self.settings.instant_apply { self.write_setting(action, value, cx); return; } let st = &mut self.devices.staged; match action { "dpi" => st.dpi = value.as_f64(), "pollingRate" => st.polling = value.as_u64().map(|n| n as u32), "liftOff" => st.lod = value.as_str().map(str::to_string), _ => st.surface = value.as_str().map(str::to_string), } cx.notify(); } /// Opens one device, finds the driver that answers and reads its status. pub(super) fn connect_tile(&mut self, key: &str, quiet: bool, cx: &mut Context) { if let Some(attempt) = self.connect_task(key, quiet, cx) { attempt.detach(); } } /// The same, as a task saying whether the device answered; none if there is /// nothing to do. Dropping the task cancels it. pub(super) fn connect_task(&mut self, key: &str, quiet: bool, cx: &mut Context) -> Option> { let index = self.devices.tiles.iter().position(|t| t.key == key)?; if matches!(self.devices.tiles[index].status, TileStatus::Connecting) { return None; } // A refresh after a write keeps showing the old readout until the new // one lands, so the page does not flash "Connecting…". if !quiet { self.devices.tiles[index].status = TileStatus::Connecting; } self.devices.selected = index; cx.notify(); let service = self.hid_service(); service.set_prefs(self.settings.link_left_right); let key = key.to_string(); Some(cx.spawn(async move |view, cx| { let connected = service.connect(&key).await; let answered = matches!(connected, Ok(Ok(_))); let mut new_name = None; let _ = view.update(cx, |v: &mut Self, cx| { let mut connected_now = false; let custom_name = v.settings.device_overrides.get(&key).and_then(|o| o.name.clone()); let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key) else { return }; match connected { Ok(Ok(device)) => { if let Some(name) = device .status .get("name") .and_then(|n| n.as_str()) .filter(|n| !n.is_empty() && *n != tile.default_name) { tile.default_name = name.to_string(); tile.name = custom_name.unwrap_or_else(|| name.to_string()); new_name = Some(tile.default_name.clone()); } tile.brand = device.brand.clone(); tile.display_brand = device.display_brand.clone().filter(|b| !b.is_empty()).unwrap_or_else(|| device.brand.clone()); connected_now = true; let readout = DeviceReadout::from_status( &device.status, device.controls.clone(), device.tabs.clone().unwrap_or_default(), ); if let Some(note) = readout.status_banner_text() { crate::logging::log(&format!( "[device] {} ({}) settings unavailable (settingsReady={}): {}", tile.name, tile.brand, readout.settings_ready, note )); } tile.status = TileStatus::Connected(readout); } Ok(Err(error)) => { if error.to_ascii_lowercase().contains("is not a mouse") { crate::logging::log(&format!( "[device] hiding non-mouse interface {key}: {error}" )); v.devices.ignored_keys.insert(key.clone()); if error.contains("Receiver") { v.retry_receiver(key.clone(), cx); } let keep = v.selected_key(); v.devices.tiles.retain(|t| t.key != key); v.reselect(keep); if v.devices.open.as_deref() == Some(key.as_str()) { v.devices.open = None; } v.refresh_presence(cx); cx.notify(); return; } if !(quiet && matches!(tile.status, TileStatus::Connected(_))) { tile.status = TileStatus::Failed(error); } } Err(_) => tile.status = TileStatus::Failed("device runtime stopped".into()), } if connected_now { v.remember_name(&key); v.sample_battery(&key); v.sync_running_profiles(cx); } v.refresh_presence(cx); cx.notify(); }); // Receivers share product ids, so the artwork is only knowable // from the name the mouse itself reports. if let Some(name) = new_name { Self::load_art(&service, &key, &name, &view, cx).await; } answered })) } /// Every connected mouse with its readout, in list order. Keyboards are left /// out: game profiles, presence and battery history are for mice. pub(super) fn connected_devices(&self) -> Vec<(String, &DeviceReadout)> { self.devices .tiles .iter() .filter(|t| !t.keyboard) .filter_map(|t| match &t.status { TileStatus::Connected(r) => Some((t.key.clone(), r)), _ => None, }) .collect() } } /// What a live setting is called in a "saved" message. fn setting_name(action: &str) -> &'static str { match action { "dpi" => "DPI", "pollingRate" => "Polling rate", "liftOff" => "Lift-off distance", "surface" => "Surface mode", "lighting" => "Lighting", _ => "Setting", } }