Krolyxon
Commit 047794f

Branches

Refs →

budctlcratesbudctl-guisrcmain.rs

2281 lines · 86.4 KB · Rust

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