Coverage Report

Created: 2026-12-05 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
super-voice-app-core/src/pages/clips.rs
Line
Count
Source
1
// SPDX-License-Identifier: GPL-3.0-only
2
//! The Clips page: making a clip from text through the daemon, keeping it in
3
//! the clips folder, and playing, exporting and deleting what is kept.
4
//!
5
//! The files are the truth (see [`crate::clips`]). A clip is written once,
6
//! when it is made, and never changed.
7
8
use std::path::Path;
9
use std::sync::Arc;
10
use std::time::{Duration, Instant};
11
12
use futures_util::future::{AbortHandle, AbortRegistration, Abortable};
13
14
use crate::audio::player::Player;
15
use crate::clips::{self, Clip};
16
use crate::pages::model_voice;
17
use crate::state::clips::{ClipsState, Making, Playing};
18
use crate::state::{TextBuffer, VoiceState};
19
20
/// What happened on the page: something the user did, or the answer to work
21
/// an [`Effect`] started.
22
#[derive(Debug, Clone)]
23
pub enum Input {
24
    /// Read the folder again.
25
    Reload,
26
    /// The folder was read.
27
    Loaded(Result<Vec<Clip>, String>),
28
    /// Make a clip of what the draft says. `voice` is the voice text to speech
29
    /// speaks in, as the app names it, kept with the clip and shown on its row.
30
    Make { voice: Option<String> },
31
    /// The clip was made and kept, or why not.
32
    Made(Result<Clip, String>),
33
    /// Stop making the clip.
34
    Cancel,
35
    /// A moment passed: a clip that has played out is let go.
36
    Tick,
37
    /// Play the clip with this id.
38
    Play(String),
39
    /// The clip's audio was read: its samples and rate.
40
    Ready {
41
        id: String,
42
        result: Result<(Vec<f32>, u32), String>,
43
    },
44
    /// Play the clip playing from this far into it, 0 to 1. A paused clip
45
    /// stays paused, there.
46
    Seek(f32),
47
    /// Pause the clip playing, where it is.
48
    Pause,
49
    /// Play the paused clip on from where it was paused.
50
    Resume,
51
    /// Stop the clip playing, or paused.
52
    Stop,
53
    /// Export the clip with this id.
54
    Export(String),
55
    /// The export finished: where the clip went, or `None` when the user
56
    /// closed the dialog.
57
    Exported {
58
        id: String,
59
        result: Result<Option<String>, String>,
60
    },
61
    /// Delete was pressed once for this clip.
62
    DeleteRequested(String),
63
    /// The delete was called off.
64
    DeleteCancelled,
65
    /// Delete was pressed again: delete this clip.
66
    DeleteConfirmed(String),
67
    /// The clip's files were deleted, or why not.
68
    Deleted {
69
        id: String,
70
        result: Result<(), String>,
71
    },
72
}
73
74
/// Work [`update`] asks for. Each says which runner does it and what it
75
/// answers with.
76
#[derive(Debug)]
77
pub enum Effect {
78
    /// Read the folder ([`run_list`]); answers [`Input::Loaded`].
79
    List,
80
    /// Have the daemon speak `text` and keep it as a clip ([`run_make`]);
81
    /// answers [`Input::Made`], or nothing once [`Input::Cancel`] aborted it
82
    /// through `abort`.
83
    Make {
84
        text: String,
85
        voice: Option<String>,
86
        abort: AbortRegistration,
87
    },
88
    /// Read a clip's audio ([`run_samples`]); answers [`Input::Ready`].
89
    ReadSamples(String),
90
    /// Ask the user where to export the clip, under this name, then write it
91
    /// there with [`export_to`]; answers [`Input::Exported`]. The dialog is
92
    /// the app's own.
93
    Export { id: String, name: String },
94
    /// Delete a clip's files ([`run_delete`]); answers [`Input::Deleted`].
95
    Delete(String),
96
}
97
98
/// Something to tell the user. Each app says it in its own words.
99
#[derive(Debug, Clone, PartialEq, Eq)]
100
pub enum Notice {
101
    /// The folder could not be read.
102
    CouldNotRead(String),
103
    /// The clip could not be made.
104
    CouldNotMake(String),
105
    /// The clip could not play.
106
    CouldNotPlay(String),
107
    /// The clip could not be exported.
108
    CouldNotExport(String),
109
    /// The clip could not be deleted.
110
    CouldNotDelete(String),
111
}
112
113
/// What an [`update`] asks of the app.
114
#[derive(Debug, Default)]
115
pub struct Outcome {
116
    /// The work to start, in order.
117
    pub effects: Vec<Effect>,
118
    /// Whether the page's notice is out of date and goes. Applied before
119
    /// [`notice`](Self::notice).
120
    pub clear_notice: bool,
121
    /// What to tell the user.
122
    pub notice: Option<Notice>,
123
}
124
125
/// What `input` does to the page.
126
26
pub fn update<B: TextBuffer>(state: &mut ClipsState<B>, input: Input) -> Outcome {
127
26
    let mut out = Outcome::default();
128
26
    match input {
129
0
        Input::Reload => out.effects.push(Effect::List),
130
        Input::Loaded(result) => {
131
0
            state.loaded = true;
132
0
            match result {
133
0
                Ok(items) => state.items = items,
134
0
                Err(e) => out.notice = Some(Notice::CouldNotRead(e)),
135
            }
136
        }
137
        make @ (Input::Make { .. } | Input::Made(_) | Input::Cancel) => {
138
7
            making(state, make, &mut out);
139
        }
140
        play @ (Input::Tick
141
        | Input::Play(_)
142
        | Input::Ready { .. }
143
        | Input::Seek(_)
144
        | Input::Pause
145
        | Input::Resume
146
        | Input::Stop) => {
147
16
            playing(state, play, &mut out);
148
        }
149
3
        kept => kept_clip(state, kept, &mut out),
150
    }
151
26
    out
152
26
}
153
154
/// The next clip: its text, making it, and stopping that.
155
7
fn making<B: TextBuffer>(state: &mut ClipsState<B>, input: Input, out: &mut Outcome) {
156
7
    match input {
157
        Input::Make { voice } => {
158
5
            let text = state.draft.text().trim().to_string();
159
5
            if text.is_empty() || 
state.making.is_some()4
{
160
2
                return;
161
3
            }
162
3
            out.clear_notice = true;
163
3
            state.exported = None;
164
3
            let (handle, abort) = AbortHandle::new_pair();
165
3
            state.making = Some(Making {
166
3
                started: Instant::now(),
167
3
                handle,
168
3
            });
169
3
            out.effects.push(Effect::Make { text, voice, abort });
170
        }
171
        Input::Made(result) => {
172
1
            state.making = None;
173
1
            match result {
174
                Ok(clip) => {
175
1
                    state.put(clip);
176
1
                    state.draft.replace_text("");
177
                }
178
0
                Err(e) => out.notice = Some(Notice::CouldNotMake(e)),
179
            }
180
        }
181
        Input::Cancel => {
182
            // Aborting the request closes it, which stops the synthesis.
183
1
            if let Some(making) = state.making.take() {
184
1
                making.handle.abort();
185
0
            }
186
        }
187
0
        _ => {}
188
    }
189
7
}
190
191
/// Playing a clip, and stopping it.
192
16
fn playing<B>(state: &mut ClipsState<B>, input: Input, out: &mut Outcome) {
193
16
    match input {
194
        // A clip that has played out is let go; one that could not play says
195
        // why.
196
        Input::Tick => {
197
1
            let ended = state
198
1
                .playing
199
1
                .as_ref()
200
1
                .and_then(|p| p.player.as_ref())
201
0
                .filter(|player| player.finished())
202
1
                .map(Player::error);
203
1
            if let Some(error) = ended {
204
0
                state.playing = None;
205
0
                if let Some(e) = error {
206
0
                    out.notice = Some(Notice::CouldNotPlay(e));
207
0
                }
208
1
            }
209
        }
210
        Input::Play(id) => {
211
5
            out.clear_notice = true;
212
            // One at a time: the one playing stops when it is let go.
213
5
            state.playing = Some(Playing::new(id.clone()));
214
5
            out.effects.push(Effect::ReadSamples(id));
215
        }
216
        Input::Ready { id, result } => {
217
            // Stopped, or another clip asked for, while this one was read.
218
1
            let Some(playing) = state.playing.as_mut().filter(|p| p.id == id) else {
219
1
                return;
220
            };
221
0
            match result {
222
                // The player is held in the state, and plays until let go.
223
                Ok((samples, rate)) => {
224
0
                    let audio: Arc<[f32]> = samples.into();
225
0
                    playing.player = Some(Player::start(audio.to_vec(), rate));
226
0
                    playing.audio = Some((audio, rate));
227
                }
228
                Err(e) => {
229
0
                    state.playing = None;
230
0
                    out.notice = Some(Notice::CouldNotPlay(e));
231
                }
232
            }
233
        }
234
        // A new player from there: the one playing stops when it is let go.
235
        // Paused, it only moves where it resumes from.
236
        Input::Seek(fraction) => {
237
3
            let Some(playing) = state.playing.as_mut() else {
238
1
                return;
239
            };
240
2
            let Some((audio, rate)) = playing.audio.clone() else {
241
1
                return;
242
            };
243
1
            if rate == 0 {
244
0
                return;
245
1
            }
246
            #[allow(
247
                clippy::cast_possible_truncation,
248
                clippy::cast_sign_loss,
249
                clippy::cast_precision_loss
250
            )]
251
1
            let frame = ((audio.len() as f64) * f64::from(fraction.clamp(0.0, 1.0))) as usize;
252
1
            let frame = frame.min(audio.len());
253
            #[allow(clippy::cast_precision_loss)]
254
1
            let from = Duration::from_secs_f64(frame as f64 / f64::from(rate));
255
1
            playing.from = from;
256
1
            if !playing.paused {
257
0
                playing.player = Some(Player::start(audio[frame..].to_vec(), rate));
258
1
            }
259
        }
260
        // Letting the player go closes the speakers; where it was is kept.
261
        Input::Pause => {
262
3
            let Some(playing) = state.playing.as_mut() else {
263
0
                return;
264
            };
265
3
            if playing.paused || playing.audio.is_none() {
266
1
                return;
267
2
            }
268
2
            let Some(at) = playing.position() else {
269
0
                return;
270
            };
271
2
            playing.player = None;
272
2
            playing.from = at;
273
2
            playing.paused = true;
274
        }
275
        Input::Resume => {
276
1
            let Some(playing) = state.playing.as_mut().filter(|p| p.paused) else {
277
1
                return;
278
            };
279
0
            let Some((audio, rate)) = playing.audio.clone() else {
280
0
                return;
281
            };
282
0
            playing.paused = false;
283
0
            let frame = frame_at(audio.len(), rate, playing.from);
284
0
            playing.player = Some(Player::start(audio[frame..].to_vec(), rate));
285
        }
286
2
        Input::Stop => state.playing = None,
287
0
        _ => {}
288
    }
289
16
}
290
291
/// The frame `at` into audio `len` frames long at `rate`, within it.
292
3
fn frame_at(len: usize, rate: u32, at: Duration) -> usize {
293
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
294
3
    let frame = (at.as_secs_f64() * f64::from(rate)).round() as usize;
295
3
    frame.min(len)
296
3
}
297
298
/// The voice a clip made now is spoken in, as the user knows it: the voice
299
/// text to speech speaks in, by its label. What [`Input::Make`] carries.
300
/// `None` while `voice` doesn't describe `(source, model)`, the synthesis
301
/// model, or says no voice.
302
#[must_use]
303
2
pub fn voice_label(voice: &VoiceState, source: &str, model: &str) -> Option<String> {
304
2
    if !model_voice::shows(voice, source, model) {
305
1
        return None;
306
1
    }
307
1
    let id = voice.resolution.as_ref()
?0
.effective.as_ref()
?0
;
308
    Some(
309
1
        voice
310
1
            .choices
311
1
            .iter()
312
1
            .find(|v| &v.id == id)
313
1
            .map_or_else(|| 
id0
.clone(), |v| v.label.clone()),
314
    )
315
2
}
316
317
/// When a clip was made, as its row says it: "Today, 09:40", "Yesterday,
318
/// 17:12", or the date and time.
319
#[must_use]
320
3
pub fn when(created: chrono::NaiveDateTime, today: chrono::NaiveDate) -> String {
321
3
    let time = created.format("%H:%M").to_string();
322
3
    let day = created.date();
323
3
    if day == today {
324
1
        crate::i18n::text("today-at", &[("time", &time)])
325
2
    } else if today.pred_opt() == Some(day) {
326
1
        crate::i18n::text("yesterday-at", &[("time", &time)])
327
    } else {
328
1
        created.format("%Y-%m-%d %H:%M").to_string()
329
    }
330
3
    .replace(['\u{2068}', '\u{2069}'], "")
331
3
}
332
333
/// `length` as minutes and seconds: "0:06", "1:42".
334
#[must_use]
335
2
pub fn clock(length: Duration) -> String {
336
2
    let seconds = length.as_secs();
337
2
    format!("{}:{:02}", seconds / 60, seconds % 60)
338
2
}
339
340
/// A clip's first line with words on it, cut to `max_chars` with an
341
/// ellipsis, at the last whole word: its name in a list or a question.
342
#[must_use]
343
2
pub fn first_line(text: &str, max_chars: usize) -> String {
344
2
    let line = text
345
2
        .lines()
346
2
        .map(str::trim)
347
3
        .find(|l| !l.is_empty())
348
        .unwrap_or_default();
349
2
    let chars: Vec<char> = line.chars().collect();
350
2
    if chars.len() <= max_chars {
351
1
        return line.to_string();
352
1
    }
353
1
    let mut end = max_chars;
354
1
    if !chars[end].is_whitespace()
355
3
        && let Some(space) = 
chars[..end].iter()1
.rposition(|c| c.is_whitespace())
356
    {
357
1
        end = space;
358
0
    }
359
1
    let cut: String = chars[..end].iter().collect();
360
1
    let cut = cut.trim_end_matches(|c: char| c.is_whitespace() || ".,;:!?-".contains(c));
361
1
    format!("{cut}\u{2026}")
362
2
}
363
364
/// Roughly how fast speech goes, for the estimate of how long a clip will
365
/// play: about 150 words a minute.
366
const SECONDS_PER_WORD: f32 = 0.4;
367
368
/// About how many seconds `words` words take to say, rounded up.
369
#[must_use]
370
3
pub fn estimated_seconds(words: usize) -> u64 {
371
    #[allow(clippy::cast_precision_loss)]
372
3
    let seconds = (words as f32 * SECONDS_PER_WORD).ceil();
373
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
374
3
    let seconds = seconds as u64;
375
3
    seconds
376
3
}
377
378
/// Exporting and deleting a kept clip.
379
3
fn kept_clip<B>(state: &mut ClipsState<B>, input: Input, out: &mut Outcome) {
380
3
    match input {
381
        Input::Export(id) => {
382
            // A retry starts clean, as the Notes page's does.
383
1
            out.clear_notice = true;
384
1
            state.exported = None;
385
1
            if let Some(clip) = state.clip(&id) {
386
1
                let name = clips::export_name(clip);
387
1
                out.effects.push(Effect::Export { id, name });
388
0
            }
389
        }
390
0
        Input::Exported { id, result } => match result {
391
0
            Ok(Some(path)) => state.exported = Some((id, path)),
392
0
            Ok(None) => {}
393
0
            Err(e) => out.notice = Some(Notice::CouldNotExport(e)),
394
        },
395
396
0
        Input::DeleteRequested(id) => state.confirming_delete = Some(id),
397
0
        Input::DeleteCancelled => state.confirming_delete = None,
398
        Input::DeleteConfirmed(id) => {
399
1
            state.confirming_delete = None;
400
1
            if state.is_playing(&id) {
401
1
                state.playing = None;
402
0
            }
403
1
            if state.exported.as_ref().is_some_and(|(e, _)| *e == id) {
404
1
                state.exported = None;
405
0
            }
406
2
            
state.items1
.retain(|c| c.id != id);
407
1
            out.effects.push(Effect::Delete(id));
408
        }
409
        Input::Deleted { id, result: Err(e) } => {
410
1
            log::warn!("Could not delete the clip {
id0
}: {
e0
}");
411
1
            out.notice = Some(Notice::CouldNotDelete(e));
412
            // The list dropped it already; read back what is there.
413
1
            out.effects.push(Effect::List);
414
        }
415
0
        _ => {}
416
    }
417
3
}
418
419
/// Read the folder.
420
0
pub async fn run_list() -> Input {
421
0
    Input::Loaded(clips::list(&clips::dir()).await.map_err(|e| e.to_string()))
422
0
}
423
424
/// Have the daemon speak `text`, and keep the audio as a clip made now. `None`
425
/// when [`Input::Cancel`] aborted it first.
426
0
pub async fn run_make(
427
0
    text: String,
428
0
    voice: Option<String>,
429
0
    abort: AbortRegistration,
430
0
) -> Option<Input> {
431
0
    Abortable::new(make(text, voice), abort)
432
0
        .await
433
        .ok()
434
0
        .map(Input::Made)
435
0
}
436
437
0
async fn make(text: String, voice: Option<String>) -> Result<Clip, String> {
438
0
    let wav = crate::daemon::client::v1::synthesize::synthesize(text.clone())
439
0
        .await
440
0
        .map_err(|e| e.to_string())?;
441
0
    let now = chrono::Local::now().naive_local();
442
0
    clips::create(&clips::dir(), wav, text, voice, now)
443
0
        .await
444
0
        .map_err(|e| e.to_string())
445
0
}
446
447
/// Read the clip `id`'s audio.
448
0
pub async fn run_samples(id: String) -> Input {
449
0
    let result = clips::samples(&clips::dir(), &id)
450
0
        .await
451
0
        .map_err(|e| e.to_string());
452
0
    Input::Ready { id, result }
453
0
}
454
455
/// Copy the clip `id` to where the user chose. Answers what
456
/// [`Input::Exported`] carries: where it went.
457
///
458
/// # Errors
459
///
460
/// When the clip could not be written there, saying where.
461
0
pub async fn export_to(id: &str, chosen: &Path) -> Result<Option<String>, String> {
462
0
    let path = clips::export_path(chosen);
463
0
    clips::export(&clips::dir(), id, &path)
464
0
        .await
465
0
        .map_err(|e| format!("{}: {e}", path.display()))?;
466
0
    Ok(Some(path.display().to_string()))
467
0
}
468
469
/// Delete the clip `id`'s files.
470
0
pub async fn run_delete(id: String) -> Input {
471
0
    let result = clips::delete(&clips::dir(), &id)
472
0
        .await
473
0
        .map_err(|e| e.to_string());
474
0
    Input::Deleted { id, result }
475
0
}
476
477
#[cfg(test)]
478
mod tests {
479
    use super::*;
480
481
    type State = ClipsState<String>;
482
483
6
    fn clip(id: &str) -> Clip {
484
6
        Clip {
485
6
            id: id.to_string(),
486
6
            created: chrono::NaiveDateTime::parse_from_str("2026-11-20 10:00", "%Y-%m-%d %H:%M")
487
6
                .expect("a time"),
488
6
            text: format!("{id} says this"),
489
6
            voice: None,
490
6
            seconds: 1.0,
491
6
        }
492
6
    }
493
494
    #[test]
495
1
    fn nothing_is_made_of_an_empty_draft_or_while_one_is_making() {
496
1
        let mut state = State::default();
497
1
        assert!(
498
1
            update(&mut state, Input::Make { voice: None })
499
1
                .effects
500
1
                .is_empty()
501
        );
502
503
1
        state.draft = "  hello  ".into();
504
1
        let out = update(
505
1
            &mut state,
506
1
            Input::Make {
507
1
                voice: Some("Ava".into()),
508
1
            },
509
1
        );
510
1
        assert!(matches!(
511
1
            out.effects.as_slice(),
512
1
            [Effect::Make { text, voice: Some(v), .. }] if text == "hello" && v == "Ava"
513
        ));
514
1
        assert!(state.making.is_some());
515
1
        assert!(
516
1
            update(&mut state, Input::Make { voice: None })
517
1
                .effects
518
1
                .is_empty()
519
        );
520
1
    }
521
522
    #[test]
523
1
    fn a_made_clip_goes_to_the_top_and_clears_the_draft() {
524
1
        let mut state = State::default();
525
1
        state.put(clip("older"));
526
1
        state.draft = "words".into();
527
1
        update(&mut state, Input::Make { voice: None });
528
529
1
        update(&mut state, Input::Made(Ok(clip("newer"))));
530
1
        assert!(state.making.is_none());
531
1
        assert_eq!(state.draft, "");
532
2
        let ids: Vec<&str> = 
state.items.iter()1
.map(|c| c.id.as_str()).collect();
533
1
        assert_eq!(ids, ["newer", "older"]);
534
1
    }
535
536
    #[test]
537
1
    fn cancelling_aborts_the_request() {
538
1
        let mut state = State::default();
539
1
        state.draft = "words".into();
540
1
        update(&mut state, Input::Make { voice: None });
541
1
        let handle = state.making.as_ref().expect("making").handle.clone();
542
543
1
        update(&mut state, Input::Cancel);
544
1
        assert!(handle.is_aborted());
545
1
        assert!(state.making.is_none());
546
1
    }
547
548
    #[test]
549
1
    fn audio_read_for_a_clip_no_longer_wanted_is_dropped() {
550
1
        let mut state = State::default();
551
1
        update(&mut state, Input::Play("a".into()));
552
1
        update(&mut state, Input::Play("b".into()));
553
1
        let out = update(
554
1
            &mut state,
555
1
            Input::Ready {
556
1
                id: "a".into(),
557
1
                result: Ok((Vec::new(), 24_000)),
558
1
            },
559
1
        );
560
1
        assert!(out.notice.is_none());
561
1
        assert!(
562
1
            state
563
1
                .playing
564
1
                .as_ref()
565
1
                .is_some_and(|p| p.id == "b" && p.player.is_none())
566
        );
567
1
    }
568
569
    #[test]
570
1
    fn a_deleted_clip_leaves_the_list_and_stops_playing() {
571
1
        let mut state = State::default();
572
1
        state.put(clip("a"));
573
1
        state.put(clip("b"));
574
1
        update(&mut state, Input::Play("a".into()));
575
1
        state.exported = Some(("a".into(), "/tmp/a.wav".into()));
576
577
1
        let out = update(&mut state, Input::DeleteConfirmed("a".into()));
578
1
        assert!(matches!(out.effects.as_slice(), [Effect::Delete(id)] if id == "a"));
579
1
        assert!(state.playing.is_none());
580
1
        assert!(state.exported.is_none());
581
1
        assert!(state.clip("a").is_none());
582
1
    }
583
584
    #[test]
585
1
    fn a_failed_delete_reads_the_folder_back() {
586
1
        let mut state = State::default();
587
1
        let out = update(
588
1
            &mut state,
589
1
            Input::Deleted {
590
1
                id: "a".into(),
591
1
                result: Err("read-only".into()),
592
1
            },
593
1
        );
594
1
        assert_eq!(out.notice, Some(Notice::CouldNotDelete("read-only".into())));
595
1
        assert!(matches!(out.effects.as_slice(), [Effect::List]));
596
1
    }
597
598
    #[test]
599
1
    fn export_names_the_file_after_the_clip() {
600
1
        let mut state = State::default();
601
1
        state.put(clip("a"));
602
1
        let out = update(&mut state, Input::Export("a".into()));
603
1
        assert!(out.clear_notice);
604
1
        assert!(matches!(
605
1
            out.effects.as_slice(),
606
1
            [Effect::Export { id, name }] if id == "a" && *name == clips::export_name(&clip("a"))
607
        ));
608
1
    }
609
610
    #[test]
611
1
    fn a_seek_waits_for_the_audio() {
612
1
        let mut state = State::default();
613
1
        update(&mut state, Input::Play("a".into()));
614
1
        update(&mut state, Input::Seek(0.5));
615
1
        let playing = state.playing.as_ref().expect("playing");
616
1
        assert!(playing.player.is_none());
617
1
        assert_eq!(playing.from, Duration::ZERO);
618
1
        update(&mut state, Input::Stop);
619
1
        update(&mut state, Input::Seek(0.5));
620
1
        assert!(state.playing.is_none());
621
1
    }
622
623
    /// A clip playing, with its audio read: four seconds at 1 kHz, its
624
    /// player held two seconds in (no speakers are opened).
625
2
    fn playing_two_seconds_in() -> State {
626
2
        let mut state = State::default();
627
2
        let mut playing = Playing::new("a".into());
628
2
        playing.audio = Some((vec![0.0; 4_000].into(), 1_000));
629
2
        playing.player = Some(Player::held_at(
630
2
            Duration::from_secs(4),
631
2
            Duration::from_secs(2),
632
2
        ));
633
2
        state.playing = Some(playing);
634
2
        state
635
2
    }
636
637
    #[test]
638
1
    fn a_pause_keeps_where_the_clip_was_and_lets_the_speakers_go() {
639
1
        let mut state = playing_two_seconds_in();
640
1
        update(&mut state, Input::Pause);
641
1
        let playing = state.playing.as_ref().expect("still there");
642
1
        assert!(playing.paused);
643
1
        assert!(playing.player.is_none());
644
1
        assert_eq!(playing.position(), Some(Duration::from_secs(2)));
645
        // A tick leaves a paused clip alone.
646
1
        update(&mut state, Input::Tick);
647
1
        assert!(state.playing.is_some());
648
        // Stop lets it go.
649
1
        update(&mut state, Input::Stop);
650
1
        assert!(state.playing.is_none());
651
1
    }
652
653
    #[test]
654
1
    fn a_seek_while_paused_moves_where_it_resumes_and_stays_paused() {
655
1
        let mut state = playing_two_seconds_in();
656
1
        update(&mut state, Input::Pause);
657
1
        update(&mut state, Input::Seek(0.75));
658
1
        let playing = state.playing.as_ref().expect("still there");
659
1
        assert!(playing.paused && playing.player.is_none());
660
1
        assert_eq!(playing.position(), Some(Duration::from_secs(3)));
661
1
    }
662
663
    #[test]
664
1
    fn resume_needs_a_paused_clip_and_pause_one_that_plays() {
665
1
        let mut state = State::default();
666
1
        update(&mut state, Input::Play("a".into()));
667
        // Its audio isn't read yet: nothing to pause.
668
1
        update(&mut state, Input::Pause);
669
1
        assert!(!state.playing.as_ref().expect("asked for").paused);
670
        // Not paused: nothing to resume.
671
1
        update(&mut state, Input::Resume);
672
1
        assert!(state.playing.as_ref().expect("asked for").player.is_none());
673
1
    }
674
675
    #[test]
676
1
    fn a_resume_starts_where_the_clip_was_paused() {
677
1
        assert_eq!(frame_at(4_000, 1_000, Duration::from_secs(2)), 2_000);
678
1
        assert_eq!(frame_at(4_000, 1_000, Duration::from_secs(9)), 4_000);
679
1
        assert_eq!(frame_at(4_000, 24_000, Duration::ZERO), 0);
680
1
    }
681
682
    #[test]
683
1
    fn the_voice_is_named_only_for_the_synthesis_model() {
684
        use crate::state::{VoiceChoice, VoiceResolution};
685
1
        let voice = VoiceState {
686
1
            resolution: Some(VoiceResolution {
687
1
                effective: Some("af_heart".into()),
688
1
                ..VoiceResolution::default()
689
1
            }),
690
1
            choices: vec![VoiceChoice {
691
1
                id: "af_heart".into(),
692
1
                label: "Heart".into(),
693
1
                kind: "preset".into(),
694
1
            }],
695
1
            target: Some(("kokoro".into(), "kokoro-82m".into())),
696
1
        };
697
1
        assert_eq!(
698
1
            voice_label(&voice, "kokoro", "kokoro-82m").as_deref(),
699
1
            Some("Heart")
700
        );
701
1
        assert!(voice_label(&voice, "kokoro", "another").is_none());
702
1
    }
703
704
    #[test]
705
1
    fn a_clip_is_about_two_and_a_half_words_a_second() {
706
1
        assert_eq!(estimated_seconds(0), 0);
707
1
        assert_eq!(estimated_seconds(1), 1);
708
1
        assert_eq!(estimated_seconds(10), 4);
709
1
    }
710
711
    #[test]
712
1
    fn a_clip_is_named_by_its_first_words() {
713
1
        assert_eq!(first_line("\n  Hello there.\nMore", 40), "Hello there.");
714
1
        assert_eq!(
715
1
            first_line("Stand-up moves to 10:30 tomorrow, in the small room.", 20),
716
1
            "Stand-up moves to\u{2026}"
717
        );
718
1
    }
719
720
    #[test]
721
1
    fn a_clock_is_minutes_and_seconds() {
722
1
        assert_eq!(clock(Duration::from_secs(6)), "0:06");
723
1
        assert_eq!(clock(Duration::from_secs(102)), "1:42");
724
1
    }
725
726
    #[test]
727
1
    fn when_says_today_yesterday_or_the_date() {
728
        let at =
729
3
            |s: &str| chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M").expect("a time");
730
1
        let today = chrono::NaiveDate::from_ymd_opt(2026, 11, 25).expect("a day");
731
1
        assert_eq!(when(at("2026-11-25 09:40"), today), "Today, 09:40");
732
1
        assert_eq!(when(at("2026-11-24 17:12"), today), "Yesterday, 17:12");
733
1
        assert_eq!(when(at("2026-11-20 08:05"), today), "2026-11-20 08:05");
734
1
    }
735
}