Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

157 KB
Raw Blame
//! Book mode of Speak: read a whole book in the active voice, one file per chapter.

use super::components::{
    Button, Tone, accent_glass, dropdown_chip, empty_state, glass_card, icon_button, icon_el, icons, popover,
    progress_bar, section_panel, segmented, status_dot,
};
use super::playbar;
use super::shell::{self, EngineStatus, VoiceInfo};
use super::theme::{Palette, motion, radius, ty};
use super::voices::kit;
use crate::engine::EngineMsg;
use crate::engine::protocol::{
    self, BookCast, BookCastProgress, BookChapterDone, BookChapterIn, BookChapterRow, BookDone, BookParams,
    BookProgress, BookStarted, BookSummary, CastMode, CastVoices, TextImport,
};
use crate::state::{AppState, Screen};
use rune::{El, ScrollSpec, TextEdit, col, el, row, text};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};

/// Longer texts open in Book mode instead of the Speak editor.
pub const LONG_WORDS: u32 = 5000;

/// File types the engine's `text.import` reads.
pub const TEXT_EXTS: &[&str] =
    &["txt", "md", "markdown", "html", "htm", "xhtml", "epub", "docx", "odt", "rtf", "fb2", "pdf", "srt", "vtt"];

pub fn is_text_path(p: &Path) -> bool {
    let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("").to_lowercase();
    name.ends_with(".fb2.zip")
        || p.extension().and_then(|e| e.to_str()).is_some_and(|e| TEXT_EXTS.iter().any(|x| x.eq_ignore_ascii_case(e)))
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Purpose {
    /// A short text goes into the editor, a long one opens as a book.
    Auto,
    Book,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DraftChapter {
    pub title: String,
    pub text: String,
    pub words: u32,
    pub est_s: f32,
    pub include: bool,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Draft {
    pub file: TextImport,
    pub chapters: Vec<DraftChapter>,
    /// The engine's suggested split: how it was found, and the chapters.
    pub auto: Option<(String, Vec<DraftChapter>)>,
    /// For "Undo split"; edits made since are dropped with it.
    pub before_split: Option<Vec<DraftChapter>>,
    /// The book its chapters are read into: one book, more chapters added to it as they are picked.
    #[serde(default)]
    pub book_id: Option<String>,
}

fn draft_chapters(list: &[protocol::TextChapter]) -> Vec<DraftChapter> {
    list.iter()
        .map(|c| DraftChapter {
            title: c.title.clone(),
            text: c.text.clone(),
            words: c.words,
            est_s: c.est_s,
            include: true,
        })
        .collect()
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
    Narrator,
    Men,
    Women,
}

impl Role {
    fn id(self) -> &'static str {
        match self {
            Role::Narrator => "narrator",
            Role::Men => "men",
            Role::Women => "women",
        }
    }

    fn from_id(id: &str) -> Option<Role> {
        [Role::Narrator, Role::Men, Role::Women].into_iter().find(|r| r.id() == id)
    }

    fn name(self) -> &'static str {
        match self {
            Role::Narrator => "Narrator",
            Role::Men => "Men",
            Role::Women => "Women",
        }
    }

    fn description(self, v: &CastVoices) -> &str {
        match self {
            Role::Narrator => &v.narrator,
            Role::Men => &v.men,
            Role::Women => &v.women,
        }
    }
}

#[derive(Default)]
struct Cast {
    req: Option<u64>,
    /// The engine's key of the running `book.cast` job.
    job: Option<String>,
    pct: f32,
    cancelling: bool,
    /// [`chapter_fingerprint`]s of the chapters the engine has searched (`book.cast_status`), in any grouping.
    searched: Vec<u64>,
    /// Chapters without dialogue: nothing for Gemma to read, so they are not marked as read by it.
    speechless: Vec<u64>,
    status_req: Option<u64>,
    /// [`included_key`] of the last search asked: its error goes once other chapters are picked.
    asked_key: u64,
    /// [`status_key`] of the chapters `searched` answers for.
    status_for: u64,
    found: Option<BookCast>,
    error: Option<String>,
    /// The book's narrator; the voice picked at the top when none is set.
    narrator: Option<String>,
    men: Option<String>,
    women: Option<String>,
    design: Option<(u64, Role)>,
    /// Takes of this Generate that Design found unclear (noise instead of the words).
    unclear: u8,
    /// Generated samples, one per role at most: they become voices only when the book starts.
    samples: Vec<(Role, Value)>,
    /// `voices.import` requests that turn samples into voices before the book starts.
    imports: Vec<(u64, Role)>,
    /// `voices.import` requests that add a sample to Your voices as soon as Generate made it.
    adopting: Vec<(u64, Role)>,
    /// The gender picked for a role's Generate ("male" or "female"); a role not listed takes Gemma's or the default.
    genders: Vec<(Role, String)>,
}

pub struct BookState {
    pub shown: bool,
    /// Files with a draft kept (and their titles), for Your books.
    drafts: Vec<(PathBuf, String)>,
    /// Generation seconds per audio second this computer has measured, for Best and for Fast.
    measured_rtf: [Option<f32>; 2],
    picking: bool,
    importing: Option<(u64, Purpose)>,
    pub draft: Option<Draft>,
    pub project: Option<BookSummary>,
    /// "Pausing…" / "Cancelling…" until the job's end event arrives.
    stopping: Option<&'static str>,
    start_req: Option<u64>,
    resume_req: Option<u64>,
    get_req: Option<u64>,
    reread_req: Option<u64>,
    /// The "Change voice" menu: `Some(None)` lists the voices, `Some(Some(id))` asks what to read again with it.
    pub voice_menu: Option<Option<String>>,
    list_req: Option<u64>,
    play_req: Option<(u64, u32)>,
    /// (book id, chapter index) last put in the player.
    played: Option<(String, u32)>,
    listed: bool,
    /// The first list after the engine started may bring back an unfinished book.
    first_list: bool,
    pub recent: Vec<BookSummary>,
    pub m4b: bool,
    pub read_titles: bool,
    pub expressiveness: f32,
    settings_loaded: bool,
    draft_restored: bool,
    draft_saved: Option<u64>,
    pub(crate) settings_dirty: bool,
    renaming: Option<(usize, TextEdit)>,
    m4b_making: bool,
    m4b_progress: (f32, Option<f32>),
    memory_wait: Option<f32>,
    /// 1 to 3: the narrator, then a voice for men's and/or women's lines.
    pub voices: u8,
    /// With two voices: whose lines the second one reads.
    pub second: Role,
    pub cast_mode: CastMode,
    cast: Cast,
    role_menu: Option<Role>,
    /// Which voice of the book "Change voice" changes.
    voice_role: Role,
    /// [`text_key`] of each chapter of the draft's book, by its index there.
    book_keys: Vec<u64>,
    link_req: Option<u64>,
    /// The restored draft's book is asked for once the engine runs.
    relink: bool,
    add_req: Option<u64>,
    /// `book.progress` of the "cast" stage: percent.
    cast_stage: Option<f32>,
}

/// Must match the engine's `narration.EXPRESSIVENESS`.
pub const EXPRESSIVENESS: f32 = 0.6;

impl Default for BookState {
    fn default() -> Self {
        BookState {
            shown: false,
            drafts: Vec::new(),
            measured_rtf: [None, None],
            picking: false,
            importing: None,
            draft: None,
            project: None,
            stopping: None,
            start_req: None,
            resume_req: None,
            get_req: None,
            reread_req: None,
            voice_menu: None,
            list_req: None,
            play_req: None,
            played: None,
            listed: false,
            first_list: false,
            recent: Vec::new(),
            m4b: false,
            read_titles: true,
            expressiveness: EXPRESSIVENESS,
            settings_loaded: false,
            draft_restored: false,
            draft_saved: None,
            settings_dirty: false,
            renaming: None,
            m4b_making: false,
            m4b_progress: (0.0, None),
            memory_wait: None,
            voices: 1,
            second: Role::Men,
            cast_mode: CastMode::Fast,
            cast: Cast::default(),
            role_menu: None,
            voice_role: Role::Narrator,
            book_keys: Vec::new(),
            link_req: None,
            relink: false,
            add_req: None,
            cast_stage: None,
        }
    }
}

impl BookState {
    pub fn running(&self) -> bool {
        self.project.as_ref().is_some_and(|p| p.status == "running")
            || self.start_req.is_some()
            || self.resume_req.is_some()
    }
}

/// The native picker runs on its own thread; the answer arrives as an event.
pub fn choose_file(s: &mut AppState, book: bool) {
    if s.book.picking || s.shell.scripted() {
        return;
    }
    s.book.picking = true;
    let purpose = if book { Purpose::Book } else { Purpose::Auto };
    std::thread::spawn(move || {
        let choice = rfd::FileDialog::new()
            .set_title(if book { "Choose a book" } else { "Choose a text file" })
            .add_filter("Books and text", TEXT_EXTS)
            .pick_file();
        crate::ui::events::post(move |s| {
            s.book.picking = false;
            if let Some(path) = choice {
                import(s, path, purpose);
            }
        });
    });
}

pub fn drop_file(s: &mut AppState, path: PathBuf) {
    let purpose = if s.screen == Screen::Speak && s.book.shown { Purpose::Book } else { Purpose::Auto };
    shell::set_screen(s, Screen::Speak);
    import(s, path, purpose);
}

fn import(s: &mut AppState, path: PathBuf, purpose: Purpose) {
    if !shell::engine_ready(s) {
        shell::toast(s, Tone::Warning, "Wait for the engine to start, then open the file again.");
        return;
    }
    let (method, params) = protocol::text_import(&path);
    match shell::request(s, method, params) {
        Some(id) => s.book.importing = Some((id, purpose)),
        None => shell::toast(s, Tone::Danger, "Could not reach the engine."),
    }
}

pub fn set_mode(s: &mut AppState, book: bool) {
    s.book.shown = book;
    s.book.renaming = None;
}

fn opened(s: &mut AppState, file: TextImport, purpose: Purpose) {
    let to_text = purpose == Purpose::Auto && file.words <= LONG_WORDS;
    if !file.language.is_empty()
        && s.shell.languages.iter().any(|l| l.code == file.language)
        && file.language != super::speak::language(s)
    {
        // A book carries its language in its own draft; set here, it would land in the draft being left.
        if to_text {
            s.book.shown = false;
            super::speak::set_language(s, &file.language);
        }
        if file.language_detected {
            shell::toast(
                s,
                Tone::Neutral,
                format!("Language set to {} (detected in the text).", super::lang::name(&file.language)),
            );
        }
    }
    for w in file.warnings.iter().take(2) {
        shell::toast(s, Tone::Warning, w.clone());
    }
    if to_text {
        let joined = file
            .chapters
            .iter()
            .map(|c| {
                if file.chapters.len() > 1 && !c.title.is_empty() {
                    format!("{}\n\n{}", c.title, c.text)
                } else {
                    c.text.clone()
                }
            })
            .collect::<Vec<_>>()
            .join("\n\n");
        super::speak::replace_text(&mut s.speak.text, &joined);
        s.book.shown = false;
        return;
    }
    if purpose == Purpose::Auto {
        shell::toast(
            s,
            Tone::Neutral,
            format!(
                "{} is long ({} words): it opened in Book mode, where each chapter becomes its own file.",
                file.name,
                group(file.words)
            ),
        );
    }
    stash_current(s);
    if let Some(saved) = read_slot(&file.path) {
        s.book.cast = Cast::default();
        if saved.cast.file.as_deref() == Some(saved.draft.file.path.as_path()) {
            restore_cast(&mut s.book.cast, saved.cast);
        }
        s.book.draft = Some(saved.draft);
        s.book.book_keys.clear();
        s.book.renaming = None;
        s.book.shown = true;
        link_book(s);
        return;
    }
    let chapters = draft_chapters(&file.chapters);
    let mut file = file;
    let auto = file.parts.take().filter(|p| !p.chapters.is_empty()).map(|p| (p.how, draft_chapters(&p.chapters)));
    file.chapters.clear(); // the texts live in the draft chapters (edited there)
    s.book.draft = Some(Draft { file, chapters, auto, before_split: None, book_id: None });
    // Another book: its speakers and voices are its own.
    s.book.cast = Cast::default();
    s.book.renaming = None;
    s.book.shown = true;
}

fn toggle_include(s: &mut AppState, i: usize) {
    if reading_locked(s) {
        return;
    }
    if let Some(c) = s.book.draft.as_mut().and_then(|d| d.chapters.get_mut(i)) {
        c.include = !c.include;
    }
}

fn start_rename(s: &mut AppState, i: usize) {
    commit_rename(s);
    if let Some(c) = s.book.draft.as_ref().and_then(|d| d.chapters.get(i)) {
        let mut edit = TextEdit::new(c.title.clone());
        edit.focused = true;
        s.book.renaming = Some((i, edit));
    }
}

fn commit_rename(s: &mut AppState) {
    let Some((i, edit)) = s.book.renaming.take() else { return };
    let title = edit.text.split_whitespace().collect::<Vec<_>>().join(" ");
    if let Some(c) = s.book.draft.as_mut().and_then(|d| d.chapters.get_mut(i))
        && !title.is_empty()
    {
        c.title = title;
    }
}

fn auto_split(s: &mut AppState) {
    if reading_locked(s) {
        return;
    }
    commit_rename(s);
    let Some(d) = s.book.draft.as_mut() else { return };
    let Some((_, parts)) = d.auto.as_ref() else { return };
    if d.before_split.is_none() {
        d.before_split = Some(std::mem::replace(&mut d.chapters, parts.clone()));
    }
}

fn undo_split(s: &mut AppState) {
    if reading_locked(s) {
        return;
    }
    s.book.renaming = None;
    if let Some(d) = s.book.draft.as_mut()
        && let Some(before) = d.before_split.take()
    {
        d.chapters = before;
    }
}

fn split_how(how: &str) -> &'static str {
    match how {
        "headings" => "at the chapter titles found in the text",
        "breaks" => "at the scene breaks (* * *), about 12 minutes each",
        "length" => "of about 12 minutes, between paragraphs where the story moves on",
        _ => "at chapter titles, scene breaks and natural pauses",
    }
}

/// The split's note and its button, shown under the totals.
fn split_line(p: Palette, d: &Draft) -> Option<El> {
    let (how, parts) = d.auto.as_ref()?;
    let (msg, button) = if d.before_split.is_some() {
        (
            format!("Split into {} parts {}.", d.chapters.len(), split_how(how)),
            Button::new("Undo split")
                .ghost()
                .small()
                .icon(&icons::REFRESH)
                .key("book-undo-split")
                .help("Back to the chapters of the file (changes made since are undone too)")
                .on_press(undo_split),
        )
    } else {
        let long = d.chapters.iter().filter(|c| c.words >= 600).count() <= 1;
        let what = if long { "No chapters in this file" } else { "Some chapters are very long" };
        (
            format!("{what}: it can be split into {} parts {}.", parts.len(), split_how(how)),
            Button::new("Split automatically")
                .secondary()
                .small()
                .icon(&icons::SPARKLE)
                .key("book-auto-split")
                .help("Undo puts the chapters back as they were")
                .on_press(auto_split),
        )
    };
    Some(
        row()
            .key("book-split")
            .w_full()
            .gap(10.0)
            .center_y()
            .pt(8.0)
            .border_sides([1.0, 0.0, 0.0, 0.0], p.well_rim)
            .child(text(msg).font(ty::CAPTION).color(p.text_dim).wrap().grow(1.0).min_w(0.0))
            .child(button.build(p)),
    )
}

/// Joins chapter `i + 1` into chapter `i`; its title becomes a paragraph of the text.
fn merge_next(s: &mut AppState, i: usize) {
    if reading_locked(s) {
        return;
    }
    commit_rename(s);
    let Some(d) = s.book.draft.as_mut() else { return };
    if i + 1 >= d.chapters.len() {
        return;
    }
    let b = d.chapters.remove(i + 1);
    let a = &mut d.chapters[i];
    a.text = format!("{}\n\n{}\n\n{}", a.text, b.title, b.text);
    a.words += b.words;
    a.est_s += b.est_s;
    a.include = a.include || b.include;
}

/// Cuts chapter `i` in two at the paragraph break nearest its middle.
fn split(s: &mut AppState, i: usize) {
    if reading_locked(s) {
        return;
    }
    commit_rename(s);
    let Some(d) = s.book.draft.as_mut() else { return };
    let Some(c) = d.chapters.get(i).cloned() else { return };
    let half = c.text.len() / 2;
    let cut = c.text.match_indices("\n\n").map(|(k, _)| k).min_by_key(|k| k.abs_diff(half));
    let Some(cut) = cut.filter(|k| *k > 0 && *k + 2 < c.text.len()) else {
        shell::toast(s, Tone::Warning, "This chapter is a single paragraph: there is nowhere to split it.");
        return;
    };
    let (head, tail) = (c.text[..cut].trim().to_owned(), c.text[cut..].trim().to_owned());
    let wa = head.split_whitespace().count() as u32;
    let wb = tail.split_whitespace().count() as u32;
    let total = (wa + wb).max(1) as f32;
    let first = DraftChapter {
        title: c.title.clone(),
        text: head,
        words: wa,
        est_s: c.est_s * wa as f32 / total,
        include: c.include,
    };
    let second = DraftChapter {
        title: format!("{} (2)", c.title),
        text: tail,
        words: wb,
        est_s: c.est_s * wb as f32 / total,
        include: c.include,
    };
    d.chapters.splice(i..=i, [first, second]);
}

fn start_blocker(s: &AppState) -> Option<String> {
    match &s.shell.engine {
        EngineStatus::Ready { .. } => {}
        EngineStatus::Idle | EngineStatus::Starting { .. } => return Some("Waiting for the engine to start…".into()),
        _ => return Some("The engine is not running. Press Retry above.".into()),
    }
    if !role_ready(s, Role::Narrator) {
        return Some("Pick or generate a voice for the narrator.".into());
    }
    if s.speak.is_generating() {
        return Some("Wait for the text being spoken to finish.".into());
    }
    if super::design::generating(s) {
        return Some("Wait for Design to finish making a voice.".into());
    }
    if s.book.running() {
        return Some("Another book is being read: pause it first.".into());
    }
    if s.book.draft.as_ref().is_some_and(|d| !d.chapters.iter().any(|c| c.include)) {
        return Some("Tick at least one chapter.".into());
    }
    if s.book.cast.design.is_some() || !s.book.cast.imports.is_empty() || !s.book.cast.adopting.is_empty() {
        return Some("Wait for the voice being made.".into());
    }
    if cast_running(s) {
        return Some("Wait for finding who speaks to finish, or cancel it.".into());
    }
    if s.book.voices > 1 {
        if !super::setuprun::has(s, "cast") {
            return Some("Install Character voices first.".into());
        }
        if s.book.cast.found.is_none() {
            return Some("Find who speaks first.".into());
        }
        if let Some(why) = unsearched_note(s) {
            return Some(why);
        }
        for role in character_roles(s.book.voices, s.book.second) {
            if !role_ready(s, *role) {
                return Some(if *role == Role::Men {
                    "Pick a voice for the men's lines.".into()
                } else {
                    "Pick a voice for the women's lines.".into()
                });
            }
        }
    }
    None
}

fn character_roles(voices: u8, second: Role) -> &'static [Role] {
    match (voices, second) {
        (3, _) => &[Role::Men, Role::Women],
        (2, Role::Women) => &[Role::Women],
        (2, _) => &[Role::Men],
        _ => &[],
    }
}

fn role_voice(s: &AppState, role: Role) -> Option<&VoiceInfo> {
    let find = |id: Option<&str>| id.and_then(|id| s.shell.voices.iter().find(|v| v.id == id));
    match role {
        Role::Narrator => find(s.book.cast.narrator.as_deref()).or_else(|| find(s.shell.active_voice.as_deref())),
        Role::Men => find(s.book.cast.men.as_deref()),
        Role::Women => find(s.book.cast.women.as_deref()),
    }
}

fn sample(s: &AppState, role: Role) -> Option<&Value> {
    s.book.cast.samples.iter().find(|(r, _)| *r == role).map(|(_, t)| t)
}

/// A generated sample, or else a voice picked for the role.
fn role_ready(s: &AppState, role: Role) -> bool {
    sample(s, role).is_some() || role_voice(s, role).is_some()
}

/// The roles this reading uses: the narrator and the character voices.
fn used_roles(s: &AppState) -> Vec<Role> {
    std::iter::once(Role::Narrator).chain(character_roles(s.book.voices, s.book.second).iter().copied()).collect()
}

/// A book voice made earlier for this book and role (opened again), for a role nobody picked yet.
fn reuse_book_voices(s: &mut AppState) {
    let Some(title) = s.book.draft.as_ref().map(book_title) else { return };
    for role in [Role::Narrator, Role::Men, Role::Women] {
        let empty = match role {
            Role::Narrator => s.book.cast.narrator.is_none(),
            Role::Men => s.book.cast.men.is_none(),
            Role::Women => s.book.cast.women.is_none(),
        };
        let found = s
            .shell
            .voices
            .iter()
            .rev()
            .find(|v| v.book.as_deref() == Some(title.as_str()) && v.book_role.as_deref() == Some(role.id()))
            .map(|v| v.id.clone());
        if let (true, Some(id)) = (empty, found) {
            set_role_voice(s, role, &id);
        }
    }
}

fn cast_voice(s: &AppState, role: Role) -> Option<&str> {
    if !character_roles(s.book.voices, s.book.second).contains(&role) {
        return None;
    }
    role_voice(s, role).map(|v| v.id.as_str())
}

/// The language the book is read in: its own (found in the file, or picked in Style while Book is shown).
pub fn book_language(s: &AppState) -> String {
    match s.book.draft.as_ref().filter(|d| !d.file.language.is_empty()) {
        Some(d) => d.file.language.clone(),
        None => super::speak::language(s),
    }
}

fn set_role_voice(s: &mut AppState, role: Role, id: &str) {
    s.book.cast.samples.retain(|(r, _)| *r != role);
    match role {
        Role::Narrator => s.book.cast.narrator = Some(id.to_owned()),
        Role::Men => s.book.cast.men = Some(id.to_owned()),
        Role::Women => s.book.cast.women = Some(id.to_owned()),
    }
}

fn included(d: &Draft) -> Vec<BookChapterIn<'_>> {
    d.chapters.iter().filter(|c| c.include).map(|c| BookChapterIn { title: &c.title, text: &c.text }).collect()
}

fn book_title(d: &Draft) -> String {
    if d.file.title.trim().is_empty() { d.file.name.clone() } else { d.file.title.clone() }
}

/// Length and opening stand for the text: the draft changes a text only by splitting or joining chapters.
fn chapter_fingerprint(c: &DraftChapter) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    c.text.len().hash(&mut h);
    c.text.chars().take(32).for_each(|ch| ch.hash(&mut h));
    h.finish()
}

/// What `book.cast_status` depends on: every chapter's text (not whether it is picked), the mode and the language.
fn status_key(s: &AppState) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    for c in s.book.draft.iter().flat_map(|d| &d.chapters) {
        chapter_fingerprint(c).hash(&mut h);
    }
    (s.book.cast_mode.as_str(), book_language(s)).hash(&mut h);
    h.finish()
}

fn included_key(s: &AppState) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    for c in s.book.draft.iter().flat_map(|d| &d.chapters).filter(|c| c.include) {
        chapter_fingerprint(c).hash(&mut h);
    }
    s.book.cast_mode.as_str().hash(&mut h);
    h.finish()
}

/// Every picked chapter was searched before: the engine answers from what it kept, without Gemma.
fn fetch_kept_cast(s: &AppState) -> bool {
    s.book.voices > 1
        && s.book.cast.found.is_none()
        && s.book.cast.error.is_none()
        && !cast_running(s)
        && status_known(s)
        && s.book.draft.as_ref().is_some_and(|d| d.chapters.iter().any(|c| c.include))
        && unsearched_note(s).is_none()
}

fn status_known(s: &AppState) -> bool {
    s.book.cast.status_req.is_none() && s.book.cast.status_for == status_key(s)
}

/// Asks the engine which chapters were searched before, whenever the chapters, the mode or the language change.
fn ask_status(s: &mut AppState) {
    if s.book.voices < 2
        || cast_running(s)
        || s.book.cast.status_req.is_some()
        || !shell::engine_ready(s)
        || !super::setuprun::has(s, "cast")
    {
        return;
    }
    let key = status_key(s);
    if key == s.book.cast.status_for {
        return;
    }
    let Some(d) = s.book.draft.as_ref() else { return };
    let all: Vec<BookChapterIn<'_>> =
        d.chapters.iter().map(|c| BookChapterIn { title: &c.title, text: &c.text }).collect();
    let (_, params) = protocol::book_cast(&all, &book_language(s), s.book.cast_mode);
    s.book.cast.status_req = shell::request(s, "book.cast_status", params);
    s.book.cast.status_for = key;
}

/// "10 of 40 chapters…" when chapters picked after the last search have no speakers found.
fn unsearched_note(s: &AppState) -> Option<String> {
    let d = s.book.draft.as_ref()?;
    let picked: Vec<&DraftChapter> = d.chapters.iter().filter(|c| c.include).collect();
    if !status_known(s) {
        return None;
    }
    let todo = picked.iter().filter(|c| !chapter_searched(s, c)).count();
    (todo > 0).then(|| {
        format!("{todo} of {} chapters are not analysed yet: press Find who speaks to analyse only them.", picked.len())
    })
}

/// A search ended: ask again which chapters are searched.
fn searched(c: &mut Cast) {
    c.status_for = 0;
}

/// Gemma has read this chapter's lines for the mode picked now.
fn chapter_searched(s: &AppState, c: &DraftChapter) -> bool {
    s.book.cast.searched.contains(&chapter_fingerprint(c))
}

fn cast_running(s: &AppState) -> bool {
    s.book.cast.req.is_some() || s.book.cast.job.is_some()
}

/// Book's speaker search has the GPU: the speech models are paused until it ends.
pub fn finding_speakers(s: &AppState) -> bool {
    cast_running(s)
}

/// Only another mode drops the speakers found: chapters not searched yet are searched on their own, and the language
/// settles only after the voices load (a passing value dropped them).
fn drop_stale_cast(s: &mut AppState) -> bool {
    let c = &s.book.cast;
    if cast_running(s) || (c.found.is_none() && c.error.is_none()) {
        return false;
    }
    if c.error.is_some() && c.asked_key != included_key(s) {
        s.book.cast.error = None;
        return true;
    }
    if c.found.as_ref().is_none_or(|f| f.mode.is_empty() || f.mode == s.book.cast_mode.as_str()) {
        return false;
    }
    s.book.cast.found = None;
    s.book.cast.error = None;
    true
}

fn find_speakers(s: &mut AppState) {
    search(s, false);
}

/// `again`: Gemma reads every ticked chapter, those it read before too.
fn search(s: &mut AppState, again: bool) {
    commit_rename(s);
    let Some(d) = s.book.draft.as_ref() else { return };
    let lang = book_language(s);
    let mode = s.book.cast_mode;
    let (m, mut p) = protocol::book_cast(&included(d), &lang, mode);
    if again {
        p["again"] = json!(true);
    }
    let key = included_key(s);
    let req = shell::request(s, m, p);
    let c = &mut s.book.cast;
    c.asked_key = key;
    c.req = req;
    c.found = None;
    c.pct = 0.0;
    c.error = req.is_none().then(|| "Could not reach the engine.".to_owned());
}

fn cancel_cast(s: &mut AppState) {
    if s.book.cast.job.is_some()
        && !s.book.cast.cancelling
        && shell::request(s, "book.cast_cancel", json!({})).is_some()
    {
        s.book.cast.cancelling = true;
    }
}

fn generate_blocker(s: &AppState) -> Option<String> {
    if s.speak.is_generating() {
        Some("Generate when the text being spoken is done.".into())
    } else if super::design::generating(s) {
        Some("Generate when Design has made its voice.".into())
    } else if s.book.running() {
        Some("A book is being read: pause it to make a voice.".into())
    } else if super::train::is_training(s) {
        Some("A voice is training and is using the GPU. Generate when it finishes.".into())
    } else if cast_running(s) {
        Some("Generate when the speakers are found.".into())
    } else if s.book.voices > 1 {
        unsearched_note(s)
    } else {
        None
    }
}

fn sample_text(lang: &str, d: &Draft) -> String {
    let known = super::design::default_text(lang);
    if !known.is_empty() {
        return known.to_owned();
    }
    let mut out = String::new();
    for w in d.chapters.iter().filter(|c| c.include).flat_map(|c| c.text.split_whitespace()) {
        if !out.is_empty() {
            out.push(' ');
        }
        out.push_str(w);
        let n = out.chars().count();
        if (n >= 80 && w.ends_with(['.', '!', '?', '…'])) || n >= 200 {
            break;
        }
    }
    out
}

/// Design now and then makes noise for a description; such a take is made again this many times before giving up.
const UNCLEAR_TRIES: u8 = 3;

fn generate_role(s: &mut AppState, role: Role) {
    if generate_blocker(s).is_some()
        || s.book.cast.design.is_some()
        || !s.book.cast.imports.is_empty()
        || !s.book.cast.adopting.is_empty()
    {
        return;
    }
    s.book.cast.unclear = 0;
    request_design(s, role);
}

/// The design terms with the gender the user picked in place of Gemma's or the default one.
fn with_gender(description: &str, gender: Option<&str>) -> String {
    let Some(gender) = gender else { return description.to_owned() };
    let rest: Vec<&str> = description.split(", ").filter(|t| !matches!(t.trim(), "male" | "female")).collect();
    std::iter::once(gender).chain(rest).collect::<Vec<_>>().join(", ")
}

fn request_design(s: &mut AppState, role: Role) {
    // Chapters without dialogue bring no suggested voices: plain ones for each role then.
    let plain = CastVoices {
        narrator: "male, middle-aged, low pitch".into(),
        men: "male, young adult, moderate pitch".into(),
        women: "female, young adult, moderate pitch".into(),
    };
    let found = s.book.cast.found.as_ref().and_then(|c| c.voices.clone());
    let voices = &found.unwrap_or(plain);
    let Some(d) = s.book.draft.as_ref() else { return };
    let lang = book_language(s);
    let params = json!({
        "model": "omnivoice",
        "language": lang,
        "text": sample_text(&lang, d),
        "description": with_gender(role.description(voices), s.book.cast.genders.iter().find(|(r, _)| *r == role).map(|(_, g)| g.as_str())),
        // HolosTTS's reading goes through the zero-shot converter, which gave the sample a foreign accent.
        "exact_stress": false,
    });
    match shell::request(s, "voices.design", params) {
        Some(id) => s.book.cast.design = Some((id, role)),
        None => shell::toast(s, Tone::Danger, "Could not reach the engine."),
    }
}

/// Turns the samples of the roles in use into voices (marked as this book's); the book starts once all are made.
fn import_samples(s: &mut AppState) -> bool {
    let Some(title) = s.book.draft.as_ref().map(book_title) else { return false };
    let lang = book_language(s);
    let wanted: Vec<(Role, Value)> =
        used_roles(s).into_iter().filter_map(|r| sample(s, r).map(|t| (r, t.clone()))).collect();
    for (role, take) in wanted {
        let Some(params) = import_params(&title, &lang, role, &take) else { continue };
        match shell::request(s, "voices.import", params) {
            Some(id) => s.book.cast.imports.push((id, role)),
            None => {
                shell::toast(s, Tone::Danger, "Could not reach the engine.");
                s.book.cast.imports.clear();
                return false;
            }
        }
    }
    !s.book.cast.imports.is_empty()
}

fn import_params(title: &str, lang: &str, role: Role, take: &Value) -> Option<Value> {
    let reference = take.get("reference").and_then(Value::as_str)?;
    Some(json!({
        "name": format!("{title} · {}", role.id()),
        "reference_path": reference,
        "language": take.get("language").and_then(Value::as_str).unwrap_or(lang),
        "book": title,
        "book_role": role.id(),
    }))
}

/// Adds a sample Generate made to Your voices, named after the book and the role; the book's voice for the role, if it
/// has one, is made anew instead.
fn adopt_sample(s: &mut AppState, role: Role) {
    let Some(title) = s.book.draft.as_ref().map(book_title) else { return };
    let lang = book_language(s);
    let Some(mut params) = sample(s, role).and_then(|t| import_params(&title, &lang, role, t)) else { return };
    let old = s
        .shell
        .voices
        .iter()
        .rev()
        .find(|v| v.book.as_deref() == Some(title.as_str()) && v.book_role.as_deref() == Some(role.id()));
    if let Some(old) = old {
        params["into"] = json!(old.id);
    }
    if let Some(id) = shell::request(s, "voices.import", params) {
        s.book.cast.adopting.push((id, role));
    }
}

fn sample_path(s: &AppState, role: Role) -> Option<PathBuf> {
    sample(s, role).and_then(|t| t.get("path")).and_then(Value::as_str).map(PathBuf::from)
}

/// What the role's ▶ plays: its generated sample, else the clip its voice speaks from in the book's language.
fn role_audio(s: &AppState, role: Role) -> Option<PathBuf> {
    if let Some(path) = sample_path(s, role) {
        return Some(path);
    }
    let v = role_voice(s, role)?;
    let lang = book_language(s);
    let file = if v.references.contains(&lang) { format!("reference_{lang}.wav") } else { "reference.wav".into() };
    Some(super::onboarding::data_dir().join("voices").join(&v.id).join(file))
}

fn take_playing(s: &AppState, path: &Path) -> bool {
    s.playbar.now.as_ref().is_some_and(|n| n.path == path && n.status == playbar::Status::Playing)
}

fn play_take(s: &mut AppState, role: Role) {
    let Some(path) = role_audio(s, role) else { return };
    let name = match role_voice(s, role) {
        Some(v) if sample(s, role).is_none() => v.name.clone(),
        _ => format!("New voice · {}", role.id()),
    };
    let what = format!("Book · {}", role.id());
    if let Err(e) = playbar::toggle(s, &path, name, what, playbar::Source::Speak) {
        shell::toast(s, Tone::Danger, e);
    }
}

const CAST_NAMES: usize = 3;

fn cast_caption(c: &BookCast) -> String {
    let (men, women, narrator) = c.lines.as_ref().map_or((0, 0, 0), |l| (l.men, l.women, l.narrator));
    let mut parts = vec![
        format!("Men: {} lines", group(men)),
        format!("Women: {} lines", group(women)),
        format!("Narrator: {}", group(narrator)),
    ];
    let mut cast: Vec<_> = c.characters.iter().collect();
    cast.sort_by_key(|x| std::cmp::Reverse(x.lines));
    if !cast.is_empty() {
        let names: Vec<&str> = cast.iter().take(CAST_NAMES).map(|x| x.name.as_str()).collect();
        let more = if cast.len() > CAST_NAMES { ", …" } else { "" };
        parts.push(format!("{}{more}", names.join(", ")));
    }
    parts.join(" · ")
}

fn start(s: &mut AppState) {
    commit_rename(s);
    drop_stale_cast(s);
    if let Some(why) = start_blocker(s) {
        shell::toast(s, Tone::Warning, why);
        return;
    }
    if import_samples(s) {
        return;
    }
    let (Some(d), Some(voice)) = (s.book.draft.as_ref(), role_voice(s, Role::Narrator)) else { return };
    let lang = book_language(s);
    let out = super::formats::output_format(s);
    let title = book_title(d);
    let req = protocol::book_start(&BookParams {
        title: &title,
        source: d.file.path.to_str(),
        format: Some(&d.file.format),
        chapters: included(d),
        voice_id: &voice.id,
        language: &lang,
        expressiveness: s.book.expressiveness,
        voice_match: s.speak.voice_match,
        quality: s.speak.quality,
        speed: s.speak.speed,
        accent: super::speak::accent_param(s, &lang).map(|_| protocol::NativeVoice::Auto),
        output_format: &out,
        m4b: s.book.m4b,
        read_titles: s.book.read_titles,
        exact_stress: s.speak.exact_stress,
        model: &super::speak::model(s),
        men: cast_voice(s, Role::Men),
        women: cast_voice(s, Role::Women),
        cast: if s.book.voices > 1 { s.book.cast_mode } else { CastMode::Fast },
    });
    shell::stop_audio(s);
    match shell::request(s, req.0, req.1) {
        Some(id) => s.book.start_req = Some(id),
        None => shell::toast(s, Tone::Danger, "Could not reach the engine."),
    }
}

fn resume(s: &mut AppState) {
    let Some(id) = s.book.project.as_ref().map(|p| p.id.clone()) else { return };
    if s.speak.is_generating() {
        shell::toast(s, Tone::Warning, "Wait for the text being spoken to finish.");
        return;
    }
    if super::design::generating(s) {
        shell::toast(s, Tone::Warning, "Wait for Design to finish making a voice.");
        return;
    }
    let (m, mut p) = protocol::book_id_request("book.resume", &id);
    settings_now(s, &mut p);
    match shell::request(s, m, p) {
        Some(r) => s.book.resume_req = Some(r),
        None => shell::toast(s, Tone::Danger, "Could not reach the engine."),
    }
}

/// `voice`: read on with another voice; `chapters`: the chapters to read again (all of them when `None`).
fn reread(s: &mut AppState, voice: Option<String>, chapters: Option<Vec<u32>>) {
    s.book.voice_menu = None;
    let Some(id) = s.book.project.as_ref().map(|p| p.id.clone()) else { return };
    let role = s.book.project.as_ref().map_or(Role::Narrator, |b| {
        if book_roles(b).contains(&s.book.voice_role) { s.book.voice_role } else { Role::Narrator }
    });
    let role = role.id();
    let (m, mut p) = protocol::book_reread(&id, voice.as_deref().map(|v| (role, v)), chapters.as_deref());
    if voice.is_none() {
        settings_now(s, &mut p);
    }
    match shell::request(s, m, p) {
        Some(r) => s.book.reread_req = Some(r),
        None => shell::toast(s, Tone::Danger, "Could not reach the engine."),
    }
}

fn pick_book_voice(s: &mut AppState, voice: String) {
    let Some(p) = s.book.project.as_ref() else { return };
    let started = p.chapter_list.iter().any(|c| c.status == "done");
    if !started {
        let partial: Vec<u32> = p.chapter_list.iter().filter(|c| c.status == "partial").map(|c| c.index).collect();
        reread(s, Some(voice), Some(partial));
    } else {
        s.book.voice_menu = Some(Some(voice));
    }
}

/// The voice a book reads a role with.
fn book_role_voice(b: &BookSummary, role: Role) -> Option<&str> {
    match role {
        Role::Narrator => b.voice_id.as_deref(),
        _ => b.voices.as_ref().and_then(|v| v.get(role.id())).and_then(|v| v.as_deref()),
    }
}

fn book_roles(b: &BookSummary) -> Vec<Role> {
    [Role::Narrator, Role::Men, Role::Women].into_iter().filter(|r| book_role_voice(b, *r).is_some()).collect()
}

/// Whitespace aside, the text a book keeps of a chapter.
fn text_key(text: &str) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    text.trim().hash(&mut h);
    h.finish()
}

/// The book the draft's chapters are read into, while it is the one loaded.
fn linked(s: &AppState) -> Option<&BookSummary> {
    let id = s.book.draft.as_ref()?.book_id.as_deref()?;
    s.book.project.as_ref().filter(|b| b.id == id)
}

/// A draft chapter's place in its book and how far it is read.
fn book_row<'a>(s: &'a AppState, c: &DraftChapter) -> Option<(&'a BookSummary, &'a BookChapterRow)> {
    let b = linked(s)?;
    let key = text_key(&c.text);
    let at = s.book.book_keys.iter().position(|k| *k == key)?;
    Some((b, b.chapter_list.iter().find(|r| r.index as usize == at)?))
}

/// A book read from the draft's file before: the draft goes on with it rather than making another.
fn same_file_book(s: &AppState) -> Option<String> {
    let d = s.book.draft.as_ref().filter(|d| d.book_id.is_none())?;
    let path = d.file.path.to_str()?;
    s.book
        .recent
        .iter()
        .filter(|b| b.source.as_deref() == Some(path))
        .max_by(|a, b| a.id.cmp(&b.id))
        .map(|b| b.id.clone())
}

/// Draft, In progress or Finished: the book the draft sets up, as far as it is read.
fn draft_status(s: &AppState) -> (&'static str, Tone, bool) {
    let id = s.book.draft.as_ref().and_then(|d| d.book_id.as_deref());
    let b = id.and_then(|id| s.book.project.iter().chain(&s.book.recent).find(|b| b.id == id));
    match b {
        Some(b) if b.status == "running" => ("In progress", Tone::Accent, true),
        Some(b) if b.chapters_done == 0 => ("Draft", Tone::Neutral, false),
        Some(b) => {
            let all = s
                .book
                .draft
                .iter()
                .flat_map(|d| &d.chapters)
                .filter(|c| c.include)
                .all(|c| book_row(s, c).is_some_and(|(_, r)| r.status == "done"));
            if all && b.status == "done" {
                ("Finished", Tone::Success, false)
            } else {
                ("In progress", Tone::Warning, false)
            }
        }
        None => ("Draft", Tone::Neutral, false),
    }
}

/// Takes a chapter out of the draft (the file is not changed).
fn remove_chapter(s: &mut AppState, i: usize) {
    if reading_locked(s) {
        return;
    }
    commit_rename(s);
    if let Some(d) = s.book.draft.as_mut()
        && i < d.chapters.len()
        && d.chapters.len() > 1
    {
        d.chapters.remove(i);
    }
}

/// Asks the draft's book for its chapters' texts, to know which draft chapters it holds.
fn link_book(s: &mut AppState) {
    let Some(id) = s.book.draft.as_ref().and_then(|d| d.book_id.clone()) else { return };
    s.book.link_req = shell::request(s, "book.get", json!({ "id": id, "text": true }));
}

/// The cells of a chapter read into the book: how far, read again, play.
fn read_cells(s: &AppState, p: Palette, mut r: El, b: &BookSummary, c: &BookChapterRow, include: bool) -> El {
    let idx = c.index;
    let running = b.status == "running";
    let (mark, help): (El, String) = match c.status.as_str() {
        "done" => (icon_el(&icons::CHECK, 14.0, p.ok), format!("Read: {} of audio", fmt_len(c.audio_s))),
        "partial" if running => (
            status_dot(p, Tone::Accent, true),
            if c.segments > 0 {
                format!("Reading: part {} of {}", c.segment.min(c.segments), c.segments)
            } else {
                "Reading…".into()
            },
        ),
        "partial" => (
            icon_el(&icons::PAUSE, 13.0, p.warn),
            format!("Stopped at part {} of {}", c.segment, c.segments.max(c.segment)),
        ),
        _ => (el().size(10.0, 10.0).radius(5.0).border(1.0, p.text_faint), "Waiting to be read".into()),
    };
    // Only what applies is shown: read again once the chapter is read and the book is not being read.
    if c.status == "done" && !running && s.book.reread_req.is_none() {
        r = r.child(small_icon(p, format!("book-redo{idx}"), &icons::REFRESH, "Read this chapter again", move |s| {
            reread(s, None, Some(vec![idx]))
        }));
    }
    r = r.child(
        el().key(format!("book-state{idx}")).size(28.0, 28.0).center().label(help.clone()).help(help).child(mark),
    );
    r = r.child(if c.status == "done" {
        let playing = chapter_playing(s, idx);
        let btn = el()
            .key(format!("book-play{idx}"))
            .role("button")
            .label(if playing { "Pause" } else { "Play" })
            .size(28.0, 28.0)
            .radius(14.0)
            .center()
            .hover(rune::Color::WHITE.alpha(0.1))
            .focusable(true)
            .motion(motion::UI)
            .on_press(move |s: &mut AppState| play_chapter(s, idx))
            .child(icon_el(if playing { &icons::PAUSE } else { &icons::PLAY }, 12.0, p.on_accent));
        accent_glass(p, btn)
    } else {
        el()
    });
    if !include { r.opacity(0.7) } else { r }
}

/// The draft's voices and Output choices, for the chapters its book reads from now on (resumed, read again).
fn settings_now(s: &AppState, params: &mut Value) {
    if linked(s).is_none() {
        return;
    }
    params["voice_id"] = json!(role_voice(s, Role::Narrator).map(|v| v.id.clone()));
    if s.book.voices > 1 {
        params["voices"] = json!({ "men": cast_voice(s, Role::Men), "women": cast_voice(s, Role::Women) });
        params["cast"] = json!(s.book.cast_mode.as_str());
    }
    for (key, on) in [("m4b", s.book.m4b), ("read_titles", s.book.read_titles), ("exact_stress", s.speak.exact_stress)]
    {
        params[key] = json!(on);
    }
}

/// Hands the Output choices to the draft's book at once: one being read makes its M4B by the box ticked last.
fn send_settings(s: &mut AppState) {
    let Some(id) = linked(s).map(|b| b.id.clone()) else { return };
    let params = json!({ "id": id, "m4b": s.book.m4b, "read_titles": s.book.read_titles });
    let _ = shell::request(s, "book.settings", params);
}

/// A chapter of the draft's book is read and its file is there.
fn has_files(s: &AppState) -> bool {
    linked(s).is_some_and(|b| b.chapter_list.iter().any(|c| c.path.as_ref().is_some_and(|p| p.is_file())))
}

/// While the draft's book is read, its chapters and voices stay as they are: Pause unlocks them.
fn reading_locked(s: &AppState) -> bool {
    linked(s).is_some_and(|b| b.status == "running") || s.book.start_req.is_some() || s.book.add_req.is_some()
}

/// The ticked chapters the book does not have yet, with their place in the draft.
fn new_chapters(s: &AppState) -> Vec<(usize, &DraftChapter)> {
    let Some(d) = s.book.draft.as_ref() else { return Vec::new() };
    let have: Vec<u64> = if linked(s).is_some() { s.book.book_keys.clone() } else { Vec::new() };
    d.chapters.iter().enumerate().filter(|(_, c)| c.include && !have.contains(&text_key(&c.text))).collect()
}

fn read_blocker(s: &AppState) -> Option<String> {
    let Some(b) = linked(s) else { return start_blocker(s) };
    if b.status == "running" {
        return None;
    }
    if new_chapters(s).is_empty() {
        let waiting = s
            .book
            .draft
            .iter()
            .flat_map(|d| &d.chapters)
            .filter(|c| c.include)
            .any(|c| book_row(s, c).is_some_and(|(_, r)| r.status != "done"));
        return (!waiting).then(|| "The ticked chapters are read: ↻ beside one reads it again.".to_owned());
    }
    start_blocker(s)
}

/// Reads the ticked chapters: a new book the first time, then more chapters into the same one.
fn read_book(s: &mut AppState) {
    if linked(s).is_none() {
        start(s);
        return;
    }
    if let Some(why) = read_blocker(s) {
        shell::toast(s, Tone::Warning, why);
        return;
    }
    let Some(id) = s.book.draft.as_ref().and_then(|d| d.book_id.clone()) else { return };
    let chapters: Vec<Value> = new_chapters(s)
        .into_iter()
        .map(|(i, c)| json!({ "title": c.title, "text": c.text, "number": i + 1 }))
        .collect();
    if chapters.is_empty() {
        resume(s);
        return;
    }
    let voice = role_voice(s, Role::Narrator).map(|v| v.id.clone());
    let mut params = json!({ "id": id, "chapters": chapters, "voice_id": voice });
    settings_now(s, &mut params);
    match shell::request(s, "book.add", params) {
        Some(r) => s.book.add_req = Some(r),
        None => shell::toast(s, Tone::Danger, "Could not reach the engine."),
    }
}

fn keep_made_chapters(s: &mut AppState, voice: String) {
    let partial: Vec<u32> = s
        .book
        .project
        .as_ref()
        .map(|p| p.chapter_list.iter().filter(|c| c.status == "partial").map(|c| c.index).collect())
        .unwrap_or_default();
    reread(s, Some(voice), Some(partial));
}

fn stop(s: &mut AppState, how: &'static str) {
    let Some(id) = s.book.project.as_ref().map(|p| p.id.clone()) else { return };
    let method = if how == "pause" { "book.pause" } else { "book.cancel" };
    let (m, p) = protocol::book_id_request(method, &id);
    if shell::request(s, m, p).is_some() {
        let running = s.book.project.as_ref().is_some_and(|p| p.status == "running");
        if running {
            s.book.stopping = Some(if how == "pause" { "Pausing…" } else { "Cancelling…" });
        } else if how == "cancel" {
            // A paused book: the engine just drops the unfinished chapter.
            if let Some(p) = s.book.project.as_mut() {
                p.status = "cancelled".into();
                reset_partial(p);
            }
        }
    }
}

fn reset_partial(p: &mut BookSummary) {
    for c in &mut p.chapter_list {
        if c.status != "done" {
            c.status = "waiting".into();
            c.segment = 0;
            c.audio_s = 0.0;
        }
    }
}

/// One line of Your books: a book read or being set up, opened in the same workspace.
struct Entry {
    key: String,
    title: String,
    path: Option<PathBuf>,
    book: Option<String>,
    word: &'static str,
    tone: Tone,
    pulse: bool,
    detail: String,
    current: bool,
}

/// Every book the engine has, and every draft kept for a file no book was read from yet.
fn book_entries(s: &AppState) -> Vec<Entry> {
    let cur = s.book.draft.as_ref();
    let cur_path = cur.map(|d| d.file.path.clone());
    let mut out = Vec::new();
    let mut books: Vec<&BookSummary> =
        s.book.recent.iter().map(|b| s.book.project.as_ref().filter(|p| p.id == b.id).unwrap_or(b)).collect();
    books.sort_by_key(|b| !of_active_voice(s, b));
    for b in books.into_iter().take(12) {
        let path = b.source.as_ref().map(PathBuf::from);
        let current =
            cur.is_some_and(|d| d.book_id.as_deref() == Some(b.id.as_str())) || (path.is_some() && path == cur_path);
        let (word, tone, pulse, detail) = if current {
            let (w, t, p) = draft_status(s);
            let d = cur.expect("current");
            (
                w,
                t,
                p,
                format!("{} of {} chapters picked", d.chapters.iter().filter(|c| c.include).count(), d.chapters.len()),
            )
        } else {
            let (w, t) = status_word(b);
            (
                w,
                t,
                b.status == "running",
                format!("{} of {} chapters · {}", b.chapters_done, b.chapters, fmt_len(b.totals.audio_s)),
            )
        };
        let path = if current { cur_path.clone() } else { path };
        out.push(Entry {
            key: b.id.clone(),
            title: b.title.clone(),
            path,
            book: Some(b.id.clone()),
            word,
            tone,
            pulse,
            detail,
            current,
        });
    }
    let mut drafts: Vec<(PathBuf, String)> = s.book.drafts.clone();
    if let Some(d) = cur
        && !drafts.iter().any(|(p, _)| *p == d.file.path)
    {
        drafts.push((d.file.path.clone(), book_title(d)));
    }
    for (path, title) in drafts {
        if out.iter().any(|e| e.path.as_ref() == Some(&path)) {
            continue;
        }
        let current = cur_path.as_ref() == Some(&path);
        let (word, tone, pulse) = if current { draft_status(s) } else { ("Draft", Tone::Neutral, false) };
        let detail = match cur.filter(|_| current) {
            Some(d) => {
                format!("{} of {} chapters picked", d.chapters.iter().filter(|c| c.include).count(), d.chapters.len())
            }
            None => "not read yet".to_owned(),
        };
        let key = format!("draft-{:016x}", text_key(&path.to_string_lossy()));
        out.push(Entry { key, title, path: Some(path), book: None, word, tone, pulse, detail, current });
    }
    out
}

fn slot_dir() -> PathBuf {
    super::onboarding::data_dir().join("book-drafts")
}

/// Where the draft of a file is kept while another book is open.
fn slot_path(path: &Path) -> PathBuf {
    slot_dir().join(format!("{:016x}.json", text_key(&path.to_string_lossy())))
}

fn save_drafts_index(drafts: &[(PathBuf, String)]) {
    let _ = std::fs::create_dir_all(slot_dir());
    if let Ok(b) = serde_json::to_vec(drafts) {
        let _ = std::fs::write(slot_dir().join("index.json"), b);
    }
}

fn load_drafts_index() -> Vec<(PathBuf, String)> {
    std::fs::read(slot_dir().join("index.json")).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
}

#[cfg(test)]
thread_local! {
    static STASHED: std::cell::RefCell<Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>> = const { std::cell::RefCell::new(None) };
}

/// Keeps the open draft in its file's slot, so the book comes back as it was left.
fn stash_current(s: &mut AppState) {
    let Some(d) = s.book.draft.clone() else { return };
    #[cfg(test)]
    STASHED.with(|k| {
        if let Some(k) = k.borrow().as_ref() {
            *k.lock().unwrap() = Some(d.file.language.clone());
        }
    });
    if !s.book.drafts.iter().any(|(p, _)| *p == d.file.path) {
        s.book.drafts.push((d.file.path.clone(), book_title(&d)));
    }
    if s.shell.scripted() {
        return;
    }
    let saved = Saved { draft: d.clone(), cast: saved_now(s), shown: true };
    if let Ok(b) = serde_json::to_vec(&saved) {
        let _ = std::fs::create_dir_all(slot_dir());
        let _ = std::fs::write(slot_path(&d.file.path), b);
    }
    save_drafts_index(&s.book.drafts);
}

fn read_slot(path: &Path) -> Option<Saved> {
    std::fs::read(slot_path(path)).ok().and_then(|b| serde_json::from_slice::<Saved>(&b).ok())
}

/// Opens a book of the list in the workspace: its kept draft, else its file read again.
fn open_entry(s: &mut AppState, path: Option<PathBuf>, book: Option<String>) {
    s.book.shown = true;
    let Some(path) = path else {
        shell::toast(s, Tone::Warning, "This book's file is not known: open it with Open book.");
        return;
    };
    if s.book.draft.as_ref().is_some_and(|d| d.file.path == path) {
        return;
    }
    stash_current(s);
    if let Some(saved) = read_slot(&path) {
        let mut draft = saved.draft;
        if draft.book_id.is_none() {
            draft.book_id = book;
        }
        s.book.cast = Cast::default();
        if saved.cast.file.as_deref() == Some(draft.file.path.as_path()) {
            restore_cast(&mut s.book.cast, saved.cast);
        }
        s.book.draft = Some(draft);
        s.book.book_keys.clear();
        s.book.renaming = None;
        link_book(s);
        return;
    }
    if !path.is_file() {
        shell::toast(s, Tone::Warning, format!("{} is not where it was: open it with Open book.", path.display()));
        return;
    }
    import(s, path, Purpose::Book);
}

/// Takes a book off the list: its draft, and the engine's record of it (the audio files stay).
fn remove_entry(s: &mut AppState, path: Option<PathBuf>, book: Option<String>) {
    if let Some(id) = book.as_deref() {
        forget_book(s, id);
    }
    if let Some(path) = path {
        s.book.drafts.retain(|(p, _)| *p != path);
        if !s.shell.scripted() {
            let _ = std::fs::remove_file(slot_path(&path));
            save_drafts_index(&s.book.drafts);
        }
        if s.book.draft.as_ref().is_some_and(|d| d.file.path == path) {
            s.book.draft = None;
            s.book.book_keys.clear();
            s.book.cast = Cast::default();
        }
    }
}

fn forget_book(s: &mut AppState, id: &str) {
    let (m, p) = protocol::book_id_request("book.delete", id);
    if shell::request(s, m, p).is_some() {
        s.book.recent.retain(|b| b.id != id);
        if s.book.project.as_ref().is_some_and(|p| p.id == id) {
            s.book.project = None;
        }
    }
}

fn close(s: &mut AppState) {
    s.book.renaming = None;
    stash_current(s);
    s.book.draft = None;
    s.book.book_keys.clear();
    s.book.cast = Cast::default();
    if !s.book.running() {
        s.book.project = None;
    }
}

fn open_folder(s: &mut AppState) {
    let Some(folder) = s.book.project.as_ref().and_then(|p| p.folder.clone()) else { return };
    let target = if folder.is_dir() { folder } else { folder.parent().map(Path::to_path_buf).unwrap_or(folder) };
    if let Err(e) = super::speak::open_file(&target) {
        shell::toast(s, Tone::Danger, e);
    }
}

fn play_chapter(s: &mut AppState, index: u32) {
    let Some(p) = s.book.project.as_ref() else { return };
    let Some(c) = p.chapter_list.iter().find(|c| c.index == index) else { return };
    if let Some(path) = c.path.as_ref().filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("wav"))) {
        let (path, title) = (path.clone(), c.title.clone());
        toggle_play(s, &path, title, index);
        return;
    }
    let id = p.id.clone();
    if let Some(now) = s.playbar.now.as_ref().filter(|n| n.what == chapter_caption(index)) {
        let path = now.path.clone();
        let title = now.title.clone();
        toggle_play(s, &path, title, index);
        return;
    }
    let (m, params) = protocol::book_play(&id, index);
    if let Some(r) = shell::request(s, m, params) {
        s.book.play_req = Some((r, index));
    }
}

fn chapter_caption(index: u32) -> String {
    format!("Book · chapter {}", index + 1)
}

fn toggle_play(s: &mut AppState, path: &Path, title: String, index: u32) {
    if let Err(e) = playbar::toggle(s, path, title, chapter_caption(index), playbar::Source::Speak) {
        shell::toast(s, Tone::Danger, e);
        return;
    }
    s.book.played = s.book.project.as_ref().map(|p| (p.id.clone(), index));
}

/// The player finished a track: a book chapter goes on to the next one when it is made.
pub fn on_track_ended(s: &mut AppState) {
    if let Some(next) = next_chapter_to_play(s) {
        play_chapter(s, next);
    }
}

fn next_chapter_to_play(s: &AppState) -> Option<u32> {
    let (id, index) = s.book.played.as_ref()?;
    if s.playbar.looped || !s.playbar.now.as_ref().is_some_and(|n| n.what == chapter_caption(*index)) {
        return None;
    }
    let p = s.book.project.as_ref().filter(|p| &p.id == id)?;
    p.chapter_list.iter().any(|c| c.index == index + 1 && c.status == "done").then_some(index + 1)
}

fn chapter_playing(s: &AppState, index: u32) -> bool {
    s.playbar.now.as_ref().is_some_and(|n| n.what == chapter_caption(index) && n.status == playbar::Status::Playing)
}

fn friendly(e: &protocol::EngineError) -> String {
    match e.code.as_str() {
        "not_ready" => format!("The engine is not ready: {}.", e.message),
        "busy" => format!("The engine is busy: {}.", e.message),
        _ if e.message.is_empty() => "Something went wrong.".into(),
        _ => e.message.clone(),
    }
}

pub fn on_engine(s: &mut AppState, msg: &EngineMsg) {
    match msg {
        EngineMsg::Ready(_) => {
            s.book.listed = false;
            s.book.first_list = true;
        }
        EngineMsg::Exited { .. } => {
            s.book.listed = false;
            s.book.stopping = None;
            s.book.start_req = None;
            s.book.resume_req = None;
            let c = &mut s.book.cast;
            if c.req.take().is_some() | c.job.take().is_some() {
                c.error = Some("The voice engine stopped. Try again once it is running.".into());
            }
            c.cancelling = false;
            c.design = None;
            c.imports.clear();
            if let Some(p) = s.book.project.as_mut().filter(|p| p.status == "running") {
                p.status = "paused".into();
                p.interrupted = true;
                p.job = None;
            }
        }
        EngineMsg::Response { id, result } => on_response(s, *id, result),
        EngineMsg::Event(ev) if ev.event.starts_with("book.") => on_event(s, &ev.event, &ev.data),
        _ => {}
    }
}

fn on_response(s: &mut AppState, id: u64, result: &Result<Value, protocol::EngineError>) {
    let b = &mut s.book;
    if let Some((req, purpose)) = b.importing.filter(|(r, _)| *r == id) {
        let _ = req;
        b.importing = None;
        match result.clone().and_then(protocol::parse_result::<TextImport>) {
            Ok(file) => opened(s, file, purpose),
            Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),
        }
    } else if b.start_req == Some(id) {
        b.start_req = None;
        match result.clone().and_then(protocol::parse_result::<BookStarted>) {
            Ok(st) => {
                let Some(d) = b.draft.as_mut() else { return };
                d.book_id = Some(st.id.clone());
                b.book_keys = d.chapters.iter().filter(|c| c.include).map(|c| text_key(&c.text)).collect();
                let d = &*d;
                let rows = d
                    .chapters
                    .iter()
                    .filter(|c| c.include)
                    .enumerate()
                    .map(|(i, c)| BookChapterRow {
                        index: i as u32,
                        title: c.title.clone(),
                        words: c.words,
                        status: "waiting".into(),
                        ..Default::default()
                    })
                    .collect::<Vec<_>>();
                b.project = Some(BookSummary {
                    id: st.id.clone(),
                    title: if d.file.title.is_empty() { d.file.name.clone() } else { d.file.title.clone() },
                    format: Some(d.file.format_label.clone()),
                    language: Some(d.file.language.clone()),
                    status: "running".into(),
                    job: Some(st.job.clone()),
                    chapters: rows.len() as u32,
                    words: rows.iter().map(|r| r.words).sum(),
                    folder: st.folder.clone(),
                    chapter_list: rows,
                    ..Default::default()
                });
                super::speak::job_notes(s, st.accent_note.as_deref(), st.reference_note.as_deref());
                request_list(s);
            }
            Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),
        }
    } else if b.cast.status_req == Some(id) {
        b.cast.status_req = None;
        let answer = result.clone().ok().and_then(|v| v.get("searched").and_then(Value::as_array).cloned());
        match (answer, s.book.draft.as_ref()) {
            (Some(list), Some(d)) if list.len() == d.chapters.len() => {
                s.book.cast.searched = d
                    .chapters
                    .iter()
                    .zip(list)
                    .filter(|(_, yes)| yes.as_bool() == Some(true))
                    .map(|(c, _)| chapter_fingerprint(c))
                    .collect();
                let speech = result.as_ref().ok().and_then(|v| v.get("speech")).and_then(Value::as_array);
                s.book.cast.speechless = speech
                    .filter(|l| l.len() == d.chapters.len())
                    .map(|l| {
                        d.chapters
                            .iter()
                            .zip(l)
                            .filter(|(_, yes)| yes.as_bool() == Some(false))
                            .map(|(c, _)| chapter_fingerprint(c))
                            .collect()
                    })
                    .unwrap_or_default();
            }
            _ => s.book.cast.status_for = 0,
        }
    } else if b.cast.req == Some(id) {
        b.cast.req = None;
        match result.clone().and_then(protocol::parse_result::<BookCast>) {
            Ok(c) if c.job.is_some() => b.cast.job = Some(c.key),
            Ok(c) => {
                b.cast.found = Some(c);
                searched(&mut b.cast);
                reuse_book_voices(s);
            }
            Err(e) => b.cast.error = Some(friendly(&e)),
        }
    } else if let Some((_, role)) = b.cast.design.filter(|(r, _)| *r == id) {
        b.cast.design = None;
        match result {
            Ok(take) if take.get("clear").and_then(Value::as_bool) == Some(false) => {
                s.book.cast.unclear += 1;
                if s.book.cast.unclear < UNCLEAR_TRIES {
                    request_design(s, role);
                } else {
                    shell::toast(s, Tone::Warning, "The voice came out as noise three times. Press Generate again.");
                }
            }
            Ok(take) => {
                s.book.cast.samples.retain(|(r, _)| *r != role);
                s.book.cast.samples.push((role, take.clone()));
                adopt_sample(s, role);
            }
            Err(e) => shell::toast(s, Tone::Danger, friendly(e)),
        }
    } else if let Some(at) = b.cast.adopting.iter().position(|(r, _)| *r == id) {
        let (_, role) = b.cast.adopting.remove(at);
        match result.as_ref().map(|v| v.get("voice").and_then(VoiceInfo::from_json)) {
            Ok(Some(info)) => {
                let voice = info.id.clone();
                match s.shell.voices.iter_mut().find(|v| v.id == voice) {
                    Some(v) => *v = info,
                    None => s.shell.voices.push(info),
                }
                // The clip is replaced in place: the player would resume the old one at the same path.
                if let Some(path) = role_audio(s, role) {
                    playbar::stop_path(s, &[path.as_path()]);
                }
                set_role_voice(s, role, &voice);
                shell::refresh_voices(s);
            }
            Ok(None) => shell::toast(s, Tone::Danger, "The engine did not return the new voice."),
            Err(e) => shell::toast(s, Tone::Danger, friendly(e)),
        }
    } else if let Some(at) = b.cast.imports.iter().position(|(r, _)| *r == id) {
        let (_, role) = b.cast.imports.remove(at);
        match result.as_ref().map(|v| v.get("voice").and_then(VoiceInfo::from_json)) {
            Ok(Some(info)) => {
                let voice = info.id.clone();
                s.shell.voices.retain(|v| v.id != voice);
                s.shell.voices.push(info);
                shell::refresh_voices(s);
                set_role_voice(s, role, &voice);
                if s.book.cast.imports.is_empty() {
                    start(s);
                }
            }
            Ok(None) => {
                s.book.cast.imports.clear();
                shell::toast(s, Tone::Danger, "The engine did not return the new voice.");
            }
            Err(e) => {
                s.book.cast.imports.clear();
                shell::toast(s, Tone::Danger, friendly(e));
            }
        }
    } else if b.resume_req == Some(id) {
        b.resume_req = None;
        match result.clone().and_then(protocol::parse_result::<BookStarted>) {
            Ok(st) => {
                if let Some(p) = b.project.as_mut().filter(|p| p.id == st.id) {
                    p.status = "running".into();
                    p.job = Some(st.job.clone());
                    p.error = None;
                    p.interrupted = false;
                }
                super::speak::job_notes(s, st.accent_note.as_deref(), st.reference_note.as_deref());
            }
            Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),
        }
    } else if b.link_req == Some(id) {
        b.link_req = None;
        match result.clone().and_then(protocol::parse_result::<BookSummary>) {
            Ok(p) => {
                let rows = result.as_ref().ok().and_then(|v| v.get("chapter_list")).and_then(Value::as_array);
                b.book_keys = rows
                    .map(|r| r.iter().map(|r| text_key(r.get("text").and_then(Value::as_str).unwrap_or(""))).collect())
                    .unwrap_or_default();
                if b.project.as_ref().is_none_or(|q| q.id == p.id || q.status != "running") {
                    b.project = Some(p);
                }
            }
            Err(e) => {
                if e.code == "not_found"
                    && let Some(d) = b.draft.as_mut()
                {
                    d.book_id = None;
                }
                b.book_keys.clear();
            }
        }
    } else if b.add_req == Some(id) {
        b.add_req = None;
        match result.clone().and_then(protocol::parse_result::<BookSummary>) {
            Ok(p) => {
                b.project = Some(p);
                request_list(s);
                link_book(s);
                resume(s);
            }
            Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),
        }
    } else if b.reread_req == Some(id) {
        b.reread_req = None;
        match result.clone().and_then(protocol::parse_result::<BookSummary>) {
            Ok(p) => {
                b.project = Some(p);
                request_list(s);
                resume(s);
            }
            Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),
        }
    } else if b.get_req == Some(id) {
        b.get_req = None;
        match result.clone().and_then(protocol::parse_result::<BookSummary>) {
            Ok(p) => b.project = Some(p),
            Err(e) => shell::toast(s, Tone::Danger, friendly(&e)),
        }
    } else if b.list_req == Some(id) {
        b.list_req = None;
        let list: Vec<BookSummary> = result
            .as_ref()
            .ok()
            .and_then(|v| v.get("books"))
            .and_then(|v| serde_json::from_value(v.clone()).ok())
            .unwrap_or_default();
        b.recent = list;
        if std::mem::replace(&mut b.first_list, false) {
            let want = match &b.project {
                Some(p) => Some(p.id.clone()),
                None if b.draft.is_none() => unfinished_of_voice(s),
                None => None,
            };
            if let Some(id) = want {
                let (m, p) = protocol::book_id_request("book.get", &id);
                s.book.get_req = shell::request(s, m, p);
            }
        }
    } else if let Some((_, index)) = b.play_req.filter(|(r, _)| *r == id) {
        b.play_req = None;
        match result {
            Ok(v) => {
                let path = v.get("path_play").and_then(Value::as_str).map(PathBuf::from);
                let title = s
                    .book
                    .project
                    .as_ref()
                    .and_then(|p| p.chapter_list.iter().find(|c| c.index == index))
                    .map(|c| c.title.clone())
                    .unwrap_or_default();
                if let Some(path) = path {
                    toggle_play(s, &path, title, index);
                }
            }
            Err(e) => shell::toast(s, Tone::Danger, friendly(e)),
        }
    }
}

fn of_active_voice(s: &AppState, b: &BookSummary) -> bool {
    b.voice_id.is_some() && b.voice_id == s.shell.active_voice
}

fn unfinished_of_voice(s: &AppState) -> Option<String> {
    let mut open = s.book.recent.iter().filter(|r| unfinished(r));
    open.clone().find(|r| of_active_voice(s, r)).or_else(|| open.next()).map(|r| r.id.clone())
}

fn unfinished(b: &BookSummary) -> bool {
    matches!(b.status.as_str(), "paused" | "error" | "running")
}

fn on_event(s: &mut AppState, name: &str, data: &Value) {
    let id = data.get("id").and_then(Value::as_str).unwrap_or("");
    let shown = s.book.project.as_ref().is_some_and(|p| p.id == id);
    match name {
        "book.progress" if shown => {
            let Ok(pr) = serde_json::from_value::<BookProgress>(data.clone()) else { return };
            let p = s.book.project.as_mut().expect("shown");
            p.totals = pr.totals;
            p.current = pr.chapter;
            p.status = "running".into();
            if let Some(c) = p.chapter_list.iter_mut().find(|c| c.index == pr.chapter)
                && c.status != "done"
            {
                c.status = "partial".into();
                c.segment = pr.segment;
                c.segments = pr.segments;
                c.audio_s = pr.chapter_audio_s;
            }
            s.book.m4b_stage(pr.stage.as_deref() == Some("m4b"));
            s.book.m4b_progress = (pr.stage_pct.unwrap_or(0.0), pr.stage_eta_s);
            s.book.memory_wait = if pr.stage.as_deref() == Some("memory") { pr.retry_in_s } else { None };
            s.book.cast_stage = (pr.stage.as_deref() == Some("cast")).then(|| pr.stage_pct.unwrap_or(0.0));
        }
        "book.cast_progress" if cast_event(s, data) => {
            if let Ok(pr) = serde_json::from_value::<BookCastProgress>(data.clone()) {
                s.book.cast.pct = pr.pct;
            }
        }
        "book.cast_done" if cast_event(s, data) => {
            let c = &mut s.book.cast;
            (c.req, c.job, c.cancelling) = (None, None, false);
            match serde_json::from_value::<BookCast>(data.clone()) {
                Ok(found) => {
                    c.found = Some(found);
                    searched(c);
                }
                Err(e) => c.error = Some(e.to_string()),
            }
        }
        "book.cast_error" if cast_event(s, data) => {
            let c = &mut s.book.cast;
            (c.req, c.job, c.cancelling) = (None, None, false);
            if data.get("code").and_then(Value::as_str) != Some("cancelled") {
                c.error =
                    Some(data.get("message").and_then(Value::as_str).unwrap_or("Something went wrong.").to_owned());
            }
        }
        "book.chapter" if shown => {
            let Ok(ch) = serde_json::from_value::<BookChapterDone>(data.clone()) else { return };
            let totals = serde_json::from_value(data.clone()).unwrap_or_default();
            if let Some(r) = ch.rtf.filter(|r| *r > 0.0) {
                let slot = &mut s.book.measured_rtf[usize::from(s.speak.quality == protocol::Quality::Fast)];
                *slot = Some(slot.map_or(r, |old| old * 0.7 + r * 0.3));
                s.book.settings_dirty = true;
            }
            let p = s.book.project.as_mut().expect("shown");
            p.totals = totals;
            p.chapters_done += 1;
            if let Some(c) = p.chapter_list.iter_mut().find(|c| c.index == ch.index) {
                c.status = "done".into();
                c.path = Some(ch.path);
                c.audio_s = ch.duration_s;
                c.rtf = ch.rtf;
                c.segment = c.segments;
            }
        }
        "book.done" => {
            if shown {
                let Ok(done) = serde_json::from_value::<BookDone>(data.clone()) else { return };
                let p = s.book.project.as_mut().expect("shown");
                p.status = "done".into();
                p.job = None;
                p.totals = done.totals;
                p.m4b = done.m4b.clone();
                p.chapters_done = p.chapters;
                let hours = fmt_len(p.totals.audio_s);
                let note = if done.m4b_requested && done.m4b.is_none() {
                    " The M4B could not be made (it needs ffmpeg with AAC)."
                } else {
                    ""
                };
                shell::toast(s, Tone::Success, format!("The book is ready: {hours} of audio.{note}"));
            }
            s.book.stopping = None;
            request_list(s);
        }
        "book.paused" => {
            if shown && let Ok(sum) = serde_json::from_value::<BookSummary>(data.clone()) {
                let p = s.book.project.as_mut().expect("shown");
                p.status = "paused".into();
                p.job = None;
                p.totals = sum.totals;
            }
            s.book.stopping = None;
            request_list(s);
        }
        "book.error" => {
            if shown {
                let code = data.get("code").and_then(Value::as_str).unwrap_or("internal").to_owned();
                let message = data.get("message").and_then(Value::as_str).unwrap_or("").to_owned();
                let p = s.book.project.as_mut().expect("shown");
                p.job = None;
                if code == "cancelled" {
                    p.status = "cancelled".into();
                    reset_partial(p);
                } else {
                    p.status = "error".into();
                    p.error = Some(protocol::EngineError::new(&code, message.clone()));
                    shell::toast(s, Tone::Danger, format!("The book stopped: {message}"));
                }
            }
            s.book.stopping = None;
            request_list(s);
        }
        _ => {}
    }
}

/// The answer to `book.cast` may come after its first events.
fn cast_event(s: &AppState, data: &Value) -> bool {
    let c = &s.book.cast;
    c.req.is_some() || (c.job.is_some() && c.job.as_deref() == data.get("key").and_then(Value::as_str))
}

impl BookState {
    fn m4b_stage(&mut self, on: bool) {
        if on {
            self.stopping = None;
        }
        self.m4b_making = on;
    }
}

fn request_list(s: &mut AppState) {
    let (m, p) = ("book.list", json!({}));
    s.book.list_req = shell::request(s, m, p);
    s.book.listed = true;
}

/// What `book-draft.json` holds: the draft, and the speakers found and voices picked for it.
#[derive(serde::Serialize, serde::Deserialize)]
struct Saved {
    #[serde(flatten)]
    draft: Draft,
    #[serde(default)]
    cast: SavedCast,
    #[serde(default)]
    shown: bool,
}

#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
struct SavedCast {
    /// The file these speakers and voices were found for: another one's are not brought back.
    #[serde(default)]
    file: Option<PathBuf>,
    #[serde(default)]
    narrator: Option<String>,
    found: Option<BookCast>,
    men: Option<String>,
    women: Option<String>,
    samples: Vec<(String, Value)>,
    #[serde(default)]
    genders: Vec<(String, String)>,
}

fn saved_now(s: &AppState) -> SavedCast {
    saved_cast(&s.book.cast, s.book.draft.as_ref().map(|d| d.file.path.as_path()))
}

fn saved_cast(c: &Cast, file: Option<&Path>) -> SavedCast {
    SavedCast {
        file: file.map(Path::to_path_buf),
        narrator: c.narrator.clone(),
        found: c.found.clone(),
        men: c.men.clone(),
        women: c.women.clone(),
        samples: c.samples.iter().map(|(r, v)| (r.id().to_string(), v.clone())).collect(),
        genders: c.genders.iter().map(|(r, g)| (r.id().to_string(), g.clone())).collect(),
    }
}

fn restore_cast(c: &mut Cast, saved: SavedCast) {
    c.narrator = saved.narrator;
    c.found = saved.found;
    c.men = saved.men;
    c.women = saved.women;
    c.samples = saved.samples.into_iter().filter_map(|(r, v)| Some((Role::from_id(&r)?, v))).collect();
    c.genders = saved.genders.into_iter().filter_map(|(r, g)| Some((Role::from_id(&r)?, g))).collect();
}

fn saved_fingerprint(s: &AppState) -> Option<u64> {
    use std::hash::{Hash, Hasher};
    let d = s.book.draft.as_ref()?;
    let mut h = std::collections::hash_map::DefaultHasher::new();
    fingerprint(d).hash(&mut h);
    serde_json::to_string(&saved_now(s)).unwrap_or_default().hash(&mut h);
    s.book.shown.hash(&mut h);
    Some(h.finish())
}

fn draft_path() -> std::path::PathBuf {
    super::onboarding::data_dir().join("book-draft.json")
}

fn fingerprint(d: &Draft) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    d.file.path.hash(&mut h);
    d.before_split.is_some().hash(&mut h);
    for c in &d.chapters {
        (&c.title, c.include, c.text.len()).hash(&mut h);
    }
    h.finish()
}

fn keep_draft(s: &mut AppState) -> bool {
    if !s.book.draft_restored {
        s.book.draft_restored = true;
        s.book.drafts = load_drafts_index();
        if s.book.draft.is_none() {
            let restored = std::fs::read(draft_path()).ok().and_then(|b| serde_json::from_slice::<Saved>(&b).ok());
            if let Some(saved) = restored {
                if saved.cast.file.as_deref() == Some(saved.draft.file.path.as_path()) {
                    restore_cast(&mut s.book.cast, saved.cast);
                }
                s.book.draft = Some(saved.draft);
                s.book.shown = saved.shown;
                s.book.relink = true;
                s.book.draft_saved = saved_fingerprint(s);
                return true;
            }
        }
    }
    let now = saved_fingerprint(s);
    if now == s.book.draft_saved {
        return false;
    }
    s.book.draft_saved = now;
    let saved = s.book.draft.clone().map(|draft| Saved { draft, cast: saved_now(s), shown: s.book.shown });
    std::thread::spawn(move || {
        let path = draft_path();
        match saved {
            Some(d) => {
                let tmp = path.with_extension("json.tmp");
                let ok = serde_json::to_vec(&d).ok().is_some_and(|b| std::fs::write(&tmp, b).is_ok());
                if ok {
                    let _ = std::fs::rename(&tmp, &path);
                }
            }
            None => {
                let _ = std::fs::remove_file(&path);
            }
        }
    });
    false
}

pub fn settle(s: &mut AppState) -> bool {
    let mut changed = drop_stale_cast(s);
    ask_status(s);
    if s.book.relink && shell::engine_ready(s) {
        s.book.relink = false;
        link_book(s);
    }
    if s.book.cast.narrator.is_none() && s.book.cast.found.is_some() && !s.shell.voices.is_empty() {
        reuse_book_voices(s);
    }
    if let Some(id) = same_file_book(s) {
        if let Some(d) = s.book.draft.as_mut() {
            d.book_id = Some(id);
        }
        link_book(s);
        changed = true;
    }
    if fetch_kept_cast(s) && s.book.importing.is_none() && shell::engine_ready(s) {
        find_speakers(s);
        changed = true;
    }
    if !s.shell.scripted() {
        changed |= keep_draft(s);
    }
    if s.book.renaming.as_ref().is_some_and(|(_, edit)| !edit.focused) {
        commit_rename(s);
        changed = true;
    }
    if !s.shell.scripted() {
        if !s.book.settings_loaded {
            s.book.settings_loaded = true;
            s.book.m4b = super::onboarding::setting("book_m4b").and_then(|v| v.as_bool()).unwrap_or(false);
            s.book.read_titles =
                super::onboarding::setting("book_read_titles").and_then(|v| v.as_bool()).unwrap_or(true);
            s.book.expressiveness = super::onboarding::setting("book_expressiveness")
                .and_then(|v| v.as_f64())
                .map(|v| v as f32)
                .unwrap_or(EXPRESSIVENESS);
            s.book.voices =
                super::onboarding::setting("book_voices").and_then(|v| v.as_u64()).map_or(1, |n| n.clamp(1, 3) as u8);
            s.book.second = match super::onboarding::setting("book_second").as_ref().and_then(Value::as_str) {
                Some("women") => Role::Women,
                _ => Role::Men,
            };
            s.book.cast_mode = super::onboarding::setting("book_cast")
                .and_then(|v| serde_json::from_value(v).ok())
                .unwrap_or_default();
            let rtf = |key: &str| {
                super::onboarding::setting(key).and_then(|v| v.as_f64()).map(|v| v as f32).filter(|v| *v > 0.0)
            };
            s.book.measured_rtf = [rtf("book_rtf_best"), rtf("book_rtf_fast")];
            changed = true;
        } else if s.book.settings_dirty {
            s.book.settings_dirty = false;
            super::onboarding::save_setting("book_m4b", json!(s.book.m4b));
            super::onboarding::save_setting("book_read_titles", json!(s.book.read_titles));
            super::onboarding::save_setting(
                "book_expressiveness",
                json!((s.book.expressiveness * 100.0).round() / 100.0),
            );
            super::onboarding::save_setting("book_voices", json!(s.book.voices));
            super::onboarding::save_setting("book_second", json!(s.book.second.id()));
            super::onboarding::save_setting("book_cast", json!(s.book.cast_mode.as_str()));
            for (key, v) in ["book_rtf_best", "book_rtf_fast"].iter().zip(s.book.measured_rtf) {
                if let Some(v) = v {
                    super::onboarding::save_setting(key, json!((v * 1000.0).round() / 1000.0));
                }
            }
        }
        if !s.book.listed && shell::engine_ready(s) {
            request_list(s);
        }
    }
    changed
}

/// "3 h 05 min", "12 min", "40 s".
pub fn fmt_len(secs: f32) -> String {
    let t = secs.max(0.0).round() as u64;
    if t >= 3600 {
        format!("{} h {:02} min", t / 3600, (t % 3600) / 60)
    } else if t >= 60 {
        format!("{} min", (t + 30) / 60)
    } else {
        format!("{t} s")
    }
}

/// "86,400".
fn group(n: u32) -> String {
    let s = n.to_string();
    let mut out = String::new();
    for (i, ch) in s.chars().enumerate() {
        if i > 0 && (s.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(ch);
    }
    out
}

pub fn mode_switch(s: &AppState, p: Palette) -> El {
    segmented(p, "speak-mode", &["Text", "Book"], usize::from(s.book.shown), |s, i| set_mode(s, i == 1))
}

pub fn panel(s: &AppState, p: Palette) -> El {
    let head =
        row().key("book-head").pin(None, Some(14.5), Some(22.0), None).gap(10.0).center_y().child(mode_switch(s, p));
    let mut c = section_panel(p, "Book").key("book-panel").grow(1.0).min_w(0.0).h_full().gap(12.0).child(head);
    c = match s.book.draft.as_ref() {
        Some(d) => c.child(draft_view(s, p, d)),
        None => c.child(empty_view(s, p)),
    };
    c
}

fn empty_view(s: &AppState, p: Palette) -> El {
    let busy = s.book.importing.is_some() || s.book.get_req.is_some();
    let open = Button::new(if busy { "Opening…" } else { "Open book…" })
        .primary()
        .large()
        .icon(&icons::FILE)
        .key("book-open")
        .disabled(busy || !matches!(s.shell.engine, EngineStatus::Ready { .. }))
        .on_press(|s| choose_file(s, true))
        .build(p);
    col().key("book-empty").w_full().grow(1.0).min_h(0.0).center().gap(14.0)
        .child(empty_state(p, &icons::FILE, "Read a whole book in your voice",
            "EPUB, DOCX, ODT, FB2, PDF with a text layer, TXT, Markdown, HTML, RTF or subtitles. Every chapter becomes its own file, and you can pause and continue later, even after closing the app."))
        .child(open)
        .child(text("or drop the file on this window").font(ty::CAPTION).color(p.text_faint))
}

fn file_card(p: Palette, title: &str, sub: String, right: El) -> El {
    glass_card(p).key("book-file").w_full().padding(12.0).child(
        row()
            .w_full()
            .gap(12.0)
            .center_y()
            .child(el().size(36.0, 36.0).radius(radius::CONTROL).center().fill(p.accent.alpha(0.14)).child(icon_el(
                &icons::FILE,
                17.0,
                p.accent,
            )))
            .child(
                col()
                    .grow(1.0)
                    .min_w(0.0)
                    .gap(2.0)
                    .child(text(title.to_owned()).font(ty::TITLE).color(p.text).truncate())
                    .child(text(sub).font(ty::CAPTION).color(p.text_faint).truncate()),
            )
            .child(right),
    )
}

fn draft_view(s: &AppState, p: Palette, d: &Draft) -> El {
    let f = &d.file;
    let mut sub = vec![if f.format_label.is_empty() { f.format.to_uppercase() } else { f.format_label.clone() }];
    if !f.language.is_empty() {
        sub.push(format!("{}{}", super::lang::name(&f.language), if f.language_detected { " (detected)" } else { "" }));
    }
    if let Some(e) = f.encoding.as_ref().filter(|e| !e.is_empty()) {
        sub.push(e.to_uppercase());
    }
    let title = if f.title.trim().is_empty() { f.name.clone() } else { f.title.clone() };
    let name_line = if f.title.trim().is_empty() || f.title == f.name {
        sub.join(" · ")
    } else {
        format!("{} · {}", f.name, sub.join(" · "))
    };
    let right = row()
        .gap(8.0)
        .center_y()
        .child(
            Button::new("Open another…")
                .ghost()
                .small()
                .key("book-open-other")
                .on_press(|s| choose_file(s, true))
                .build(p),
        )
        .child(icon_button(p, "book-close", &icons::CLOSE, "Close this file", close));
    let inc: Vec<&DraftChapter> = d.chapters.iter().filter(|c| c.include).collect();
    let words: u32 = inc.iter().map(|c| c.words).sum();
    let speed = s.speak.speed.max(0.5);
    let audio = inc.iter().map(|c| c.est_s).sum::<f32>() / speed;
    let measured = s.book.measured_rtf[usize::from(s.speak.quality == protocol::Quality::Fast)];
    let make = measured.map(|r| audio * r);
    let stat = |value: String, what: &str| {
        col()
            .grow(1.0)
            .min_w(0.0)
            .gap(2.0)
            .child(text(value).font(ty::TITLE).color(p.text).truncate())
            .child(text(what.to_owned()).font(ty::CAPTION).color(p.text_faint).truncate())
    };
    let stats = row()
        .w_full()
        .gap(16.0)
        .child(stat(format!("{} of {}", inc.len(), d.chapters.len()), "chapters"))
        .child(stat(group(words), "words"))
        .child(stat(format!("~{}", fmt_len(audio)), "of audio"))
        .child(match make {
            Some(m) => stat(format!("~{}", fmt_len(m)), "to make"),
            None => stat("After chapter 1".to_owned(), "time to make"),
        });
    let totals = col()
        .key("book-totals")
        .w_full()
        .gap(10.0)
        .px(18.0)
        .py(12.0)
        .radius(radius::CONTROL)
        .fill(p.well)
        .border(1.0, p.well_rim)
        .child(stats)
        .children(split_line(p, d));
    let list = col()
        .w_full()
        .gap(2.0)
        .children(d.chapters.iter().enumerate().map(|(i, c)| draft_row(s, p, i, c, i + 1 == d.chapters.len())));
    let linked = linked(s);
    let block = read_blocker(s);
    let voice = role_voice(s, Role::Narrator).map(|v| v.name.clone()).unwrap_or_else(|| "no voice".into());
    let hint = block.clone().unwrap_or_else(|| {
        if linked.is_some() {
            return "The ticked chapters not read yet are read into the same book and folder".to_owned();
        }
        format!(
            "Read by {voice} in {} · saved as {} files, one per chapter",
            super::lang::name(&super::speak::language(s)),
            super::formats::output_format(s).to_uppercase()
        )
    });
    let starting = s.book.start_req.is_some() || s.book.add_req.is_some();
    let bar = match linked.filter(|b| b.status == "running") {
        Some(b) => project_bar(s, p, b),
        None => row()
            .key("book-bar")
            .w_full()
            .gap(16.0)
            .center_y()
            .child(
                col().grow(1.0).min_w(0.0).gap(2.0).child(text("Ready to read").font(ty::LABEL).color(p.text)).child(
                    text(hint).font(ty::CAPTION).color(if block.is_some() { p.warn } else { p.text_faint }).wrap(),
                ),
            )
            .children(has_files(s).then(|| {
                Button::new("Open folder")
                    .ghost()
                    .icon(&icons::FOLDER)
                    .key("book-open-folder")
                    .on_press(open_folder)
                    .build(p)
            }))
            .child(
                Button::new(if starting { "Starting…" } else { "Read the book" })
                    .primary()
                    .large()
                    .icon(&icons::SPARKLE)
                    .key("book-start")
                    .disabled(block.is_some() || starting)
                    .on_press(read_book)
                    .build(p),
            ),
    };
    let mut c = col()
        .key("book-draft")
        .w_full()
        .grow(1.0)
        .min_h(0.0)
        .gap(12.0)
        .child(file_card(p, &title, name_line, right))
        .child(totals);
    if let Some(w) = f.warnings.first() {
        c = c.child(text(w.clone()).font(ty::CAPTION).color(p.warn).wrap());
    }
    if let Some(b) = linked.filter(|b| b.status == "running" || b.chapters_done > 0) {
        c = c.child(progress_block(s, p, b));
    }
    c = c.child(chapter_scroller(p, Some(select_all_row(p, d)), list));
    c = c.child(cast_view(s, p));
    c.child(bar)
}

fn cast_view(s: &AppState, p: Palette) -> El {
    let b = &s.book;
    let label = |t: &str| text(t.to_owned()).font(ty::LABEL).color(p.text);
    let locked = reading_locked(s);
    let lock = |e: El| if locked { e.disabled(true).opacity(0.42) } else { e };
    let count = lock(segmented(
        p,
        "book-voices",
        &["One voice", "Two voices", "Three voices"],
        usize::from(b.voices.clamp(1, 3) - 1),
        |s, i| {
            if reading_locked(s) {
                return;
            }
            s.book.voices = i as u8 + 1;
            s.book.settings_dirty = true;
        },
    ));
    let c = col()
        .key("book-cast")
        .w_full()
        .gap(10.0)
        .child(row().key("book-voices-row").w_full().gap(12.0).center_y().child(label("Voices")).child(count));
    if b.voices < 2 {
        return c.child(roles_view(s, p));
    }
    if !super::setuprun::has(s, "cast") {
        let says = "Reading each speaker's lines in their own voice needs a language model that finds who speaks: \
                    Gemma 4 12B (7.4 GB)."
            .to_owned();
        return c.child(super::setuprun::install_line_says(s, p, "cast", "Character voices", Some(says)));
    }
    let mut c = c;
    if b.voices == 2 {
        let second =
            lock(segmented(p, "book-second", &["Men", "Women"], usize::from(b.second == Role::Women), |s, i| {
                if reading_locked(s) {
                    return;
                }
                s.book.second = if i == 1 { Role::Women } else { Role::Men };
                s.book.settings_dirty = true;
            }));
        c = c.child(
            row()
                .key("book-second-row")
                .w_full()
                .gap(12.0)
                .center_y()
                .child(label("The second voice reads:"))
                .child(second),
        );
    }
    let mode = lock(segmented(
        p,
        "book-accuracy",
        &["Fast", "Careful"],
        usize::from(b.cast_mode == CastMode::Careful),
        |s, i| {
            if reading_locked(s) {
                return;
            }
            s.book.cast_mode = if i == 1 { CastMode::Careful } else { CastMode::Fast };
            s.book.settings_dirty = true;
        },
    ));
    let hint = if b.cast_mode == CastMode::Careful {
        "Careful reads the book twice, so it takes about twice as long, and leaves the lines it is unsure of to the narrator."
    } else {
        "Fast reads the book once."
    };
    let mut block = col()
        .key("book-accuracy-row")
        .w_full()
        .gap(4.0)
        .child(
            row()
                .w_full()
                .gap(12.0)
                .center_y()
                .child(label("Accuracy"))
                .child(mode)
                .child(el().grow(1.0))
                .children(find_action(s, p)),
        )
        .child(text(hint).font(ty::CAPTION).color(p.text_faint).wrap());
    if let Some(status) = find_status(s, p) {
        block = block.child(status);
    }
    c.child(block).child(roles_view(s, p))
}

/// Find who speaks, or Cancel while it runs; nothing once the speakers are found.
fn find_action(s: &AppState, p: Palette) -> Option<El> {
    let c = &s.book.cast;
    if cast_running(s) {
        return Some(
            Button::new(if c.cancelling { "Cancelling…" } else { "Cancel" })
                .ghost()
                .small()
                .key("book-find-cancel")
                .disabled(c.cancelling || c.job.is_none())
                .on_press(cancel_cast)
                .build(p),
        );
    }
    if reading_locked(s) {
        return None;
    }
    if c.found.is_some() && unsearched_note(s).is_none() {
        return Some(
            Button::new("Search again")
                .ghost()
                .small()
                .icon(&icons::REFRESH)
                .key("book-find-again")
                .help("Gemma reads the ticked chapters again, even those read before")
                .disabled(!shell::engine_ready(s))
                .on_press(|s| search(s, true))
                .build(p),
        );
    }
    let none = s.book.draft.as_ref().is_none_or(|d| !d.chapters.iter().any(|c| c.include));
    Some(
        Button::new("Find who speaks")
            .secondary()
            .small()
            .icon(&icons::USER)
            .key("book-find-go")
            .disabled(none || !shell::engine_ready(s))
            .on_press(find_speakers)
            .build(p),
    )
}

fn find_status(s: &AppState, p: Palette) -> Option<El> {
    let c = &s.book.cast;
    let (line, color) = if cast_running(s) {
        (format!("Finding who speaks… {:.0}%", c.pct), p.text)
    } else {
        match (&c.found, &c.error) {
            (Some(found), _) => (cast_caption(found), p.text_dim),
            (None, Some(e)) => (e.clone(), p.warn),
            (None, None) => return None,
        }
    };
    Some(text(line).key("book-find").font(ty::CAPTION).color(color).wrap())
}

fn roles_view(s: &AppState, p: Palette) -> El {
    let found = s.book.cast.found.is_some() || s.book.voices < 2;
    let blocker = generate_blocker(s);
    let roles = std::iter::once(Role::Narrator).chain(character_roles(s.book.voices, s.book.second).iter().copied());
    let mut c = col().key("book-roles").w_full().gap(6.0);
    for role in roles {
        c = c.child(role_row(s, p, role, found && blocker.is_none()));
    }
    if reading_locked(s) {
        return c.child(
            text("Voices, accuracy and chapters stay as they are while the book is read: pause it to change them.")
                .font(ty::CAPTION)
                .color(p.text_faint)
                .wrap(),
        );
    }
    if found && let Some(why) = blocker.filter(|why| start_blocker(s).as_ref() != Some(why)) {
        c = c.child(text(why).font(ty::CAPTION).color(p.warn).wrap());
    }
    c
}

fn role_row(s: &AppState, p: Palette, role: Role, can: bool) -> El {
    let c = &s.book.cast;
    let voice = role_voice(s, role);
    let name = if sample(s, role).is_some() {
        "New voice (generated)"
    } else {
        voice.map_or("Pick a voice", |v| v.name.as_str())
    };
    let picker = dropdown_chip(
        p,
        &format!("book-role-{}", role.id()),
        &icons::USER,
        name,
        format!("{} voice: {name}", role.name()),
        !reading_locked(s),
        move |s| s.book.role_menu = Some(role),
    );
    let making = role_making(s, role);
    let busy = c.design.is_some() || !c.imports.is_empty() || !c.adopting.is_empty();
    let mut r = row()
        .key(format!("book-role-row-{}", role.id()))
        .w_full()
        .gap(10.0)
        .center_y()
        .child(text(role.name()).font(ty::LABEL).color(p.text_dim).w(80.0))
        .child(gender_pick(s, p, role))
        .child(row().grow(1.0).min_w(0.0).gap(10.0).center_y().child(picker).child(role_mismatch(p, role, voice)));
    if let Some(path) = role_audio(s, role) {
        let playing = take_playing(s, &path);
        let btn = el()
            .key(format!("book-role-play-{}", role.id()))
            .role("button")
            .label(if playing { "Pause" } else { "Play" })
            .size(28.0, 28.0)
            .radius(14.0)
            .center()
            .hover(rune::Color::WHITE.alpha(0.1))
            .focusable(true)
            .motion(motion::UI)
            .on_press(move |s: &mut AppState| {
                if !role_making(s, role) {
                    play_take(s, role)
                }
            })
            .child(icon_el(if playing { &icons::PAUSE } else { &icons::PLAY }, 12.0, p.on_accent));
        let btn = accent_glass(p, btn);
        r = r.child(if making { btn.disabled(true).opacity(0.42) } else { btn });
    }
    r.child(
        Button::new(if making { "Generating…" } else { "Generate" })
            .secondary()
            .small()
            .icon(&icons::SPARKLE)
            .key(format!("book-role-gen-{}", role.id()))
            .disabled(!can || busy || !shell::engine_ready(s))
            .on_press(move |s| generate_role(s, role))
            .build(p),
    )
}

fn role_making(s: &AppState, role: Role) -> bool {
    let c = &s.book.cast;
    c.design.is_some_and(|(_, r)| r == role)
        || c.imports.iter().any(|(_, r)| *r == role)
        || c.adopting.iter().any(|(_, r)| *r == role)
}

/// Who Generate makes for the role: Auto is Gemma's choice, or else the role's default.
fn gender_pick(s: &AppState, p: Palette, role: Role) -> El {
    const GENDERS: [&str; 2] = ["male", "female"];
    let at = s
        .book
        .cast
        .genders
        .iter()
        .find(|(r, _)| *r == role)
        .and_then(|(_, g)| GENDERS.iter().position(|x| x == g))
        .map_or(0, |i| i + 1);
    let pick =
        segmented(p, &format!("book-role-gender-{}", role.id()), &["Auto", "Male", "Female"], at, move |s, i| {
            if reading_locked(s) {
                return;
            }
            s.book.cast.genders.retain(|(r, _)| *r != role);
            if i > 0 {
                s.book.cast.genders.push((role, GENDERS[i - 1].to_owned()));
            }
        });
    if reading_locked(s) { pick.disabled(true).opacity(0.42) } else { pick }
}

/// A book voice made for another role than the one it is picked for.
fn role_mismatch(p: Palette, role: Role, voice: Option<&VoiceInfo>) -> El {
    let Some(made) = voice.and_then(|v| v.book_role.as_deref()).filter(|r| *r != role.id()) else { return el() };
    let why = format!("Expected {}, got {made}", role.id());
    row()
        .key(format!("book-role-mismatch-{}", role.id()))
        .gap(6.0)
        .center_y()
        .label(why.clone())
        .help(format!("{why}: this voice was made for the {made} of its book"))
        .child(icon_el(&icons::ALERT, 14.0, p.warn))
        .child(text(why).font(ty::CAPTION).color(p.warn))
}

fn role_menu(s: &AppState, p: Palette, role: Role) -> El {
    let chosen = role_voice(s, role).map(|v| v.id.as_str());
    let mut list = col().w_full().gap(2.0);
    let (own, book) = shell::by_kind(&s.shell.voices);
    for (i, v) in own.iter().chain(&book).enumerate() {
        if i == own.len() {
            list = list.child(shell::group_heading(p, "Book voices"));
        }
        let on = chosen == Some(v.id.as_str());
        let id = v.id.clone();
        list = list.child(
            row()
                .key(format!("book-role-voice-{}", v.id))
                .role("button")
                .label(v.name.clone())
                .w_full()
                .h(38.0)
                .px(12.0)
                .gap(10.0)
                .center_y()
                .radius(19.0)
                .fill(if on { p.accent.alpha(0.14) } else { rune::Color::TRANSPARENT })
                .hover(p.glass_hover)
                .focusable(true)
                .on_press(move |s: &mut AppState| {
                    set_role_voice(s, role, &id);
                    s.book.role_menu = None;
                })
                .child(text(v.name.clone()).font(ty::LABEL).color(p.text).grow(1.0).truncate())
                .child(el().w(16.0).children(on.then(|| icon_el(&icons::CHECK, 14.0, p.accent)))),
        );
    }
    if s.shell.voices.is_empty() {
        list = list.child(text("No voices yet").font(ty::CAPTION).color(p.text_faint).px(12.0).py(10.0));
    }
    popover(
        p,
        "book-role-menu",
        &format!("book-role-{}", role.id()),
        280.0,
        rune::Align::Start,
        |s: &mut AppState| s.book.role_menu = None,
        list,
    )
}

fn chapter_scroller(p: Palette, head: Option<El>, list: El) -> El {
    let scroll = col()
        .key("book-chapters-scroll")
        .w_full()
        .grow(1.0)
        .min_h(0.0)
        .scroll(ScrollSpec { stick_bottom: false })
        .scroll_edge_fade(14.0)
        .child(list);
    super::components::well(p)
        .key("book-chapters")
        .w_full()
        .grow(1.0)
        .min_h(120.0)
        .padding(6.0)
        .child(col().w_full().grow(1.0).min_h(0.0).gap(4.0).children(head).child(scroll))
}

fn toggle_all(s: &mut AppState) {
    if reading_locked(s) {
        return;
    }
    if let Some(d) = s.book.draft.as_mut() {
        let all = d.chapters.iter().all(|c| c.include);
        for c in &mut d.chapters {
            c.include = !all;
        }
    }
}

fn select_all_row(p: Palette, d: &Draft) -> El {
    let all = d.chapters.iter().all(|c| c.include);
    let n = d.chapters.iter().filter(|c| c.include).count();
    row()
        .key("book-select-all")
        .w_full()
        .min_h(36.0)
        .px(8.0)
        .gap(10.0)
        .center_y()
        .border_sides([0.0, 0.0, 1.0, 0.0], p.well_rim)
        .child(check_box(p, "book-inc-all".into(), all, toggle_all))
        .child(
            text(if all { "Deselect all" } else { "Select all" })
                .key("book-select-all-label")
                .font(ty::LABEL)
                .color(p.text_dim)
                .role("button")
                .on_press(toggle_all),
        )
        .child(el().grow(1.0))
        .child(text(format!("{n} of {} selected", d.chapters.len())).font(ty::CAPTION).color(p.text_faint))
}

fn check_box(p: Palette, key: String, on: bool, on_press: impl Fn(&mut AppState) + 'static) -> El {
    let b = el()
        .key(key)
        .role("checkbox")
        .label("Include")
        .checked(on)
        .focusable(true)
        .size(20.0, 20.0)
        .radius(radius::SMALL)
        .center()
        .motion(motion::UI)
        .on_press(on_press);
    if on {
        b.fill(p.accent).child(icon_el(&icons::CHECK, 13.0, p.on_accent))
    } else {
        b.fill(p.well).border(1.0, p.rim_top).hover(p.glass_hover)
    }
}

fn draft_row(s: &AppState, p: Palette, i: usize, c: &DraftChapter, last: bool) -> El {
    let renaming = s.book.renaming.as_ref().filter(|(k, _)| *k == i);
    let title: El = match renaming {
        Some((_, edit)) => kit::submit_field(
            &p,
            edit,
            "Chapter title",
            |s: &mut AppState| &mut s.book.renaming.as_mut().expect("renaming").1,
            commit_rename,
        ),
        None => text(c.title.clone())
            .key(format!("book-title{i}"))
            .font(ty::LABEL)
            .color(if c.include { p.text } else { p.text_faint })
            .truncate()
            .grow(1.0)
            .min_w(0.0)
            .role("button")
            .label(format!("Rename {}", c.title))
            .help("Click to rename")
            .on_press(move |s: &mut AppState| start_rename(s, i)),
    };
    let meta = format!("{} words · {}", group(c.words), fmt_len(c.est_s / s.speak.speed.max(0.5)));
    let mut r = row()
        .key(format!("book-ch{i}"))
        .w_full()
        .min_h(40.0)
        .px(8.0)
        .gap(10.0)
        .center_y()
        .radius(radius::CONTROL)
        .hover(p.glass_hover)
        .child(check_box(p, format!("book-inc{i}"), c.include, move |s| toggle_include(s, i)))
        .child(text(format!("{}", i + 1)).font(ty::NUM).color(p.text_faint).w(26.0))
        .child(el().grow(1.0).min_w(0.0).child(title))
        .child(
            text(meta)
                .font(ty::CAPTION)
                .color(p.text_faint)
                .help("Words, and about how long this chapter's audio will be"),
        );
    if s.book.voices > 1 {
        let speechless = s.book.cast.speechless.contains(&chapter_fingerprint(c));
        r = r.child(if chapter_searched(s, c) {
            let (help, color) = if speechless {
                ("No dialogue: the narrator reads it all, so it needs no search", p.warn)
            } else {
                ("Speakers found: Gemma has read this chapter, so it needs no new search", p.accent)
            };
            el().key(format!("book-searched{i}")).size(28.0, 28.0).center().label(help).help(help).child(icon_el(
                &icons::BRAIN,
                15.0,
                color,
            ))
        } else {
            el()
        });
    }
    if let Some((b, row)) = book_row(s, c) {
        return read_cells(s, p, r, b, row, c.include);
    }
    r = r.child(small_icon(p, format!("book-split{i}"), &SPLIT, "Split this chapter in two", move |s| split(s, i)));
    if !last {
        r = r.child(small_icon(p, format!("book-merge{i}"), &MERGE, "Join the next chapter into this one", move |s| {
            merge_next(s, i)
        }));
    }
    r = r.child(small_icon(
        p,
        format!("book-remove{i}"),
        &icons::TRASH,
        "Remove this chapter from the book",
        move |s| remove_chapter(s, i),
    ));
    if !c.include {
        r = r.opacity(0.7);
    }
    r
}

fn small_icon(
    p: Palette,
    key: String,
    glyph: &'static rune::Icon,
    help: &str,
    on_press: impl Fn(&mut AppState) + 'static,
) -> El {
    el().key(key)
        .role("button")
        .label(help.to_owned())
        .help(help.to_owned())
        .size(28.0, 28.0)
        .radius(14.0)
        .center()
        .hover(p.glass_hover)
        .focusable(true)
        .motion(motion::UI)
        .on_press(on_press)
        .child(icon_el(glyph, 14.0, p.text_dim))
}

fn status_word(b: &BookSummary) -> (&'static str, Tone) {
    match b.status.as_str() {
        "running" => ("Reading", Tone::Accent),
        "paused" if b.interrupted => ("Interrupted", Tone::Warning),
        "paused" => ("Paused", Tone::Warning),
        "done" => ("Finished", Tone::Success),
        "error" => ("Stopped by an error", Tone::Danger),
        "cancelled" => ("Cancelled", Tone::Neutral),
        _ => ("Not started", Tone::Neutral),
    }
}

fn progress_block(s: &AppState, p: Palette, b: &BookSummary) -> El {
    let running = b.status == "running";
    let t = &b.totals;
    let k = (b.current + 1).min(b.chapters.max(1));
    let label = match b.status.as_str() {
        "running" if s.book.cast_stage.is_some() => {
            format!("Finding who speaks… {:.0}%", s.book.cast_stage.unwrap_or(0.0))
        }
        "running" if s.book.m4b_making => format!("Making the M4B… {:.0}%", s.book.m4b_progress.0),
        "running" => format!("Chapter {k} of {} · {:.0}%", b.chapters, t.percent),
        "done" if b.chapters == 1 => "The chapter is read".to_owned(),
        "done" => format!("All {} chapters read", b.chapters),
        _ => format!("{} of {} chapters done · {:.0}%", b.chapters_done, b.chapters, t.percent),
    };
    let making = running && s.book.m4b_making;
    let mut facts = vec![match t.est_audio_s.filter(|_| b.status != "done" && !making) {
        Some(est) => format!("{} of about {} of audio", fmt_len(t.audio_s), fmt_len(est)),
        None => format!("{} of audio", fmt_len(t.audio_s)),
    }];
    if making {
        facts.push(match s.book.m4b_progress.1 {
            Some(eta) => format!("about {} left", fmt_len(eta)),
            None => "starting…".to_owned(),
        });
    } else if let Some(eta) = t.eta_s.filter(|_| b.status != "done") {
        facts.push(format!("ready in about {}", fmt_len(eta)));
    }
    if let Some(r) = t.rtf.filter(|r| *r > 0.0 && !making) {
        facts.push(if r < 1.0 {
            format!("{:.0}× faster than real time", 1.0 / r)
        } else {
            format!("{r:.1}× slower than real time")
        });
    }
    if b.status == "done" && t.elapsed_s > 0.0 {
        facts.push(format!("made in {}", fmt_len(t.elapsed_s)));
    }
    col()
        .key("book-progress")
        .w_full()
        .gap(8.0)
        .child(
            row()
                .w_full()
                .center_y()
                .justify_between()
                .gap(10.0)
                .child(text(label).font(ty::LABEL).color(p.text))
                .child(text(facts.join(" · ")).font(ty::NUM).color(p.text_dim)),
        )
        .child(progress_bar(
            p,
            Some(if let Some(pct) = s.book.cast_stage.filter(|_| running) {
                pct / 100.0
            } else if making {
                s.book.m4b_progress.0 / 100.0
            } else {
                (t.percent / 100.0).max(if running { 0.01 } else { 0.0 })
            }),
        ))
}

fn project_bar(s: &AppState, p: Palette, b: &BookSummary) -> El {
    let voice = b.voice_id.as_ref().and_then(|id| s.shell.voices.iter().find(|v| &v.id == id)).map(|v| v.name.clone());
    let (title, hint) = match b.status.as_str() {
        "running" if s.book.stopping.is_none() && s.book.memory_wait.is_some() => (
            "Waiting for free memory…".to_owned(),
            format!("The computer ran short of memory. Reading goes on from the same sentence in {}; closing other programs helps.", fmt_len(s.book.memory_wait.unwrap_or(0.0))),
        ),
        "running" if s.book.stopping.is_none() && s.book.cast_stage.is_some() => (
            "Finding who speaks…".to_owned(),
            "Each line's speaker is found before the first chapter is read in its voice.".to_owned(),
        ),
        "running" if s.book.stopping.is_none() && s.book.m4b_making => (
            "Making the M4B…".to_owned(),
            "Every chapter is read and its file is in the book's folder. Now all of them are joined into one audiobook file with chapter marks.".to_owned(),
        ),
        "running" => (s.book.stopping.unwrap_or("Reading…").to_owned(), "Pause any time: it continues from the same sentence. Speak, Redub and training wait until the book is paused or done.".to_owned()),
        "done" => ("Finished".to_owned(), match &b.m4b {
            Some(m) => format!("Chapter files and {} are in the book's folder.", m.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()),
            None => "One file per chapter, in the book's folder.".to_owned(),
        }),
        "cancelled" => ("Cancelled".to_owned(), "Finished chapters are kept. Resume starts again at the first unfinished chapter.".to_owned()),
        _ => (if b.status == "new" { "Not started".to_owned() } else { "Paused".to_owned() }, match voice {
            Some(v) => format!("Resume reads on with {v} and the settings the book started with."),
            None => "Resume reads on with the settings the book started with.".to_owned(),
        }),
    };
    let mut r = row().key("book-bar").w_full().gap(12.0).center_y().child(
        col()
            .grow(1.0)
            .min_w(0.0)
            .gap(2.0)
            .child(text(title).font(ty::LABEL).color(p.text))
            .child(text(hint).font(ty::CAPTION).color(p.text_faint).wrap()),
    );
    let waiting = s.book.stopping.is_some() || s.book.resume_req.is_some();
    match b.status.as_str() {
        "running" => {
            r = r
                .child(
                    Button::new("Cancel")
                        .ghost()
                        .key("book-cancel")
                        .disabled(waiting)
                        .on_press(|s| stop(s, "cancel"))
                        .build(p),
                )
                .child(
                    Button::new("Pause")
                        .large()
                        .icon(&icons::PAUSE)
                        .key("book-pause")
                        .disabled(waiting)
                        .on_press(|s| stop(s, "pause"))
                        .build(p),
                );
        }
        "done" => {
            r = r
                .child(
                    Button::new("Change voice")
                        .ghost()
                        .icon(&icons::USER)
                        .key("book-voice")
                        .disabled(s.book.reread_req.is_some())
                        .on_press(|s| s.book.voice_menu = Some(None))
                        .build(p),
                )
                .child(Button::new("New book").ghost().key("book-new").on_press(|s| choose_file(s, true)).build(p))
                .child(
                    Button::new("Open folder")
                        .primary()
                        .large()
                        .icon(&icons::FOLDER)
                        .key("book-open-folder")
                        .on_press(open_folder)
                        .build(p),
                );
        }
        _ => {
            r = r.child(
                Button::new("Change voice")
                    .ghost()
                    .icon(&icons::USER)
                    .key("book-voice")
                    .disabled(waiting || s.book.reread_req.is_some())
                    .on_press(|s| s.book.voice_menu = Some(None))
                    .build(p),
            );
            if b.status == "paused" || b.status == "error" {
                r = r.child(
                    Button::new("Cancel")
                        .ghost()
                        .key("book-cancel")
                        .help("Drop the unfinished chapter; finished chapters are kept")
                        .on_press(|s| stop(s, "cancel"))
                        .build(p),
                );
            }
            let blocked =
                s.speak.is_generating() || s.book.recent.iter().any(|x| x.status == "running" && x.id != b.id);
            r = r.child(
                Button::new(if s.book.resume_req.is_some() { "Resuming…" } else { "Resume" })
                    .primary()
                    .large()
                    .icon(&icons::PLAY)
                    .key("book-resume")
                    .disabled(waiting || blocked || !matches!(s.shell.engine, EngineStatus::Ready { .. }))
                    .on_press(resume)
                    .build(p),
            );
        }
    }
    r
}

pub fn voice_overlay(s: &AppState, p: Palette) -> Option<El> {
    if let Some(role) = s.book.role_menu.filter(|_| s.book.draft.is_some()) {
        return Some(role_menu(s, p, role));
    }
    let pick = s.book.voice_menu.as_ref()?;
    let b = s.book.project.as_ref()?;
    let name = |id: &str| super::voices::voice_name(s, id).unwrap_or(id).to_owned();
    let roles = book_roles(b);
    let role = if roles.contains(&s.book.voice_role) { s.book.voice_role } else { Role::Narrator };
    let body = match pick {
        None => {
            let mut list = col().w_full().gap(2.0);
            for v in &s.shell.voices {
                let current = book_role_voice(b, role) == Some(v.id.as_str());
                let id = v.id.clone();
                let mut r = row()
                    .key(format!("book-voice-{}", v.id))
                    .w_full()
                    .h(38.0)
                    .px(12.0)
                    .gap(10.0)
                    .center_y()
                    .radius(19.0)
                    .child(
                        text(v.name.clone())
                            .font(ty::LABEL)
                            .color(if current { p.text_dim } else { p.text })
                            .grow(1.0)
                            .truncate(),
                    )
                    .child(el().w(16.0).children(current.then(|| icon_el(&icons::CHECK, 14.0, p.accent))));
                if !current {
                    r = r
                        .role("button")
                        .label(format!("Read with {}", v.name))
                        .hover(p.glass_hover)
                        .focusable(true)
                        .on_press(move |s: &mut AppState| pick_book_voice(s, id.clone()));
                }
                list = list.child(r);
            }
            let names: Vec<&str> = roles.iter().map(|r| r.name()).collect();
            let at = roles.iter().position(|r| *r == role).unwrap_or(0);
            let tabs = (roles.len() > 1).then(|| {
                let roles = roles.clone();
                segmented(p, "book-voice-role", &names, at, move |s, i| s.book.voice_role = roles[i])
            });
            let head = match role {
                Role::Narrator => "Read this book with",
                Role::Men => "Read men's lines with",
                Role::Women => "Read women's lines with",
            };
            col()
                .w_full()
                .gap(6.0)
                .children(tabs.map(|t| el().px(6.0).pt(4.0).child(t)))
                .child(text(head).font(ty::LABEL).color(p.text).px(12.0).pt(4.0))
                .child(list)
        }
        Some(id) => {
            let (new, old) =
                (name(id), book_role_voice(b, role).map(name).unwrap_or_else(|| "another voice".to_owned()));
            let (all, keep) = (id.clone(), id.clone());
            col()
                .w_full()
                .gap(10.0)
                .padding(6.0)
                .child(text(format!("Read with {new}")).font(ty::LABEL).color(p.text))
                .child(
                    text(format!("{} of {} chapters are made with {old}.", b.chapters_done, b.chapters))
                        .font(ty::CAPTION)
                        .color(p.text_dim)
                        .wrap(),
                )
                .child(
                    Button::new(format!("Read all {} chapters again", b.chapters))
                        .primary()
                        .key("book-voice-all")
                        .on_press(move |s| reread(s, Some(all.clone()), None))
                        .build(p),
                )
                .child(
                    Button::new(format!("Keep them, read the rest with {new}"))
                        .ghost()
                        .key("book-voice-keep")
                        .on_press(move |s| keep_made_chapters(s, keep.clone()))
                        .build(p),
                )
                .child(
                    Button::new("Back")
                        .ghost()
                        .small()
                        .key("book-voice-back")
                        .on_press(|s| s.book.voice_menu = Some(None))
                        .build(p),
                )
        }
    };
    let scrim = el()
        .key("book-voice-scrim")
        .pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
        .on_press(|s: &mut AppState| s.book.voice_menu = None);
    let panel = col()
        .key("book-voice-menu")
        .w(300.0)
        .padding(8.0)
        .radius(radius::PANEL + 4.0)
        .fill(rune::oklcha(0.2, 0.03, 255.0, 0.88))
        .gradient(p.glass_top, p.glass_bottom)
        .border_gradient(1.0, p.rim_top, p.rim_bottom)
        .shadow(18.0, 50.0, p.shadow)
        .backdrop_blur(28.0)
        .anchored("book-voice", rune::Side::Top, rune::Align::Start, 8.0)
        .transition(rune::Transition::scale(0.98))
        .child(body);
    Some(el().key("book-voice-layer").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).child(scrim).child(panel))
}

pub fn side_panel(s: &AppState, p: Palette, own_scroll: bool) -> El {
    let head = row()
        .key("book-side-head")
        .pin(None, Some(16.5), Some(22.0), None)
        .gap(8.0)
        .center_y()
        .child(super::formats::output_chip(s, p, "book-outfmt"));
    let m4b = kit::checkbox(&p, s.book.m4b, "Also make an M4B audiobook", |s| {
        s.book.m4b = !s.book.m4b;
        s.book.settings_dirty = true;
        send_settings(s);
    });
    let titles = kit::checkbox(&p, s.book.read_titles, "Read chapter titles", |s| {
        s.book.read_titles = !s.book.read_titles;
        s.book.settings_dirty = true;
    });
    // Keyed slots: both checkboxes have the same own key. The inset keeps the scroll area's clip off their border.
    let opts = col()
        .key("book-opts")
        .w_full()
        .pl(2.0)
        .gap(10.0)
        .child(el().key("book-opt-m4b").w_full().help("One file with chapter marks, for audiobook players").child(m4b))
        .child(
            el().key("book-opt-titles").w_full().help("Each chapter starts with its title read aloud").child(titles),
        );
    let mut list = col().w_full().gap(6.0);
    let entries = book_entries(s);
    for e in &entries {
        let (path, book) = (e.path.clone(), e.book.clone());
        let (path2, book2) = (e.path.clone(), e.book.clone());
        let mut card = row()
            .key(format!("book-recent-{}", e.key))
            .w_full()
            .px(10.0)
            .py(8.0)
            .gap(8.0)
            .center_y()
            .radius(radius::CONTROL)
            .fill(if e.current { p.accent.alpha(0.12) } else { p.glass_hover.alpha(0.0) })
            .hover(p.glass_hover)
            .focusable(true)
            .role("button")
            .label(format!("Open {}", e.title))
            .on_press(move |s: &mut AppState| open_entry(s, path.clone(), book.clone()))
            .child(
                col()
                    .grow(1.0)
                    .min_w(0.0)
                    .gap(2.0)
                    .child(text(e.title.clone()).font(ty::LABEL).color(p.text).truncate())
                    .child(row().gap(6.0).center_y().child(status_dot(p, e.tone, e.pulse)).child(
                        text(format!("{} · {}", e.word, e.detail)).font(ty::CAPTION).color(p.text_faint).truncate(),
                    )),
            );
        if !e.pulse {
            card = card.child(small_icon(
                p,
                format!("book-forget-{}", e.key),
                &icons::TRASH,
                "Remove from the list (the audio files stay)",
                move |s| remove_entry(s, path2.clone(), book2.clone()),
            ));
        }
        list = list.child(card);
    }
    let books = if entries.is_empty() {
        col().key("book-recent-empty").w_full().child(
            text("Books you read appear here, so you can come back to them.")
                .font(ty::CAPTION)
                .color(p.text_faint)
                .wrap(),
        )
    } else {
        col()
            .key("book-recent")
            .w_full()
            .gap(8.0)
            .child(text("Your books").font(ty::LABEL).color(p.text_dim))
            .child(list)
    };
    let body = col().w_full().gap(16.0).child(opts).child(books);
    let body = if own_scroll {
        col()
            .key("book-side-scroll")
            .w_full()
            .grow(1.0)
            .min_h(0.0)
            .scroll(ScrollSpec { stick_bottom: false })
            .scroll_edge_fade(14.0)
            .child(body)
    } else {
        body
    };
    section_panel(p, "Output").key("book-side").w_full().grow(1.0).min_h(0.0).gap(12.0).child(head).child(body)
}

/// Join: two lines meeting in one.
static MERGE: rune::Icon = rune::Icon {
    name: "merge",
    view: 16.0,
    body: r#"<g fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 2.5V5.5A2.5 2.5 0 0 0 6.5 8H8M12 2.5V5.5A2.5 2.5 0 0 1 9.5 8H8V13.5M5.8 11.4L8 13.6L10.2 11.4"/></g>"#,
};

/// Split: one line forking in two.
static SPLIT: rune::Icon = rune::Icon {
    name: "split",
    view: 16.0,
    body: r#"<g fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2.5V7M8 7L4 11V13.5M8 7L12 11V13.5"/></g>"#,
};

// A public-domain book (Herman Melville, 1851) for the snapshots.
const CHAPTERS: [(&str, u32); 9] = [
    ("Etymology", 640),
    ("Chapter 1. Loomings", 2210),
    ("Chapter 2. The Carpet-Bag", 1900),
    ("Chapter 3. The Spouter-Inn", 5150),
    ("Chapter 4. The Counterpane", 1550),
    ("Chapter 5. Breakfast", 900),
    ("Chapter 6. The Street", 1100),
    ("Chapter 7. The Chapel", 1100),
    ("Chapter 8. The Pulpit", 1050),
];

fn scene_base(s: &mut AppState) {
    super::speak::scene_idle(s);
    s.book.shown = true;
    s.book.m4b = true;
    s.book.read_titles = true;
    s.shell.languages = Vec::new();
}

fn scene_file() -> TextImport {
    TextImport {
        path: "/home/me/Books/Moby-Dick.epub".into(),
        name: "Moby-Dick.epub".into(),
        format: "epub".into(),
        format_label: "EPUB".into(),
        title: "Moby-Dick".into(),
        encoding: None,
        language: "en".into(),
        language_detected: true,
        words: CHAPTERS.iter().map(|c| c.1).sum(),
        est_s: CHAPTERS.iter().map(|c| c.1 as f32 / 145.0 * 60.0).sum(),
        chapters: Vec::new(),
        parts: None,
        warnings: Vec::new(),
    }
}

fn scene_project(s: &mut AppState, status: &str, done: usize, seg: (u32, u32)) {
    scene_imported(s);
    for (i, c) in s.book.draft.as_mut().expect("draft").chapters.iter_mut().enumerate() {
        c.text = format!("Chapter {i}.");
        c.include = true;
    }
    s.book.book_keys = (0..CHAPTERS.len()).map(|i| text_key(&format!("Chapter {i}."))).collect();
    s.book.draft.as_mut().expect("draft").book_id = Some("under-the-old-lime-tree-20261113-101500".into());
    let rows = CHAPTERS
        .iter()
        .enumerate()
        .map(|(i, (t, w))| {
            let d = *w as f32 / 145.0 * 60.0;
            let st = if i < done {
                "done"
            } else if i == done && seg.0 > 0 {
                "partial"
            } else {
                "waiting"
            };
            BookChapterRow {
                index: i as u32,
                title: (*t).into(),
                words: *w,
                status: st.into(),
                segment: if st == "partial" { seg.0 } else { 0 },
                segments: if st == "partial" { seg.1 } else { 0 },
                audio_s: if st == "done" {
                    d
                } else if st == "partial" {
                    d * seg.0 as f32 / seg.1 as f32
                } else {
                    0.0
                },
                rtf: (st == "done").then_some(0.30 + 0.01 * i as f32),
                path: (st == "done").then(|| PathBuf::from(format!("/tmp/books/{:02} - {t}.mp3", i + 1))),
            }
        })
        .collect::<Vec<_>>();
    let audio: f32 = rows.iter().map(|r| r.audio_s).sum();
    let total: f32 = CHAPTERS.iter().map(|c| c.1 as f32 / 145.0 * 60.0).sum();
    let finished = status == "done";
    s.book.project = Some(BookSummary {
        id: "under-the-old-lime-tree-20261113-101500".into(),
        title: "Moby-Dick".into(),
        format: Some("EPUB".into()),
        language: Some("en".into()),
        voice_id: Some("me".into()),
        status: status.into(),
        job: (status == "running").then(|| "job-4".into()),
        chapters: rows.len() as u32,
        chapters_done: done as u32,
        current: done.min(rows.len() - 1) as u32,
        folder: Some("/tmp/books/Moby-Dick".into()),
        m4b: finished.then(|| PathBuf::from("/tmp/books/Moby-Dick/Moby-Dick.m4b")),
        words: CHAPTERS.iter().map(|c| c.1).sum(),
        totals: protocol::BookTotals {
            percent: 100.0 * audio / total,
            audio_s: audio,
            elapsed_s: audio * 0.32,
            rtf: Some(0.32),
            eta_s: (!finished).then_some((total - audio) * 0.32),
            est_audio_s: Some(total),
        },
        chapter_list: rows,
        ..Default::default()
    });
    s.book.recent = vec![
        s.book.project.clone().unwrap_or_default(),
        BookSummary {
            id: "kobzar-20261101-090000".into(),
            title: "Кобзар".into(),
            status: "done".into(),
            chapters: 24,
            chapters_done: 24,
            totals: protocol::BookTotals { audio_s: 31_200.0, ..Default::default() },
            ..Default::default()
        },
    ];
}

pub fn scene_imported(s: &mut AppState) {
    scene_base(s);
    let chapters = CHAPTERS
        .iter()
        .enumerate()
        .map(|(i, (t, w))| DraftChapter {
            title: (*t).into(),
            text: String::new(),
            words: *w,
            est_s: *w as f32 / 145.0 * 60.0,
            include: i > 0,
        })
        .collect();
    s.book.draft = Some(Draft { file: scene_file(), chapters, auto: None, before_split: None, book_id: None });
    s.book.recent = vec![BookSummary {
        id: "kobzar-20261101-090000".into(),
        title: "Кобзар".into(),
        status: "done".into(),
        chapters: 24,
        chapters_done: 24,
        totals: protocol::BookTotals { audio_s: 31_200.0, ..Default::default() },
        ..Default::default()
    }];
}

pub fn scene_imported_uk(s: &mut AppState) {
    scene_imported(s);
    if let Some(v) = shell::active_voice(s).map(|v| v.id.clone()) {
        s.speak.languages.insert(v, "uk".into());
    }
}

pub fn scene_autosplit_offer(s: &mut AppState) {
    scene_base(s);
    let one = |title: &str, words: u32| DraftChapter {
        title: title.into(),
        text: String::new(),
        words,
        est_s: words as f32 / 145.0 * 60.0,
        include: true,
    };
    let parts = [1833, 1601, 1957, 1925, 1704, 2222, 1763, 1708, 1083]
        .iter()
        .enumerate()
        .map(|(i, w)| one(&format!("Частина {}", i + 1), *w))
        .collect();
    let mut file = scene_file();
    file.title = "Тіні забутих предків".into();
    file.name = "Тіні забутих предків - Михайло Коцюбинський.epub".into();
    file.language = "uk".into();
    s.book.draft = Some(Draft {
        file,
        chapters: vec![one("Тіні забутих предків", 15796)],
        auto: Some(("length".into(), parts)),
        before_split: None,
        book_id: None,
    });
}

pub fn scene_autosplit_done(s: &mut AppState) {
    scene_autosplit_offer(s);
    auto_split(s);
}

pub fn scene_generating(s: &mut AppState) {
    scene_project(s, "running", 3, (37, 112));
}

pub fn scene_m4b(s: &mut AppState) {
    scene_project(s, "running", 9, (0, 0));
    s.book.m4b_making = true;
    s.book.m4b_progress = (37.0, Some(130.0));
    if let Some(r) = s.book.recent.first_mut() {
        r.status = "paused".into();
    }
}

pub fn scene_memory_wait(s: &mut AppState) {
    scene_project(s, "running", 3, (37, 112));
    s.book.memory_wait = Some(60.0);
}

pub fn scene_paused(s: &mut AppState) {
    scene_project(s, "paused", 3, (37, 112));
}

pub fn scene_interrupted(s: &mut AppState) {
    scene_project(s, "paused", 3, (37, 112));
    if let Some(p) = s.book.project.as_mut() {
        p.interrupted = true;
    }
}

pub fn scene_finished(s: &mut AppState) {
    scene_project(s, "done", CHAPTERS.len(), (0, 0));
    playbar::scene_now(
        s,
        "/tmp/books/02.wav",
        CHAPTERS[1].0,
        &chapter_caption(1),
        playbar::Source::Speak,
        playbar::Status::Playing,
        312.0,
        2031.0,
    );
}

pub fn scene_voice_roles(s: &mut AppState) {
    scene_project(s, "done", CHAPTERS.len(), (0, 0));
    let first = s.shell.voices.first().map(|v| v.id.clone());
    if let Some(b) = s.book.project.as_mut() {
        b.voices = Some([("men".to_owned(), first.clone()), ("women".to_owned(), first)].into_iter().collect());
    }
    s.book.voice_role = Role::Men;
    s.book.voice_menu = Some(None);
}

pub fn scene_linked(s: &mut AppState) {
    scene_imported(s);
    for (i, c) in s.book.draft.as_mut().unwrap().chapters.iter_mut().enumerate() {
        c.text = format!("Chapter {i}.");
    }
    s.book.draft.as_mut().unwrap().book_id = Some("moby".into());
    s.book.book_keys = (1..4).map(|i| text_key(&format!("Chapter {i}."))).collect();
    let row = |i: u32, status: &str| BookChapterRow {
        index: i,
        title: CHAPTERS[i as usize + 1].0.into(),
        status: status.into(),
        audio_s: 900.0,
        segment: 12,
        segments: 40,
        ..Default::default()
    };
    s.book.project = Some(BookSummary {
        id: "moby".into(),
        title: "Moby-Dick".into(),
        status: "running".into(),
        folder: Some(PathBuf::from("/tmp/books/Moby-Dick")),
        chapters: 3,
        chapters_done: 1,
        chapter_list: vec![row(0, "done"), row(1, "partial"), row(2, "waiting")],
        totals: protocol::BookTotals { audio_s: 900.0, percent: 45.0, ..Default::default() },
        ..Default::default()
    });
}

pub fn scene_empty(s: &mut AppState) {
    scene_base(s);
}

pub fn scene_three_voices(s: &mut AppState) {
    scene_imported(s);
    s.shell.components = None;
    s.book.voices = 3;
    s.book.cast_mode = CastMode::Careful;
}

pub fn scene_cast_found(s: &mut AppState) {
    scene_three_voices(s);
    let who = |name: &str, gender: &str, lines: u32| crate::engine::protocol::CastCharacter {
        name: name.into(),
        gender: gender.into(),
        lines,
    };
    if let Some(d) = s.book.draft.as_ref() {
        s.book.cast.searched = d.chapters.iter().map(chapter_fingerprint).collect();
    }
    s.book.cast.found = Some(BookCast {
        key: "k".into(),
        characters: vec![who("Queequeg", "m", 212), who("Captain Peleg", "m", 148), who("Mrs. Hussey", "f", 31)],
        lines: Some(crate::engine::protocol::CastLines { men: 1402, women: 68, narrator: 40 }),
        ..Default::default()
    });
    for role in [Role::Narrator, Role::Men, Role::Women] {
        let id = format!("moby-dick-{}", role.id());
        s.shell.voices.push(VoiceInfo {
            id: id.clone(),
            name: format!("Moby-Dick · {}", role.id()),
            language: "en".into(),
            book: Some("Moby-Dick".into()),
            book_role: Some(role.id().into()),
            ..Default::default()
        });
        set_role_voice(s, role, &id);
    }
}

pub fn scenes() -> &'static [super::Scene] {
    &[
        ("book_three_voices", scene_three_voices),
        ("book_cast_found", scene_cast_found),
        ("book_autosplit_offer", scene_autosplit_offer),
        ("book_autosplit_done", scene_autosplit_done),
        ("book_empty", scene_empty),
        ("book_imported", scene_imported),
        ("book_imported_uk", scene_imported_uk),
        ("book_generating", scene_generating),
        ("book_memory_wait", scene_memory_wait),
        ("book_m4b", scene_m4b),
        ("book_paused", scene_paused),
        ("book_interrupted", scene_interrupted),
        ("book_finished", scene_finished),
        ("book_linked", scene_linked),
        ("book_voice_roles", scene_voice_roles),
    ]
}

#[cfg(test)]
mod draft_tests {
    use super::*;

    fn sample() -> Draft {
        let one = |t: &str, text: &str| DraftChapter {
            title: t.into(),
            text: text.into(),
            words: 2,
            est_s: 1.0,
            include: true,
        };
        let mut file = scene_file();
        file.title = "Тіні забутих предків".into();
        Draft {
            file,
            chapters: vec![one("Частина 1", "Іван був"), one("Частина 2", "дев'ятнадцятою дитиною")],
            auto: Some(("length".into(), vec![one("1", "a")])),
            before_split: Some(vec![one("Тіні", "Іван був дев'ятнадцятою")]),
            book_id: None,
        }
    }

    #[test]
    fn a_draft_survives_a_restart_whole() {
        let d = sample();
        let back: Draft = serde_json::from_slice(&serde_json::to_vec(&d).unwrap()).unwrap();
        assert_eq!(fingerprint(&back), fingerprint(&d));
        assert_eq!(back.file.title, "Тіні забутих предків");
        assert_eq!(back.chapters[1].text, "дев'ятнадцятою дитиною");
        assert!(back.before_split.is_some() && back.auto.is_some());
    }

    #[test]
    fn every_edit_changes_the_fingerprint() {
        let d = sample();
        let mut renamed = d.clone();
        renamed.chapters[0].title = "Пролог".into();
        let mut unticked = d.clone();
        unticked.chapters[1].include = false;
        let mut joined = d.clone();
        let second = joined.chapters.remove(1);
        joined.chapters[0].text += &second.text;
        for other in [renamed, unticked, joined] {
            assert_ne!(fingerprint(&other), fingerprint(&d));
        }
    }
}

#[cfg(test)]
mod play_next_tests {
    use super::*;

    fn ended(index: u32) -> AppState {
        let mut s = AppState::default();
        scene_project(&mut s, "running", 3, (37, 112));
        let id = s.book.project.as_ref().unwrap().id.clone();
        s.book.played = Some((id, index));
        playbar::scene_now(
            &mut s,
            "/tmp/c.wav",
            "Chapter",
            &chapter_caption(index),
            playbar::Source::Speak,
            playbar::Status::Ended,
            60.0,
            60.0,
        );
        s
    }

    #[test]
    fn goes_on_to_a_made_chapter() {
        assert_eq!(next_chapter_to_play(&ended(1)), Some(2));
    }

    #[test]
    fn stops_before_a_chapter_not_made_yet() {
        assert_eq!(next_chapter_to_play(&ended(2)), None);
    }

    #[test]
    fn stops_when_looping_or_another_track_plays() {
        let mut s = ended(0);
        s.playbar.looped = true;
        assert_eq!(next_chapter_to_play(&s), None);
        let mut s = ended(0);
        s.book.played = Some(("other-book".into(), 0));
        assert_eq!(next_chapter_to_play(&s), None);
    }
}

#[cfg(test)]
mod voice_tests {
    use super::*;
    use crate::ui::shell::VoiceInfo;

    fn book(id: &str, voice: &str, status: &str) -> BookSummary {
        BookSummary {
            id: id.into(),
            title: id.into(),
            voice_id: Some(voice.into()),
            status: status.into(),
            chapters: 3,
            chapters_done: 1,
            ..Default::default()
        }
    }

    fn state() -> AppState {
        let mut s = AppState::default();
        s.shell.voices = ["taras", "sage"]
            .iter()
            .map(|v| VoiceInfo { id: (*v).into(), name: v.to_uppercase(), ..Default::default() })
            .collect();
        s.shell.active_voice = Some("sage".into());
        s.book.recent = vec![book("a", "taras", "paused"), book("b", "sage", "paused"), book("c", "gone", "done")];
        s
    }

    #[test]
    fn the_active_voices_unfinished_book_opens_first() {
        let mut s = state();
        assert_eq!(unfinished_of_voice(&s).as_deref(), Some("b"));
        s.shell.active_voice = Some("nobody".into());
        assert_eq!(unfinished_of_voice(&s).as_deref(), Some("a"));
    }
}

#[cfg(test)]
mod cast_tests {
    use super::*;
    use crate::engine::protocol::{CastCharacter, CastLines};

    fn found() -> BookCast {
        let who =
            |name: &str, gender: &str, lines: u32| CastCharacter { name: name.into(), gender: gender.into(), lines };
        BookCast {
            key: "k".into(),
            characters: vec![
                who("Ruth", "f", 256),
                who("Martin Eden", "m", 1312),
                who("Arthur", "m", 90),
                who("Mrs. Morse", "f", 12),
            ],
            lines: Some(CastLines { men: 1402, women: 268, narrator: 40 }),
            ..Default::default()
        }
    }

    fn state(voices: u8, second: Role) -> AppState {
        let mut s = AppState::default();
        scene_imported(&mut s);
        s.book.voices = voices;
        s.book.second = second;
        s
    }

    fn take_found(s: &mut AppState) {
        let d = s.book.draft.as_ref().unwrap();
        s.book.cast.searched = d.chapters.iter().map(chapter_fingerprint).collect();
        s.book.cast.found = Some(BookCast { mode: s.book.cast_mode.as_str().into(), ..found() });
    }

    #[test]
    fn a_noise_take_is_not_kept_as_a_voice() {
        let mut s = state(3, Role::Men);
        take_found(&mut s);
        let noise = json!({"clear": false, "path": "/t/a.wav", "reference": "/t/voice.wav", "language": "en"});
        for tries in 1..=UNCLEAR_TRIES {
            s.book.cast.design = Some((7, Role::Men));
            on_response(&mut s, 7, &Ok(noise.clone()));
            assert_eq!(s.book.cast.unclear, tries);
        }
        assert!(s.book.cast.samples.is_empty());
    }

    #[test]
    fn a_generated_sample_becomes_a_voice_only_when_the_book_starts() {
        let mut s = state(3, Role::Men);
        s.shell.components = None;
        take_found(&mut s);
        let take = json!({"clear": true, "path": "/t/a.wav", "reference": "/t/voice.wav", "language": "uk"});
        for _ in 0..2 {
            s.book.cast.design = Some((7, Role::Men));
            on_response(&mut s, 7, &Ok(take.clone()));
        }
        assert_eq!(s.book.cast.samples.len(), 1, "a new sample replaces the old one");
        assert!(role_ready(&s, Role::Men));
        s.book.cast.women = Some("pro".into());
        let voices = s.shell.voices.len();
        assert_eq!(start_blocker(&s), None);
        assert_eq!(s.shell.voices.len(), voices, "nothing is made before the book starts");
        s.book.cast.imports.push((9, Role::Men));
        let made = json!({"voice": {"id": "book-men", "name": "Book · men", "language": "uk", "book": "Book", "book_role": "men"}});
        on_response(&mut s, 9, &Ok(made));
        assert_eq!(s.book.cast.men.as_deref(), Some("book-men"));
        assert!(s.book.cast.samples.is_empty() && s.book.cast.imports.is_empty());
    }

    #[test]
    fn the_speakers_and_picked_voices_come_back_after_a_restart() {
        let mut s = state(3, Role::Men);
        take_found(&mut s);
        s.book.cast.women = Some("pro".into());
        s.book.cast.samples.push((Role::Men, json!({"path": "/t/a.wav", "reference": "/t/r.wav"})));
        s.book.shown = true;
        let saved = Saved { draft: s.book.draft.clone().unwrap(), cast: saved_now(&s), shown: true };
        let bytes = serde_json::to_vec(&saved).unwrap();
        let back: Saved = serde_json::from_slice(&bytes).unwrap();
        let mut t = state(3, Role::Men);
        restore_cast(&mut t.book.cast, back.cast);
        assert!(back.shown);
        assert_eq!(saved_now(&t), saved_now(&s));
        assert!(!drop_stale_cast(&mut t), "the speakers found stay with the same chapters");
        let old = serde_json::to_vec(&s.book.draft).unwrap();
        assert!(serde_json::from_slice::<Saved>(&old).is_ok(), "a draft saved before still opens");
    }

    #[test]
    fn every_role_with_a_voice_can_be_heard() {
        let mut s = state(3, Role::Men);
        assert_eq!(role_audio(&s, Role::Women), None);
        s.book.cast.women = Some(s.shell.voices[0].id.clone());
        assert!(role_audio(&s, Role::Women).is_some_and(|p| p.ends_with("reference.wav")));
        s.book.cast.samples.push((Role::Women, json!({"path": "/t/a.wav", "reference": "/t/r.wav"})));
        assert_eq!(role_audio(&s, Role::Women), Some(PathBuf::from("/t/a.wav")));
    }

    #[test]
    fn the_engines_answer_marks_the_chapters_searched() {
        let mut s = state(3, Role::Men);
        for (i, c) in s.book.draft.as_mut().unwrap().chapters.iter_mut().enumerate() {
            c.text = format!("Chapter {i} text.");
        }
        let n = s.book.draft.as_ref().unwrap().chapters.len();
        s.book.cast.status_req = Some(5);
        s.book.cast.status_for = status_key(&s);
        assert!(!status_known(&s), "not before the answer");
        let answer: Vec<bool> = (0..n).map(|i| i == 1 || i == 2).collect();
        on_response(&mut s, 5, &Ok(json!({ "searched": answer })));
        assert!(status_known(&s));
        let d = s.book.draft.as_ref().unwrap();
        assert!(chapter_searched(&s, &d.chapters[1]) && chapter_searched(&s, &d.chapters[2]));
        assert!(!chapter_searched(&s, &d.chapters[3]));
        let picked = d.chapters.iter().filter(|c| c.include).count();
        let todo = d.chapters.iter().filter(|c| c.include && !chapter_searched(&s, c)).count();
        assert_eq!(
            unsearched_note(&s),
            Some(format!(
                "{todo} of {picked} chapters are not analysed yet: press Find who speaks to analyse only them."
            ))
        );
        s.book.cast_mode = CastMode::Fast;
        s.book.cast_mode = CastMode::Careful;
        assert!(!status_known(&s), "another mode asks the engine again");
        assert_eq!(unsearched_note(&s), None, "nothing is claimed while unknown");
    }

    #[test]
    fn a_book_read_with_several_voices_changes_each() {
        let mut b = BookSummary { voice_id: Some("n".into()), ..Default::default() };
        assert_eq!(book_roles(&b), vec![Role::Narrator]);
        b.voices = Some([("men".to_owned(), Some("m".to_owned())), ("women".to_owned(), None)].into_iter().collect());
        assert_eq!(book_roles(&b), vec![Role::Narrator, Role::Men]);
        assert_eq!(book_role_voice(&b, Role::Men), Some("m"));
    }

    #[test]
    fn chapters_searched_before_bring_their_speakers_back_by_themselves() {
        let mut s = state(3, Role::Men);
        s.shell.components = None;
        let d = s.book.draft.as_ref().unwrap();
        s.book.cast.searched = d.chapters.iter().map(chapter_fingerprint).collect();
        s.book.cast.status_for = status_key(&s);
        assert!(fetch_kept_cast(&s), "book.cast is asked, and answers from what the engine kept");
        s.book.cast.error = Some("busy".into());
        s.book.cast.asked_key = included_key(&s);
        assert!(!fetch_kept_cast(&s), "not again after an error for the same chapters");
        toggle_include(&mut s, 1);
        assert!(drop_stale_cast(&mut s), "the error goes with other chapters picked");
        assert!(fetch_kept_cast(&s));
    }

    #[test]
    fn the_list_shows_one_line_per_book_and_the_draft_of_each() {
        let mut s = state(3, Role::Men);
        let path = s.book.draft.as_ref().unwrap().file.path.clone();
        s.book.recent[0].source = Some(path.to_string_lossy().into_owned());
        s.book.draft.as_mut().unwrap().book_id = Some(s.book.recent[0].id.clone());
        let entries = book_entries(&s);
        assert_eq!(
            entries.iter().filter(|e| e.path.as_ref() == Some(&path)).count(),
            1,
            "the book and its draft are one line"
        );
        assert!(entries.iter().any(|e| e.current));
        s.book.drafts.push((PathBuf::from("/books/other.epub"), "Other".into()));
        assert!(book_entries(&s).iter().any(|e| e.title == "Other" && e.word == "Draft" && !e.current));
        close(&mut s);
        assert!(s.book.draft.is_none());
        assert!(book_entries(&s).iter().any(|e| e.path.as_ref() == Some(&path)), "a closed draft stays in the list");
    }

    #[test]
    fn the_draft_reads_more_chapters_into_its_book() {
        let mut s = AppState::default();
        scene_linked(&mut s);
        let fresh: Vec<usize> = new_chapters(&s).iter().map(|(i, _)| *i).collect();
        assert_eq!(fresh, vec![4, 5, 6, 7, 8], "ticked chapters the book lacks, by their place");
        let d = s.book.draft.as_ref().unwrap();
        assert_eq!(book_row(&s, &d.chapters[1]).map(|(_, r)| r.status.as_str()), Some("done"));
        assert!(book_row(&s, &d.chapters[4]).is_none());
        assert_eq!(read_blocker(&s), None, "a running book shows its own bar");
        s.book.project.as_mut().unwrap().status = "done".into();
        for c in s.book.draft.as_mut().unwrap().chapters.iter_mut() {
            c.include = c.text == "Chapter 1.";
        }
        assert_eq!(read_blocker(&s).as_deref(), Some("The ticked chapters are read: ↻ beside one reads it again."));
    }

    #[test]
    fn a_file_read_before_goes_on_in_its_book() {
        let mut s = state(1, Role::Men);
        let path = s.book.draft.as_ref().unwrap().file.path.to_str().unwrap().to_owned();
        s.book.recent[0].source = Some(path);
        let id = s.book.recent[0].id.clone();
        assert_eq!(same_file_book(&s), Some(id.clone()));
        s.book.draft.as_mut().unwrap().book_id = Some(id);
        assert_eq!(same_file_book(&s), None);
        let before = s.book.draft.as_ref().unwrap().chapters.len();
        remove_chapter(&mut s, 0);
        assert_eq!(s.book.draft.as_ref().unwrap().chapters.len(), before - 1);
        close(&mut s);
        assert!(s.book.draft.is_none());
    }

    #[test]
    fn picking_a_voice_drops_the_roles_sample() {
        let mut s = state(3, Role::Men);
        s.book.cast.samples.push((Role::Women, json!({"path": "/t/a.wav", "reference": "/t/r.wav"})));
        set_role_voice(&mut s, Role::Women, "pro");
        assert!(sample(&s, Role::Women).is_none());
        assert_eq!(s.book.cast.women.as_deref(), Some("pro"));
    }

    #[test]
    fn the_book_keeps_its_language_and_narrator() {
        let mut s = state(3, Role::Men);
        let first = s.shell.voices[0].id.clone();
        s.shell.active_voice = None;
        s.book.draft.as_mut().unwrap().file.language = "uk".into();
        assert_eq!(book_language(&s), "uk");
        s.shell.languages = ["en", "uk"]
            .iter()
            .map(|c| crate::engine::protocol::SpeechLanguage {
                code: (*c).into(),
                name: String::new(),
                native: String::new(),
                common: true,
            })
            .collect();
        let active = s.shell.active_voice.clone();
        set_role_voice(&mut s, Role::Narrator, &first);
        assert_eq!(s.shell.active_voice, active, "the book's narrator leaves the voice at the top alone");
        assert_eq!(role_voice(&s, Role::Narrator).map(|v| v.id.as_str()), Some(first.as_str()));
        assert_eq!(book_language(&s), "uk");
    }

    #[test]
    fn one_box_selects_or_clears_every_chapter() {
        let mut s = state(1, Role::Men);
        toggle_all(&mut s);
        assert!(s.book.draft.as_ref().unwrap().chapters.iter().all(|c| c.include));
        toggle_all(&mut s);
        assert!(s.book.draft.as_ref().unwrap().chapters.iter().all(|c| !c.include));
    }

    #[test]
    fn one_voice_reads_as_before() {
        let mut s = state(1, Role::Men);
        s.shell.components = Some(Vec::new());
        assert_eq!(start_blocker(&s), None);
        assert_eq!((cast_voice(&s, Role::Men), cast_voice(&s, Role::Women)), (None, None));
    }

    #[test]
    fn character_voices_need_the_component() {
        let mut s = state(3, Role::Men);
        s.shell.components = Some(vec!["speech".into()]);
        assert_eq!(start_blocker(&s).as_deref(), Some("Install Character voices first."));
    }

    #[test]
    fn two_voices_need_the_speakers_and_the_second_voice() {
        let mut s = state(2, Role::Women);
        assert_eq!(start_blocker(&s).as_deref(), Some("Find who speaks first."));
        take_found(&mut s);
        assert_eq!(start_blocker(&s).as_deref(), Some("Pick a voice for the women's lines."));
        s.book.cast.men = Some("pro".into());
        assert_eq!(start_blocker(&s).as_deref(), Some("Pick a voice for the women's lines."));
        s.book.cast.women = Some("pro".into());
        assert_eq!(start_blocker(&s), None);
        assert_eq!((cast_voice(&s, Role::Men), cast_voice(&s, Role::Women)), (None, Some("pro")));
    }

    #[test]
    fn three_voices_need_both_voices_and_no_running_search() {
        let mut s = state(3, Role::Women);
        take_found(&mut s);
        s.book.cast.women = Some("pro".into());
        assert_eq!(start_blocker(&s).as_deref(), Some("Pick a voice for the men's lines."));
        s.book.cast.men = Some("deleted".into());
        assert_eq!(start_blocker(&s).as_deref(), Some("Pick a voice for the men's lines."));
        s.book.cast.men = Some("me".into());
        assert_eq!(start_blocker(&s), None);
        s.book.cast.job = Some("k".into());
        assert_eq!(start_blocker(&s).as_deref(), Some("Wait for finding who speaks to finish, or cancel it."));
    }

    #[test]
    fn the_summary_names_the_main_characters() {
        assert_eq!(
            cast_caption(&found()),
            "Men: 1,402 lines · Women: 268 lines · Narrator: 40 · Martin Eden, Ruth, Arthur, …"
        );
        let few = BookCast { characters: found().characters[..1].to_vec(), lines: None, ..Default::default() };
        assert_eq!(cast_caption(&few), "Men: 0 lines · Women: 0 lines · Narrator: 0 · Ruth");
    }

    #[test]
    fn a_result_goes_stale_with_other_chapters_or_mode_but_not_language() {
        let mut s = state(2, Role::Men);
        take_found(&mut s);
        assert!(!drop_stale_cast(&mut s));
        toggle_include(&mut s, 0);
        assert!(!drop_stale_cast(&mut s), "a part of the chapters found needs no new search");
        toggle_include(&mut s, 0);
        assert!(!drop_stale_cast(&mut s), "nor does picking a chapter again");
        s.book.draft.as_mut().unwrap().chapters[1].text.push_str(" More.");
        assert!(!drop_stale_cast(&mut s), "a chapter not searched yet keeps what was found");
        let d = s.book.draft.as_ref().unwrap();
        let unread = chapter_fingerprint(&d.chapters[1]);
        let picked = d.chapters.iter().filter(|c| c.include).count();
        s.book.cast.searched = d.chapters.iter().map(chapter_fingerprint).filter(|f| *f != unread).collect();
        s.book.cast.status_for = status_key(&s);
        assert_eq!(
            start_blocker(&s),
            Some(format!("1 of {picked} chapters are not analysed yet: press Find who speaks to analyse only them."))
        );
        assert_eq!(generate_blocker(&s), start_blocker(&s));
        let text = &mut s.book.draft.as_mut().unwrap().chapters[1].text;
        text.truncate(text.len() - 6);

        take_found(&mut s);
        s.book.cast_mode = CastMode::Careful;
        assert!(drop_stale_cast(&mut s));

        take_found(&mut s);
        crate::ui::speak::set_language(&mut s, "de");
        assert!(!drop_stale_cast(&mut s), "the language settles only after the voices load");

        take_found(&mut s);
        s.book.cast.error = Some("busy".into());
        s.book.cast.job = Some("k".into());
        s.book.cast_mode = CastMode::Fast;
        assert!(!drop_stale_cast(&mut s), "a search still running keeps what it shows");
    }

    #[test]
    fn a_picked_gender_replaces_gemmas() {
        assert_eq!(
            with_gender("female, elderly, low pitch, american accent", Some("male")),
            "male, elderly, low pitch, american accent"
        );
        assert_eq!(with_gender("male, young adult", None), "male, young adult");
        assert_eq!(with_gender("young adult, moderate pitch", Some("female")), "female, young adult, moderate pitch");
    }

    #[test]
    fn opening_a_book_leaves_the_language_of_the_draft_it_leaves() {
        let mut s = AppState::default();
        s.book.shown = true;
        let mut uk = scene_file();
        uk.path = std::env::temp_dir().join("mimvox-test-uk.epub");
        uk.language = "uk".into();
        s.book.draft =
            Some(Draft { file: uk.clone(), chapters: vec![], auto: None, before_split: None, book_id: None });
        s.shell.languages = ["en", "uk", "de"]
            .iter()
            .map(|c| crate::engine::protocol::SpeechLanguage {
                code: (*c).into(),
                name: String::new(),
                native: String::new(),
                common: true,
            })
            .collect();
        let mut en = scene_file();
        en.path = std::env::temp_dir().join("mimvox-test-de.epub");
        en.language = "de".into();
        en.words = LONG_WORDS + 1;
        let left = std::sync::Arc::new(std::sync::Mutex::new(None));
        STASHED.with(|k| *k.borrow_mut() = Some(left.clone()));
        opened(&mut s, en, Purpose::Book);
        STASHED.with(|k| *k.borrow_mut() = None);
        assert_eq!(left.lock().unwrap().as_deref(), Some("uk"), "the draft left keeps its language");
        assert_eq!(book_language(&s), "de");
    }
}