//! The macro editor on a mouse's Buttons tab: record key presses, then store //! them on the mouse. `js/macros.ts` says what each mouse allows. use super::*; use super::widgets::panel; use crate::hid::MacroPanel; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; const DELAYS: [u32; 5] = [10, 20, 50, 100, 250]; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub(super) struct Step { key: String, down: bool, delay: u32, } #[derive(Default)] pub(super) struct MacroEditor { slot: i64, button: Option, steps: Vec, /// The delay given to steps as they are recorded; the second of `DELAYS` /// until chosen. delay: Option, pub(super) recorder: Option, busy: bool, /// Waiting for a second press, for a save that erases other macros. confirming: bool, error: Option, round: u64, } impl MacroEditor { pub(super) fn reset(&mut self) { *self = MacroEditor { round: self.round + 1, recorder: self.recorder.take(), ..Default::default() }; } fn delay(&self) -> u32 { self.delay.unwrap_or(DELAYS[1]) } /// One press and release of `key`, with the held modifiers around it. fn record(&mut self, key: &str, modifiers: &[&str], most: usize) { let delay = self.delay(); let step = |key: &str, down: bool| Step { key: key.to_string(), down, delay }; let mut new: Vec = modifiers.iter().map(|m| step(m, true)).collect(); new.push(step(key, true)); new.push(step(key, false)); new.extend(modifiers.iter().rev().map(|m| step(m, false))); if self.steps.len() + new.len() > most { self.error = Some(format!("This macro is full: it holds {most} steps.")); return; } self.error = None; self.confirming = false; self.steps.extend(new); } } impl AppView { pub(super) fn ensure_macro_recorder(&mut self, cx: &mut Context) { if self.macros.recorder.is_none() { self.macros.recorder = Some(cx.focus_handle()); } } fn macro_run(&mut self, op: &'static str, args: Value, cx: &mut Context) { let Some(key) = self.devices.open.clone() else { return }; if self.macros.busy { return; } self.macros.busy = true; self.macros.confirming = false; self.macros.error = None; let round = self.macros.round; let service = self.hid_service(); cx.notify(); cx.spawn(async move |view, cx| { let answer = service.macros(&key, op, args).await; let _ = view.update(cx, |v: &mut Self, cx| { if v.macros.round != round { return; } v.macros.busy = false; match answer { Ok(Ok(value)) if op == "read" => match serde_json::from_value(value) { Ok(steps) => v.macros.steps = steps, Err(error) => v.macros.error = Some(error.to_string()), }, Ok(Ok(_)) => v.show_toast("Macro saved.", false, cx), Ok(Err(error)) => v.macros.error = Some(crate::write_safety::problem(&error)), Err(_) => v.macros.error = Some("device runtime stopped".to_string()), } cx.notify(); }); }) .detach(); } pub(super) fn render_macros(&self, spec: &MacroPanel, cx: &mut Context) -> Div { let (fg, muted, accent) = (cx.theme().foreground, cx.theme().muted_foreground, cx.theme().primary); let slot = self.macros.slot; let device = if self.devices.tiles.get(self.devices.selected).is_some_and(|t| t.keyboard) { "keyboard" } else { "mouse" }; let button = self.macros.button.or_else(|| spec.buttons.first().map(|b| b.value)).unwrap_or(0); let note = |text: String| div().text_xs().text_color(muted).child(text); let label = |text: &'static str| div().text_xs().text_color(muted).child(text); let mut card = panel(cx) .child(super::device_overview::card_title("Macros", cx)) .child(note(spec.note.clone())); if !spec.slots.is_empty() { let mut slots = segmented(cx); for choice in &spec.slots { let value = choice.value; // Just the number where there are many. let text = if spec.slots.len() > 6 { (value + 1).to_string() } else { choice.label.clone() }; slots = slots.child(self.chip(format!("macro-slot-{value}"), text, slot == value, cx, move |this, cx| { this.macros.slot = value; this.macros.steps.clear(); this.macros.confirming = false; this.macros.error = None; cx.notify(); })); } card = card.child(label("Macro")).child(h_flex().child(slots)); } if !spec.buttons.is_empty() { let mut buttons = segmented(cx); for choice in &spec.buttons { let value = choice.value; buttons = buttons.child(self.chip( format!("macro-button-{value}"), choice.label.clone(), button == value, cx, move |this, cx| { this.macros.button = Some(value); cx.notify(); }, )); } card = card.child(label("Button")).child(h_flex().child(buttons)); } let mut delays = segmented(cx); for ms in DELAYS { delays = delays.child(self.chip(format!("macro-delay-{ms}"), format!("{ms} ms"), self.macros.delay() == ms, cx, move |this, cx| { this.macros.delay = Some(ms); cx.notify(); })); } card = card.child(label("Delay for new steps")).child(h_flex().child(delays)); let (most, modifiers) = (spec.max_steps, spec.modifiers); if let Some(handle) = self.macros.recorder.clone() { let focus = handle.clone(); card = card.child( div() .id("macro-recorder") .track_focus(&handle) .px_3() .py_3() .rounded_md() .border_1() .border_color(cx.theme().border) .focus(move |style| style.border_color(accent)) .cursor_pointer() .text_sm() .text_color(muted) .child("Click here, then type. Each key is added as a press and a release.") .on_click(cx.listener(move |_, _, window, cx| window.focus(&focus, cx))) .on_key_down(cx.listener(move |this, event: &KeyDownEvent, _, cx| { cx.stop_propagation(); let Some(text) = super::receiver_panel::combination(&event.keystroke) else { return }; let mut parts: Vec<&str> = text.trim_start_matches("Keyboard: ").split('+').collect(); let Some(key) = parts.pop() else { return }; if !modifiers && !parts.is_empty() { this.macros.error = Some("This mouse's macros can't hold Ctrl, Shift, Alt or Win.".to_string()); } else { this.macros.record(key, &parts, most); } cx.notify(); })), ); } if spec.mouse { let mut clicks = h_flex().gap_1().flex_wrap(); for name in ["Left", "Right", "Middle", "Back", "Forward"] { clicks = clicks.child(self.chip(format!("macro-click-{name}"), format!("+ {name} click"), false, cx, move |this, cx| { this.macros.record(&format!("Mouse {name}"), &[], most); cx.notify(); })); } card = card.child(clicks); } let mut steps = h_flex().gap_1().flex_wrap(); for step in &self.macros.steps { let arrow = if step.down { "↓" } else { "↑" }; steps = steps.child( div() .px_2() .py_0p5() .rounded_md() .bg(Hsla { a: 0.08, ..fg }) .text_xs() .child(format!("{arrow} {} · {} ms", step.key, step.delay)), ); } card = card.child(note(format!("{} of {most} steps", self.macros.steps.len()))).child(steps); let empty = self.macros.steps.is_empty(); let busy = self.macros.busy; let small = |id: &'static str, text: &'static str, enabled: bool| { Button::new(id).compact().ghost().label(text).disabled(!enabled) }; let mut actions = h_flex() .gap_2() .justify_end() .child(small("macro-undo", "Remove last", !empty).on_click(cx.listener(|this, _, _, cx| { this.macros.steps.pop(); cx.notify(); }))) .child(small("macro-clear", "Clear", !empty).on_click(cx.listener(|this, _, _, cx| { this.macros.steps.clear(); cx.notify(); }))); if spec.readable { actions = actions.child(small("macro-read", if device == "keyboard" { "Read from keyboard" } else { "Read from mouse" }, !busy).on_click(cx.listener(move |this, _, _, cx| { this.macro_run("read", json!({ "slot": slot, "button": button }), cx) }))); } let warns = spec.warning.is_some(); let confirming = self.macros.confirming; actions = actions.child( Button::new("macro-save") .compact() .label(if confirming { "Erase the others and save" } else if device == "keyboard" { "Save to keyboard" } else { "Save to mouse" }) .disabled(busy) .on_click(cx.listener(move |this, _, _, cx| { if warns && !this.macros.confirming { this.macros.confirming = true; cx.notify(); } else { let args = json!({ "slot": slot, "button": button, "steps": this.macros.steps }); this.macro_run("save", args, cx); } })), ); if confirming { card = card.children(spec.warning.clone().map(|w| div().text_sm().text_color(cx.theme().danger).child(w))); } card = card.child(actions); if busy { card = card.child(note("Working…".to_string())); } card.children(self.macros.error.clone().map(|e| div().text_sm().text_color(cx.theme().danger).child(e))) } } #[cfg(test)] mod tests { use super::MacroEditor; #[test] fn a_recorded_combination_wraps_the_key_in_its_modifiers() { let mut editor = MacroEditor::default(); editor.record("C", &["Ctrl", "Shift"], 30); let shape: Vec<(String, bool)> = editor.steps.iter().map(|s| (s.key.clone(), s.down)).collect(); let want = [("Ctrl", true), ("Shift", true), ("C", true), ("C", false), ("Shift", false), ("Ctrl", false)]; assert_eq!(shape, want.map(|(k, d)| (k.to_string(), d))); assert!(editor.steps.iter().all(|s| s.delay == 20)); } #[test] fn a_full_macro_refuses_more_rather_than_cutting_a_key_in_half() { let mut editor = MacroEditor::default(); editor.record("A", &[], 3); editor.record("B", &[], 3); assert_eq!(editor.steps.len(), 2); assert!(editor.error.is_some()); } }