//! Per-game profiles: applying them as games start and stop, and their 1:1 //! device settings editor (reusing `render_device_body` directly with the //! profile's saved overrides overlaid on top of the connected device). use super::*; fn snapshot_lighting(spec: &crate::hid::LightingSpec) -> Option { let mut obj = serde_json::Map::new(); if let Some(m) = &spec.mode { obj.insert("mode".into(), serde_json::json!(m)); } if let Some(c) = &spec.color { obj.insert("color".into(), serde_json::json!(c)); } if let Some(c2) = &spec.color2 { obj.insert("color2".into(), serde_json::json!(c2)); } if let Some(s) = spec.speed { obj.insert("speed".into(), serde_json::json!(s)); } (!obj.is_empty()).then_some(serde_json::Value::Object(obj)) } /// Returns a clone of `tile` with `profile`'s saved overrides overlaid onto its /// readout so `render_device_body` displays the profile's exact settings 1:1. fn tile_with_profile(tile: &Tile, profile: &crate::profiles::GameProfile) -> Tile { let mut copy = tile.clone(); let TileStatus::Connected(r) = &mut copy.status else { return copy; }; if let Some(dpi) = profile.dpi { r.dpi = Some(dpi); } if let Some(dpi_y) = profile.dpi_y { r.dpi_y = Some(dpi_y); } if let Some(hz) = profile.polling { r.polling_hz = Some(hz as f64); } if let Some(lod) = &profile.lod { r.lod = Some(lod.clone()); } if let Some(surface) = &profile.surface { r.surface = Some(surface.clone()); } for control in r.tabs.controls_mut() { if let Some(val) = profile.controls.get(&control.id) { control.current = val.clone(); } } if let (Some(spec), Some(obj)) = (&mut r.tabs.lighting, profile.lighting.as_ref().and_then(|v| v.as_object())) { if let Some(m) = obj.get("mode").and_then(|v| v.as_str()) { spec.mode = Some(m.to_string()); } if let Some(c) = obj.get("color").and_then(|v| v.as_str()) { spec.color = Some(c.to_string()); } if let Some(c2) = obj.get("color2").and_then(|v| v.as_str()) { spec.color2 = Some(c2.to_string()); } if let Some(s) = obj.get("speed").and_then(|v| v.as_f64()) { spec.speed = Some(s); } } if let Some(mag) = &mut r.tabs.magnetic { let apply_mag = |buttons: &mut [crate::hid::MagneticButton], field: &str, target: &str, val: &serde_json::Value| { let indices: Vec = match target { "both" => (0..buttons.len()).collect(), other => other.parse::().ok().filter(|&i| i < buttons.len()).into_iter().collect(), }; for i in indices { let b = &mut buttons[i]; match field { "switch" => b.switch_type = val.as_str().map(str::to_string), "trigger" => b.trigger_point = val.as_i64(), "release" => b.release_point = val.as_i64(), "rtOn" => { if let Some(on) = val.as_bool() { b.rapid_trigger_enabled = on; } } "rt" => b.rapid_trigger = val.as_i64(), _ => {} } } }; // Apply `both` overrides first so per-button (`0`/`1`) overrides win on top. for pass_both in [true, false] { for (id, val) in &profile.controls { let Some(rest) = id.strip_prefix("mag.") else { continue }; let Some((field, target)) = rest.split_once('.') else { continue }; if (target == "both") == pass_both { apply_mag(&mut mag.buttons, field, target, val); } } } } copy } pub(super) struct ProfileOverride { pub(super) game_id: String, pub(super) game_name: String, /// The device the profile was applied to (and will be restored on). pub(super) device: String, } impl AppView { /// Returns `(game_id, device_key)` when the Games profile editor is active, /// so device controls route edits into the profile instead of hardware. pub(super) fn editing_profile(&self) -> Option<(String, String)> { if self.page != Page::Games { return None; } let game_id = self.profile_editor.clone()?; let device = self.devices.tiles.get(self.profile_target()?)?.key.clone(); Some((game_id, device)) } /// Seeds a `LightEdit` from a game profile's saved lighting override (or the /// device's current lighting). pub(super) fn profile_light_edit( &self, game_id: &str, device: &str, spec: &crate::hid::LightingSpec, ) -> LightEdit { let obj = self .profile_for(game_id, device) .and_then(|p| p.lighting) .and_then(|v| v.as_object().cloned()); LightEdit { mode: obj .as_ref() .and_then(|o| o.get("mode")) .and_then(|v| v.as_str()) .map(str::to_string) .or_else(|| spec.mode.clone()), color: obj .as_ref() .and_then(|o| o.get("color")) .and_then(|v| v.as_str()) .map(str::to_string) .or_else(|| spec.color.clone()), color2: obj .as_ref() .and_then(|o| o.get("color2")) .and_then(|v| v.as_str()) .map(str::to_string) .or_else(|| spec.color2.clone()), speed: obj .as_ref() .and_then(|o| o.get("speed")) .and_then(|v| v.as_f64()) .or(spec.speed), } } pub(crate) fn apply_game_updates( &mut self, updates: &[crate::game_watcher::GameUpdate], cx: &mut Context, ) { // Edges, found by comparing with what was known before this batch. let mut started = Vec::new(); let mut closed = Vec::new(); for update in updates { let Some(running) = update.running else { continue }; let was = self.games.iter().find(|g| g.id == update.id).map(|g| g.running); match (was, running) { (Some(false), true) => started.push(update.id.clone()), (Some(true), false) => closed.push(update.id.clone()), _ => {} } } if crate::game_watcher::apply_updates(&mut self.games, updates) { cx.notify(); self.refresh_presence(cx); } for id in closed { self.on_game_closed(&id, cx); } for id in started { self.on_game_started(&id, cx); } } // ── toasts ─────────────────────────────────────────────────────────── /// The device that inherits a profile saved before profiles were per-device: /// the first mouse-like (has a DPI) connected one. pub(super) fn legacy_heir(&self) -> Option { self.connected_devices().into_iter().find(|(_, r)| r.dpi.is_some()).map(|(k, _)| k) } /// The profile a game has for this device (its own, or the inherited legacy one). pub(super) fn profile_for(&self, game_id: &str, device: &str) -> Option { let heir = self.legacy_heir().as_deref() == Some(device); self.profiles.effective(game_id, device, heir).cloned() } pub(super) fn game_name(&self, id: &str) -> String { self.games.iter().find(|g| g.id == id).map(|g| g.name.clone()).unwrap_or_else(|| id.to_string()) } /// A game launched: announce profiles that don't auto-apply, and apply the /// ones that do. pub(super) fn on_game_started(&mut self, id: &str, cx: &mut Context) { let notice = self .connected_devices() .iter() .filter_map(|(key, _)| self.profile_for(id, key)) .find(|p| p.is_meaningful() && !p.auto_apply) .map(|p| p.describe()); if let Some(described) = notice { let text = format!("\"{}\" has a profile ({described}). Apply it from the Games page.", self.game_name(id)); self.announce(text, false, true, cx); } self.sync_running_profiles(cx); } /// Applies every auto-apply profile that should be in force: for each game /// that is running and each connected device, unless that pair is already /// applied or being applied. Safe to call whenever a game starts or a /// device connects - a device that shows up after the game launched is /// picked up here too. pub(super) fn sync_running_profiles(&mut self, cx: &mut Context) { self.sync_profiles(None, cx); } fn sync_profiles(&mut self, closed: Option<&str>, cx: &mut Context) { let running: Vec = self.games.iter().filter(|g| g.running).map(|g| g.id.clone()).collect(); let devices: Vec = self.connected_devices().into_iter().map(|(k, _)| k).collect(); for game in running { for device in &devices { let Some(profile) = self.profile_for(&game, device) else { continue }; if !profile.auto_apply || !profile.is_meaningful() { continue; } let pair = (game.clone(), device.clone()); let taken = self.profile_overrides.iter().any(|o| o.game_id == game && &o.device == device); if taken || self.profile_inflight.contains(&pair) || self.profile_inflight.contains(&(String::new(), device.clone())) { continue; } self.apply_profile(&game, device, profile, true, cx); } } let restores = crate::profiles::restores(); for device in devices { let Some(restore) = restores.get(&device) else { continue }; if self.profile_overrides.iter().any(|o| o.device == device) || self.profile_inflight.iter().any(|(_, d)| d == &device) { continue; } if !restore.is_meaningful() { crate::profiles::set_restore(&device, None); continue; } let described = restore.describe(); let text = match closed { Some(name) => format!("{name} closed - restored your default {described}."), None => format!("Restored your default {described}."), }; self.profile_inflight.push((String::new(), device.clone())); self.apply_profile_inner("", closed.unwrap_or("default"), &device, restore.clone(), None, Some(text), true, cx); } } /// The game closed: put back what each of its profiles replaced. pub(super) fn on_game_closed(&mut self, id: &str, cx: &mut Context) { self.profile_overrides.retain(|o| o.game_id != id); let name = self.game_name(id); self.sync_profiles(Some(&name), cx); } /// Pushes a profile to one connected device. `auto` marks a launch-triggered /// apply, which remembers the pre-game settings to restore on close. pub(super) fn apply_profile(&mut self, game_id: &str, device: &str, profile: crate::profiles::GameProfile, auto: bool, cx: &mut Context) { let wants_buttons = auto && profile.controls.keys().any(|id| id.starts_with(ONBOARD_BUTTON)); if !wants_buttons { return self.apply_profile_with(game_id, device, profile, auto, None, cx); } let selected = self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.key == device); if let Some(list) = self.onboard().filter(|_| selected) { let buttons = onboard_buttons(list); return self.apply_profile_with(game_id, device, profile, auto, Some(buttons), cx); } let pair = (game_id.to_string(), device.to_string()); self.profile_inflight.push(pair.clone()); let read = self.hid_service().onboard_profiles(device); let (game_id, device) = pair.clone(); cx.spawn(async move |view, cx| { let buttons = read.await.ok().and_then(Result::ok).map(|list| onboard_buttons(&list)); let _ = view.update(cx, |v: &mut Self, cx| { v.profile_inflight.retain(|p| p != &pair); if !v.games.iter().any(|g| g.id == game_id && g.running) { v.sync_running_profiles(cx); return; } v.apply_profile_with(&game_id, &device, profile, auto, buttons, cx); }); }) .detach(); } fn apply_profile_with( &mut self, game_id: &str, device: &str, profile: crate::profiles::GameProfile, auto: bool, buttons: Option>, cx: &mut Context, ) { let Some(r) = self.connected_devices().into_iter().find(|(k, _)| k == device).map(|(_, r)| r) else { self.announce("Connect this device to apply a profile.".into(), true, auto, cx); return; }; let name = self.game_name(game_id); let described = profile.describe(); let override_ = if auto { let snapshot = { let mut controls = std::collections::BTreeMap::new(); for id in profile.controls.keys() { if let Some(spec) = r.tabs.controls().find(|c| &c.id == id) { if !spec.current.is_null() { controls.insert(id.clone(), spec.current.clone()); } } else if let (Some(rest), Some(mag)) = (id.strip_prefix("mag."), &r.tabs.magnetic) { if let Some((field, target)) = rest.split_once('.') { let indices: Vec = match target { "both" => (0..mag.buttons.len()).collect(), other => other.parse::().ok().filter(|&i| i < mag.buttons.len()).into_iter().collect(), }; for i in indices { let b = &mag.buttons[i]; let val = match field { "switch" => b.switch_type.as_ref().map(|s| serde_json::json!(s)), "trigger" => b.trigger_point.map(|v| serde_json::json!(v)), "release" => Some(b.release_point.map_or(serde_json::Value::Null, |v| serde_json::json!(v))), "rtOn" => Some(serde_json::json!(b.rapid_trigger_enabled)), "rt" => b.rapid_trigger.map(|v| serde_json::json!(v)), _ => None, }; if let Some(v) = val { controls.insert(format!("mag.{field}.{i}"), v); } } } } } for (id, action) in buttons.into_iter().flatten() { if profile.controls.contains_key(&id) { controls.entry(id).or_insert(action); } } let lighting = profile .lighting .as_ref() .and_then(|_| r.tabs.lighting.as_ref().and_then(snapshot_lighting)); crate::profiles::GameProfile { dpi: profile.dpi.and(r.dpi), dpi_y: profile.dpi_y.and(r.dpi_y.or(r.dpi)), polling: profile.polling.and(r.polling_hz.map(|hz| hz as u32)), lod: profile.lod.as_ref().and(r.lod.clone()), surface: profile.surface.as_ref().and(r.surface.clone()), controls, lighting, auto_apply: false, } }; let restore = match crate::profiles::restores().remove(device) { Some(saved) => saved.or(&snapshot), None => snapshot, }; if restore.is_meaningful() { crate::profiles::set_restore(device, Some(restore)); } Some(ProfileOverride { game_id: game_id.to_string(), game_name: name.clone(), device: device.to_string() }) } else { None }; if auto { self.profile_inflight.push((game_id.to_string(), device.to_string())); } self.apply_profile_inner(game_id, &name, device, profile, override_, Some(format!("Applied \"{name}\" profile - {described}.")), auto, cx); } pub(super) fn apply_profile_inner( &mut self, game_id: &str, name: &str, device: &str, profile: crate::profiles::GameProfile, override_: Option, success: Option, overlay: bool, cx: &mut Context, ) { let (game_id, name, key) = (game_id.to_string(), name.to_string(), device.to_string()); let service = self.hid_service(); cx.spawn(async move |view, cx| { let result = service.apply_profile(&key, profile.to_js()).await; let _ = view.update(cx, |v: &mut Self, cx| { v.profile_inflight.retain(|(g, d)| !(g == &game_id && d == &key)); let restoring = game_id.is_empty(); let running = v.games.iter().any(|g| g.id == game_id && g.running); let orphaned = override_.is_some() && !running; let restored = restoring && matches!(result, Ok(Ok(_))); match result { Ok(Ok(applied)) => { for (field, action) in [ ("dpi", "dpi"), ("pollingRateHz", "pollingRate"), ("liftOffDistance", "liftOff"), ("gamingSurfaceMode", "surface"), ] { if let Some(value) = applied.get(field) { v.patch_readout(&key, action, value, cx); } } // Only take over once the write is confirmed to have landed. if let Some(o) = override_.filter(|_| running) { v.profile_overrides.push(o); } if restoring { crate::profiles::set_restore(&key, None); } if let Some(text) = success { v.announce(text, false, overlay, cx); } v.refresh_presence(cx); cx.notify(); } Ok(Err(error)) => { let problem = crate::write_safety::problem(&error); v.announce(format!("Couldn't apply \"{name}\" profile. {problem}"), true, overlay, cx); } Err(_) => { let problem = crate::write_safety::problem("device runtime stopped"); v.announce(format!("Couldn't apply \"{name}\" profile. {problem}"), true, overlay, cx); } } if orphaned || restored { if key.starts_with("mock:") { v.sync_running_profiles(cx); } else { v.devices.sync_after_read.insert(key.clone()); } } v.read_back(&key, Vec::new(), cx); }); }) .detach(); } /// Edits (and persists) one game's profile for one device. pub(super) fn edit_profile(&mut self, game_id: &str, device: &str, change: impl FnOnce(&mut crate::profiles::GameProfile), cx: &mut Context) { let mut profile = self.profile_for(game_id, device).unwrap_or_default(); change(&mut profile); let heir = self.legacy_heir().as_deref() == Some(device); self.profiles.set(game_id, device, profile, heir); self.profiles.save(); cx.notify(); } /// The device the profile screen is editing: the one picked, else the first /// connected, else the first listed. pub(super) fn profile_target(&self) -> Option { let tiles = &self.devices.tiles; self.profile_device .as_ref() .and_then(|key| tiles.iter().position(|t| &t.key == key)) .or_else(|| tiles.iter().position(|t| matches!(t.status, TileStatus::Connected(_)))) .or(if tiles.is_empty() { None } else { Some(0) }) } /// One game's device profile: renders the exact 1:1 Devices page UI for the /// selected device, saving every edit into the game's profile instead of /// writing live to hardware. pub(super) fn render_profile_editor( &self, game_id: &str, view_width: f32, view_height: f32, cx: &mut Context, ) -> AnyElement { let fg = cx.theme().foreground; let muted = cx.theme().muted_foreground; let border = Hsla { a: 0.55, ..cx.theme().border }; let name = self.game_name(game_id); let target = self.profile_target(); let game = self.games.iter().find(|g| g.id == game_id); let custom = game.is_some_and(|g| g.custom); let art: AnyElement = if custom { match crate::games::custom::icon_path(game_id).filter(|p| p.is_file()) { Some(path) => img(path).size(px(44.)).rounded_md().flex_none().into_any_element(), None => div() .size(px(44.)) .rounded_md() .flex_none() .flex() .items_center() .justify_center() .bg(Hsla { a: 0.14, ..cx.theme().primary }) .text_base() .font_weight(FontWeight::SEMIBOLD) .text_color(cx.theme().primary) .child(game.map(|g| g.mark().to_string()).unwrap_or_else(|| "?".into())) .into_any_element(), } } else { match game.and_then(crate::games::card_art_path) { Some(path) => img(path) .w(px(44.)) .h(px(58.)) .rounded_md() .object_fit(ObjectFit::Cover) .flex_none() .into_any_element(), None => div() .w(px(44.)) .h(px(58.)) .rounded_md() .flex_none() .flex() .items_center() .justify_center() .bg(Hsla { a: 0.14, ..cx.theme().primary }) .text_base() .font_weight(FontWeight::SEMIBOLD) .text_color(cx.theme().primary) .child(game.map(|g| g.mark().to_string()).unwrap_or_else(|| "?".into())) .into_any_element(), } }; let target_tile = target.and_then(|i| self.devices.tiles.get(i)); let active_profile = target_tile .map(|t| self.profile_for(game_id, &t.key).unwrap_or_default()) .unwrap_or_default(); let program = custom .then(|| game.and_then(|g| g.executables.first().cloned())) .flatten() .filter(|s| !s.is_empty()); let subtitle = match (program, active_profile.is_meaningful()) { (Some(exe), true) => format!("{exe} · {}", active_profile.describe()), (Some(exe), false) => exe, (None, true) => active_profile.describe(), (None, false) => "No overrides yet".to_string(), }; let mut toolbar = h_flex() .gap_2p5() .items_center() .flex_none() .px_3() .py_1p5() .rounded_xl() .border_1() .border_color(border) .bg(cx.theme().sidebar); let mut has_toolbar = false; if let Some(tile) = target_tile { if matches!(tile.status, TileStatus::Connected(_)) { has_toolbar = true; let device = tile.key.clone(); let (gid_auto, dev_auto) = (game_id.to_string(), device.clone()); let (gid_apply, dev_apply, applying) = (game_id.to_string(), device.clone(), active_profile.clone()); let (gid_clear, dev_clear) = (game_id.to_string(), device.clone()); toolbar = toolbar .child( h_flex() .gap_2() .items_center() .child(div().text_xs().font_weight(FontWeight::MEDIUM).text_color(fg).child("Auto-apply")) .child( Switch::new("profile-auto") .checked(active_profile.auto_apply) .on_change(cx.listener(move |this, on: &bool, _, cx| { let on = *on; this.edit_profile(&gid_auto, &dev_auto, |p| p.auto_apply = on, cx) })), ), ) .child(div().w(px(1.)).h(px(18.)).bg(border)) .child( Button::new("profile-apply") .primary() .compact() .label("Apply now") .disabled(!active_profile.is_meaningful()) .on_click(cx.listener(move |this, _, _, cx| { if applying.is_meaningful() { this.apply_profile(&gid_apply, &dev_apply, applying.clone(), false, cx); } })), ) .when(active_profile.is_meaningful(), |row| { row.child( Button::new("profile-clear") .compact() .label("Clear") .on_click(cx.listener(move |this, _, _, cx| { this.ask_before_clearing_profile(&gid_clear, &dev_clear, cx); })), ) }); } } if custom { has_toolbar = true; let gid_remove = game_id.to_string(); toolbar = toolbar.child( Button::new("custom-remove") .compact() .label("Remove") .on_click(cx.listener(move |this, _, _, cx| this.ask_before_removing_game(&gid_remove, cx))), ); } let header = h_flex() .gap_3() .items_center() .justify_between() .child( h_flex() .gap_3() .items_center() .min_w_0() .child( Button::new("profile-back") .ghost() .icon(IconName::ArrowLeft) .tooltip("Back to games") .accessibility_label("Back to games") .on_click(cx.listener(|this, _, _, cx| { this.profile_editor = None; this.control_sliders.clear(); this.slider_live.clear(); cx.notify(); })), ) .child(art) .child( div() .flex() .flex_col() .min_w_0() .child(self.render_profile_title(game_id, name, cx)) .child(div().text_xs().text_color(muted).truncate().child(subtitle)), ), ) .when(has_toolbar, |row| row.child(toolbar)); // Device picker: only shown when there are multiple devices to choose from. let picker: Option = (self.devices.tiles.len() > 1).then(|| { let mut row = segmented(cx); for (i, tile) in self.devices.tiles.iter().enumerate() { let key = tile.key.clone(); let has_profile = self.profiles.get(game_id, &tile.key).is_some_and(|p| p.is_meaningful()); let label = match (tile.name.as_str(), tile.display_brand.as_str()) { ("", "") => "Unknown device".to_string(), ("", brand) => format!("{brand} device"), (name, _) => name.to_string(), }; row = row.child(self.chip( format!("pf-device-{}", tile.key), if has_profile { format!("{label} ●") } else { label }, target == Some(i), cx, move |this, cx| { this.profile_device = Some(key.clone()); this.control_sliders.clear(); this.slider_live.clear(); if let Some(t) = this.devices.tiles.iter().find(|t| t.key == key) { if matches!(t.status, TileStatus::Idle | TileStatus::Failed(_)) { this.connect_tile(&key, false, cx); } } cx.notify(); }, )); } h_flex().child(row).into_any_element() }); let body: AnyElement = match target_tile { None => div() .text_sm() .text_color(muted) .child("No device found. Connect a mouse and it will appear here.") .into_any_element(), Some(tile) => { let virtual_tile = tile_with_profile(tile, &active_profile); self.render_device_body(&virtual_tile, view_width, view_height, true, cx) } }; div() .relative() .flex() .flex_col() .size_full() .p_4() .gap_4() .overflow_hidden() .child(header) .children(picker) .child(body) // The device body's button rows open their picker here too. .children(self.render_button_modal(cx)) .into_any_element() } } const ONBOARD_BUTTON: &str = "logi.button.primary."; fn onboard_buttons(list: &crate::hid::OnboardProfiles) -> std::collections::BTreeMap { let Some(running) = list.profiles.iter().find(|p| p.is_current) else { return Default::default() }; running .button_assignments .iter() .enumerate() .filter_map(|(n, a)| a.get("action").and_then(|v| v.as_str()).filter(|a| *a != "Custom").map(|a| (format!("{ONBOARD_BUTTON}{n}"), serde_json::json!(a)))) .collect() }