Krolyxon
Commit 6e8f058

Branches

Refs →

budctlcratesbudctl-guisrcmain.rs

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