| 1 | //! `budctl-gui`: control wireless earbuds from Linux, in a window. |
| 2 | //! |
| 3 | //! A thin layer over budctl-core, like the CLI: `worker.rs` talks to the buds on a thread of its |
| 4 | //! own, and the window shows what they report. The mouse comes first; vim-like keys work on top |
| 5 | //! (`keys.rs`). `--demo` shows made-up buds instead. |
| 6 | |
| 7 | mod buds; |
| 8 | mod earbuds; |
| 9 | mod equalizer; |
| 10 | mod gestures; |
| 11 | mod icons; |
| 12 | mod keys; |
| 13 | mod overview; |
| 14 | mod settings; |
| 15 | mod theme; |
| 16 | mod ui; |
| 17 | mod worker; |
| 18 | |
| 19 | use std::collections::VecDeque; |
| 20 | use std::path::PathBuf; |
| 21 | use std::process::ExitCode; |
| 22 | use std::sync::mpsc::Sender; |
| 23 | use std::time::{Duration, Instant}; |
| 24 | |
| 25 | use budctl_core::Kind; |
| 26 | use budctl_core::bt::BdAddr; |
| 27 | use budctl_core::status::{AncLevel, EqBand, EqPreset, NoiseControl, NoiseMode, Switch}; |
| 28 | use iced::keyboard::{self, Key, Modifiers}; |
| 29 | use iced::widget::operation::{self, RelativeOffset}; |
| 30 | use iced::widget::{Column, column, container, mouse_area, opaque, row, scrollable, space, stack, text, text_input}; |
| 31 | use iced::{Alignment, Border, Color, Element, Font, Length, Size, Subscription, Task, Theme, event, mouse, window}; |
| 32 | |
| 33 | use icons::Icon; |
| 34 | use keys::Action; |
| 35 | use theme::Look; |
| 36 | use worker::{Command, Event, Reading}; |
| 37 | |
| 38 | const USAGE: &str = "usage: budctl-gui [--device <MAC>] [--theme <palette.json>] [--demo] [--debug] |
| 39 | |
| 40 | --device picks the buds when more than one supported pair is connected. |
| 41 | --demo shows made-up buds, without Bluetooth. |
| 42 | --debug hex-dumps every frame sent and received on stderr, as budctl --debug does. |
| 43 | Colors come from --theme, else from ~/.config/budctl/theme.json if it exists, else built in. |
| 44 | The palette file takes the keys of a matugen palette like Aurora's (bg, fg, primary, …). |
| 45 | Press ? in the window for the keys."; |
| 46 | |
| 47 | /// The page's scrolling area, so the cursor can be kept in view. |
| 48 | const SCROLL: &str = "page"; |
| 49 | /// The name field of the preset-name dialog, so it can take the keyboard. |
| 50 | const NAME_INPUT: &str = "name"; |
| 51 | |
| 52 | /// When the window gets focus and the last reading is older than this, the buds are read again: |
| 53 | /// the phone may have changed something meanwhile. |
| 54 | const STALE: Duration = Duration::from_secs(30); |
| 55 | |
| 56 | fn main() -> ExitCode { |
| 57 | let options = match parse_args(std::env::args().skip(1)) { |
| 58 | Ok(Args::Run(options)) => options, |
| 59 | Ok(Args::Help) => { |
| 60 | println!("{USAGE}"); |
| 61 | return ExitCode::SUCCESS; |
| 62 | } |
| 63 | Err(message) => { |
| 64 | eprintln!("budctl-gui: {message}\n{USAGE}"); |
| 65 | return ExitCode::from(1); |
| 66 | } |
| 67 | }; |
| 68 | if options.debug { |
| 69 | budctl_core::debug::enable(); |
| 70 | } |
| 71 | let theme_file = options.theme.clone().or_else(theme::default_file); |
| 72 | let font = theme::system_font(); |
| 73 | let boot = move || App::new(theme_file.clone(), font, options.device, options.demo); |
| 74 | let result = iced::application(boot, App::update, App::view) |
| 75 | .title("budctl") |
| 76 | .theme(App::theme) |
| 77 | .subscription(App::subscription) |
| 78 | .default_font(font) |
| 79 | .window(window::Settings { |
| 80 | size: Size::new(1040.0, 800.0), |
| 81 | min_size: Some(Size::new(760.0, 540.0)), |
| 82 | platform_specific: window::settings::PlatformSpecific { |
| 83 | application_id: "budctl".to_owned(), |
| 84 | ..window::settings::PlatformSpecific::default() |
| 85 | }, |
| 86 | ..window::Settings::default() |
| 87 | }) |
| 88 | .run(); |
| 89 | match result { |
| 90 | Ok(()) => ExitCode::SUCCESS, |
| 91 | Err(e) => { |
| 92 | eprintln!("budctl-gui: {e}"); |
| 93 | ExitCode::FAILURE |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | #[derive(Default)] |
| 99 | struct Options { |
| 100 | theme: Option<PathBuf>, |
| 101 | device: Option<BdAddr>, |
| 102 | demo: bool, |
| 103 | debug: bool, |
| 104 | } |
| 105 | |
| 106 | enum Args { |
| 107 | Run(Options), |
| 108 | Help, |
| 109 | } |
| 110 | |
| 111 | fn parse_args(mut args: impl Iterator<Item = String>) -> Result<Args, String> { |
| 112 | let mut options = Options::default(); |
| 113 | while let Some(arg) = args.next() { |
| 114 | match arg.as_str() { |
| 115 | "--theme" => options.theme = Some(PathBuf::from(args.next().ok_or("--theme needs a file")?)), |
| 116 | "--device" => { |
| 117 | let address = args.next().ok_or("--device needs an address")?; |
| 118 | options.device = Some(address.parse().map_err(|e| format!("--device: {e}"))?); |
| 119 | } |
| 120 | "--demo" => options.demo = true, |
| 121 | "--debug" => options.debug = true, |
| 122 | "-h" | "--help" => return Ok(Args::Help), |
| 123 | other => return Err(format!("unknown argument {other:?}")), |
| 124 | } |
| 125 | } |
| 126 | Ok(Args::Run(options)) |
| 127 | } |
| 128 | |
| 129 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 130 | enum Page { |
| 131 | Overview, |
| 132 | Equalizer, |
| 133 | Gestures, |
| 134 | Earbuds, |
| 135 | Settings, |
| 136 | } |
| 137 | |
| 138 | impl Page { |
| 139 | const ALL: [Page; 5] = [ |
| 140 | Page::Overview, |
| 141 | Page::Equalizer, |
| 142 | Page::Gestures, |
| 143 | Page::Earbuds, |
| 144 | Page::Settings, |
| 145 | ]; |
| 146 | |
| 147 | fn title(self) -> &'static str { |
| 148 | match self { |
| 149 | Page::Overview => "Overview", |
| 150 | Page::Equalizer => "Equalizer", |
| 151 | Page::Gestures => "Gestures", |
| 152 | Page::Earbuds => "Earbud settings", |
| 153 | Page::Settings => "App settings", |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | fn icon(self) -> Icon { |
| 158 | match self { |
| 159 | Page::Overview => Icon::Overview, |
| 160 | Page::Equalizer => Icon::Equalizer, |
| 161 | Page::Gestures => Icon::Gestures, |
| 162 | Page::Earbuds => Icon::Earbud, |
| 163 | Page::Settings => Icon::Settings, |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /// The next page in the sidebar, or the previous one, going round. |
| 168 | fn step(self, forward: bool) -> Page { |
| 169 | let count = Page::ALL.len(); |
| 170 | let at = Page::ALL.iter().position(|&page| page == self).unwrap_or(0); |
| 171 | let to = if forward { at + 1 } else { at + count - 1 }; |
| 172 | Page::ALL.get(to % count).copied().unwrap_or(self) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// What the keyboard cursor can rest on, and what a write changes. |
| 177 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 178 | enum Item { |
| 179 | NoiseMode, |
| 180 | AncLevel, |
| 181 | /// A switch, by its key. |
| 182 | Switch(&'static str), |
| 183 | /// A row that opens a page. |
| 184 | Open(Page), |
| 185 | /// An EQ preset, by its id. |
| 186 | Preset(u8), |
| 187 | /// One band of a custom EQ preset: the preset's id and the band's frequency. |
| 188 | Band(u8, u16), |
| 189 | /// A bud's gesture, by its place among the Gestures page's rows. |
| 190 | Gesture(u8), |
| 191 | /// A mode of the hold cycle, by its place among the modes the buds offer. |
| 192 | Cycle(u8), |
| 193 | /// Find my earbuds. |
| 194 | Find, |
| 195 | /// The bass level. |
| 196 | Bass, |
| 197 | /// "New preset", on the Equalizer page. |
| 198 | NewPreset, |
| 199 | /// "Rename", on a custom EQ preset's card. |
| 200 | Rename(u8), |
| 201 | /// The bin on a custom EQ preset's row. |
| 202 | Delete(u8), |
| 203 | /// The pencil on a custom EQ preset's row: open its bands. |
| 204 | Edit(u8), |
| 205 | /// "Done", on the open bands. |
| 206 | Done, |
| 207 | } |
| 208 | |
| 209 | /// The dialog that asks for a preset's name. |
| 210 | #[derive(Debug, Clone, PartialEq)] |
| 211 | struct NamePrompt { |
| 212 | target: NameTarget, |
| 213 | text: String, |
| 214 | /// What is wrong with the name, after a try. |
| 215 | problem: Option<String>, |
| 216 | } |
| 217 | |
| 218 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 219 | enum NameTarget { |
| 220 | New, |
| 221 | /// A custom preset, by its id. |
| 222 | Rename(u8), |
| 223 | } |
| 224 | |
| 225 | /// What a page needs besides the buds: the item under the keyboard cursor, if it shows, and the |
| 226 | /// items with a write on its way. |
| 227 | #[derive(Clone, Copy)] |
| 228 | struct Marks<'a> { |
| 229 | focus: Option<Item>, |
| 230 | pending: &'a [Item], |
| 231 | } |
| 232 | |
| 233 | /// A gesture's action picked on the screen and not on the buds yet. |
| 234 | #[derive(Debug, Clone, PartialEq)] |
| 235 | struct TouchDraft { |
| 236 | /// The gesture, by its place among the Gestures page's rows. |
| 237 | row: u8, |
| 238 | action: String, |
| 239 | } |
| 240 | |
| 241 | /// Bands of a custom EQ preset moved on the screen and not saved on the buds yet. |
| 242 | #[derive(Debug, Clone, PartialEq)] |
| 243 | struct Draft { |
| 244 | preset: u8, |
| 245 | /// All the preset's bands, as shown. |
| 246 | bands: Vec<EqBand>, |
| 247 | } |
| 248 | |
| 249 | /// Where the connection to the buds stands. |
| 250 | #[derive(Debug, Clone, PartialEq)] |
| 251 | enum Link { |
| 252 | /// Made-up buds (`--demo`): nothing talks to Bluetooth. |
| 253 | Demo, |
| 254 | /// Looking for the buds, or reading them for the first time. |
| 255 | Connecting, |
| 256 | /// The buds answered the last command. |
| 257 | Live, |
| 258 | /// The last command failed. |
| 259 | Failed { kind: Kind, message: String }, |
| 260 | } |
| 261 | |
| 262 | #[derive(Debug, Clone)] |
| 263 | enum Message { |
| 264 | Open(Page), |
| 265 | Noise(NoiseMode), |
| 266 | /// A switch's key, and whether to turn it on. |
| 267 | Switch(&'static str, bool), |
| 268 | /// Select an EQ preset, by its id. |
| 269 | Preset(u8), |
| 270 | /// Move a band of a custom EQ preset. With `save`, save the preset right away, else when |
| 271 | /// [`Message::SaveBands`] comes (the mouse lets go of the slider). |
| 272 | Band { |
| 273 | preset: u8, |
| 274 | hz: u16, |
| 275 | gain: i8, |
| 276 | save: bool, |
| 277 | }, |
| 278 | /// Save the moved bands of a custom EQ preset. |
| 279 | SaveBands(u8), |
| 280 | /// Give a gesture (by its row) an action. With `save`, write it right away. |
| 281 | Action { |
| 282 | row: u8, |
| 283 | action: String, |
| 284 | save: bool, |
| 285 | }, |
| 286 | /// Put a mode (by its place) in the hold cycle, or take it out. |
| 287 | Cycle(u8, bool), |
| 288 | /// Ring the buds (after a confirmation), or stop them ringing. |
| 289 | Find, |
| 290 | /// The answer to "Ring the buds?". |
| 291 | ConfirmFind(bool), |
| 292 | /// Move the bass level. With `save`, set it on the buds right away, else when |
| 293 | /// [`Message::SaveBass`] comes (the mouse lets go of the slider). |
| 294 | Bass { |
| 295 | level: i8, |
| 296 | save: bool, |
| 297 | }, |
| 298 | SaveBass, |
| 299 | /// Ask for a new preset's name. |
| 300 | NewPreset, |
| 301 | /// Ask for a custom preset's (by its id) new name. |
| 302 | RenamePreset(u8), |
| 303 | NameInput(String), |
| 304 | SubmitName, |
| 305 | CancelName, |
| 306 | /// Open a custom preset's (by its id) bands, or close them if they are open. |
| 307 | EditPreset(u8), |
| 308 | /// Close the open bands. |
| 309 | DoneEditing, |
| 310 | /// Delete a custom preset (by its id), after a confirmation. |
| 311 | DeletePreset(u8), |
| 312 | /// The answer to "Delete the preset?". |
| 313 | ConfirmDelete(bool), |
| 314 | ShowHelp, |
| 315 | /// Read the buds again. |
| 316 | Refresh, |
| 317 | Worker(Event), |
| 318 | /// The window got focus: the palette file may have changed meanwhile, and so may the buds. |
| 319 | Focused, |
| 320 | Key(Key, Modifiers), |
| 321 | /// A mouse button went down: the mouse is in use, so the keyboard cursor hides. |
| 322 | Pointer, |
| 323 | CloseHelp, |
| 324 | } |
| 325 | |
| 326 | struct App { |
| 327 | page: Page, |
| 328 | buds: buds::Buds, |
| 329 | /// The level "Noise cancelling" turns on at: the one last reported or picked. |
| 330 | anc_level: AncLevel, |
| 331 | look: Look, |
| 332 | theme: Theme, |
| 333 | palette: theme::Source, |
| 334 | keys: keys::Keys, |
| 335 | /// Where the keyboard cursor is, among [`App::items`]. |
| 336 | cursor: usize, |
| 337 | /// Whether it shows. Only keys show it; a click hides it. |
| 338 | cursor_shown: bool, |
| 339 | /// Whether the list of keys is open. |
| 340 | help: bool, |
| 341 | /// `--device`, for the worker. |
| 342 | device: Option<BdAddr>, |
| 343 | link: Link, |
| 344 | /// Where commands go, once the worker is up. |
| 345 | worker: Option<Sender<Command>>, |
| 346 | /// The commands sent and not answered yet, oldest first: the item each one writes, or `None` |
| 347 | /// for a read. The worker answers them in order. |
| 348 | in_flight: VecDeque<Option<Item>>, |
| 349 | /// When the buds were last read. |
| 350 | read_at: Option<Instant>, |
| 351 | /// Bands moved and not saved yet. |
| 352 | draft: Option<Draft>, |
| 353 | /// A gesture's action picked and not written yet. |
| 354 | touch_draft: Option<TouchDraft>, |
| 355 | /// A bass level moved and not set yet. |
| 356 | bass_draft: Option<i8>, |
| 357 | /// The buds were told to ring and not yet to stop. |
| 358 | ringing: bool, |
| 359 | /// "Ring the buds?" is open. |
| 360 | confirm_find: bool, |
| 361 | /// Why the palette file could not be used, if it could not. |
| 362 | palette_problem: Option<String>, |
| 363 | /// The preset-name dialog, when it is open. |
| 364 | prompt: Option<NamePrompt>, |
| 365 | /// "Delete the preset?" is open, for this preset. |
| 366 | confirm_delete: Option<u8>, |
| 367 | /// The custom preset whose bands are open on the Equalizer page. |
| 368 | editing: Option<u8>, |
| 369 | } |
| 370 | |
| 371 | impl App { |
| 372 | fn new(theme_file: Option<PathBuf>, font: Font, device: Option<BdAddr>, demo: bool) -> Self { |
| 373 | let buds = if demo { buds::demo() } else { buds::unknown() }; |
| 374 | let anc_level = buds |
| 375 | .status |
| 376 | .noise_control |
| 377 | .as_ref() |
| 378 | .and_then(|now| now.level.as_deref()) |
| 379 | .and_then(anc_level) |
| 380 | .unwrap_or(AncLevel::Deep); |
| 381 | let mut app = App { |
| 382 | page: Page::Overview, |
| 383 | buds, |
| 384 | anc_level, |
| 385 | look: Look { |
| 386 | p: theme::BUILT_IN, |
| 387 | font, |
| 388 | }, |
| 389 | theme: theme::iced_theme(&theme::BUILT_IN), |
| 390 | palette: theme::Source::new(theme_file), |
| 391 | keys: keys::Keys::default(), |
| 392 | cursor: 0, |
| 393 | cursor_shown: false, |
| 394 | help: false, |
| 395 | device, |
| 396 | link: if demo { Link::Demo } else { Link::Connecting }, |
| 397 | worker: None, |
| 398 | in_flight: VecDeque::new(), |
| 399 | read_at: None, |
| 400 | draft: None, |
| 401 | touch_draft: None, |
| 402 | bass_draft: None, |
| 403 | ringing: false, |
| 404 | confirm_find: false, |
| 405 | palette_problem: None, |
| 406 | prompt: None, |
| 407 | confirm_delete: None, |
| 408 | editing: None, |
| 409 | }; |
| 410 | app.refresh_palette(); |
| 411 | app |
| 412 | } |
| 413 | |
| 414 | fn update(&mut self, message: Message) -> Task<Message> { |
| 415 | match message { |
| 416 | Message::Open(page) => return self.open(page), |
| 417 | Message::Noise(mode) => self.write(Item::NoiseMode, Command::Noise(mode)), |
| 418 | Message::Switch(key, on) => self.write(Item::Switch(key), Command::Switch(key, on)), |
| 419 | Message::Preset(id) => self.select(id), |
| 420 | Message::Band { preset, hz, gain, save } => { |
| 421 | self.move_band(preset, hz, gain); |
| 422 | if save { |
| 423 | self.save_bands(preset); |
| 424 | } |
| 425 | } |
| 426 | Message::SaveBands(preset) => self.save_bands(preset), |
| 427 | Message::Action { row, action, save } => { |
| 428 | self.touch_draft = Some(TouchDraft { row, action }); |
| 429 | if save { |
| 430 | self.save_touch(row); |
| 431 | } |
| 432 | } |
| 433 | Message::Cycle(mode, on) => self.cycle(mode, on), |
| 434 | Message::Find if self.ringing => self.write(Item::Find, Command::Find(false)), |
| 435 | Message::Find => self.confirm_find = true, |
| 436 | Message::ConfirmFind(ring) => { |
| 437 | self.confirm_find = false; |
| 438 | if ring { |
| 439 | self.write(Item::Find, Command::Find(true)); |
| 440 | } |
| 441 | } |
| 442 | Message::ShowHelp => self.help = true, |
| 443 | Message::Bass { level, save } => { |
| 444 | let (low, high) = self.buds.bass_range.unwrap_or((i8::MIN, i8::MAX)); |
| 445 | self.bass_draft = Some(level.clamp(low, high)); |
| 446 | if save { |
| 447 | self.save_bass(); |
| 448 | } |
| 449 | } |
| 450 | Message::SaveBass => self.save_bass(), |
| 451 | Message::NewPreset => return self.ask_name(NameTarget::New, String::new()), |
| 452 | Message::RenamePreset(id) => { |
| 453 | let name = self.buds.preset(id).map(|p| p.name.clone()).unwrap_or_default(); |
| 454 | return self.ask_name(NameTarget::Rename(id), name); |
| 455 | } |
| 456 | Message::NameInput(text) => { |
| 457 | if let Some(prompt) = &mut self.prompt { |
| 458 | prompt.text = text; |
| 459 | prompt.problem = None; |
| 460 | } |
| 461 | } |
| 462 | Message::SubmitName => self.submit_name(), |
| 463 | Message::CancelName => self.prompt = None, |
| 464 | Message::EditPreset(id) => { |
| 465 | self.editing = if self.editing == Some(id) { None } else { Some(id) }; |
| 466 | } |
| 467 | Message::DoneEditing => self.editing = None, |
| 468 | Message::DeletePreset(id) => self.confirm_delete = Some(id), |
| 469 | Message::ConfirmDelete(yes) => { |
| 470 | if let (true, Some(id)) = (yes, self.confirm_delete.take()) |
| 471 | && let Some(preset) = self.buds.preset(id) |
| 472 | { |
| 473 | let command = Command::DeleteEq(buds::key(preset)); |
| 474 | if self.editing == Some(id) { |
| 475 | self.editing = None; |
| 476 | } |
| 477 | self.write(Item::Preset(id), command); |
| 478 | } |
| 479 | self.confirm_delete = None; |
| 480 | } |
| 481 | Message::Refresh => self.refresh(), |
| 482 | Message::Worker(event) => self.answer(event), |
| 483 | Message::Focused => { |
| 484 | self.refresh_palette(); |
| 485 | // The phone may have changed something, or the buds may be back: read again |
| 486 | // when the reading is old or the last command failed. |
| 487 | let stale = self.read_at.is_some_and(|at| at.elapsed() >= STALE); |
| 488 | let failed = matches!(self.link, Link::Failed { .. }); |
| 489 | if (stale || failed) && self.in_flight.is_empty() { |
| 490 | self.refresh(); |
| 491 | } |
| 492 | } |
| 493 | Message::Key(key, modifiers) => return self.key(&key, modifiers), |
| 494 | Message::Pointer => self.cursor_shown = false, |
| 495 | Message::CloseHelp => self.help = false, |
| 496 | } |
| 497 | Task::none() |
| 498 | } |
| 499 | |
| 500 | /// Changes a setting: at once with the made-up buds, else through the worker. Until the buds |
| 501 | /// answer, the item shows that it is saving and takes no other write. |
| 502 | fn write(&mut self, item: Item, command: Command) { |
| 503 | if self.link == Link::Demo { |
| 504 | match command { |
| 505 | Command::Noise(mode) => self.apply_noise(NoiseControl { |
| 506 | mode: mode.name().to_owned(), |
| 507 | level: match mode { |
| 508 | NoiseMode::Anc(level) => Some(level.name().to_owned()), |
| 509 | NoiseMode::Off | NoiseMode::Transparency => None, |
| 510 | }, |
| 511 | }), |
| 512 | Command::Switch(key, on) => { |
| 513 | if let Some(switch) = self.buds.status.switches.iter().find(|s| s.key == key) { |
| 514 | let switch = Switch { on, ..switch.clone() }; |
| 515 | self.apply_switch(switch); |
| 516 | } |
| 517 | } |
| 518 | Command::Eq(preset) => self.buds.set_eq(preset), |
| 519 | Command::Touch { side, gesture, action } => { |
| 520 | if let Some(entry) = self.buds.touch.as_mut().and_then(|touch| { |
| 521 | touch |
| 522 | .gestures |
| 523 | .iter_mut() |
| 524 | .find(|g| g.side == side && g.gesture == gesture && g.group.is_none()) |
| 525 | }) { |
| 526 | entry.action = action; |
| 527 | } |
| 528 | self.touch_draft = None; |
| 529 | } |
| 530 | Command::HoldCycle(modes) => { |
| 531 | if let Some(touch) = &mut self.buds.touch { |
| 532 | touch.hold_cycle = Some(modes); |
| 533 | } |
| 534 | } |
| 535 | Command::Find(ring) => self.ringing = ring, |
| 536 | Command::Bass(level) => { |
| 537 | self.buds.bass = Some(level); |
| 538 | self.bass_draft = None; |
| 539 | } |
| 540 | Command::CreateEq(name) => { |
| 541 | let customs = || { |
| 542 | self.buds |
| 543 | .eq |
| 544 | .iter() |
| 545 | .flat_map(|eq| eq.presets.iter()) |
| 546 | .filter(|p| p.custom) |
| 547 | }; |
| 548 | let model = customs().next().cloned(); |
| 549 | let id = customs().map(|p| p.id).max().map_or(4, |id| id.saturating_add(1)); |
| 550 | if let Some(model) = model { |
| 551 | self.editing = Some(id); |
| 552 | self.buds.set_custom(EqPreset { |
| 553 | name, |
| 554 | id, |
| 555 | custom: true, |
| 556 | bands: model.bands.iter().map(|b| EqBand { hz: b.hz, gain: 0 }).collect(), |
| 557 | range: model.range, |
| 558 | }); |
| 559 | } |
| 560 | } |
| 561 | Command::DeleteEq(_) => { |
| 562 | let id = item_preset(item); |
| 563 | if let Some(eq) = &mut self.buds.eq { |
| 564 | eq.presets.retain(|p| !(p.custom && p.id == id)); |
| 565 | } |
| 566 | if self.buds.status.eq.as_deref() == Some(&format!("custom-{id}")) { |
| 567 | self.buds.set_eq("pure-raw".to_owned()); |
| 568 | } |
| 569 | self.draft = None; |
| 570 | } |
| 571 | Command::RenameEq(_, name) => { |
| 572 | if let Some(preset) = self.buds.preset(item_preset(item)) { |
| 573 | let preset = EqPreset { name, ..preset.clone() }; |
| 574 | self.buds.set_custom(preset); |
| 575 | } |
| 576 | } |
| 577 | Command::CustomEq(_, bands) => { |
| 578 | if let Some(preset) = self.buds.preset(item_preset(item)) { |
| 579 | let mut preset = preset.clone(); |
| 580 | for band in &bands { |
| 581 | if let Some(shown) = preset.bands.iter_mut().find(|b| b.hz == band.hz) { |
| 582 | shown.gain = band.gain; |
| 583 | } |
| 584 | } |
| 585 | self.buds.set_custom(preset); |
| 586 | } |
| 587 | self.draft = None; |
| 588 | } |
| 589 | Command::Read => {} |
| 590 | } |
| 591 | } else if !self.pending().contains(&item) { |
| 592 | self.send(command, Some(item)); |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | /// Reads the buds again; with the made-up buds, starts them over. |
| 597 | fn refresh(&mut self) { |
| 598 | match self.link { |
| 599 | Link::Demo => { |
| 600 | self.buds = buds::demo(); |
| 601 | self.draft = None; |
| 602 | self.touch_draft = None; |
| 603 | } |
| 604 | _ if self.in_flight.contains(&None) => {} |
| 605 | _ => { |
| 606 | if self.read_at.is_none() { |
| 607 | self.link = Link::Connecting; |
| 608 | } |
| 609 | self.send(Command::Read, None); |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | fn send(&mut self, command: Command, item: Option<Item>) { |
| 615 | let Some(worker) = &self.worker else { |
| 616 | return; |
| 617 | }; |
| 618 | if worker.send(command).is_ok() { |
| 619 | self.in_flight.push_back(item); |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | /// Takes in what the worker reports. |
| 624 | fn answer(&mut self, event: Event) { |
| 625 | match event { |
| 626 | Event::Ready(worker) => { |
| 627 | self.worker = Some(worker); |
| 628 | self.send(Command::Read, None); |
| 629 | } |
| 630 | Event::Found(name) => self.buds.name = name, |
| 631 | Event::Lost(message) => { |
| 632 | self.buds.connected = false; |
| 633 | self.link = Link::Failed { |
| 634 | kind: Kind::NotFound, |
| 635 | message, |
| 636 | }; |
| 637 | } |
| 638 | Event::Read(reading) => { |
| 639 | self.in_flight.pop_front(); |
| 640 | self.apply_reading(*reading); |
| 641 | } |
| 642 | Event::Noise(now) => { |
| 643 | self.in_flight.pop_front(); |
| 644 | self.apply_noise(now); |
| 645 | self.link = Link::Live; |
| 646 | } |
| 647 | Event::Switch(switch) => { |
| 648 | self.in_flight.pop_front(); |
| 649 | self.apply_switch(switch); |
| 650 | self.link = Link::Live; |
| 651 | } |
| 652 | Event::Eq(now) => { |
| 653 | self.in_flight.pop_front(); |
| 654 | self.buds.set_eq(now); |
| 655 | self.link = Link::Live; |
| 656 | } |
| 657 | Event::CustomEq(preset) => { |
| 658 | self.in_flight.pop_front(); |
| 659 | let id = preset.id; |
| 660 | self.buds.set_custom(preset); |
| 661 | self.link = Link::Live; |
| 662 | // Bands moved while this write was on its way go out now. |
| 663 | match &self.draft { |
| 664 | Some(draft) if draft.preset == id => { |
| 665 | if self.buds.preset(id).is_some_and(|saved| saved.bands == draft.bands) { |
| 666 | self.draft = None; |
| 667 | } else { |
| 668 | self.save_bands(id); |
| 669 | } |
| 670 | } |
| 671 | _ => {} |
| 672 | } |
| 673 | } |
| 674 | Event::Touch(gestures) => { |
| 675 | let done = self.in_flight.pop_front(); |
| 676 | if let Some(touch) = &mut self.buds.touch { |
| 677 | touch.gestures = gestures; |
| 678 | } |
| 679 | self.link = Link::Live; |
| 680 | // An action picked while this write was on its way goes out now. |
| 681 | if let Some(Some(Item::Gesture(row))) = done { |
| 682 | self.save_touch(row); |
| 683 | } |
| 684 | } |
| 685 | Event::Presets(eq) => { |
| 686 | let done = self.in_flight.pop_front(); |
| 687 | self.buds.set_presets(eq); |
| 688 | self.link = Link::Live; |
| 689 | // A new preset opens its bands: it is the one in use. |
| 690 | if done == Some(Some(Item::NewPreset)) { |
| 691 | self.editing = equalizer::in_use(&self.buds).map(|preset| preset.id); |
| 692 | } |
| 693 | } |
| 694 | Event::Bass(level) => { |
| 695 | self.in_flight.pop_front(); |
| 696 | self.buds.bass = Some(level); |
| 697 | self.link = Link::Live; |
| 698 | // A level moved while this one was on its way goes out now. |
| 699 | self.save_bass(); |
| 700 | } |
| 701 | Event::Ringing(ring) => { |
| 702 | self.in_flight.pop_front(); |
| 703 | self.ringing = ring; |
| 704 | self.link = Link::Live; |
| 705 | } |
| 706 | Event::HoldCycle(modes) => { |
| 707 | self.in_flight.pop_front(); |
| 708 | if let Some(touch) = &mut self.buds.touch { |
| 709 | touch.hold_cycle = Some(modes); |
| 710 | } |
| 711 | self.link = Link::Live; |
| 712 | } |
| 713 | Event::Failed { kind, message } => { |
| 714 | // The buds keep what they had: show that, not what was picked. |
| 715 | match self.in_flight.pop_front() { |
| 716 | Some(Some(Item::Preset(id))) if self.draft.as_ref().is_some_and(|d| d.preset == id) => { |
| 717 | self.draft = None; |
| 718 | } |
| 719 | Some(Some(Item::Gesture(row))) if self.touch_draft.as_ref().is_some_and(|d| d.row == row) => { |
| 720 | self.touch_draft = None; |
| 721 | } |
| 722 | Some(Some(Item::Bass)) => self.bass_draft = None, |
| 723 | _ => {} |
| 724 | } |
| 725 | if kind == Kind::NotFound { |
| 726 | self.buds.connected = false; |
| 727 | } |
| 728 | self.link = Link::Failed { kind, message }; |
| 729 | } |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | fn apply_reading(&mut self, reading: Reading) { |
| 734 | self.buds.eq = reading.eq; |
| 735 | self.buds.touch = reading.touch; |
| 736 | self.buds.bass_range = reading.bass_range; |
| 737 | if let Some(level) = reading |
| 738 | .status |
| 739 | .noise_control |
| 740 | .as_ref() |
| 741 | .and_then(|now| now.level.as_deref()) |
| 742 | .and_then(anc_level) |
| 743 | { |
| 744 | self.anc_level = level; |
| 745 | } |
| 746 | self.buds.status = reading.status; |
| 747 | self.buds.connected = true; |
| 748 | self.link = Link::Live; |
| 749 | self.read_at = Some(Instant::now()); |
| 750 | } |
| 751 | |
| 752 | fn apply_noise(&mut self, now: NoiseControl) { |
| 753 | if let Some(level) = now.level.as_deref().and_then(anc_level) { |
| 754 | self.anc_level = level; |
| 755 | } |
| 756 | self.buds.status.noise_control = Some(now); |
| 757 | } |
| 758 | |
| 759 | fn apply_switch(&mut self, switch: Switch) { |
| 760 | if let Some(shown) = self.buds.status.switches.iter_mut().find(|s| s.key == switch.key) { |
| 761 | *shown = switch; |
| 762 | } |
| 763 | } |
| 764 | |
| 765 | /// Selects an EQ preset: a built-in one by name, a custom one by saving it unchanged. The |
| 766 | /// preset in use is left alone. |
| 767 | fn select(&mut self, id: u8) { |
| 768 | let Some(preset) = self.buds.preset(id) else { |
| 769 | return; |
| 770 | }; |
| 771 | if self.buds.status.eq.as_deref() == Some(buds::key(preset).as_str()) { |
| 772 | return; |
| 773 | } |
| 774 | let command = if preset.custom { |
| 775 | Command::CustomEq(buds::key(preset), Vec::new()) |
| 776 | } else { |
| 777 | Command::Eq(preset.name.clone()) |
| 778 | }; |
| 779 | self.write(Item::Preset(id), command); |
| 780 | } |
| 781 | |
| 782 | /// Moves a band on the screen, within the preset's range. Nothing goes to the buds yet. |
| 783 | fn move_band(&mut self, id: u8, hz: u16, gain: i8) { |
| 784 | let Some(preset) = self.buds.preset(id) else { |
| 785 | return; |
| 786 | }; |
| 787 | let (low, high) = preset.range.unwrap_or((i8::MIN, i8::MAX)); |
| 788 | let mut bands = match self.draft.take() { |
| 789 | Some(draft) if draft.preset == id => draft.bands, |
| 790 | _ => preset.bands.clone(), |
| 791 | }; |
| 792 | if let Some(band) = bands.iter_mut().find(|band| band.hz == hz) { |
| 793 | band.gain = gain.clamp(low, high); |
| 794 | } |
| 795 | self.draft = Some(Draft { preset: id, bands }); |
| 796 | } |
| 797 | |
| 798 | /// Saves the moved bands of a custom preset. If a write to it is on its way, they go out |
| 799 | /// when it is answered: the latest bands win. |
| 800 | fn save_bands(&mut self, id: u8) { |
| 801 | let Some(draft) = self.draft.clone().filter(|draft| draft.preset == id) else { |
| 802 | return; |
| 803 | }; |
| 804 | let Some(preset) = self.buds.preset(id) else { |
| 805 | return; |
| 806 | }; |
| 807 | if !self.pending().contains(&Item::Preset(id)) { |
| 808 | self.write(Item::Preset(id), Command::CustomEq(buds::key(preset), draft.bands)); |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | /// A gesture row: the bud, the gesture, and the actions it takes. |
| 813 | fn gesture_row(&self, row: u8) -> Option<(&'static str, String, Vec<String>)> { |
| 814 | let touch = self.buds.touch.as_ref()?; |
| 815 | let rows = gestures::rows(touch); |
| 816 | let found = rows.get(usize::from(row))?; |
| 817 | Some((found.side, found.gesture.to_owned(), found.actions.to_vec())) |
| 818 | } |
| 819 | |
| 820 | /// The action a gesture row has: the one picked on the screen, else the buds' own. |
| 821 | fn gesture_action(&self, row: u8) -> Option<String> { |
| 822 | if let Some(draft) = self.touch_draft.as_ref().filter(|draft| draft.row == row) { |
| 823 | return Some(draft.action.clone()); |
| 824 | } |
| 825 | let (side, gesture, _) = self.gesture_row(row)?; |
| 826 | self.buds.action(side, &gesture).map(str::to_owned) |
| 827 | } |
| 828 | |
| 829 | /// Writes the action picked for a gesture row. If a write to it is on its way, the pick |
| 830 | /// goes out when that is answered: the latest pick wins. |
| 831 | fn save_touch(&mut self, row: u8) { |
| 832 | let Some(draft) = self.touch_draft.clone().filter(|draft| draft.row == row) else { |
| 833 | return; |
| 834 | }; |
| 835 | let Some((side, gesture, _)) = self.gesture_row(row) else { |
| 836 | return; |
| 837 | }; |
| 838 | if self.buds.action(side, &gesture) == Some(draft.action.as_str()) { |
| 839 | self.touch_draft = None; |
| 840 | } else if !self.pending().contains(&Item::Gesture(row)) { |
| 841 | let command = Command::Touch { |
| 842 | side: side.to_owned(), |
| 843 | gesture, |
| 844 | action: draft.action, |
| 845 | }; |
| 846 | self.write(Item::Gesture(row), command); |
| 847 | } |
| 848 | } |
| 849 | |
| 850 | /// Puts a mode in the hold cycle or takes it out. The buds need two modes to step |
| 851 | /// through, so the last two stay. |
| 852 | fn cycle(&mut self, mode: u8, on: bool) { |
| 853 | let Some(touch) = &self.buds.touch else { |
| 854 | return; |
| 855 | }; |
| 856 | let (Some(name), Some(now)) = (touch.cycle_modes.get(usize::from(mode)), &touch.hold_cycle) else { |
| 857 | return; |
| 858 | }; |
| 859 | let mut modes: Vec<String> = now.iter().filter(|m| *m != name).cloned().collect(); |
| 860 | if on { |
| 861 | modes.push(name.clone()); |
| 862 | } |
| 863 | let busy = self.pending().iter().any(|item| matches!(item, Item::Cycle(_))); |
| 864 | if modes.len() >= 2 && !busy { |
| 865 | self.write(Item::Cycle(mode), Command::HoldCycle(modes)); |
| 866 | } |
| 867 | } |
| 868 | |
| 869 | /// Opens the preset-name dialog, with the keyboard in its field. |
| 870 | fn ask_name(&mut self, target: NameTarget, text: String) -> Task<Message> { |
| 871 | self.prompt = Some(NamePrompt { |
| 872 | target, |
| 873 | text, |
| 874 | problem: None, |
| 875 | }); |
| 876 | operation::focus(NAME_INPUT) |
| 877 | } |
| 878 | |
| 879 | /// Creates or renames the preset, if the name will do. What the buds themselves refuse (a |
| 880 | /// name too long for them, a fourth preset) comes back as an error. |
| 881 | fn submit_name(&mut self) { |
| 882 | let Some(prompt) = self.prompt.clone() else { |
| 883 | return; |
| 884 | }; |
| 885 | let renaming = match prompt.target { |
| 886 | NameTarget::Rename(id) => Some(id), |
| 887 | NameTarget::New => None, |
| 888 | }; |
| 889 | let taken = self |
| 890 | .buds |
| 891 | .custom_names() |
| 892 | .any(|(id, name)| name == prompt.text && Some(id) != renaming); |
| 893 | let problem = if prompt.text.is_empty() || prompt.text.trim() != prompt.text { |
| 894 | Some("A name cannot be empty, or start or end with a space.".to_owned()) |
| 895 | } else if prompt.text.chars().any(char::is_control) { |
| 896 | Some("A name cannot hold control characters.".to_owned()) |
| 897 | } else if taken { |
| 898 | Some(format!("A preset is called {} already.", prompt.text)) |
| 899 | } else { |
| 900 | None |
| 901 | }; |
| 902 | if let Some(problem) = problem { |
| 903 | self.prompt = Some(NamePrompt { |
| 904 | problem: Some(problem), |
| 905 | ..prompt |
| 906 | }); |
| 907 | return; |
| 908 | } |
| 909 | self.prompt = None; |
| 910 | match prompt.target { |
| 911 | NameTarget::New => self.write(Item::NewPreset, Command::CreateEq(prompt.text)), |
| 912 | NameTarget::Rename(id) => { |
| 913 | let unchanged = self.buds.preset(id).is_some_and(|p| p.name == prompt.text); |
| 914 | if let (false, Some(preset)) = (unchanged, self.buds.preset(id)) { |
| 915 | let command = Command::RenameEq(buds::key(preset), prompt.text); |
| 916 | self.write(Item::Preset(id), command); |
| 917 | } |
| 918 | } |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | /// Sets the bass level moved on the screen. If a level is on its way, this one goes out |
| 923 | /// when that is answered: the latest level wins. |
| 924 | fn save_bass(&mut self) { |
| 925 | let Some(level) = self.bass_draft else { |
| 926 | return; |
| 927 | }; |
| 928 | if self.buds.bass == Some(level) { |
| 929 | self.bass_draft = None; |
| 930 | } else if !self.pending().contains(&Item::Bass) { |
| 931 | self.write(Item::Bass, Command::Bass(level)); |
| 932 | } |
| 933 | } |
| 934 | |
| 935 | /// The items with a write on its way. |
| 936 | fn pending(&self) -> Vec<Item> { |
| 937 | self.in_flight.iter().flatten().copied().collect() |
| 938 | } |
| 939 | |
| 940 | /// Shows `page` from its top, with the cursor on its first item. |
| 941 | fn open(&mut self, page: Page) -> Task<Message> { |
| 942 | self.page = page; |
| 943 | self.cursor = 0; |
| 944 | operation::snap_to(SCROLL, RelativeOffset::START) |
| 945 | } |
| 946 | |
| 947 | fn key(&mut self, key: &Key, modifiers: Modifiers) -> Task<Message> { |
| 948 | if self.confirm_delete.is_some() { |
| 949 | // Only Enter deletes; any other key says no. |
| 950 | let yes = matches!(key, Key::Named(keyboard::key::Named::Enter)); |
| 951 | return self.update(Message::ConfirmDelete(yes)); |
| 952 | } |
| 953 | if self.prompt.is_some() { |
| 954 | // The name field takes the keys, and Enter in it; only Esc is ours. |
| 955 | if matches!(key, Key::Named(keyboard::key::Named::Escape)) { |
| 956 | self.prompt = None; |
| 957 | } |
| 958 | return Task::none(); |
| 959 | } |
| 960 | let Some(action) = self.keys.press(key, modifiers) else { |
| 961 | return Task::none(); |
| 962 | }; |
| 963 | if self.help { |
| 964 | // The list of keys is in front of everything: a key only closes it. |
| 965 | self.help = false; |
| 966 | return Task::none(); |
| 967 | } |
| 968 | if self.confirm_find { |
| 969 | // Only Enter rings the buds; any other key says no. |
| 970 | let ring = matches!(key, Key::Named(keyboard::key::Named::Enter)); |
| 971 | return self.update(Message::ConfirmFind(ring)); |
| 972 | } |
| 973 | match action { |
| 974 | Action::Quit => iced::exit(), |
| 975 | Action::Help => { |
| 976 | self.help = true; |
| 977 | Task::none() |
| 978 | } |
| 979 | Action::Escape => { |
| 980 | self.cursor_shown = false; |
| 981 | Task::none() |
| 982 | } |
| 983 | Action::Refresh => { |
| 984 | self.refresh(); |
| 985 | Task::none() |
| 986 | } |
| 987 | Action::NextPage => self.open(self.page.step(true)), |
| 988 | Action::PreviousPage => self.open(self.page.step(false)), |
| 989 | Action::Page(n) => match Page::ALL.get(n) { |
| 990 | Some(&page) => self.open(page), |
| 991 | None => Task::none(), |
| 992 | }, |
| 993 | Action::Down |
| 994 | | Action::Up |
| 995 | | Action::First |
| 996 | | Action::Last |
| 997 | | Action::Left |
| 998 | | Action::Right |
| 999 | | Action::Activate => self.on_cursor(action), |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | /// What the current page offers the keyboard cursor, top to bottom. |
| 1004 | fn items(&self) -> Vec<Item> { |
| 1005 | match self.page { |
| 1006 | Page::Overview if self.has_reading() => overview::items(&self.buds), |
| 1007 | Page::Equalizer if self.has_reading() => equalizer::items(&self.buds, self.editing), |
| 1008 | Page::Gestures if self.has_reading() => gestures::items(&self.buds), |
| 1009 | Page::Earbuds if self.has_reading() => earbuds::items(), |
| 1010 | _ => Vec::new(), |
| 1011 | } |
| 1012 | } |
| 1013 | |
| 1014 | /// Whether there is anything to show: the made-up buds, or a reading of the real ones. |
| 1015 | fn has_reading(&self) -> bool { |
| 1016 | self.link == Link::Demo || self.read_at.is_some() |
| 1017 | } |
| 1018 | |
| 1019 | /// The item under the cursor, when the cursor shows. |
| 1020 | fn focus(&self) -> Option<Item> { |
| 1021 | let items = self.items(); |
| 1022 | let last = items.len().checked_sub(1)?; |
| 1023 | self.cursor_shown.then(|| items.get(self.cursor.min(last)).copied())? |
| 1024 | } |
| 1025 | |
| 1026 | fn on_cursor(&mut self, action: Action) -> Task<Message> { |
| 1027 | let items = self.items(); |
| 1028 | let Some(last) = items.len().checked_sub(1) else { |
| 1029 | return Task::none(); |
| 1030 | }; |
| 1031 | self.cursor = self.cursor.min(last); |
| 1032 | if !self.cursor_shown { |
| 1033 | // The first key only shows the cursor, so nothing changes where it cannot be seen. |
| 1034 | self.cursor_shown = true; |
| 1035 | return self.follow(); |
| 1036 | } |
| 1037 | match action { |
| 1038 | Action::Down => self.cursor = (self.cursor + 1).min(last), |
| 1039 | Action::Up => self.cursor = self.cursor.saturating_sub(1), |
| 1040 | Action::First => self.cursor = 0, |
| 1041 | Action::Last => self.cursor = last, |
| 1042 | _ => { |
| 1043 | let change = items.get(self.cursor).and_then(|&item| self.change(item, action)); |
| 1044 | return match change { |
| 1045 | Some(message) => self.update(message), |
| 1046 | None => Task::none(), |
| 1047 | }; |
| 1048 | } |
| 1049 | } |
| 1050 | self.follow() |
| 1051 | } |
| 1052 | |
| 1053 | /// What `action` (`h`, `l` or Enter) does to `item`, if anything. |
| 1054 | fn change(&self, item: Item, action: Action) -> Option<Message> { |
| 1055 | match item { |
| 1056 | Item::NoiseMode => { |
| 1057 | let modes = [NoiseMode::Off, NoiseMode::Anc(self.anc_level), NoiseMode::Transparency]; |
| 1058 | let now = self.buds.status.noise_control.as_ref()?; |
| 1059 | let at = modes.iter().position(|mode| mode.name() == now.mode); |
| 1060 | step(&modes, at, action).map(Message::Noise) |
| 1061 | } |
| 1062 | Item::AncLevel => { |
| 1063 | let levels = [AncLevel::Light, AncLevel::Medium, AncLevel::Deep]; |
| 1064 | let at = levels.iter().position(|&level| level == self.anc_level); |
| 1065 | step(&levels, at, action).map(|level| Message::Noise(NoiseMode::Anc(level))) |
| 1066 | } |
| 1067 | Item::Switch(key) => { |
| 1068 | let on = self.buds.status.switches.iter().find(|s| s.key == key)?.on; |
| 1069 | let want = match action { |
| 1070 | Action::Left => false, |
| 1071 | Action::Right => true, |
| 1072 | _ => !on, |
| 1073 | }; |
| 1074 | (want != on).then_some(Message::Switch(key, want)) |
| 1075 | } |
| 1076 | Item::Open(page) => (action != Action::Left).then_some(Message::Open(page)), |
| 1077 | Item::Preset(id) => { |
| 1078 | let chosen = self.buds.status.eq.as_deref() == self.buds.preset(id).map(buds::key).as_deref(); |
| 1079 | (action != Action::Left && !chosen).then_some(Message::Preset(id)) |
| 1080 | } |
| 1081 | Item::Band(id, hz) => { |
| 1082 | let preset = self.buds.preset(id)?; |
| 1083 | let gain = match &self.draft { |
| 1084 | Some(draft) if draft.preset == id => &draft.bands, |
| 1085 | _ => &preset.bands, |
| 1086 | } |
| 1087 | .iter() |
| 1088 | .find(|band| band.hz == hz)? |
| 1089 | .gain; |
| 1090 | let (low, high) = preset.range.unwrap_or((i8::MIN, i8::MAX)); |
| 1091 | let to = match action { |
| 1092 | Action::Left => gain.checked_sub(1)?.max(low), |
| 1093 | Action::Right => gain.checked_add(1)?.min(high), |
| 1094 | _ => return None, |
| 1095 | }; |
| 1096 | (to != gain).then_some(Message::Band { |
| 1097 | preset: id, |
| 1098 | hz, |
| 1099 | gain: to, |
| 1100 | save: true, |
| 1101 | }) |
| 1102 | } |
| 1103 | Item::Gesture(row) => { |
| 1104 | let (_, _, actions) = self.gesture_row(row)?; |
| 1105 | let now = self.gesture_action(row)?; |
| 1106 | let places: Vec<usize> = (0..actions.len()).collect(); |
| 1107 | let at = actions.iter().position(|a| *a == now); |
| 1108 | let to = step(&places, at, action)?; |
| 1109 | actions.get(to).map(|action| Message::Action { |
| 1110 | row, |
| 1111 | action: action.clone(), |
| 1112 | save: true, |
| 1113 | }) |
| 1114 | } |
| 1115 | Item::Find => (action != Action::Left).then_some(Message::Find), |
| 1116 | Item::NewPreset => (action != Action::Left).then_some(Message::NewPreset), |
| 1117 | Item::Rename(id) => (action != Action::Left).then_some(Message::RenamePreset(id)), |
| 1118 | Item::Delete(id) => (action != Action::Left).then_some(Message::DeletePreset(id)), |
| 1119 | Item::Edit(id) => (action != Action::Left).then_some(Message::EditPreset(id)), |
| 1120 | Item::Done => (action != Action::Left).then_some(Message::DoneEditing), |
| 1121 | Item::Bass => { |
| 1122 | let (low, high) = self.buds.bass_range?; |
| 1123 | let now = self.bass_draft.or(self.buds.bass); |
| 1124 | let to = match (action, now) { |
| 1125 | // Not set yet: the first step starts from the middle. |
| 1126 | (Action::Left | Action::Right, None) => 0, |
| 1127 | (Action::Left, Some(level)) => level.checked_sub(1)?.max(low), |
| 1128 | (Action::Right, Some(level)) => level.checked_add(1)?.min(high), |
| 1129 | _ => return None, |
| 1130 | }; |
| 1131 | (Some(to) != now).then_some(Message::Bass { level: to, save: true }) |
| 1132 | } |
| 1133 | Item::Cycle(mode) => { |
| 1134 | let touch = self.buds.touch.as_ref()?; |
| 1135 | let on = touch |
| 1136 | .hold_cycle |
| 1137 | .as_ref()? |
| 1138 | .contains(touch.cycle_modes.get(usize::from(mode))?); |
| 1139 | let want = match action { |
| 1140 | Action::Left => false, |
| 1141 | Action::Right => true, |
| 1142 | _ => !on, |
| 1143 | }; |
| 1144 | (want != on).then_some(Message::Cycle(mode, want)) |
| 1145 | } |
| 1146 | } |
| 1147 | } |
| 1148 | |
| 1149 | /// Scrolls the page so the cursor stays in view: the first item at the top, the last at the |
| 1150 | /// bottom, the others in between. |
| 1151 | fn follow(&self) -> Task<Message> { |
| 1152 | let count = self.items().len(); |
| 1153 | if !self.cursor_shown || count < 2 { |
| 1154 | return Task::none(); |
| 1155 | } |
| 1156 | let y = self.cursor as f32 / (count - 1) as f32; |
| 1157 | operation::snap_to(SCROLL, RelativeOffset { x: 0.0, y }) |
| 1158 | } |
| 1159 | |
| 1160 | fn refresh_palette(&mut self) { |
| 1161 | let palette = match self.palette.refresh() { |
| 1162 | None => return, |
| 1163 | Some(Ok(palette)) => { |
| 1164 | self.palette_problem = None; |
| 1165 | palette |
| 1166 | } |
| 1167 | Some(Err(e)) => { |
| 1168 | eprintln!("budctl-gui: {e}; using the built-in colors"); |
| 1169 | self.palette_problem = Some(e); |
| 1170 | theme::BUILT_IN |
| 1171 | } |
| 1172 | }; |
| 1173 | self.look.p = palette; |
| 1174 | self.theme = theme::iced_theme(&palette); |
| 1175 | } |
| 1176 | |
| 1177 | fn theme(&self) -> Theme { |
| 1178 | self.theme.clone() |
| 1179 | } |
| 1180 | |
| 1181 | fn subscription(&self) -> Subscription<Message> { |
| 1182 | let events = event::listen_with(|event, _status, _window| match event { |
| 1183 | iced::Event::Window(window::Event::Focused) => Some(Message::Focused), |
| 1184 | iced::Event::Keyboard(keyboard::Event::KeyPressed { key, modifiers, .. }) => { |
| 1185 | Some(Message::Key(key, modifiers)) |
| 1186 | } |
| 1187 | iced::Event::Mouse(mouse::Event::ButtonPressed(_)) => Some(Message::Pointer), |
| 1188 | _ => None, |
| 1189 | }); |
| 1190 | if self.link == Link::Demo { |
| 1191 | return events; |
| 1192 | } |
| 1193 | let worker = Subscription::run_with(self.device, worker::run).map(Message::Worker); |
| 1194 | Subscription::batch([events, worker]) |
| 1195 | } |
| 1196 | |
| 1197 | fn view(&self) -> Element<'_, Message> { |
| 1198 | let look = self.look; |
| 1199 | let pending = self.pending(); |
| 1200 | let page = match self.page { |
| 1201 | Page::Overview if self.has_reading() => { |
| 1202 | let marks = Marks { |
| 1203 | focus: self.focus(), |
| 1204 | pending: &pending, |
| 1205 | }; |
| 1206 | overview::view(look, &self.buds, self.anc_level, self.bass_draft, marks) |
| 1207 | } |
| 1208 | Page::Overview => self.connecting(), |
| 1209 | Page::Equalizer if self.has_reading() => { |
| 1210 | let marks = Marks { |
| 1211 | focus: self.focus(), |
| 1212 | pending: &pending, |
| 1213 | }; |
| 1214 | equalizer::view(look, &self.buds, self.editing, self.draft.as_ref(), marks) |
| 1215 | } |
| 1216 | Page::Gestures if self.has_reading() => { |
| 1217 | let marks = Marks { |
| 1218 | focus: self.focus(), |
| 1219 | pending: &pending, |
| 1220 | }; |
| 1221 | gestures::view(look, &self.buds, self.touch_draft.as_ref(), marks) |
| 1222 | } |
| 1223 | Page::Earbuds if self.has_reading() => { |
| 1224 | let marks = Marks { |
| 1225 | focus: self.focus(), |
| 1226 | pending: &pending, |
| 1227 | }; |
| 1228 | earbuds::view(look, &self.buds, self.ringing, marks) |
| 1229 | } |
| 1230 | Page::Settings => { |
| 1231 | let colors = settings::Colors { |
| 1232 | file: self.palette.file(), |
| 1233 | problem: self.palette_problem.as_deref(), |
| 1234 | }; |
| 1235 | settings::view(look, colors) |
| 1236 | } |
| 1237 | page => column![ |
| 1238 | ui::title(look, page.title()), |
| 1239 | text("This page comes in a later step.").size(14).color(look.p.dim) |
| 1240 | ] |
| 1241 | .spacing(12) |
| 1242 | .into(), |
| 1243 | }; |
| 1244 | let page = column![self.problem(), page].spacing(18); |
| 1245 | let p = look.p; |
| 1246 | let content = scrollable( |
| 1247 | container(container(page).max_width(860)) |
| 1248 | .center_x(Length::Fill) |
| 1249 | .padding([30, 36]), |
| 1250 | ) |
| 1251 | .id(SCROLL) |
| 1252 | .height(Length::Fill) |
| 1253 | .style(move |theme, status| { |
| 1254 | let mut style = scrollable::default(theme, status); |
| 1255 | for rail in [&mut style.vertical_rail, &mut style.horizontal_rail] { |
| 1256 | rail.background = None; |
| 1257 | rail.border = Border::default(); |
| 1258 | rail.scroller.background = p.surface_highest.into(); |
| 1259 | rail.scroller.border = Border::default().rounded(4); |
| 1260 | } |
| 1261 | style |
| 1262 | }); |
| 1263 | let window = row![self.sidebar(), ui::divider(look), content]; |
| 1264 | if self.help { |
| 1265 | stack![window, self.help()].into() |
| 1266 | } else if self.confirm_find { |
| 1267 | stack![window, self.confirm_find()].into() |
| 1268 | } else if let Some(prompt) = &self.prompt { |
| 1269 | stack![window, self.name_prompt(prompt)].into() |
| 1270 | } else if let Some(id) = self.confirm_delete { |
| 1271 | stack![window, self.confirm_delete(id)].into() |
| 1272 | } else { |
| 1273 | window.into() |
| 1274 | } |
| 1275 | } |
| 1276 | |
| 1277 | /// The Overview before the first reading: connecting, or why it did not work. |
| 1278 | fn connecting(&self) -> Element<'_, Message> { |
| 1279 | let look = self.look; |
| 1280 | let p = look.p; |
| 1281 | let (headline, detail) = match &self.link { |
| 1282 | Link::Failed { |
| 1283 | kind: Kind::NotFound, |
| 1284 | message, |
| 1285 | } => ("Your buds are not connected", message.as_str()), |
| 1286 | Link::Failed { |
| 1287 | kind: Kind::Busy, |
| 1288 | message, |
| 1289 | } => ("The control channel is busy", message.as_str()), |
| 1290 | Link::Failed { message, .. } => ("Something went wrong", message.as_str()), |
| 1291 | _ => ( |
| 1292 | "Connecting to your buds…", |
| 1293 | "budctl looks for the paired buds it supports and reads them.", |
| 1294 | ), |
| 1295 | }; |
| 1296 | let retry = matches!(self.link, Link::Failed { .. }) |
| 1297 | .then(|| container(ui::outline_button(look, "Try again", Message::Refresh)).width(180)); |
| 1298 | let words = column![ |
| 1299 | text(headline).size(20).font(look.bold()).color(p.fg), |
| 1300 | text(detail).size(14).color(p.dim) |
| 1301 | ] |
| 1302 | .spacing(8); |
| 1303 | column![ |
| 1304 | ui::title(look, "Overview"), |
| 1305 | ui::panel(look, column![words].push(retry).spacing(18).into()) |
| 1306 | ] |
| 1307 | .spacing(18) |
| 1308 | .into() |
| 1309 | } |
| 1310 | |
| 1311 | /// A failure after the buds were read once: what went wrong, above the page. |
| 1312 | fn problem(&self) -> Option<Element<'_, Message>> { |
| 1313 | let Link::Failed { message, .. } = &self.link else { |
| 1314 | return None; |
| 1315 | }; |
| 1316 | // Before the first reading, the Overview says it already. |
| 1317 | self.read_at?; |
| 1318 | let look = self.look; |
| 1319 | let p = look.p; |
| 1320 | let content = row![ |
| 1321 | text(message.as_str()).size(14).color(p.err).width(Length::Fill), |
| 1322 | container(ui::outline_button(look, "Try again", Message::Refresh)).width(140) |
| 1323 | ] |
| 1324 | .spacing(16) |
| 1325 | .align_y(Alignment::Center); |
| 1326 | Some( |
| 1327 | container(content) |
| 1328 | .padding([12, 16]) |
| 1329 | .width(Length::Fill) |
| 1330 | .style(move |_| container::Style { |
| 1331 | background: Some(p.surface.into()), |
| 1332 | border: Border { |
| 1333 | color: p.err, |
| 1334 | width: 1.0, |
| 1335 | radius: 14.0.into(), |
| 1336 | }, |
| 1337 | ..container::Style::default() |
| 1338 | }) |
| 1339 | .into(), |
| 1340 | ) |
| 1341 | } |
| 1342 | |
| 1343 | fn sidebar(&self) -> Element<'_, Message> { |
| 1344 | let look = self.look; |
| 1345 | let p = look.p; |
| 1346 | let (light, state) = match &self.link { |
| 1347 | Link::Demo | Link::Live => (p.ok, "Connected"), |
| 1348 | Link::Connecting => (p.dim, "Connecting…"), |
| 1349 | Link::Failed { kind: Kind::Busy, .. } => (p.err, "Busy"), |
| 1350 | Link::Failed { .. } if !self.buds.connected => (p.dim, "Not connected"), |
| 1351 | Link::Failed { .. } => (p.err, "Error"), |
| 1352 | }; |
| 1353 | let device = container( |
| 1354 | column![ |
| 1355 | text(self.buds.name.as_str()).size(16).font(look.bold()).color(p.fg), |
| 1356 | row![ui::light(light), text(state).size(13).color(p.dim), space::horizontal()] |
| 1357 | .push((self.link == Link::Demo).then(|| ui::tag(look, "demo"))) |
| 1358 | .spacing(8) |
| 1359 | .align_y(Alignment::Center), |
| 1360 | ui::outline_button(look, "Refresh", Message::Refresh), |
| 1361 | ] |
| 1362 | .spacing(12), |
| 1363 | ) |
| 1364 | .padding(16) |
| 1365 | .style(move |_| container::Style { |
| 1366 | background: Some(p.surface.into()), |
| 1367 | border: Border { |
| 1368 | color: p.line, |
| 1369 | width: 1.0, |
| 1370 | radius: 18.0.into(), |
| 1371 | }, |
| 1372 | ..container::Style::default() |
| 1373 | }); |
| 1374 | let pages = Page::ALL.into_iter().fold(Column::new().spacing(3), |pages, page| { |
| 1375 | pages.push(ui::nav_item( |
| 1376 | look, |
| 1377 | page.icon(), |
| 1378 | page.title(), |
| 1379 | page == self.page, |
| 1380 | Message::Open(page), |
| 1381 | )) |
| 1382 | }); |
| 1383 | let hint = text("Press ? for keys").size(12.5).color(p.dim); |
| 1384 | container(column![device, pages, space::vertical(), hint].spacing(22)) |
| 1385 | .padding([18, 14]) |
| 1386 | .width(268) |
| 1387 | .height(Length::Fill) |
| 1388 | .style(move |_| container::Style { |
| 1389 | background: Some(p.surface_low.into()), |
| 1390 | ..container::Style::default() |
| 1391 | }) |
| 1392 | .into() |
| 1393 | } |
| 1394 | |
| 1395 | /// "Ring the buds?", over a dimmed window: the sound is loud enough to hurt in the ears. |
| 1396 | fn confirm_find(&self) -> Element<'_, Message> { |
| 1397 | let look = self.look; |
| 1398 | let p = look.p; |
| 1399 | let words = column![ |
| 1400 | text("Ring your buds?").size(22).font(look.bold()).color(p.fg), |
| 1401 | text("Take them out of your ears first: the sound is loud. They ring until you press Stop.") |
| 1402 | .size(14) |
| 1403 | .color(p.dim), |
| 1404 | ] |
| 1405 | .spacing(8); |
| 1406 | let buttons = row![ |
| 1407 | space::horizontal(), |
| 1408 | ui::pill(look, "Cancel", false, Message::ConfirmFind(false)), |
| 1409 | ui::pill(look, "Ring", true, Message::ConfirmFind(true)), |
| 1410 | ] |
| 1411 | .spacing(10); |
| 1412 | let dialog = ui::panel(look, column![words, buttons].spacing(22).into()); |
| 1413 | let backdrop = container(container(dialog).width(480)) |
| 1414 | .center(Length::Fill) |
| 1415 | .style(|_| container::Style { |
| 1416 | background: Some(Color { a: 0.6, ..Color::BLACK }.into()), |
| 1417 | ..container::Style::default() |
| 1418 | }); |
| 1419 | opaque(backdrop) |
| 1420 | } |
| 1421 | |
| 1422 | /// "Delete the preset?", over a dimmed window: its bands are lost. |
| 1423 | fn confirm_delete(&self, id: u8) -> Element<'_, Message> { |
| 1424 | let look = self.look; |
| 1425 | let p = look.p; |
| 1426 | let name = self |
| 1427 | .buds |
| 1428 | .preset(id) |
| 1429 | .map_or("this preset", |preset| preset.name.as_str()); |
| 1430 | let words = column![ |
| 1431 | text(format!("Delete {name}?")).size(22).font(look.bold()).color(p.fg), |
| 1432 | text("Its bands are lost. The buds keep their other presets.") |
| 1433 | .size(14) |
| 1434 | .color(p.dim), |
| 1435 | ] |
| 1436 | .spacing(8); |
| 1437 | let buttons = row![ |
| 1438 | space::horizontal(), |
| 1439 | ui::pill(look, "Cancel", false, Message::ConfirmDelete(false)), |
| 1440 | ui::pill(look, "Delete", true, Message::ConfirmDelete(true)), |
| 1441 | ] |
| 1442 | .spacing(10); |
| 1443 | let dialog = ui::panel(look, column![words, buttons].spacing(22).into()); |
| 1444 | let backdrop = container(container(dialog).width(460)) |
| 1445 | .center(Length::Fill) |
| 1446 | .style(|_| container::Style { |
| 1447 | background: Some(Color { a: 0.6, ..Color::BLACK }.into()), |
| 1448 | ..container::Style::default() |
| 1449 | }); |
| 1450 | opaque(backdrop) |
| 1451 | } |
| 1452 | |
| 1453 | /// The dialog that asks for a preset's name, over a dimmed window. |
| 1454 | fn name_prompt<'a>(&'a self, prompt: &'a NamePrompt) -> Element<'a, Message> { |
| 1455 | let look = self.look; |
| 1456 | let p = look.p; |
| 1457 | let (heading, action) = match prompt.target { |
| 1458 | NameTarget::New => ("New preset".to_owned(), "Create"), |
| 1459 | NameTarget::Rename(id) => { |
| 1460 | let name = self.buds.preset(id).map_or("the preset", |preset| preset.name.as_str()); |
| 1461 | (format!("Rename {name}"), "Rename") |
| 1462 | } |
| 1463 | }; |
| 1464 | let field = text_input("Name", &prompt.text) |
| 1465 | .id(NAME_INPUT) |
| 1466 | .on_input(Message::NameInput) |
| 1467 | .on_submit(Message::SubmitName) |
| 1468 | .size(16) |
| 1469 | .padding([10, 14]) |
| 1470 | .style(move |_, _| text_input::Style { |
| 1471 | background: p.surface_high.into(), |
| 1472 | border: Border { |
| 1473 | color: p.accent, |
| 1474 | width: 1.0, |
| 1475 | radius: 10.0.into(), |
| 1476 | }, |
| 1477 | icon: p.dim, |
| 1478 | placeholder: p.dim, |
| 1479 | value: p.fg, |
| 1480 | selection: p.accent_dim, |
| 1481 | }); |
| 1482 | let problem = prompt |
| 1483 | .problem |
| 1484 | .as_deref() |
| 1485 | .map(|problem| text(problem).size(13).color(p.err)); |
| 1486 | let buttons = row![ |
| 1487 | space::horizontal(), |
| 1488 | ui::pill(look, "Cancel", false, Message::CancelName), |
| 1489 | ui::pill(look, action, true, Message::SubmitName), |
| 1490 | ] |
| 1491 | .spacing(10); |
| 1492 | let dialog = column![text(heading).size(22).font(look.bold()).color(p.fg), field] |
| 1493 | .push(problem) |
| 1494 | .push(buttons) |
| 1495 | .spacing(16); |
| 1496 | let backdrop = container(container(ui::panel(look, dialog.into())).width(460)) |
| 1497 | .center(Length::Fill) |
| 1498 | .style(|_| container::Style { |
| 1499 | background: Some(Color { a: 0.6, ..Color::BLACK }.into()), |
| 1500 | ..container::Style::default() |
| 1501 | }); |
| 1502 | opaque(backdrop) |
| 1503 | } |
| 1504 | |
| 1505 | /// The list of keys, over a dimmed window. A key or a click closes it. |
| 1506 | fn help(&self) -> Element<'_, Message> { |
| 1507 | let look = self.look; |
| 1508 | let p = look.p; |
| 1509 | let rows = keys::HELP.iter().fold(Column::new().spacing(9), |rows, &(keys, what)| { |
| 1510 | rows.push(row![ |
| 1511 | text(keys).size(14).font(look.medium()).color(p.fg).width(170), |
| 1512 | text(what).size(14).color(p.dim) |
| 1513 | ]) |
| 1514 | }); |
| 1515 | let list = ui::panel(look, column![ui::title(look, "Keys"), rows].spacing(18).into()); |
| 1516 | let backdrop = container(container(list).width(560)) |
| 1517 | .center(Length::Fill) |
| 1518 | .style(|_| container::Style { |
| 1519 | background: Some(Color { a: 0.6, ..Color::BLACK }.into()), |
| 1520 | ..container::Style::default() |
| 1521 | }); |
| 1522 | opaque(mouse_area(backdrop).on_press(Message::CloseHelp)) |
| 1523 | } |
| 1524 | } |
| 1525 | |
| 1526 | /// The choice `action` moves to from the one at `at`: `h` and `l` stop at the ends, Enter goes |
| 1527 | /// round. With nothing chosen, any of them picks the first. |
| 1528 | fn step<T: Copy>(choices: &[T], at: Option<usize>, action: Action) -> Option<T> { |
| 1529 | let to = match (action, at) { |
| 1530 | (_, None) => 0, |
| 1531 | (Action::Left, Some(at)) => at.checked_sub(1)?, |
| 1532 | (Action::Right, Some(at)) => at + 1, |
| 1533 | (Action::Activate, Some(at)) => (at + 1).checked_rem(choices.len())?, |
| 1534 | _ => return None, |
| 1535 | }; |
| 1536 | choices.get(to).copied() |
| 1537 | } |
| 1538 | |
| 1539 | /// The level a [`NoiseControl::level`] names. |
| 1540 | fn anc_level(name: &str) -> Option<AncLevel> { |
| 1541 | [AncLevel::Light, AncLevel::Medium, AncLevel::Deep] |
| 1542 | .into_iter() |
| 1543 | .find(|level| level.name() == name) |
| 1544 | } |
| 1545 | |
| 1546 | /// The preset a write to `item` is for. |
| 1547 | fn item_preset(item: Item) -> u8 { |
| 1548 | match item { |
| 1549 | Item::Preset(id) | Item::Band(id, _) => id, |
| 1550 | _ => 0, |
| 1551 | } |
| 1552 | } |
| 1553 | |
| 1554 | #[cfg(test)] |
| 1555 | mod tests { |
| 1556 | use super::*; |
| 1557 | use iced::keyboard::key::Named; |
| 1558 | use std::fs; |
| 1559 | use std::path::Path; |
| 1560 | use std::sync::mpsc::{self, Receiver}; |
| 1561 | |
| 1562 | /// With the made-up buds. |
| 1563 | fn app() -> App { |
| 1564 | App::new(None, Font::DEFAULT, None, true) |
| 1565 | } |
| 1566 | |
| 1567 | /// Talking to a worker that the test plays: the receiver gets what the app sends it. |
| 1568 | fn live() -> (App, Receiver<Command>) { |
| 1569 | let mut app = App::new(None, Font::DEFAULT, None, false); |
| 1570 | let (worker, commands) = mpsc::channel(); |
| 1571 | let _ = app.update(Message::Worker(Event::Ready(worker))); |
| 1572 | (app, commands) |
| 1573 | } |
| 1574 | |
| 1575 | fn reading() -> Reading { |
| 1576 | Reading { |
| 1577 | status: buds::demo().status, |
| 1578 | eq: buds::demo().eq, |
| 1579 | touch: buds::demo().touch, |
| 1580 | bass_range: buds::demo().bass_range, |
| 1581 | } |
| 1582 | } |
| 1583 | |
| 1584 | /// Presses keys, given by name and separated by spaces: `j`, `G`, `Enter`, `Esc`. |
| 1585 | fn press(app: &mut App, keys: &str) { |
| 1586 | for name in keys.split_whitespace() { |
| 1587 | let (key, modifiers) = match name { |
| 1588 | "Enter" => (Key::Named(Named::Enter), Modifiers::empty()), |
| 1589 | "Esc" => (Key::Named(Named::Escape), Modifiers::empty()), |
| 1590 | c if c.chars().all(char::is_uppercase) => (Key::Character(c.into()), Modifiers::SHIFT), |
| 1591 | c => (Key::Character(c.into()), Modifiers::empty()), |
| 1592 | }; |
| 1593 | let _ = app.update(Message::Key(key, modifiers)); |
| 1594 | } |
| 1595 | } |
| 1596 | |
| 1597 | fn mode(app: &App) -> &str { |
| 1598 | &app.buds.status.noise_control.as_ref().unwrap().mode |
| 1599 | } |
| 1600 | |
| 1601 | fn switch(app: &App, key: &str) -> bool { |
| 1602 | app.buds.status.switches.iter().find(|s| s.key == key).unwrap().on |
| 1603 | } |
| 1604 | |
| 1605 | #[test] |
| 1606 | fn noise_cancelling_remembers_its_level() { |
| 1607 | let mut app = app(); |
| 1608 | let _ = app.update(Message::Noise(NoiseMode::Anc(AncLevel::Light))); |
| 1609 | let _ = app.update(Message::Noise(NoiseMode::Transparency)); |
| 1610 | assert_eq!(app.anc_level, AncLevel::Light); |
| 1611 | let now = app.buds.status.noise_control.as_ref().unwrap(); |
| 1612 | assert_eq!((now.mode.as_str(), now.level.as_deref()), ("transparency", None)); |
| 1613 | let _ = app.update(Message::Noise(NoiseMode::Anc(app.anc_level))); |
| 1614 | let now = app.buds.status.noise_control.as_ref().unwrap(); |
| 1615 | assert_eq!((now.mode.as_str(), now.level.as_deref()), ("anc", Some("light"))); |
| 1616 | } |
| 1617 | |
| 1618 | #[test] |
| 1619 | fn switches_change_by_key() { |
| 1620 | let mut app = app(); |
| 1621 | let _ = app.update(Message::Switch("game", true)); |
| 1622 | assert!(switch(&app, "game")); |
| 1623 | } |
| 1624 | |
| 1625 | #[test] |
| 1626 | fn the_overview_items_in_order() { |
| 1627 | let mut app = app(); |
| 1628 | assert_eq!( |
| 1629 | app.items(), |
| 1630 | [ |
| 1631 | Item::NoiseMode, |
| 1632 | Item::AncLevel, |
| 1633 | Item::Switch("game"), |
| 1634 | Item::Switch("spatial"), |
| 1635 | Item::Switch("bass-boost"), |
| 1636 | Item::Bass, |
| 1637 | Item::Switch("wind"), |
| 1638 | Item::Switch("dual"), |
| 1639 | Item::Open(Page::Equalizer), |
| 1640 | Item::Open(Page::Gestures), |
| 1641 | Item::Open(Page::Earbuds), |
| 1642 | ] |
| 1643 | ); |
| 1644 | let _ = app.update(Message::Noise(NoiseMode::Off)); |
| 1645 | assert!(!app.items().contains(&Item::AncLevel)); |
| 1646 | } |
| 1647 | |
| 1648 | #[test] |
| 1649 | fn the_first_key_only_shows_the_cursor() { |
| 1650 | let mut app = app(); |
| 1651 | assert_eq!(app.focus(), None); |
| 1652 | press(&mut app, "l"); |
| 1653 | assert_eq!(app.focus(), Some(Item::NoiseMode)); |
| 1654 | assert_eq!(mode(&app), "anc"); |
| 1655 | } |
| 1656 | |
| 1657 | #[test] |
| 1658 | fn h_and_l_step_through_choices_and_enter_goes_round() { |
| 1659 | let mut app = app(); |
| 1660 | press(&mut app, "j l"); |
| 1661 | assert_eq!(mode(&app), "transparency"); |
| 1662 | press(&mut app, "l"); |
| 1663 | assert_eq!(mode(&app), "transparency"); |
| 1664 | press(&mut app, "h h h"); |
| 1665 | assert_eq!(mode(&app), "off"); |
| 1666 | press(&mut app, "Enter Enter"); |
| 1667 | assert_eq!(mode(&app), "transparency"); |
| 1668 | press(&mut app, "Enter"); |
| 1669 | assert_eq!(mode(&app), "off"); |
| 1670 | // On the strength: deep at first. |
| 1671 | press(&mut app, "l j"); |
| 1672 | assert_eq!(app.focus(), Some(Item::AncLevel)); |
| 1673 | press(&mut app, "h h h"); |
| 1674 | assert_eq!(app.anc_level, AncLevel::Light); |
| 1675 | press(&mut app, "Enter"); |
| 1676 | assert_eq!(app.anc_level, AncLevel::Medium); |
| 1677 | assert_eq!( |
| 1678 | app.buds.status.noise_control.as_ref().unwrap().level.as_deref(), |
| 1679 | Some("medium") |
| 1680 | ); |
| 1681 | } |
| 1682 | |
| 1683 | #[test] |
| 1684 | fn switches_take_h_l_and_enter() { |
| 1685 | let mut app = app(); |
| 1686 | press(&mut app, "j j j"); |
| 1687 | assert_eq!(app.focus(), Some(Item::Switch("game"))); |
| 1688 | press(&mut app, "l"); |
| 1689 | assert!(switch(&app, "game")); |
| 1690 | press(&mut app, "l"); |
| 1691 | assert!(switch(&app, "game")); |
| 1692 | press(&mut app, "h"); |
| 1693 | assert!(!switch(&app, "game")); |
| 1694 | press(&mut app, "Enter"); |
| 1695 | assert!(switch(&app, "game")); |
| 1696 | } |
| 1697 | |
| 1698 | #[test] |
| 1699 | fn moving_stops_at_the_ends() { |
| 1700 | let mut app = app(); |
| 1701 | press(&mut app, "k k"); |
| 1702 | assert_eq!(app.focus(), Some(Item::NoiseMode)); |
| 1703 | press(&mut app, "G j j"); |
| 1704 | assert_eq!(app.focus(), Some(Item::Open(Page::Earbuds))); |
| 1705 | press(&mut app, "g g"); |
| 1706 | assert_eq!(app.focus(), Some(Item::NoiseMode)); |
| 1707 | } |
| 1708 | |
| 1709 | #[test] |
| 1710 | fn rows_open_pages_and_the_cursor_starts_over() { |
| 1711 | let mut app = app(); |
| 1712 | press(&mut app, "G G h"); |
| 1713 | assert_eq!(app.page, Page::Overview); |
| 1714 | press(&mut app, "l"); |
| 1715 | assert_eq!(app.page, Page::Earbuds); |
| 1716 | assert_eq!(app.cursor, 0); |
| 1717 | assert!(app.cursor_shown); |
| 1718 | } |
| 1719 | |
| 1720 | #[test] |
| 1721 | fn pages_by_key() { |
| 1722 | let mut app = app(); |
| 1723 | press(&mut app, "J"); |
| 1724 | assert_eq!(app.page, Page::Equalizer); |
| 1725 | press(&mut app, "K K"); |
| 1726 | assert_eq!(app.page, Page::Settings); |
| 1727 | press(&mut app, "1"); |
| 1728 | assert_eq!(app.page, Page::Overview); |
| 1729 | press(&mut app, "g t"); |
| 1730 | assert_eq!(app.page, Page::Equalizer); |
| 1731 | press(&mut app, "g T"); |
| 1732 | assert_eq!(app.page, Page::Overview); |
| 1733 | press(&mut app, "9"); |
| 1734 | assert_eq!(app.page, Page::Overview); |
| 1735 | } |
| 1736 | |
| 1737 | #[test] |
| 1738 | fn esc_and_clicks_hide_the_cursor() { |
| 1739 | let mut app = app(); |
| 1740 | press(&mut app, "j j"); |
| 1741 | assert!(app.focus().is_some()); |
| 1742 | press(&mut app, "Esc"); |
| 1743 | assert_eq!(app.focus(), None); |
| 1744 | press(&mut app, "j"); |
| 1745 | let _ = app.update(Message::Pointer); |
| 1746 | assert_eq!(app.focus(), None); |
| 1747 | // It comes back where it was. |
| 1748 | press(&mut app, "j"); |
| 1749 | assert_eq!(app.focus(), Some(Item::AncLevel)); |
| 1750 | } |
| 1751 | |
| 1752 | #[test] |
| 1753 | fn the_list_of_keys_closes_on_any_key() { |
| 1754 | let mut app = app(); |
| 1755 | press(&mut app, "?"); |
| 1756 | assert!(app.help); |
| 1757 | press(&mut app, "j"); |
| 1758 | assert!(!app.help); |
| 1759 | assert_eq!(app.focus(), None); |
| 1760 | press(&mut app, "?"); |
| 1761 | let _ = app.update(Message::CloseHelp); |
| 1762 | assert!(!app.help); |
| 1763 | } |
| 1764 | |
| 1765 | #[test] |
| 1766 | fn live_buds_are_read_first() { |
| 1767 | let (mut app, commands) = live(); |
| 1768 | assert!(matches!(commands.try_recv(), Ok(Command::Read))); |
| 1769 | assert_eq!(app.link, Link::Connecting); |
| 1770 | assert!(app.items().is_empty(), "nothing to move over before the first reading"); |
| 1771 | // A second refresh while the read is on its way sends nothing. |
| 1772 | press(&mut app, "r"); |
| 1773 | assert!(commands.try_recv().is_err()); |
| 1774 | |
| 1775 | let _ = app.update(Message::Worker(Event::Found("realme Buds T310".to_owned()))); |
| 1776 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 1777 | assert_eq!(app.link, Link::Live); |
| 1778 | assert_eq!(app.buds.name, "realme Buds T310"); |
| 1779 | assert!(app.buds.connected); |
| 1780 | assert_eq!(app.items().len(), 11); |
| 1781 | } |
| 1782 | |
| 1783 | #[test] |
| 1784 | fn focus_tries_again_after_a_failure() { |
| 1785 | let (mut app, commands) = live(); |
| 1786 | let _ = commands.try_recv(); |
| 1787 | let _ = app.update(Message::Worker(Event::Failed { |
| 1788 | kind: Kind::NotFound, |
| 1789 | message: "realme Buds T310 is paired but not connected".to_owned(), |
| 1790 | })); |
| 1791 | let _ = app.update(Message::Focused); |
| 1792 | assert!(matches!(commands.try_recv(), Ok(Command::Read))); |
| 1793 | assert_eq!(app.link, Link::Connecting); |
| 1794 | // A fresh reading is not read again on focus. |
| 1795 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 1796 | let _ = app.update(Message::Focused); |
| 1797 | assert!(commands.try_recv().is_err()); |
| 1798 | } |
| 1799 | |
| 1800 | #[test] |
| 1801 | fn the_preset_in_use_is_not_written_again() { |
| 1802 | let (mut app, commands) = live(); |
| 1803 | let _ = commands.try_recv(); |
| 1804 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 1805 | let _ = app.update(Message::Preset(4)); |
| 1806 | assert!(commands.try_recv().is_err(), "Custom1 is in use already"); |
| 1807 | let _ = app.update(Message::Preset(3)); |
| 1808 | assert!(matches!(commands.try_recv(), Ok(Command::Eq(name)) if name == "pure-bass")); |
| 1809 | } |
| 1810 | |
| 1811 | #[test] |
| 1812 | fn live_writes_wait_for_the_buds() { |
| 1813 | let (mut app, commands) = live(); |
| 1814 | let _ = commands.try_recv(); |
| 1815 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 1816 | |
| 1817 | let _ = app.update(Message::Switch("game", true)); |
| 1818 | assert!(matches!(commands.try_recv(), Ok(Command::Switch("game", true)))); |
| 1819 | assert!(!switch(&app, "game"), "the switch changes when the buds say so"); |
| 1820 | assert_eq!(app.pending(), [Item::Switch("game")]); |
| 1821 | // While it is on its way, the same switch takes no other write. |
| 1822 | press(&mut app, "j j j Enter"); |
| 1823 | assert!(commands.try_recv().is_err()); |
| 1824 | |
| 1825 | let game = Switch { |
| 1826 | key: "game", |
| 1827 | label: "Game mode", |
| 1828 | on: true, |
| 1829 | }; |
| 1830 | let _ = app.update(Message::Worker(Event::Switch(game))); |
| 1831 | assert!(switch(&app, "game")); |
| 1832 | assert!(app.pending().is_empty()); |
| 1833 | |
| 1834 | let _ = app.update(Message::Noise(NoiseMode::Transparency)); |
| 1835 | assert!(matches!( |
| 1836 | commands.try_recv(), |
| 1837 | Ok(Command::Noise(NoiseMode::Transparency)) |
| 1838 | )); |
| 1839 | assert_eq!(mode(&app), "anc"); |
| 1840 | let now = NoiseControl { |
| 1841 | mode: "transparency".to_owned(), |
| 1842 | level: None, |
| 1843 | }; |
| 1844 | let _ = app.update(Message::Worker(Event::Noise(now))); |
| 1845 | assert_eq!(mode(&app), "transparency"); |
| 1846 | } |
| 1847 | |
| 1848 | #[test] |
| 1849 | fn failures_say_why_and_clear_the_write() { |
| 1850 | let (mut app, commands) = live(); |
| 1851 | let _ = app.update(Message::Worker(Event::Failed { |
| 1852 | kind: Kind::Busy, |
| 1853 | message: "control channel busy".to_owned(), |
| 1854 | })); |
| 1855 | assert!(matches!(app.link, Link::Failed { kind: Kind::Busy, .. })); |
| 1856 | assert!(app.problem().is_none(), "the Overview says it, not a banner"); |
| 1857 | |
| 1858 | let _ = commands.try_recv(); |
| 1859 | let _ = app.update(Message::Refresh); |
| 1860 | assert!(matches!(commands.try_recv(), Ok(Command::Read))); |
| 1861 | assert_eq!(app.link, Link::Connecting); |
| 1862 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 1863 | |
| 1864 | let _ = app.update(Message::Switch("dual", false)); |
| 1865 | let _ = app.update(Message::Worker(Event::Failed { |
| 1866 | kind: Kind::NotFound, |
| 1867 | message: "the buds closed the control link".to_owned(), |
| 1868 | })); |
| 1869 | assert!(app.pending().is_empty()); |
| 1870 | assert!(switch(&app, "dual")); |
| 1871 | assert!(!app.buds.connected); |
| 1872 | assert!(app.problem().is_some()); |
| 1873 | } |
| 1874 | |
| 1875 | #[test] |
| 1876 | fn presets_and_bands_by_key() { |
| 1877 | let mut app = app(); |
| 1878 | press(&mut app, "J"); |
| 1879 | assert_eq!(app.page, Page::Equalizer); |
| 1880 | press(&mut app, "j l"); |
| 1881 | assert_eq!(app.buds.status.eq.as_deref(), Some("pure-raw")); |
| 1882 | assert_eq!(app.buds.eq_name(), "Pure raw"); |
| 1883 | // Custom1's pencil, after the four built-in presets and Custom1's row, opens its bands. |
| 1884 | press(&mut app, "j j j j j Enter"); |
| 1885 | assert_eq!(app.editing, Some(4)); |
| 1886 | assert_eq!( |
| 1887 | app.buds.status.eq.as_deref(), |
| 1888 | Some("pure-raw"), |
| 1889 | "opening selects nothing" |
| 1890 | ); |
| 1891 | press(&mut app, "G"); |
| 1892 | assert_eq!(app.focus(), Some(Item::Band(4, 16000))); |
| 1893 | // Moving a band saves the preset, which puts it in use. |
| 1894 | press(&mut app, "l"); |
| 1895 | assert_eq!(app.buds.status.eq.as_deref(), Some("custom-4")); |
| 1896 | let last = |app: &App| app.buds.preset(4).unwrap().bands.last().unwrap().gain; |
| 1897 | assert_eq!(last(&app), 3); |
| 1898 | press(&mut app, "l l l l l"); |
| 1899 | assert_eq!(last(&app), 6, "it stops at the top of the range"); |
| 1900 | } |
| 1901 | |
| 1902 | #[test] |
| 1903 | fn band_moves_wait_for_the_write_before_them() { |
| 1904 | let (mut app, commands) = live(); |
| 1905 | let _ = commands.try_recv(); |
| 1906 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 1907 | let _ = app.update(Message::EditPreset(4)); |
| 1908 | press(&mut app, "J G G l"); |
| 1909 | let gain = |bands: &[EqBand]| bands.last().map(|band| band.gain); |
| 1910 | assert!(matches!( |
| 1911 | commands.try_recv(), |
| 1912 | Ok(Command::CustomEq(name, bands)) if name == "custom-4" && gain(&bands) == Some(3) |
| 1913 | )); |
| 1914 | // While that write is on its way, moves only change the screen. |
| 1915 | press(&mut app, "l l"); |
| 1916 | assert!(commands.try_recv().is_err()); |
| 1917 | assert_eq!(app.draft.as_ref().and_then(|draft| gain(&draft.bands)), Some(5)); |
| 1918 | // The answer comes: the latest bands go out at once. |
| 1919 | let mut saved = buds::demo().preset(4).unwrap().clone(); |
| 1920 | if let Some(band) = saved.bands.last_mut() { |
| 1921 | band.gain = 3; |
| 1922 | } |
| 1923 | let _ = app.update(Message::Worker(Event::CustomEq(saved.clone()))); |
| 1924 | assert!(matches!( |
| 1925 | commands.try_recv(), |
| 1926 | Ok(Command::CustomEq(_, bands)) if gain(&bands) == Some(5) |
| 1927 | )); |
| 1928 | assert_eq!(app.pending(), [Item::Preset(4)]); |
| 1929 | // A failure drops the moves: the screen shows what the buds kept. |
| 1930 | let _ = app.update(Message::Worker(Event::Failed { |
| 1931 | kind: Kind::Failed, |
| 1932 | message: "no reply".to_owned(), |
| 1933 | })); |
| 1934 | assert_eq!(app.draft, None); |
| 1935 | assert_eq!(gain(&app.buds.preset(4).unwrap().bands), Some(3)); |
| 1936 | } |
| 1937 | |
| 1938 | fn cycle(app: &App) -> Vec<String> { |
| 1939 | app.buds.touch.as_ref().unwrap().hold_cycle.clone().unwrap() |
| 1940 | } |
| 1941 | |
| 1942 | #[test] |
| 1943 | fn gestures_and_the_hold_cycle_by_key() { |
| 1944 | let mut app = app(); |
| 1945 | press(&mut app, "3 j j"); |
| 1946 | assert_eq!(app.page, Page::Gestures); |
| 1947 | assert_eq!(app.focus(), Some(Item::Gesture(1))); |
| 1948 | press(&mut app, "l"); |
| 1949 | assert_eq!(app.buds.action("left", "triple-tap"), Some("next")); |
| 1950 | press(&mut app, "h h h"); |
| 1951 | assert_eq!( |
| 1952 | app.buds.action("left", "triple-tap"), |
| 1953 | Some("none"), |
| 1954 | "it stops at the first" |
| 1955 | ); |
| 1956 | |
| 1957 | press(&mut app, "G k l"); |
| 1958 | assert_eq!(app.focus(), Some(Item::Cycle(1))); |
| 1959 | assert_eq!(cycle(&app), ["off", "anc", "transparency"]); |
| 1960 | press(&mut app, "h"); |
| 1961 | assert_eq!(cycle(&app), ["off", "anc"]); |
| 1962 | press(&mut app, "j h"); |
| 1963 | assert_eq!(cycle(&app), ["off", "anc"], "a hold needs two modes"); |
| 1964 | } |
| 1965 | |
| 1966 | #[test] |
| 1967 | fn gesture_picks_wait_for_the_write_before_them() { |
| 1968 | let (mut app, commands) = live(); |
| 1969 | let _ = commands.try_recv(); |
| 1970 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 1971 | press(&mut app, "3 j j l"); |
| 1972 | assert!(matches!( |
| 1973 | commands.try_recv(), |
| 1974 | Ok(Command::Touch { side, gesture, action }) |
| 1975 | if side == "left" && gesture == "triple-tap" && action == "next" |
| 1976 | )); |
| 1977 | // While that write is on its way, picks only change the screen. |
| 1978 | press(&mut app, "l l"); |
| 1979 | assert!(commands.try_recv().is_err()); |
| 1980 | assert_eq!(app.gesture_action(1).as_deref(), Some("volume-up")); |
| 1981 | // The answer comes: the latest pick goes out at once. |
| 1982 | let mut table = reading().touch.unwrap().gestures; |
| 1983 | table[1].action = "next".to_owned(); |
| 1984 | let _ = app.update(Message::Worker(Event::Touch(table))); |
| 1985 | assert!(matches!( |
| 1986 | commands.try_recv(), |
| 1987 | Ok(Command::Touch { action, .. }) if action == "volume-up" |
| 1988 | )); |
| 1989 | assert_eq!(app.pending(), [Item::Gesture(1)]); |
| 1990 | } |
| 1991 | |
| 1992 | #[test] |
| 1993 | fn ringing_needs_a_yes() { |
| 1994 | let mut app = app(); |
| 1995 | press(&mut app, "4 j Enter"); |
| 1996 | assert_eq!(app.page, Page::Earbuds); |
| 1997 | assert!(app.confirm_find); |
| 1998 | press(&mut app, "Esc"); |
| 1999 | assert!(!app.confirm_find); |
| 2000 | assert!(!app.ringing); |
| 2001 | press(&mut app, "Enter j"); |
| 2002 | assert!(!app.ringing, "only Enter says yes"); |
| 2003 | press(&mut app, "Enter Enter"); |
| 2004 | assert!(app.ringing); |
| 2005 | // Stopping asks nothing. |
| 2006 | press(&mut app, "Enter"); |
| 2007 | assert!(!app.confirm_find); |
| 2008 | assert!(!app.ringing); |
| 2009 | } |
| 2010 | |
| 2011 | #[test] |
| 2012 | fn live_ringing_waits_for_the_buds() { |
| 2013 | let (mut app, commands) = live(); |
| 2014 | let _ = commands.try_recv(); |
| 2015 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 2016 | let _ = app.update(Message::Find); |
| 2017 | let _ = app.update(Message::ConfirmFind(true)); |
| 2018 | assert!(matches!(commands.try_recv(), Ok(Command::Find(true)))); |
| 2019 | assert!(!app.ringing); |
| 2020 | let _ = app.update(Message::Worker(Event::Ringing(true))); |
| 2021 | assert!(app.ringing); |
| 2022 | let _ = app.update(Message::Find); |
| 2023 | assert!(matches!(commands.try_recv(), Ok(Command::Find(false)))); |
| 2024 | } |
| 2025 | |
| 2026 | #[test] |
| 2027 | fn the_bass_level_by_key() { |
| 2028 | let mut app = app(); |
| 2029 | press(&mut app, "j j j j j j"); |
| 2030 | assert_eq!(app.focus(), Some(Item::Bass), "under bass boost, on the Overview"); |
| 2031 | assert_eq!(app.buds.bass, None, "the buds do not say"); |
| 2032 | press(&mut app, "l"); |
| 2033 | assert_eq!(app.buds.bass, Some(0), "the first step starts from the middle"); |
| 2034 | press(&mut app, "l l"); |
| 2035 | assert_eq!(app.buds.bass, Some(2)); |
| 2036 | press(&mut app, "h h h h h h h h"); |
| 2037 | assert_eq!(app.buds.bass, Some(-5), "it stops at the bottom"); |
| 2038 | } |
| 2039 | |
| 2040 | #[test] |
| 2041 | fn bass_moves_wait_for_the_level_before_them() { |
| 2042 | let (mut app, commands) = live(); |
| 2043 | let _ = commands.try_recv(); |
| 2044 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 2045 | let _ = app.update(Message::Bass { level: 2, save: false }); |
| 2046 | assert!( |
| 2047 | commands.try_recv().is_err(), |
| 2048 | "a drag sends nothing until the mouse lets go" |
| 2049 | ); |
| 2050 | let _ = app.update(Message::SaveBass); |
| 2051 | assert!(matches!(commands.try_recv(), Ok(Command::Bass(2)))); |
| 2052 | let _ = app.update(Message::Bass { level: 4, save: true }); |
| 2053 | assert!(commands.try_recv().is_err()); |
| 2054 | let _ = app.update(Message::Worker(Event::Bass(2))); |
| 2055 | assert!(matches!(commands.try_recv(), Ok(Command::Bass(4)))); |
| 2056 | let _ = app.update(Message::Worker(Event::Bass(4))); |
| 2057 | assert_eq!(app.buds.bass, Some(4)); |
| 2058 | assert_eq!(app.bass_draft, None); |
| 2059 | assert!(commands.try_recv().is_err()); |
| 2060 | } |
| 2061 | |
| 2062 | #[test] |
| 2063 | fn presets_are_created_and_renamed() { |
| 2064 | let mut app = app(); |
| 2065 | let _ = app.update(Message::NewPreset); |
| 2066 | assert!(app.prompt.is_some()); |
| 2067 | // Typing goes to the field, not to the cursor. |
| 2068 | press(&mut app, "j j"); |
| 2069 | assert_eq!(app.focus(), None); |
| 2070 | let _ = app.update(Message::NameInput(" Gym".to_owned())); |
| 2071 | let _ = app.update(Message::SubmitName); |
| 2072 | assert!(app.prompt.as_ref().is_some_and(|p| p.problem.is_some())); |
| 2073 | let _ = app.update(Message::NameInput("Custom1".to_owned())); |
| 2074 | let _ = app.update(Message::SubmitName); |
| 2075 | assert!(app.prompt.as_ref().is_some_and(|p| p.problem.is_some()), "taken"); |
| 2076 | let _ = app.update(Message::NameInput("Gym".to_owned())); |
| 2077 | let _ = app.update(Message::SubmitName); |
| 2078 | assert_eq!(app.prompt, None); |
| 2079 | assert_eq!(app.buds.eq_name(), "Gym", "a new preset is put to use"); |
| 2080 | let gym = app |
| 2081 | .buds |
| 2082 | .custom_names() |
| 2083 | .find(|(_, name)| *name == "Gym") |
| 2084 | .map(|(id, _)| id) |
| 2085 | .unwrap(); |
| 2086 | assert_eq!(app.editing, Some(gym), "and its bands open"); |
| 2087 | |
| 2088 | let _ = app.update(Message::RenamePreset(gym)); |
| 2089 | assert_eq!(app.prompt.as_ref().map(|p| p.text.as_str()), Some("Gym")); |
| 2090 | let _ = app.update(Message::NameInput("Run".to_owned())); |
| 2091 | let _ = app.update(Message::SubmitName); |
| 2092 | assert_eq!(app.buds.preset(gym).map(|p| p.name.as_str()), Some("Run")); |
| 2093 | |
| 2094 | let _ = app.update(Message::RenamePreset(gym)); |
| 2095 | press(&mut app, "Esc"); |
| 2096 | assert_eq!(app.prompt, None); |
| 2097 | } |
| 2098 | |
| 2099 | #[test] |
| 2100 | fn live_presets_are_created_and_renamed_by_the_buds() { |
| 2101 | let (mut app, commands) = live(); |
| 2102 | let _ = commands.try_recv(); |
| 2103 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 2104 | let _ = app.update(Message::NewPreset); |
| 2105 | let _ = app.update(Message::NameInput("Gym".to_owned())); |
| 2106 | let _ = app.update(Message::SubmitName); |
| 2107 | assert!(matches!(commands.try_recv(), Ok(Command::CreateEq(name)) if name == "Gym")); |
| 2108 | assert_eq!(app.pending(), [Item::NewPreset]); |
| 2109 | let mut presets = buds::demo().eq.unwrap(); |
| 2110 | let mut gym = presets.presets.last().unwrap().clone(); |
| 2111 | gym.id = 5; |
| 2112 | gym.name = "Gym".to_owned(); |
| 2113 | presets.presets.push(gym); |
| 2114 | presets.current = Some("custom-5".to_owned()); |
| 2115 | let _ = app.update(Message::Worker(Event::Presets(presets))); |
| 2116 | assert_eq!(app.buds.eq_name(), "Gym"); |
| 2117 | assert_eq!(app.editing, Some(5)); |
| 2118 | assert!(app.pending().is_empty()); |
| 2119 | |
| 2120 | let _ = app.update(Message::RenamePreset(4)); |
| 2121 | let _ = app.update(Message::NameInput("Run".to_owned())); |
| 2122 | let _ = app.update(Message::SubmitName); |
| 2123 | assert!(matches!( |
| 2124 | commands.try_recv(), |
| 2125 | Ok(Command::RenameEq(preset, name)) if preset == "custom-4" && name == "Run" |
| 2126 | )); |
| 2127 | } |
| 2128 | |
| 2129 | #[test] |
| 2130 | fn presets_are_deleted_after_a_yes() { |
| 2131 | let mut app = app(); |
| 2132 | let _ = app.update(Message::DeletePreset(4)); |
| 2133 | assert_eq!(app.confirm_delete, Some(4)); |
| 2134 | press(&mut app, "j"); |
| 2135 | assert_eq!(app.confirm_delete, None, "any other key says no"); |
| 2136 | assert!(app.buds.preset(4).is_some()); |
| 2137 | let _ = app.update(Message::DeletePreset(4)); |
| 2138 | press(&mut app, "Enter"); |
| 2139 | assert!(app.buds.preset(4).is_none()); |
| 2140 | assert_eq!(app.buds.status.eq.as_deref(), Some("pure-raw")); |
| 2141 | |
| 2142 | let (mut app, commands) = live(); |
| 2143 | let _ = commands.try_recv(); |
| 2144 | let _ = app.update(Message::Worker(Event::Read(Box::new(reading())))); |
| 2145 | let _ = app.update(Message::DeletePreset(4)); |
| 2146 | let _ = app.update(Message::ConfirmDelete(true)); |
| 2147 | assert!(matches!(commands.try_recv(), Ok(Command::DeleteEq(preset)) if preset == "custom-4")); |
| 2148 | assert_eq!(app.pending(), [Item::Preset(4)]); |
| 2149 | } |
| 2150 | |
| 2151 | #[test] |
| 2152 | fn the_pencil_opens_the_bands_and_done_closes_them() { |
| 2153 | let mut app = app(); |
| 2154 | press(&mut app, "J"); |
| 2155 | let bands = |app: &App| app.items().iter().any(|item| matches!(item, Item::Band(..))); |
| 2156 | assert!(!bands(&app)); |
| 2157 | let _ = app.update(Message::EditPreset(4)); |
| 2158 | assert!(bands(&app)); |
| 2159 | let _ = app.update(Message::DoneEditing); |
| 2160 | assert!(!bands(&app)); |
| 2161 | // The pencil again closes them too. |
| 2162 | let _ = app.update(Message::EditPreset(4)); |
| 2163 | let _ = app.update(Message::EditPreset(4)); |
| 2164 | assert!(!bands(&app)); |
| 2165 | } |
| 2166 | |
| 2167 | #[test] |
| 2168 | fn steps() { |
| 2169 | let abc = ['a', 'b', 'c']; |
| 2170 | assert_eq!(step(&abc, Some(0), Action::Left), None); |
| 2171 | assert_eq!(step(&abc, Some(0), Action::Right), Some('b')); |
| 2172 | assert_eq!(step(&abc, Some(2), Action::Right), None); |
| 2173 | assert_eq!(step(&abc, Some(2), Action::Activate), Some('a')); |
| 2174 | assert_eq!(step(&abc, None, Action::Left), Some('a')); |
| 2175 | } |
| 2176 | |
| 2177 | #[test] |
| 2178 | fn arguments() { |
| 2179 | let args = |list: &[&str]| parse_args(list.iter().map(|s| (*s).to_owned())); |
| 2180 | assert!(matches!(args(&[]), Ok(Args::Run(Options { demo: false, .. })))); |
| 2181 | assert!(matches!(args(&["--demo"]), Ok(Args::Run(Options { demo: true, .. })))); |
| 2182 | assert!(matches!(args(&["--debug"]), Ok(Args::Run(Options { debug: true, .. })))); |
| 2183 | assert!(matches!( |
| 2184 | args(&["--theme", "x.json"]), |
| 2185 | Ok(Args::Run(Options { theme: Some(_), .. })) |
| 2186 | )); |
| 2187 | assert!(matches!( |
| 2188 | args(&["--device", "88:0E:85:46:FE:5C"]), |
| 2189 | Ok(Args::Run(Options { device: Some(_), .. })) |
| 2190 | )); |
| 2191 | assert!(matches!(args(&["--help"]), Ok(Args::Help))); |
| 2192 | assert!(args(&["--theme"]).is_err()); |
| 2193 | assert!(args(&["--device", "nope"]).is_err()); |
| 2194 | assert!(args(&["--bogus"]).is_err()); |
| 2195 | } |
| 2196 | |
| 2197 | /// Renders every page to `target/gui-snapshots/`, so the look can be checked without a |
| 2198 | /// display. `BUDCTL_THEME=<file>` renders with that palette. |
| 2199 | #[test] |
| 2200 | fn pages_render() { |
| 2201 | let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/gui-snapshots"); |
| 2202 | let _ = fs::remove_dir_all(&dir); |
| 2203 | let font = theme::system_font(); |
| 2204 | let palette = std::env::var_os("BUDCTL_THEME").map(PathBuf::from); |
| 2205 | let on = |page: Page, keys: &str| { |
| 2206 | let mut app = App::new(palette.clone(), font, None, true); |
| 2207 | app.page = page; |
| 2208 | press(&mut app, keys); |
| 2209 | app |
| 2210 | }; |
| 2211 | let mut shots: Vec<(String, f32, App)> = Page::ALL |
| 2212 | .into_iter() |
| 2213 | .map(|page| (format!("{page:?}").to_lowercase(), 800.0, on(page, ""))) |
| 2214 | .collect(); |
| 2215 | shots.push(("overview-full".to_owned(), 1240.0, on(Page::Overview, ""))); |
| 2216 | shots.push(("overview-cursor".to_owned(), 800.0, on(Page::Overview, "j j j j"))); |
| 2217 | shots.push(("keys".to_owned(), 800.0, on(Page::Overview, "?"))); |
| 2218 | let mut editing = on(Page::Equalizer, ""); |
| 2219 | let _ = editing.update(Message::EditPreset(4)); |
| 2220 | press(&mut editing, "G G k k"); |
| 2221 | shots.push(("equalizer-cursor".to_owned(), 1100.0, editing)); |
| 2222 | shots.push(("equalizer-pencil".to_owned(), 800.0, on(Page::Equalizer, "j j j j j j"))); |
| 2223 | shots.push(("gestures-cursor".to_owned(), 1000.0, on(Page::Gestures, "j j"))); |
| 2224 | shots.push(("find-confirm".to_owned(), 800.0, on(Page::Earbuds, "j Enter"))); |
| 2225 | shots.push(( |
| 2226 | "overview-bass".to_owned(), |
| 2227 | 1340.0, |
| 2228 | on(Page::Overview, "j j j j j j l l"), |
| 2229 | )); |
| 2230 | let mut naming = on(Page::Equalizer, ""); |
| 2231 | let _ = naming.update(Message::RenamePreset(4)); |
| 2232 | let _ = naming.update(Message::NameInput("Custom1 ".to_owned())); |
| 2233 | let _ = naming.update(Message::SubmitName); |
| 2234 | shots.push(("name-prompt".to_owned(), 800.0, naming)); |
| 2235 | shots.push(("equalizer-builtin".to_owned(), 1000.0, on(Page::Equalizer, "j l"))); |
| 2236 | let mut deleting = on(Page::Equalizer, ""); |
| 2237 | let _ = deleting.update(Message::DeletePreset(4)); |
| 2238 | shots.push(("delete-confirm".to_owned(), 800.0, deleting)); |
| 2239 | let mut connecting = App::new(palette.clone(), font, None, false); |
| 2240 | connecting.link = Link::Connecting; |
| 2241 | shots.push(("connecting".to_owned(), 800.0, connecting)); |
| 2242 | let mut busy = App::new(palette.clone(), font, None, false); |
| 2243 | busy.answer(Event::Failed { |
| 2244 | kind: Kind::Busy, |
| 2245 | message: "control channel busy: is another app connected?".to_owned(), |
| 2246 | }); |
| 2247 | shots.push(("busy".to_owned(), 800.0, busy)); |
| 2248 | let (mut saving, _commands) = live(); |
| 2249 | saving.answer(Event::Read(Box::new(reading()))); |
| 2250 | saving.answer(Event::Failed { |
| 2251 | kind: Kind::Failed, |
| 2252 | message: "the buds did not answer: no reply to command 0x0403".to_owned(), |
| 2253 | }); |
| 2254 | let _ = saving.update(Message::Switch("spatial", false)); |
| 2255 | let _ = saving.update(Message::Noise(NoiseMode::Off)); |
| 2256 | shots.push(("saving".to_owned(), 1240.0, saving)); |
| 2257 | for (name, height, app) in shots { |
| 2258 | let settings = iced::Settings { |
| 2259 | default_font: font, |
| 2260 | ..iced::Settings::default() |
| 2261 | }; |
| 2262 | let mut ui = iced_test::Simulator::with_size(settings, Size::new(1040.0, height), app.view()); |
| 2263 | let snapshot = ui.snapshot(&app.theme).unwrap(); |
| 2264 | assert!(snapshot.matches_image(dir.join(name)).unwrap()); |
| 2265 | } |
| 2266 | } |
| 2267 | } |