forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

notices.rs707 lines, 28.7 KiBHistoryRawDownload
1//! The notice queue, and the toasts it draws (DESIGN §8).
2
3use crate::*;
4use std::cell::Cell;
5use std::collections::VecDeque;
6use std::ops::Deref;
7use std::path::PathBuf;
8
9/// `n` of a thing in words: "1 silence", "2 silences". One door, so no
10/// message ships a "(s)" or a "1 silences".
11pub(crate) fn count_noun(n: usize, one: &str, many: &str) -> String {
12 format!("{n} {}", if n == 1 { one } else { many })
13}
14
15/// How many messages wait in the queue before the oldest is dropped. A queue
16/// with no ceiling is a way for a stuck loop to eat the heap; eight is more than
17/// a user will ever answer in a row. Only the newest is drawn, in the status bar,
18/// and a new message replaces it, so in practice the queue holds one line plus
19/// any questions still waiting for an answer.
20pub(crate) const NOTICES_MAX: usize = 8;
21
22/// How long an info or warn toast stays before it hides itself (DESIGN §8).
23/// Errors have no such timer: they name a remedy and wait for a ✕.
24pub(crate) const TOAST_HIDE: Duration = Duration::from_secs(5);
25
26/// How many buttons one toast can carry. Two is what an export's outcome needs
27/// (Play, and Show in folder); a third would crowd the message off the bar.
28pub(crate) const TOAST_ACTIONS_MAX: usize = 2;
29
30/// How loud a toast is. The tone picks the stripe colour and whether the toast
31/// times out at all.
32#[derive(Clone, Copy, PartialEq, Eq, Debug)]
33pub(crate) enum Tone {
34 Info,
35 Warn,
36 Err,
37}
38
39impl Tone {
40 /// The tone is read off the words a message already opens with: a refusal or
41 /// a failure is an error, a no-op or an empty result is a warning, and
42 /// everything else -- a save, a snap -- is information.
43 pub(crate) fn of(message: &str) -> Tone {
44 // The keywords are matched as whole words in capitals whatever the case
45 // of the message, so a sentence-case line reads the same as the old
46 // ALL-CAPS one, and "piano" does not read as "NO".
47 let words: Vec<String> = message
48 .split(|c: char| !c.is_alphanumeric())
49 .filter(|w| !w.is_empty())
50 .map(str::to_uppercase)
51 .collect();
52 let has = |word: &str| words.iter().any(|w| w == word);
53 let has_pair =
54 |first: &str, second: &str| words.windows(2).any(|p| p[0] == first && p[1] == second);
55 if has("FAILED")
56 || has("ERROR")
57 || has("REFUSED")
58 || has("CANNOT")
59 || has_pair("COULD", "NOT")
60 {
61 Tone::Err
62 } else if has("NOTHING") || has("NO") || has("EMPTY") {
63 Tone::Warn
64 } else {
65 Tone::Info
66 }
67 }
68
69 /// Whether a toast of this tone hides on its own. Errors do not: a failure
70 /// that vanished before it was read is the failure nobody learns about.
71 pub(crate) fn auto_hides(self) -> bool {
72 self != Tone::Err
73 }
74}
75
76/// What a toast's button does. The action is the toast's own: the button acts on
77/// the thing the message is about, and the toast goes with the click.
78#[derive(Clone, Debug, PartialEq)]
79pub(crate) enum ToastAction {
80 /// Takes back the last timeline edit, as `ctrl+z` does. The delete and lift
81 /// toasts in `timeline_edit.rs` offer it.
82 Undo,
83 /// Reveals a written file in the file manager.
84 ShowInFolder(PathBuf),
85 /// Opens a written file in the system's default player.
86 Play(PathBuf),
87 /// Unlocks the lane an edit was refused on (DESIGN §7). The refusal names
88 /// the lane, so the button can name it too.
89 Unlock(Lane),
90 /// Reloads the open project from disk, dropping the edits the window
91 /// holds. Offered when the project file changed under unsaved edits.
92 Reload,
93 /// Dismisses the question and keeps the window's edits. The file stays as
94 /// the other side wrote it until the next save.
95 KeepMine,
96 /// Takes an autosave's unsaved edits over the saved project, as one undo
97 /// step. Offered when a project opens with a newer autosave beside it.
98 Recover,
99 /// Deletes the autosave that was offered for recovery.
100 Discard,
101 /// Saves the open project, then opens the one that was asked for.
102 SaveThenOpen(PathBuf),
103 /// Opens the one that was asked for and lets this project's unsaved edits go.
104 OpenDiscarding(PathBuf),
105}
106
107/// One notice on screen or waiting behind the ones on screen. `Deref`s to its
108/// text, so a reader that only wants the words reads them as it always did.
109#[derive(Clone, Debug, PartialEq)]
110pub(crate) struct Toast {
111 /// Unique for the life of the process. A hide timer names the toast it was
112 /// started for, so a timer that fires late finds nothing with that id and
113 /// cannot hide a newer toast that happens to say the same thing.
114 pub(crate) id: u64,
115 pub(crate) text: SharedString,
116 pub(crate) tone: Tone,
117 /// The buttons, in the order they are drawn. At most [`TOAST_ACTIONS_MAX`].
118 pub(crate) actions: Vec<ToastAction>,
119 /// Whether this toast's hide timer has been started. Set the first frame
120 /// the toast is drawn, which is where the timer can be spawned from.
121 pub(crate) timer_armed: Cell<bool>,
122 /// Stays until its button is pressed, whatever its tone. A question the
123 /// person must answer (the recovery offer) is this: a 5 s hide is a question
124 /// that disappears unanswered, and the edits it guards go with it.
125 pub(crate) sticky: bool,
126}
127
128impl Toast {
129 /// A toast whose tone is read off its words and that has no action.
130 pub(crate) fn new(text: SharedString) -> Toast {
131 let tone = Tone::of(&text);
132 Toast::with(text, tone, Vec::new(), false)
133 }
134
135 fn with(text: SharedString, tone: Tone, mut actions: Vec<ToastAction>, sticky: bool) -> Toast {
136 // A process-wide counter, not a per-queue one: a timer must be able to
137 // tell its own toast from one that was pushed later, whatever queue
138 // either lives in.
139 static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
140 actions.truncate(TOAST_ACTIONS_MAX);
141 Toast {
142 id: NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
143 text,
144 tone,
145 actions,
146 timer_armed: Cell::new(false),
147 sticky,
148 }
149 }
150
151 /// Whether this toast's hide timer runs at all: an info or warn toast that
152 /// is not sticky. Errors and sticky toasts wait for a button or the ✕.
153 pub(crate) fn hides(&self) -> bool {
154 self.tone.auto_hides() && !self.sticky
155 }
156}
157
158impl Deref for Toast {
159 type Target = SharedString;
160
161 fn deref(&self) -> &SharedString {
162 &self.text
163 }
164}
165
166/// The whole of the queue's policy, where it can be read at once and tested
167/// without a window: dedupe against the back, a ceiling, oldest out first.
168/// [`Player::notify_user`] is the door every message comes through; this is
169/// what the door does for a message with no action.
170pub(crate) fn push_notice(notices: &mut VecDeque<Toast>, message: SharedString) {
171 let tone = Tone::of(&message);
172 push_toast(notices, message, tone, Vec::new());
173}
174
175/// [`push_notice`] with its buttons attached, for the door that takes them.
176pub(crate) fn push_toast(
177 notices: &mut VecDeque<Toast>,
178 message: SharedString,
179 tone: Tone,
180 actions: Vec<ToastAction>,
181) {
182 push_toast_with(notices, message, tone, actions, false);
183}
184
185/// [`push_toast`] for a question that stays on screen until it is answered
186/// ([`Toast::sticky`]).
187pub(crate) fn push_sticky_toast(
188 notices: &mut VecDeque<Toast>,
189 message: SharedString,
190 tone: Tone,
191 actions: Vec<ToastAction>,
192) {
193 push_toast_with(notices, message, tone, actions, true);
194}
195
196fn push_toast_with(
197 notices: &mut VecDeque<Toast>,
198 message: SharedString,
199 tone: Tone,
200 actions: Vec<ToastAction>,
201 sticky: bool,
202) {
203 // A repeat of what is already at the back is dropped -- holding a key that
204 // refuses would otherwise fill the queue with one sentence, and the toasts
205 // would be a count of how long the key was held.
206 if notices.back().is_some_and(|toast| toast.text == message) {
207 return;
208 }
209 // One slot: the newest message replaces the one on screen, so an old failure
210 // never lingers under a newer line, and a success replaces the failure it
211 // follows. A question that waits for its answer is kept beside it.
212 notices.retain(|toast| toast.sticky);
213 if notices.len() >= NOTICES_MAX {
214 // The oldest goes, but never an unanswered question while anything else
215 // could go instead.
216 match notices.iter().position(|toast| !toast.sticky) {
217 Some(at) => {
218 notices.remove(at);
219 }
220 None => {
221 notices.pop_front();
222 }
223 }
224 }
225 notices.push_back(Toast::with(message, tone, actions, sticky));
226}
227
228/// The toast the status bar draws: the newest sticky one (a question still
229/// waiting for its answer), else the newest notice of all.
230pub(crate) fn current_toast(notices: &VecDeque<Toast>) -> Option<&Toast> {
231 notices
232 .iter()
233 .rev()
234 .find(|toast| toast.sticky)
235 .or_else(|| notices.back())
236}
237
238/// Takes one toast out of the queue by id. `true` when there was one to take.
239/// Every way a toast leaves -- its timer, its ✕, its action -- comes through
240/// here, and matching on the id is what keeps a late timer from taking a newer
241/// toast with the same words.
242pub(crate) fn remove_toast(notices: &mut VecDeque<Toast>, id: u64) -> bool {
243 let before = notices.len();
244 notices.retain(|toast| toast.id != id);
245 notices.len() != before
246}
247
248/// The tail an open/load notice grows when the file has sound the engine cannot
249/// decode: it plays perfectly, in silence, and that is the one thing the window
250/// would otherwise never say (the engine's own word for it, verbatim).
251pub(crate) fn audio_notice(session: &PlaybackSession) -> Option<String> {
252 session.audio_disabled_reason().map(audio_tail)
253}
254
255/// [`audio_notice`]'s own tail, for a reason already read -- the one place the
256/// engine's word is spelled into a line, so the open path and the mid-session
257/// one cannot drift apart.
258pub(crate) fn audio_tail(reason: &str) -> String {
259 format!(" — no audio: {reason}")
260}
261
262/// The same fact said on its own, for a device that dies *after* a file was
263/// opened: [`audio_notice`] is a tail to append to "OPENED x", and a death
264/// mid-session has no line to hang off -- so it leads with the state word the
265/// strip reads first, and the tail is the same one.
266pub(crate) fn audio_lost_line(reason: &str) -> String {
267 format!("Audio lost{}", audio_tail(reason))
268}
269
270/// A decode failure that arrives *after* a file was opened, said on its own
271/// line: the same shape as [`audio_lost_line`] and for the same reason -- a
272/// death mid-session has no open line to hang a tail off, so it leads with the
273/// state word the strip reads first.
274///
275/// The picture twin of the sound line above, and it exists because a decode
276/// failure used to reach nobody at all: the worker printed it to stderr and
277/// dropped the channel, and a closed channel is what a finished film looks like
278/// from the app's side. A file with a damaged middle froze on its last good
279/// picture and the transport said ENDED. The reason is the engine's own words,
280/// verbatim -- the app spells none of them.
281pub(crate) fn decode_failed_line(reason: &str) -> String {
282 format!("Decode failed — {reason}")
283}
284
285/// What a frame of a reason watch decides, as a pure value: the cache's own
286/// session generation against the frame's says whether the two are even talking
287/// about the same session, and only then what the reason did.
288///
289/// One type for every reason the engine states, not one per source: the sound
290/// device and the decode worker both write a string the app has to notice
291/// changed, and the thing that decides is the same comparison in both cases.
292#[derive(Clone, Copy, PartialEq, Eq, Debug)]
293pub(crate) enum ReasonStep {
294 /// The cache describes the session *before* this one
295 /// (`Player::session_swapped`): it is seeded and nothing is announced -- a
296 /// preview that opens or closes is not a device that came back.
297 Seed,
298 /// The same session's reason arrived, or changed to a new one.
299 Push,
300 /// ...and the same session's reason is gone: the line it earned is retracted.
301 Clear,
302 /// The ordinary frame.
303 Nothing,
304}
305
306/// [`Player::watch_audio`]'s and [`Player::watch_decode`]'s whole decision,
307/// pure: `cached_gen` is the session
308/// generation the cache describes, `session_gen` the one the frame is serving, and
309/// two reasons are what the engine says the sound is (`None` for sound that is
310/// up).
311///
312/// The generation is what keeps another session's reason out of this session's
313/// cache: `pump` serves the preview while one is up and the timeline otherwise,
314/// so a flip reads a reason that was never about the cached session at all -- a
315/// live device on one side and a dead one on the other is not a change, it is
316/// two different questions.
317pub(crate) fn reason_step(
318 cached_gen: u64,
319 session_gen: u64,
320 was: Option<&str>,
321 now: Option<&str>,
322) -> ReasonStep {
323 if cached_gen != session_gen {
324 return ReasonStep::Seed;
325 }
326 match (was, now) {
327 (Some(was), Some(now)) if was == now => ReasonStep::Nothing,
328 (_, Some(_)) => ReasonStep::Push,
329 (Some(_), None) => ReasonStep::Clear,
330 (None, None) => ReasonStep::Nothing,
331 }
332}
333
334/// What a *change* in the engine's sound reason does to the notice queue, as a
335/// pure step: the line pushed when a reason arrives, the same line taken back
336/// when the reason clears. [`Player::watch_audio`] is the only caller and owns
337/// the caching; this owns the queue, so a test can drive both directions without
338/// a window and without a device that dies on cue.
339///
340/// The reason is the engine's to write, and the engine's writer is the wave
341/// branch's: `tick`'s dead branch sets the lost-device reason and `rearm_audio`
342/// clears it (its own test observes both). This side is the reader and never
343/// spells the engine's words, so the end-to-end flip is asserted on the merged
344/// tree while this lane drives the same step through the seam below -- on this
345/// lane's base engine no path flips the reason at all.
346pub(crate) fn audio_change_notice(
347 notices: &mut VecDeque<Toast>,
348 was: Option<&str>,
349 now: Option<&str>,
350) {
351 match (was, now) {
352 (_, Some(reason)) if was != Some(reason) => {
353 // A lost device is an error: the film plays in silence until it is
354 // fixed, and the toast stays until someone has read it.
355 push_toast(
356 notices,
357 audio_lost_line(reason).into(),
358 Tone::Err,
359 Vec::new(),
360 );
361 }
362 // The sound is back: the line goes with it, or the strip keeps saying NO
363 // AUDIO over a film that plays. Only that line -- whatever else is
364 // queued is none of this step's business.
365 (Some(was), None) => {
366 let line = audio_lost_line(was);
367 notices.retain(|notice| notice.text.as_ref() != line.as_str());
368 }
369 _ => {}
370 }
371}
372
373/// What a *change* in the engine's **decode** reason does to the notice queue:
374/// the line pushed when a reason arrives, the same line taken back when the
375/// reason clears. [`audio_change_notice`]'s twin, step for step, because the
376/// thing that changed is the same kind of thing -- a reason the engine started
377/// or stopped stating between two frames.
378///
379/// The retraction is what keeps this from becoming noise: a decode that fails,
380/// is seeked away from and succeeds has to take its line back, or the strip
381/// keeps saying DECODE FAILED over a film that plays.
382pub(crate) fn decode_change_notice(
383 notices: &mut VecDeque<Toast>,
384 was: Option<&str>,
385 now: Option<&str>,
386) {
387 match (was, now) {
388 (_, Some(reason)) if was != Some(reason) => {
389 push_toast(
390 notices,
391 decode_failed_line(reason).into(),
392 Tone::Err,
393 Vec::new(),
394 );
395 }
396 (Some(was), None) => {
397 let line = decode_failed_line(was);
398 notices.retain(|notice| notice.text.as_ref() != line.as_str());
399 }
400 _ => {}
401 }
402}
403
404/// A toast's line is one line: what a too-long line must never do is lose its
405/// *state* word, which sits at the front, or stop mid-word with nothing saying
406/// it stopped (user report, `OPENED he_is_not_the_only_one.mp4 — 1 subtitle
407/// track(s) in `). Every message is a handful of words plus a file name, so the
408/// one part long enough to overflow alone is the name -- elided through its
409/// middle here, head and tail kept, before gpui's own end ellipsis
410/// ([`crate::ui::stance`]) ever has to cut a word.
411pub(crate) const LEDGER_WORD_MAX: usize = 28;
412
413pub(crate) fn ledger_line(message: &str) -> String {
414 message
415 .split(' ')
416 .map(|word| match word.chars().count() > LEDGER_WORD_MAX {
417 false => word.to_string(),
418 // Chars, not bytes: a name is whatever the filesystem holds.
419 true => {
420 let chars: Vec<char> = word.chars().collect();
421 let head = LEDGER_WORD_MAX / 2 - 1;
422 let tail = LEDGER_WORD_MAX - head - 1;
423 format!(
424 "{}…{}",
425 chars[..head].iter().collect::<String>(),
426 chars[chars.len() - tail..].iter().collect::<String>()
427 )
428 }
429 })
430 .collect::<Vec<_>>()
431 .join(" ")
432}
433
434#[cfg(test)]
435mod tests {
436 use super::*;
437
438 fn texts(notices: &VecDeque<Toast>) -> Vec<&str> {
439 notices.iter().map(|toast| toast.text.as_ref()).collect()
440 }
441
442 /// The class this guards: a notice queued behind an earlier one is never
443 /// *lost* -- `push_notice` still appends it to the back -- and the toast
444 /// status bar draws the newest, so the newest message is the
445 /// one a reader of `back()` always reaches.
446 ///
447 /// This is a value-level check on the queue only -- this binary has no
448 /// `TestAppContext`, so it cannot measure what actually painted.
449 #[test]
450 fn a_notice_queued_behind_an_unread_one_is_still_reachable_at_the_back() {
451 let mut notices = VecDeque::new();
452 push_notice(&mut notices, "SAVED test_h264.edith".into());
453 let refusal = "Can't close this gap: it would put A1 out of sync.";
454 push_notice(&mut notices, refusal.into());
455 // One slot: the refusal replaces the SAVED toast on screen, and it is
456 // reachable whole -- not truncated, because `push_notice` never
457 // touches a message's text.
458 assert_eq!(notices.len(), 1);
459 assert_eq!(notices.back().unwrap().text.as_ref(), refusal);
460 }
461
462 /// A repeat of what is already on screen adds nothing, so holding a key
463 /// that refuses cannot keep re-announcing one sentence. A repeat after a
464 /// different message is a new toast, and it replaces that one.
465 #[test]
466 fn a_repeat_of_the_back_is_dropped_and_a_repeat_after_another_is_not() {
467 let mut notices = VecDeque::new();
468 push_notice(&mut notices, "SNAP ON".into());
469 push_notice(&mut notices, "SNAP ON".into());
470 assert_eq!(texts(&notices), vec!["SNAP ON"]);
471 push_notice(&mut notices, "SNAP OFF".into());
472 assert_eq!(texts(&notices), vec!["SNAP OFF"]);
473 push_notice(&mut notices, "SNAP ON".into());
474 assert_eq!(texts(&notices), vec!["SNAP ON"]);
475 }
476
477 /// The queue has a ceiling, and the oldest message is the one that goes.
478 #[test]
479 fn a_sticky_question_never_hides_and_is_drawn_over_newer_notices() {
480 let mut notices = VecDeque::new();
481 push_sticky_toast(
482 &mut notices,
483 "Unsaved edits from 3 minutes ago were found".into(),
484 Tone::Info,
485 vec![ToastAction::Recover, ToastAction::Discard],
486 );
487 assert!(!notices.back().unwrap().hides(), "a question waits for its answer");
488 push_notice(&mut notices, "Snapped to 1.0s".into());
489 assert!(notices.back().unwrap().hides(), "an ordinary notice still hides");
490 assert_eq!(
491 current_toast(&notices).map(|t| t.text.as_ref()),
492 Some("Unsaved edits from 3 minutes ago were found"),
493 "the question stays on the bar over a notice pushed after it"
494 );
495 }
496
497 /// The question is kept beside the one ordinary slot: no notice pushed
498 /// after it can drop it.
499 #[test]
500 fn a_sticky_question_survives_newer_notices() {
501 let mut notices = VecDeque::new();
502 push_sticky_toast(&mut notices, "Unsaved edits were found".into(), Tone::Info, Vec::new());
503 for n in 0..NOTICES_MAX + 3 {
504 push_notice(&mut notices, format!("NOTE {n}").into());
505 }
506 assert_eq!(notices.len(), 2);
507 assert!(notices.iter().any(|t| t.sticky), "the question is the one never dropped");
508 assert_eq!(notices.back().unwrap().text.as_ref(), format!("NOTE {}", NOTICES_MAX + 2));
509 }
510
511 #[test]
512 fn with_no_question_the_bar_shows_the_newest_notice() {
513 let mut notices = VecDeque::new();
514 push_notice(&mut notices, "A".into());
515 push_notice(&mut notices, "B".into());
516 assert_eq!(current_toast(&notices).map(|t| t.text.as_ref()), Some("B"));
517 assert!(current_toast(&VecDeque::new()).is_none());
518 }
519
520 /// One slot: however many notices arrive, only the newest is kept.
521 #[test]
522 fn the_newest_notice_replaces_the_one_before_it() {
523 let mut notices = VecDeque::new();
524 for n in 0..NOTICES_MAX + 2 {
525 push_notice(&mut notices, format!("NOTE {n}").into());
526 }
527 assert_eq!(notices.len(), 1);
528 assert_eq!(
529 notices.back().unwrap().text.as_ref(),
530 format!("NOTE {}", NOTICES_MAX + 1)
531 );
532 }
533
534 /// Every toast has its own id, so a timer started for one cannot hide
535 /// another -- including one that says exactly the same thing.
536 #[test]
537 fn a_stale_timer_cannot_hide_a_newer_toast_with_the_same_words() {
538 let mut notices = VecDeque::new();
539 push_notice(&mut notices, "SNAP ON".into());
540 let first = notices.back().unwrap().id;
541 assert!(remove_toast(&mut notices, first));
542 push_notice(&mut notices, "SNAP ON".into());
543 let second = notices.back().unwrap().id;
544 assert_ne!(first, second);
545 assert!(
546 !remove_toast(&mut notices, first),
547 "the old timer found something"
548 );
549 assert_eq!(notices.len(), 1);
550 assert!(remove_toast(&mut notices, second));
551 assert!(notices.is_empty());
552 }
553
554 /// The tone is read off the words the way the colour always was: a failure
555 /// or refusal is an error, a no-op is a warning, and the rest is information.
556 #[test]
557 fn the_tone_is_read_off_the_words() {
558 assert_eq!(Tone::of("SCAN FAILED: no audio"), Tone::Err);
559 assert_eq!(Tone::of("the clip REFUSED to move"), Tone::Err);
560 assert_eq!(Tone::of("Nothing detached — not grouped"), Tone::Warn);
561 assert_eq!(Tone::of("SNAP ON"), Tone::Info);
562 assert_eq!(
563 Tone::of(&format!("{}out.mp4", crate::EXPORT_DONE)),
564 Tone::Info
565 );
566 }
567
568 /// The same words in sentence case read the same tone: the sweep to sentence
569 /// case must not move a warning or an error to information.
570 #[test]
571 fn the_tone_is_read_off_the_words_in_any_case() {
572 assert_eq!(Tone::of("Scan failed: no audio"), Tone::Err);
573 assert_eq!(Tone::of("The clip refused to move"), Tone::Err);
574 assert_eq!(Tone::of("Cannot move the clip"), Tone::Err);
575 assert_eq!(Tone::of("Nothing detached: not grouped"), Tone::Warn);
576 assert_eq!(
577 Tone::of("Nothing added: this file has no playable stream"),
578 Tone::Warn
579 );
580 assert_eq!(Tone::of("Snap on"), Tone::Info);
581 assert_eq!(Tone::of("Clip deleted"), Tone::Info);
582 }
583
584 /// A keyword counts only as a whole word: "piano" is not "NO", and
585 /// "nothing" inside a longer word is not the warning.
586 #[test]
587 fn the_tone_keywords_match_whole_words_only() {
588 assert_eq!(Tone::of("Playing the piano track"), Tone::Info);
589 assert_eq!(Tone::of("Piano sample saved"), Tone::Info);
590 assert_eq!(Tone::of("Renamed the piano clip"), Tone::Info);
591 assert_eq!(Tone::of("No audio on this clip"), Tone::Warn);
592 assert_eq!(Tone::of("Could not open the file"), Tone::Err);
593 }
594
595 /// Info and warn time out; errors stay until they are dismissed. This is
596 /// the rule the stack's timer is built on, so it is pinned where a change
597 /// to the tone would have to show up.
598 #[test]
599 fn only_errors_stay_on_screen_until_dismissed() {
600 assert!(Tone::Info.auto_hides());
601 assert!(Tone::Warn.auto_hides());
602 assert!(!Tone::Err.auto_hides());
603 assert_eq!(Toast::new("SNAP ON".into()).tone, Tone::Info);
604 assert!(!Toast::new("Decode failed — x".into()).tone.auto_hides());
605 }
606
607 /// The engine losing the sound is an error, and getting it back takes the
608 /// same line away again -- and nothing else in the queue.
609 #[test]
610 fn a_lost_sound_is_an_error_and_its_return_retracts_only_its_line() {
611 // A question stays on screen whatever else arrives, so it is the
612 // line that must survive the retraction.
613 let mut notices = VecDeque::new();
614 push_sticky_toast(&mut notices, "Unsaved edits were found".into(), Tone::Info, Vec::new());
615 audio_change_notice(&mut notices, None, Some("device gone"));
616 let lost = audio_lost_line("device gone");
617 assert_eq!(notices.back().unwrap().text.as_ref(), lost);
618 assert_eq!(notices.back().unwrap().tone, Tone::Err);
619 audio_change_notice(&mut notices, Some("device gone"), None);
620 assert_eq!(texts(&notices), vec!["Unsaved edits were found"]);
621 }
622
623 /// The line the strip paints keeps its state word and never stops
624 /// mid-word without a sign: a long name loses its middle, everything
625 /// short is untouched, and the count at the end survives.
626 #[test]
627 fn a_long_name_loses_its_middle_rather_than_the_state_word() {
628 assert_eq!(ledger_line("SNAP OFF"), "SNAP OFF");
629 let long =
630 ledger_line("OPENED he_is_not_the_only_one_at_all_here.mp4 · 1 subtitle track(s)");
631 assert!(long.starts_with("OPENED "), "{long}");
632 assert!(long.ends_with(" · 1 subtitle track(s)"), "{long}");
633 assert!(long.contains('…'), "{long}");
634 assert!(
635 long.split(' ')
636 .all(|w| w.chars().count() <= LEDGER_WORD_MAX),
637 "{long}"
638 );
639 }
640
641 /// The delete and lift toasts carry Undo as their action, read as
642 /// information (so they hide on their own, DESIGN §8), and are removed by
643 /// id the way the button removes them before it acts.
644 #[test]
645 fn a_delete_toast_carries_undo_and_goes_by_its_id() {
646 let mut notices = VecDeque::new();
647 push_toast(
648 &mut notices,
649 "Clip deleted".into(),
650 Tone::of("Clip deleted"),
651 vec![ToastAction::Undo],
652 );
653 let toast = notices.back().unwrap();
654 assert_eq!(toast.actions, [ToastAction::Undo]);
655 assert_eq!(toast.tone, Tone::Info);
656 assert!(toast.tone.auto_hides());
657 let id = toast.id;
658 assert!(remove_toast(&mut notices, id));
659 assert!(notices.is_empty());
660 }
661
662 /// An export's outcome offers Play and Show in folder, in that order, and
663 /// a toast keeps at most two buttons however many it is handed.
664 #[test]
665 fn a_toast_keeps_up_to_two_buttons_in_the_order_given() {
666 let path = PathBuf::from("/tmp/out.mp4");
667 let mut notices = VecDeque::new();
668 push_toast(
669 &mut notices,
670 "Export done → out.mp4".into(),
671 Tone::Info,
672 vec![
673 ToastAction::Play(path.clone()),
674 ToastAction::ShowInFolder(path.clone()),
675 ],
676 );
677 assert_eq!(
678 notices.back().unwrap().actions,
679 [
680 ToastAction::Play(path.clone()),
681 ToastAction::ShowInFolder(path.clone()),
682 ]
683 );
684 push_toast(
685 &mut notices,
686 "three buttons".into(),
687 Tone::Info,
688 vec![
689 ToastAction::Undo,
690 ToastAction::Unlock(Lane::V1),
691 ToastAction::ShowInFolder(path),
692 ],
693 );
694 assert_eq!(notices.back().unwrap().actions.len(), TOAST_ACTIONS_MAX);
695 }
696
697 /// A message with no button carries none, and the export's own toast is
698 /// still a toast that hides on its own rather than waiting for a ✕.
699 #[test]
700 fn a_plain_notice_has_no_buttons() {
701 let mut notices = VecDeque::new();
702 push_notice(&mut notices, "Clip moved".into());
703 let toast = notices.back().unwrap();
704 assert!(toast.actions.is_empty());
705 assert!(toast.tone.auto_hides());
706 }
707}