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.

50.6 KB
Raw Blame
//! Screens never poll: background work reports through `events::post`, and `settle` reads only `AppState`.

use super::components::{
    Button, Tone, accent_glass, badge, glass_card, glass_edge, icon_button, icon_el, icons, status_dot, toast_stack,
};
use super::theme::{self, Palette, motion, radius, ty};
use crate::audio::Player;
use crate::engine::protocol::PausedTraining;
use crate::engine::{EngineClient, EngineConfig, EngineMsg};
use crate::state::{AppState, Screen};
use rune::{Align, ChromeInsets, Color, Cx, El, Side, Tx, col, el, row, text};
use serde_json::{Value, json};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::PathBuf;
use std::time::{Duration, Instant};

pub use super::components::Toast;

#[derive(Clone, Debug, Default, PartialEq)]
pub enum EngineStatus {
    #[default]
    Idle,
    Starting {
        since: f64,
    },
    Ready {
        device: Option<String>,
        tts: Option<String>,
        rvc: Option<String>,
    },
    Stopped {
        code: Option<i32>,
        detail: String,
    },
    Unavailable {
        reason: String,
    },
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct VoiceInfo {
    pub id: String,
    pub name: String,
    pub preset: Option<String>,
    pub dataset_minutes: f32,
    pub parts: u32,
    pub trained: bool,
    pub trained_epochs: u32,
    pub paused: Option<PausedTraining>,
    pub language: String,
    /// Languages with their own `reference_<lang>.wav`.
    pub references: Vec<String>,
    /// Detected by the engine; `None` until the speech worker has transcribed the clip.
    pub reference_language: Option<String>,
    /// Made by Book for this book and role ("men", "women", "narrator").
    pub book: Option<String>,
    pub book_role: Option<String>,
}

impl VoiceInfo {
    pub fn lang(&self) -> &str {
        if self.language.is_empty() { "en" } else { &self.language }
    }

    pub fn reference_lang(&self) -> &str {
        self.reference_language.as_deref().filter(|l| !l.is_empty()).unwrap_or(self.lang())
    }

    pub fn reference_mismatch(&self) -> bool {
        self.reference_language
            .as_deref()
            .is_some_and(|l| !l.is_empty() && super::lang::base(l) != super::lang::base(self.lang()))
    }

    /// Its own `reference_<code>.wav`, or `reference.wav` when that clip is (or is assumed to be) in `code`.
    pub fn has_reference_in(&self, code: &str) -> bool {
        let code = super::lang::base(code);
        self.references.iter().any(|r| super::lang::base(r) == code) || super::lang::base(self.reference_lang()) == code
    }

    pub fn from_json(v: &Value) -> Option<VoiceInfo> {
        Some(VoiceInfo {
            id: v.get("id")?.as_str()?.to_owned(),
            name: v.get("name").and_then(Value::as_str).unwrap_or("Untitled").to_owned(),
            preset: v.get("preset").and_then(Value::as_str).map(str::to_owned),
            dataset_minutes: v.get("dataset_minutes").and_then(Value::as_f64).unwrap_or(0.0) as f32,
            parts: v.get("parts").and_then(Value::as_u64).unwrap_or(0) as u32,
            trained: v.get("trained").and_then(Value::as_bool).unwrap_or(false),
            trained_epochs: v.get("trained_epochs").and_then(Value::as_u64).unwrap_or(0) as u32,
            paused: v
                .get("training_paused")
                .filter(|p| p.is_object())
                .and_then(|p| serde_json::from_value(p.clone()).ok()),
            language: v.get("language").and_then(Value::as_str).filter(|l| !l.is_empty()).unwrap_or("en").to_owned(),
            references: v
                .get("references")
                .and_then(Value::as_array)
                .map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect())
                .unwrap_or_default(),
            reference_language: v
                .get("reference_language")
                .and_then(Value::as_str)
                .filter(|l| !l.is_empty())
                .map(str::to_owned),
            book: v.get("book").and_then(Value::as_str).filter(|b| !b.is_empty()).map(str::to_owned),
            book_role: v.get("book_role").and_then(Value::as_str).map(str::to_owned),
        })
    }
}

pub struct ShellState {
    /// App clock at the last event; outside an event (a press handler) use [`clock_now`].
    pub now: f64,
    /// Wall-clock instant of app clock 0; headless runs keep a virtual clock.
    epoch: Option<Instant>,
    clock_due: Option<f64>,
    pub engine: EngineStatus,
    pub gpu: bool,
    pub voices: Vec<VoiceInfo>,
    pub languages: Vec<crate::engine::protocol::SpeechLanguage>,
    pub speech_models: Vec<crate::engine::protocol::SpeechModel>,
    pub translators: Vec<String>,
    pub zero_shot_vc: bool,
    /// `None` until the engine says.
    pub components: Option<Vec<String>>,
    pub components_off: Vec<String>,
    /// Why speech cannot run while `tts` is `no_memory`.
    pub tts_message: Option<String>,
    pub active_voice: Option<String>,
    pub voice_menu_open: bool,
    /// Headless previews only (`caption::scenes`); `None` in the real app.
    pub caption_preview: Option<rune::CaptionView>,
    pub icon: Option<rune::Image>,
    icon_cache: Option<rune::ImageCache>,
    pub toasts: Vec<Toast>,
    pub audio_error: Option<String>,
    pub data_dir: PathBuf,
    pub preparing: Option<String>,
    /// So a voice is warmed once per engine start.
    warm_for: Option<String>,
    warm_req: Option<u64>,
    next_toast: u64,
    scripted: bool,
    voices_req: Option<u64>,
    first_voice_list: bool,
}

impl ShellState {
    pub fn dismiss_toast(&mut self, id: u64) {
        self.toasts.retain(|t| t.id != id);
    }
    pub fn scripted(&self) -> bool {
        self.scripted
    }
    /// Test/scene helper: pretend the engine is in this state.
    pub fn set_engine(&mut self, status: EngineStatus) {
        self.engine = status;
    }
    pub fn preparing_voice(&self) -> bool {
        self.preparing.is_some() && self.preparing == self.active_voice
    }
}

pub fn image_cache(s: &AppState) -> Option<&rune::ImageCache> {
    s.shell.icon_cache.as_ref()
}

/// Decodes before the first frame so the mark never pops in; Rune keeps mip levels, so 512 px stays crisp.
pub fn setup_icon(s: &mut AppState, waker: rune::Waker) {
    let cache = rune::ImageCache::new(waker);
    let icon = cache.load(crate::ICON_PNG);
    let _ = icon.wait();
    s.shell.icon = Some(icon);
    s.shell.icon_cache = Some(cache);
}

pub fn brand_mark(s: &AppState, size: f32) -> El {
    let mark = el().key("brand-mark").size(size, size).a11y_hidden();
    match &s.shell.icon {
        Some(icon) => mark.pixels(icon.pixels()),
        None => mark,
    }
}

/// Headless runs must not start processes or open audio; `--realtime` runs for real (demo recordings).
pub fn headless_run() -> bool {
    let mut args = std::env::args();
    let headless =
        args.any(|a| matches!(a.as_str(), "--snap" | "--tree" | "--script" | "--list-scenes" | "--trace" | "--video"));
    headless && !std::env::args().any(|a| a == "--realtime")
}

impl Default for ShellState {
    fn default() -> Self {
        ShellState {
            now: 0.0,
            epoch: None,
            clock_due: None,
            engine: EngineStatus::Idle,
            voices: Vec::new(),
            languages: Vec::new(),
            translators: Vec::new(),
            speech_models: Vec::new(),
            zero_shot_vc: false,
            components: None,
            components_off: Vec::new(),
            tts_message: None,
            active_voice: None,
            voice_menu_open: false,
            caption_preview: None,
            icon: None,
            icon_cache: None,
            toasts: Vec::new(),
            audio_error: None,
            data_dir: if cfg!(test) {
                super::onboarding::data_dir()
            } else {
                crate::engine::default_data_dir().unwrap_or_else(std::env::temp_dir)
            },
            preparing: None,
            warm_for: None,
            warm_req: None,
            next_toast: 0,
            // Tests never write the user's files (the book draft, settings).
            scripted: headless_run() || cfg!(test),
            voices_req: None,
            first_voice_list: true,
            gpu: false,
        }
    }
}

/// For start times stamped in press handlers, which get no `Tx`.
pub fn clock_now(s: &AppState) -> f64 {
    match s.shell.epoch {
        Some(e) => e.elapsed().as_secs_f64().max(s.shell.now),
        None => s.shell.now,
    }
}

pub fn toast(s: &mut AppState, tone: Tone, text: impl Into<String>) {
    let now = clock_now(s);
    let sh = &mut s.shell;
    sh.next_toast += 1;
    let text = text.into();
    let base = if tone == Tone::Danger { 7.0 } else { 4.0 };
    let life = (base + text.chars().count() as f64 / 15.0).min(14.0);
    sh.toasts.push(Toast { id: sh.next_toast, tone, text, expires: now + life });
    if sh.toasts.len() > 3 {
        sh.toasts.remove(0);
    }
}

pub fn engine_ready(s: &AppState) -> bool {
    s.engine.is_some() && matches!(s.shell.engine, EngineStatus::Ready { .. })
}

/// Turns a panic (an unimplemented backend) into an error string.
pub fn guard<T>(f: impl FnOnce() -> T) -> Result<T, String> {
    catch_unwind(AssertUnwindSafe(f)).map_err(|p| {
        p.downcast_ref::<&str>()
            .map(|m| (*m).to_owned())
            .or_else(|| p.downcast_ref::<String>().cloned())
            .unwrap_or_else(|| "internal error".into())
    })
}

/// The answer comes to `on_engine` as `EngineMsg::Response`.
pub fn request(s: &mut AppState, method: &str, params: Value) -> Option<u64> {
    let client = s.engine.as_ref()?;
    match guard(|| client.request(method, params)) {
        Ok(id) => Some(id),
        Err(_) => {
            s.engine = None;
            s.shell.engine = EngineStatus::Stopped { code: None, detail: "The engine connection failed.".into() };
            None
        }
    }
}

pub fn voices_loading(s: &AppState) -> bool {
    s.shell.voices_req.is_some()
}

pub fn refresh_voices(s: &mut AppState) {
    s.shell.voices_req = request(s, "voices.list", json!({}));
}

pub fn active_voice(s: &AppState) -> Option<&VoiceInfo> {
    let id = s.shell.active_voice.as_deref()?;
    s.shell.voices.iter().find(|v| v.id == id)
}

pub fn set_screen(s: &mut AppState, screen: Screen) {
    s.screen = if screen != Screen::Onboarding && !s.shell.scripted && super::onboarding::needed(s) {
        Screen::Onboarding
    } else {
        screen
    };
    s.shell.voice_menu_open = false;
}

pub fn stop_audio(s: &mut AppState) {
    super::playbar::stop(s);
}

pub fn audio_unavailable(s: &AppState) -> String {
    s.shell.audio_error.clone().unwrap_or_else(|| "No audio output is available.".into())
}

pub const NOT_INSTALLED: &str = "The speech engine is not installed yet.";

pub fn restart_engine(s: &mut AppState) {
    if let Some(old) = super::api::detach(s) {
        let _ = guard(|| old.shutdown());
    }
    if !super::onboarding::runtime_toml_path().is_file() {
        s.shell.engine = EngineStatus::Unavailable { reason: NOT_INSTALLED.into() };
        return;
    }
    s.shell.engine = EngineStatus::Starting { since: clock_now(s) };
    let cfg = match guard(EngineConfig::discover) {
        Ok(Ok(cfg)) => cfg,
        Ok(Err(e)) => {
            s.shell.engine = EngineStatus::Unavailable { reason: format!("{e:#}") };
            return;
        }
        Err(_) => {
            s.shell.engine = EngineStatus::Unavailable { reason: "This build has no engine client yet.".into() };
            return;
        }
    };
    s.shell.data_dir = cfg.data_dir.clone();
    s.record.data_dir = cfg.data_dir.clone();
    let sink = super::api::engine_sink(s);
    match guard(|| EngineClient::spawn(&cfg, sink)) {
        Ok(Ok(c)) => super::api::attach(s, c),
        Ok(Err(e)) => s.shell.engine = EngineStatus::Stopped { code: None, detail: format!("{e:#}") },
        Err(_) => s.shell.engine = EngineStatus::Unavailable { reason: "This build has no engine client yet.".into() },
    }
}

/// After sleep or a device change the old stream stays open but never asks for sound: reopen the default device.
pub fn restart_audio(s: &mut AppState) {
    s.player = None;
    s.shell.audio_error = None;
    start_audio(s);
}

fn start_audio(s: &mut AppState) {
    if s.player.is_some() {
        return;
    }
    match guard(|| Player::new(Some(super::playbar::sink()))) {
        Ok(Ok(p)) => s.player = Some(p),
        Ok(Err(e)) => s.shell.audio_error = Some(format!("No audio output: {e}")),
        Err(_) => s.shell.audio_error = Some("Audio is not available in this build.".into()),
    }
}

/// Start the engine this long after launch, so the first frames stay still.
const ENGINE_START_DELAY: f64 = 0.25;

static CENTER_ON_OPEN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

pub fn center_on_open() {
    CENTER_ON_OPEN.store(true, std::sync::atomic::Ordering::Relaxed);
}

/// Rune runs this only for input, an animation, an event or a due timer (armed by [`settle`]);
/// an idle window never runs it.
pub fn on_frame(s: &mut AppState, clock: f64, tx: &mut Tx) -> bool {
    super::stats::count(&super::stats::HOOKS);
    if CENTER_ON_OPEN.swap(false, std::sync::atomic::Ordering::Relaxed) {
        tx.center_window();
    }
    if let Some(t) = super::stats::quit_at() {
        if clock >= t {
            super::stats::write();
            tx.quit();
            return false;
        }
        tx.wake_at(t);
    }
    if s.shell.epoch.is_none() && !s.shell.scripted {
        s.shell.epoch = Instant::now().checked_sub(Duration::from_secs_f64(clock.max(0.0)));
    }
    settle(s, tx)
}

/// True when what the window shows changed.
pub fn settle(s: &mut AppState, tx: &mut Tx) -> bool {
    let now = tx.clock().max(s.shell.now);
    s.shell.now = now;
    let mut changed = false;

    if !s.shell.scripted && matches!(s.shell.engine, EngineStatus::Idle) {
        if now < ENGINE_START_DELAY {
            tx.wake_at(ENGINE_START_DELAY);
        } else {
            start_audio(s);
            if s.onboarding.runtime_present {
                restart_engine(s);
            } else {
                s.shell.engine = EngineStatus::Unavailable { reason: NOT_INSTALLED.into() };
            }
            changed = true;
        }
    }

    changed |= super::onboarding::settle(s);
    changed |= super::voices::settle(s);
    changed |= super::record::settle(s);
    changed |= super::train::settle(s);
    changed |= super::speak::settle(s);
    changed |= super::design::settle(s);
    changed |= super::book::settle(s);
    changed |= super::redub::settle(s);
    changed |= super::history::settle(s);
    changed |= super::formats::settle(s);
    if super::train::take_quit(s, tx) {
        return true;
    }
    changed |= ensure_warm(s);
    changed |= super::playbar::settle(s, tx);
    changed |= super::update::settle(s, tx);
    changed |= super::api::settle(s);
    changed |= super::settings::settle(s);

    let before = s.shell.toasts.len();
    s.shell.toasts.retain(|t| t.expires > now);
    changed |= s.shell.toasts.len() != before;
    if let Some(next) = s.shell.toasts.iter().map(|t| t.expires).reduce(f64::min) {
        tx.wake_at(next);
    }

    if s.shell.clock_due.is_some_and(|due| due <= now + 1e-3) {
        super::stats::count(&super::stats::TIMERS);
        s.shell.clock_due = None;
        changed = true;
    }
    match clock_origin(s) {
        Some(origin) => {
            // `fmt_time` rounds, so the shown second changes at k + 0.5 s.
            let k = (now - origin - 0.5).floor() + 1.0;
            let due = origin + k.max(0.0) + 0.5;
            s.shell.clock_due = Some(due);
            tx.wake_at(due);
        }
        None => s.shell.clock_due = None,
    }

    if let Some(due) = super::onboarding::next_due(s) {
        tx.wake_at(due);
    }
    changed
}

fn clock_origin(s: &AppState) -> Option<f64> {
    match s.screen {
        Screen::Speak => super::speak::clock_origin(s),
        Screen::Redub => super::redub::clock_origin(s),
        Screen::Train => super::train::clock_origin(s),
        _ => None,
    }
}

pub fn on_engine_msg(s: &mut AppState, client: u64, m: EngineMsg) {
    if s.engine.as_ref().map(|e| e.id()) != Some(client) {
        return;
    }
    on_engine(s, &m);
    super::onboarding::on_engine(s, &m);
    super::voices::on_engine(s, &m);
    super::voiceimport::on_engine(s, &m);
    super::design::on_engine(s, &m);
    super::record::on_engine(s, &m);
    super::train::on_engine(s, &m);
    super::speak::on_engine(s, &m);
    super::book::on_engine(s, &m);
    super::modules::on_engine(s, &m);
    super::redub::on_engine(s, &m);
    super::formats::on_engine(s, &m);
    super::trash::on_engine(s, &m);
    super::history::on_engine(s, &m);
}

pub fn on_engine(s: &mut AppState, msg: &EngineMsg) {
    match msg {
        EngineMsg::Ready(hello) => {
            let device = (!hello.device.name.is_empty()).then(|| hello.device.name.clone());
            s.shell.gpu = hello.device.backend.eq_ignore_ascii_case("cuda");
            s.shell.engine = EngineStatus::Ready {
                device,
                tts: Some(hello.models.tts.as_str().to_owned()),
                rvc: Some(hello.models.rvc.as_str().to_owned()),
            };
            s.shell.tts_message = hello.models.tts_message.clone();
            if !hello.languages.is_empty() {
                s.shell.languages = hello.languages.clone();
            }
            s.shell.translators = hello.translators.clone();
            s.shell.speech_models = hello.speech_models.clone();
            s.shell.zero_shot_vc = hello.zero_shot_vc;
            s.shell.components = Some(hello.components.clone());
            s.shell.components_off = hello.components_off.clone();
            s.redub.can_separate = hello.components.iter().any(|c| c == "music_removal");
            reset_warm(s);
            refresh_voices(s);
        }
        EngineMsg::Response { id, result } if s.shell.voices_req == Some(*id) => {
            s.shell.voices_req = None;
            if let Ok(v) = result {
                let list: Vec<VoiceInfo> = v
                    .get("voices")
                    .and_then(Value::as_array)
                    .map(|a| a.iter().filter_map(VoiceInfo::from_json).collect())
                    .unwrap_or_default();
                apply_voice_list(s, list);
            }
        }
        // Model status changes after `ready` (load finished, GPU handed over to training and back).
        EngineMsg::Event(ev) if ev.event == "models" => {
            let get = |k: &str| ev.data.get(k).and_then(Value::as_str).map(str::to_owned);
            let (new_tts, new_rvc) = (get("tts"), get("rvc"));
            if new_tts.is_some() {
                s.shell.tts_message = get("tts_message");
            }
            if let EngineStatus::Ready { tts, rvc, .. } = &mut s.shell.engine {
                let was_ready = tts.as_deref() == Some("ready") && rvc.as_deref() == Some("ready");
                if new_tts.is_some() {
                    *tts = new_tts;
                }
                if new_rvc.is_some() {
                    *rvc = new_rvc;
                }
                let now_ready = tts.as_deref() == Some("ready") && rvc.as_deref() == Some("ready");
                if now_ready && !was_ready {
                    // Fresh models lost any warm state: warm the active voice again.
                    reset_warm(s);
                }
            }
        }
        EngineMsg::Response { id, result } if s.shell.warm_req == Some(*id) => {
            s.shell.warm_req = None;
            let warming = result.as_ref().ok().and_then(|v| v.get("warming")).and_then(Value::as_bool).unwrap_or(false);
            if !warming {
                s.shell.preparing = None;
            }
        }
        EngineMsg::Event(ev) if ev.event == "voice.warm" => {
            let id = ev.data.get("id").and_then(Value::as_str);
            if id.is_some() && id == s.shell.preparing.as_deref() {
                s.shell.preparing = None;
            }
            if let (Some(id), Some(l)) = (id, ev.data.get("reference_language")) {
                set_reference_language(s, id, l);
            }
        }
        EngineMsg::Event(ev) if ev.event == "train.done" => reset_warm(s),
        EngineMsg::Exited { code, stderr_tail } => {
            s.engine = None;
            reset_warm(s);
            let tail: Vec<&str> = stderr_tail.lines().rev().take(3).collect();
            let detail = tail.into_iter().rev().collect::<Vec<_>>().join("\n");
            s.shell.engine = EngineStatus::Stopped { code: *code, detail };
            toast(s, Tone::Danger, "The voice engine stopped");
        }
        _ => {}
    }
}

pub fn set_reference_language(s: &mut AppState, voice_id: &str, value: &Value) {
    let lang = value.as_str().filter(|l| !l.is_empty()).map(str::to_owned);
    if let Some(v) = s.shell.voices.iter_mut().find(|v| v.id == voice_id) {
        v.reference_language = lang;
    }
}

fn reset_warm(s: &mut AppState) {
    s.shell.warm_for = None;
    s.shell.warm_req = None;
    s.shell.preparing = None;
}

/// Once per engine start, whenever a voice becomes active. True when the "Preparing voice" state appeared.
fn ensure_warm(s: &mut AppState) -> bool {
    if !engine_ready(s) {
        return false;
    }
    let Some(id) = s.shell.active_voice.clone() else { return false };
    if s.shell.warm_for.as_deref() == Some(id.as_str()) {
        return false;
    }
    s.shell.warm_for = Some(id.clone());
    // A voice whose clip is in another language than English also gets the native-accent clip ready (and, untrained,
    // the zero-shot converter).
    let mut params = json!({ "id": id });
    if let Some(v) = super::speak::warm_accent(s) {
        params["accent"] = json!("native-us");
        params["native_voice"] = json!(v.as_str());
    }
    s.shell.warm_req = request(s, "voices.warm", params);
    if s.shell.warm_req.is_some() {
        s.shell.preparing = Some(id);
        return true;
    }
    false
}

fn apply_voice_list(s: &mut AppState, list: Vec<VoiceInfo>) {
    let keep = s.shell.active_voice.as_ref().filter(|id| list.iter().any(|v| &v.id == *id)).cloned();
    s.shell.active_voice = keep.or_else(|| list.iter().find(|v| v.trained).or(list.first()).map(|v| v.id.clone()));
    let first = std::mem::replace(&mut s.shell.first_voice_list, false);
    s.shell.voices = list;
    if first && s.screen == Screen::Onboarding && !s.shell.voices.is_empty() && !super::onboarding::needed(s) {
        s.screen = Screen::Speak;
    }
}

pub fn view(s: &AppState, cx: &mut Cx<AppState>) -> El {
    let p = theme::palette(s, cx);
    // Room for the window controls: macOS traffic lights (leading), the caption buttons (trailing).
    let mut insets = cx.chrome_insets();
    if let Some(preview) = s.shell.caption_preview {
        insets.trailing = 3.0 * super::caption::CELL;
        insets.caption = preview;
    }
    let header_w = cx.layout_with("header", |r| r[2]).unwrap_or(1300.0);
    let side = |key: &str| cx.layout_with(key, |r| r[2]).unwrap_or(0.0);
    let trailing = if insets.trailing > 0.0 { insets.trailing + 14.0 } else { 12.0 };
    let left = 16.0 + insets.leading + side("brand");
    let (was_tight, mut right_full) = HEADER_FIT.get();
    let right_now = side("right");
    if !was_tight || right_full == 0.0 {
        right_full = right_now;
    }
    let paused = super::train::status_line(s).is_some_and(|l| l.starts_with("Paused"));
    let tabs = STEPS.len() as f32;
    let tabs_full = tabs * if paused { 132.0 } else { 100.0 } + 8.0;
    let tabs_icons = tabs * 52.0 + 8.0;
    let fixed = left + trailing + 6.0 * 14.0 + 8.0;
    let compact = header_w < fixed + right_full + tabs_full;
    let tight = header_w < fixed + right_full + tabs_icons;
    HEADER_FIT.set((tight, right_full));
    let right = trailing + right_now;
    let tabs_now = if compact { tabs_icons } else { tabs_full };
    let free = (header_w - left - trailing - 6.0 * 14.0 - tabs_now - right_now).max(0.0);
    let balance = (right - left).clamp(-free, free);
    let fit = HeaderFit { compact, tight, balance };
    let page = body_page(s, cx);
    let mut body = col().key("body").w_full().grow(1.0).min_h(0.0).pt(14.0).gap(12.0);
    if let Some(b) = super::update::banner(s, p) {
        body = body.child(b);
    }
    if let Some(b) = super::onboarding::runtime_banner(s, p) {
        body = body.child(b);
    }
    if let Some(b) = engine_banner(s, p) {
        body = body.child(b);
    }
    let fade = rune::Transition::opacity().springs(rune::SpringPair::new(motion::SCREEN, motion::SCREEN_EXIT));
    body = body.child(
        col()
            .key(format!("screen-{:?}", s.screen))
            .w_full()
            .grow(1.0)
            .min_h(0.0)
            .transition(fade)
            .child(page.transition(fade)),
    );
    // Header, background and glass panels are cached textures (`El::cache`): uncached, hovering across the window
    // on a 165 Hz display drew whole frames at 36 W on the GPU against 12 W idle.
    let mut overlays: Vec<El> = Vec::new();
    if s.shell.voice_menu_open && s.screen != Screen::Onboarding {
        overlays.push(voice_menu(s, p));
    }
    overlays.extend(super::update::overlay(s, &p));
    overlays.extend(super::settings::overlay(s, &p));
    overlays.extend(super::relocate::overlay(s, &p));
    overlays.extend(super::record::over_dialog(s, &p));
    overlays.extend(super::train::close_overlay(s, &p));
    overlays.extend(super::formats::overlay(s, p));
    overlays.extend(super::book::voice_overlay(s, p));
    overlays.extend(super::formats::output_overlay(s, p));
    overlays.extend(super::speak::model_overlay(s, p));
    overlays.extend(super::redub::fold_overlay(s, p));
    overlays.extend(super::refclip::more_overlay(s, &p));
    overlays.extend(super::voiceimport::overlay(s, &p));
    overlays.extend(super::lang::overlay(s, &p)); // after the panels: a language chip inside one opens above it
    overlays.extend(super::record::files_overlay(s, &p));
    let dock =
        super::playbar::view(s, p, cx.layout_with(super::playbar::RAIL, |r| r), cx.env().scale, !overlays.is_empty());
    let toasts_at = if dock.is_some() { super::playbar::DOCK_H + 14.0 } else { 26.0 };
    let mut root = el().key("root").w_full().h_full().fill(p.bg_top).child(background(p)).child(
        col().key("chrome").w_full().h_full().child(header(s, p, insets, fit).cache()).child(body).children(dock),
    );
    let rounded = cfg!(target_os = "linux")
        && s.shell.caption_preview.is_none()
        && insets.trailing > 0.0
        && !insets.caption.maximized;
    if rounded {
        root = root.radius(WINDOW_RADIUS).clip_rounded(WINDOW_RADIUS);
    }
    for overlay in overlays {
        root = root.child(overlay);
    }
    for layer in super::playbar::overlay(s, p, cx.layout_with("root", |r| [r[2], r[3]])) {
        root = root.child(layer);
    }
    let root = super::formats::window_drops(root, s).child(toast_stack(p, &s.shell.toasts, toasts_at));
    if rounded {
        root.child(
            el().key("window-rim")
                .pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
                .radius(WINDOW_RADIUS)
                .border(1.0, Color::WHITE.alpha(0.08))
                .inert(),
        )
    } else {
        root
    }
}

const WINDOW_RADIUS: f32 = 12.0;

fn body_page(s: &AppState, cx: &mut Cx<AppState>) -> El {
    match s.screen {
        Screen::Onboarding => super::onboarding::view(s, cx),
        Screen::Voices => super::voices::view(s, cx),
        Screen::Record => super::record::view(s, cx),
        Screen::Train => super::train::view(s, cx),
        Screen::Speak => super::speak::view(s, cx),
        Screen::Redub => super::redub::view(s, cx),
        Screen::Design => super::design::view(s, cx),
    }
}

/// Static on purpose: animating the fields redrew the whole window, blur included, and kept the CPU busy idle.
fn background(p: Palette) -> El {
    const fn field(_period: f32, phase: f32) -> f32 {
        0.55 + 0.35 * phase
    }
    let a = 0.3;
    let blob = |key: &'static str, c: Color, w: f32, h: f32, strength: f32| {
        let a = a * strength;
        el().key(key).size(w, h).inert().radial_gradient(
            [0.5, 0.5],
            [w / 2.0, h / 2.0],
            [(0.0, c.alpha(a)), (0.4, c.alpha(a * 0.5)), (0.75, c.alpha(a * 0.12)), (1.0, c.alpha(0.0))],
        )
    };
    el().key("bg")
        .pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
        .inert()
        .cache()
        .gradient(p.bg_top, p.bg_bottom)
        .child(blob("field-ice", p.aurora[0], 880.0, 620.0, field(29.0, 0.0)).pin(
            Some(-260.0),
            Some(-300.0),
            None,
            None,
        ))
        .child(blob("field-teal", p.aurora[1], 720.0, 560.0, field(37.0, 0.3)).pin(
            None,
            Some(-120.0),
            Some(-240.0),
            None,
        ))
        .child(blob("field-steel", p.aurora[2], 820.0, 600.0, field(33.0, 0.6)).pin(
            Some(-80.0),
            None,
            None,
            Some(-340.0),
        ))
        .child(blob("field-blue", p.aurora[3], 700.0, 520.0, field(41.0, 0.15)).pin(
            None,
            None,
            Some(-60.0),
            Some(-300.0),
        ))
        .child(blob("field-mid", p.aurora[0], 560.0, 420.0, field(47.0, 0.8)).pin(Some(300.0), Some(160.0), None, None))
}

thread_local! {
    static HEADER_FIT: std::cell::Cell<(bool, f32)> = const { std::cell::Cell::new((false, 0.0)) };
}

/// Also the window's title bar height (`main.rs` passes it to `Titlebar::new`).
pub const HEADER_HEIGHT: f32 = 56.0;

#[derive(Clone, Copy)]
struct HeaderFit {
    /// Tabs show icons only.
    compact: bool,
    /// The engine status shows only its dot.
    tight: bool,
    /// Right minus left side width: positive pads the left gap, negative the right one.
    balance: f32,
}

fn header(s: &AppState, p: Palette, insets: ChromeInsets, fit: HeaderFit) -> El {
    let mark = brand_mark(s, 32.0);
    let brand = row()
        .key("brand")
        .gap(10.0)
        .center_y()
        .window_drag()
        .child(mark)
        .child(text("Mimvox").font(ty::TITLE).color(p.text))
        .child(super::update::version_button(s, p));
    let right = row()
        .key("right")
        .gap(8.0)
        .center_y()
        .window_drag()
        .child(engine_pill(s, p, fit.tight))
        .children((s.screen != Screen::Onboarding).then(|| voice_pill(s, p)));
    col()
        .key("header")
        .w_full()
        .h(HEADER_HEIGHT)
        .fill(p.glass)
        .gradient(p.glass_top, p.glass_bottom)
        .shadow(6.0, 24.0, p.shadow_soft)
        .window_drag()
        .child(
            row()
                .key("header-row")
                .w_full()
                .h_full()
                .center_y()
                .gap(14.0)
                .pl(16.0 + insets.leading)
                .pr(if insets.trailing > 0.0 { insets.trailing + 14.0 } else { 12.0 })
                .child(brand)
                .child(el().key("header-pad-l").w(fit.balance.max(0.0)).h_full().window_drag())
                .child(el().key("header-gap-l").grow(1.0).h_full().window_drag())
                .child(if s.screen == Screen::Onboarding { el() } else { tabs(s, p, fit.compact) })
                .child(el().key("header-gap-r").grow(1.0).h_full().window_drag())
                .child(el().key("header-pad-r").w((-fit.balance).max(0.0)).h_full().window_drag())
                .child(right),
        )
        .children((insets.trailing > 0.0).then(|| super::caption::buttons(p, insets.caption, HEADER_HEIGHT)))
        .child(
            el().key("header-rim")
                .pin(Some(0.0), None, Some(0.0), Some(0.0))
                .h(1.0)
                .inert()
                .fill(p.rim_bottom.alpha(0.16)),
        )
        .child(
            el().key("header-sheen")
                .pin(Some(0.0), Some(0.0), Some(0.0), None)
                .h(1.0)
                .inert()
                .fill(p.sheen.alpha(0.12)),
        )
}

const STEPS: [(Screen, &str, &rune::Icon); 5] = [
    (Screen::Record, "Record", &icons::MIC),
    (Screen::Train, "Train", &icons::CHIP),
    (Screen::Speak, "Speak", &icons::VOLUME),
    (Screen::Redub, "Redub", &super::redub::ICON),
    (Screen::Design, "Design", &super::design::ICON),
];

fn tabs(s: &AppState, p: Palette, compact: bool) -> El {
    // The Train tab's "Paused 118/300" badge needs more room than a percentage.
    let paused_badge = super::train::status_line(s).is_some_and(|l| l.starts_with("Paused"));
    let (w, h, pad) = (
        if compact {
            52.0
        } else if paused_badge {
            132.0
        } else {
            100.0
        },
        38.0,
        4.0,
    );
    let idx = STEPS.iter().position(|(sc, ..)| *sc == s.screen);
    let on_lens = p.on_accent;
    let mut strip = row().key("tab-strip");
    for (i, (screen, name, glyph)) in STEPS.iter().enumerate() {
        let on = idx == Some(i);
        let screen = *screen;
        let ink = if on { on_lens } else { p.text_dim };
        let mut tab = row()
            .key(*name)
            .role("tab")
            .label(*name)
            .checked(on)
            .focusable(true)
            .size(w, h)
            .gap(7.0)
            .center()
            .radius(h / 2.0)
            .hover(if on { Color::TRANSPARENT } else { p.glass_hover })
            .on_press_tx(move |s: &mut AppState, tx: &mut Tx| {
                set_screen(s, screen);
                tx.color_motion(motion::SCREEN);
            })
            .child(icon_el(glyph, 15.0, ink).a11y_hidden())
            .children((!compact).then(|| text(*name).font(ty::LABEL).color(ink).a11y_hidden()));
        if compact {
            tab = tab.help(*name);
        }
        if screen == Screen::Train
            && let Some(line) = super::train::status_line(s)
        {
            tab = tab.gap(5.0).child(train_badge(p, &line, on, compact));
        }
        strip = strip.child(tab);
    }
    let lens = el()
        .key("tab-indicator")
        .size(w, h)
        .absolute(pad + idx.unwrap_or(0) as f32 * w, pad)
        .radius(h / 2.0)
        .opacity(if idx.is_some() { 1.0 } else { 0.0 })
        .motion(motion::BOUNCY)
        .lead(motion::TAB_LEAD, motion::SCREEN)
        .a11y_hidden();
    let lens = accent_glass(p, lens);
    let bar = el()
        .key("tabs")
        .size(w * STEPS.len() as f32 + pad * 2.0, h + pad * 2.0)
        .padding(pad)
        .radius((h + pad * 2.0) / 2.0)
        .fill(p.well)
        .border_gradient(1.0, Color::BLACK.alpha(0.35), p.well_rim)
        .box_shadow(rune::Shadow {
            x: 0.0,
            y: 2.0,
            blur: 8.0,
            spread: 0.0,
            color: Color::BLACK.alpha(0.35),
            inset: true,
        });
    bar.child(lens).child(strip)
}

fn train_badge(p: Palette, line: &str, on_lens: bool, compact: bool) -> El {
    let paused = line.strip_prefix("Paused ");
    let label = match paused {
        Some(k) => k.to_owned(),
        None => line.rsplit(' ').next().filter(|w| w.ends_with('%')).unwrap_or("…").to_owned(),
    };
    let mut pill = row()
        .key("train-badge")
        .role("status")
        .label(line.to_owned())
        .h(18.0)
        .px(6.0)
        .gap(3.0)
        .center()
        .radius(9.0)
        .fill(if on_lens { p.on_accent.alpha(0.85) } else { p.accent.alpha(0.2) });
    if paused.is_some() {
        pill = pill.child(icon_el(&icons::PAUSE, 11.0, p.accent).a11y_hidden());
        if compact {
            return pill;
        }
    }
    pill.child(text(label).font(ty::CAPTION).color(p.accent).a11y_hidden())
}

pub struct EngineLook {
    pub tone: Tone,
    pub label: String,
    pub pulse: bool,
    pub retry: bool,
}

/// RVC is "missing" by design when voice training is not installed.
pub fn models_missing(s: &AppState) -> bool {
    let EngineStatus::Ready { tts, rvc, .. } = &s.shell.engine else { return false };
    tts.as_deref() == Some("missing") || (super::setuprun::has(s, "training") && rvc.as_deref() == Some("missing"))
}

pub fn engine_look(s: &AppState) -> EngineLook {
    let look = |tone, label: &str, pulse, retry| EngineLook { tone, label: label.to_owned(), pulse, retry };
    if super::setuprun::running(s) {
        let label = match s.setup.steps.is_empty() {
            true => "Setting up…".to_owned(),
            false => format!("Setting up · {:.0}%", super::setuprun::progress(s) * 100.0),
        };
        return EngineLook { tone: Tone::Accent, label, pulse: true, retry: false };
    }
    if s.screen == Screen::Onboarding && s.setup.phase == super::setuprun::Phase::Stopped {
        return look(Tone::Neutral, "Setup stopped", false, false);
    }
    match &s.shell.engine {
        EngineStatus::Idle | EngineStatus::Starting { .. } => look(Tone::Warning, "Starting engine…", true, false),
        EngineStatus::Ready { tts, rvc, .. } => {
            let any = |want: &str| [tts, rvc].iter().any(|m| m.as_deref() == Some(want));
            if tts.as_deref() == Some("no_memory") {
                look(Tone::Danger, "Not enough memory", false, false)
            } else if models_missing(s) {
                look(Tone::Danger, "Models missing", false, false)
            } else if any("paused") && super::book::finding_speakers(s) {
                look(Tone::Neutral, "Finding speakers · speech paused", false, false)
            } else if any("paused") {
                look(Tone::Neutral, "Training · speech paused", false, false)
            } else if any("loading") {
                look(Tone::Warning, "Loading models…", true, false)
            } else {
                look(Tone::Success, "Ready", false, false)
            }
        }
        EngineStatus::Unavailable { reason } if reason == NOT_INSTALLED => {
            look(Tone::Neutral, "Not installed", false, false)
        }
        EngineStatus::Stopped { .. } | EngineStatus::Unavailable { .. } => {
            look(Tone::Danger, "Engine stopped", false, true)
        }
    }
}

pub fn engine_details(s: &AppState) -> (String, Vec<String>) {
    if super::setuprun::running(s) {
        return ("Setup is running; the engine starts again by itself when it finishes.".to_owned(), Vec::new());
    }
    let finding = super::book::finding_speakers(s);
    engine_help(&s.shell.engine, super::setuprun::has(s, "training"), s.shell.tts_message.as_deref(), finding)
}

fn engine_pill(s: &AppState, p: Palette, tight: bool) -> El {
    let look = engine_look(s);
    let (summary, facts) = engine_details(s);
    let mut help = summary;
    for f in facts {
        help.push('\n');
        help.push_str(&f);
    }
    // On the start screen it only shows the state: Settings needs the engine, and moving the data folder while
    // setup writes into it would break the install.
    let settings = s.screen != Screen::Onboarding;
    let pill = glass_edge(
        p,
        row()
            .key("engine-pill")
            .role(if settings { "button" } else { "status" })
            .label(if settings { format!("Engine status and settings: {}", look.label) } else { look.label.clone() })
            .h(32.0)
            .pl(13.0)
            .pr(if settings { 11.0 } else { 13.0 })
            .gap(8.0)
            .center()
            .radius(16.0)
            .fill(p.glass)
            .gradient(p.glass_top, p.glass_bottom)
            .border_gradient(1.0, p.rim_top, p.rim_bottom)
            .shadow(3.0, 10.0, p.shadow_soft),
    )
    .motion(motion::UI)
    .help(help)
    .child(status_dot(p, look.tone, look.pulse))
    .children((!tight).then(|| text(look.label).font(ty::LABEL).color(p.text).a11y_hidden()));
    if !settings {
        return pill;
    }
    pill.hover(p.glass_hover)
        .focusable(true)
        .on_press(super::settings::open)
        .child(icon_el(&icons::SLIDERS, 14.0, p.text_dim).a11y_hidden())
}

/// `finding`: Book's speaker search, not training, has paused the speech models.
fn engine_help(
    engine: &EngineStatus,
    training: bool,
    tts_message: Option<&str>,
    finding: bool,
) -> (String, Vec<String>) {
    let model = |m: &Option<String>| match m.as_deref() {
        Some("ready") => "ready".to_owned(),
        Some("loading") => "loading…".to_owned(),
        Some("paused") if finding => "paused while Book finds who speaks".to_owned(),
        Some("paused") => "paused while a voice trains".to_owned(),
        Some("missing") => "not installed".to_owned(),
        Some("no_memory") => "not enough memory (RAM)".to_owned(),
        Some(other) => other.to_owned(),
        None => "not loaded yet".to_owned(),
    };
    match engine {
        EngineStatus::Idle | EngineStatus::Starting { .. } => {
            ("Starting the speech engine. Speak and Redub are available in a few seconds.".to_owned(), Vec::new())
        }
        EngineStatus::Ready { device, tts, rvc } => {
            let any = |want: &str| [tts, rvc].iter().any(|m| m.as_deref() == Some(want));
            let missing = tts.as_deref() == Some("missing") || (training && rvc.as_deref() == Some("missing"));
            let no_memory = tts.as_deref() == Some("no_memory");
            let summary = if no_memory {
                "Speech cannot run on this computer: it has too little memory (RAM) for the speech model on the processor."
            } else if missing {
                "Some models are not installed: run setup again."
            } else if any("paused") && finding {
                "Book is finding who speaks: the speech models are paused so it has the GPU. They come back when it ends."
            } else if any("paused") {
                "A voice is training: the speech models are paused so training has the GPU. They come back when training ends or pauses."
            } else if any("loading") {
                "Loading the speech models into memory. The first start takes up to about half a minute."
            } else {
                "Ready: the speech models are loaded."
            };
            let mut t = summary.to_owned();
            if let Some(why) = tts_message.filter(|_| no_memory) {
                t.push_str(&format!("\n{}", sentence(why)));
            }
            let mut facts = Vec::new();
            if let Some(d) = device {
                facts.push(format!("Device: {d}"));
            }
            let conversion = if training {
                model(rvc)
            } else {
                "not installed (voice training is not part of this install)".to_owned()
            };
            facts.push(format!("Speech model: {}", model(tts)));
            facts.push(format!("Voice conversion: {conversion}"));
            (t, facts)
        }
        EngineStatus::Stopped { code, detail } => {
            let mut t = match code {
                Some(c) => format!("The engine stopped (exit code {c})."),
                None => "The engine stopped.".to_owned(),
            };
            let last = detail.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("").trim();
            if !last.is_empty() {
                t.push_str(&format!("\n{last}"));
            }
            (t, vec!["Details are in logs/engine.log in the data folder.".to_owned()])
        }
        EngineStatus::Unavailable { reason } if reason == NOT_INSTALLED => {
            (format!("{NOT_INSTALLED} Run setup on the start screen."), Vec::new())
        }
        EngineStatus::Unavailable { reason } => (format!("The engine cannot run: {reason}"), Vec::new()),
    }
}

/// An engine message (lower case, no full stop) as a sentence.
pub fn sentence(message: &str) -> String {
    let mut chars = message.trim().chars();
    let mut out: String = chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default();
    if !out.ends_with(['.', '!', '?']) {
        out.push('.');
    }
    out
}

fn voice_pill(s: &AppState, p: Palette) -> El {
    let name = active_voice(s).map(|v| v.name.clone()).unwrap_or_else(|| "No voice yet".to_owned());
    let has = active_voice(s).is_some();
    let open = s.shell.voice_menu_open;
    let chip = row()
        .key("voice-pill")
        .role("button")
        .label("Choose voice")
        .h(32.0)
        .pl(12.0)
        .pr(12.0)
        .gap(8.0)
        .center()
        .radius(16.0)
        .fill(if open { p.lens } else { p.glass })
        .gradient(p.glass_top, p.glass_bottom)
        .border_gradient(1.0, p.rim_top, if open { p.accent.alpha(0.4) } else { p.rim_bottom })
        .shadow(3.0, 10.0, p.shadow_soft);
    glass_edge(p, chip)
        .hover(p.glass_hover)
        .focusable(true)
        .motion(motion::UI)
        .on_press(|s: &mut AppState| s.shell.voice_menu_open = !s.shell.voice_menu_open)
        .child(icon_el(&icons::USER, 14.0, if has { p.accent } else { p.text_dim }))
        .child(
            text(name)
                .font(ty::LABEL)
                .color(if has { p.text } else { p.text_dim })
                .max_w(110.0)
                .truncate()
                .a11y_hidden(),
        )
        .child(icon_el(&icons::CHEVRON_DOWN, 12.0, p.text_dim))
}

/// The user's own voices, then the ones Book made for its books.
pub fn by_kind(voices: &[VoiceInfo]) -> (Vec<&VoiceInfo>, Vec<&VoiceInfo>) {
    voices.iter().partition(|v| v.book.is_none())
}

pub fn group_heading(p: Palette, title: &str) -> El {
    text(title.to_owned()).font(ty::OVERLINE).color(p.text_faint).px(12.0).pt(8.0).pb(2.0)
}

fn voice_menu(s: &AppState, p: Palette) -> El {
    let scrim = el()
        .key("voice-scrim")
        .pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0))
        .on_press(|s: &mut AppState| s.shell.voice_menu_open = false);
    let mut list = col().w_full().gap(2.0);
    let (own, book) = by_kind(&s.shell.voices);
    for (i, v) in own.iter().chain(&book).enumerate() {
        if i == own.len() {
            list = list.child(group_heading(p, "Book voices"));
        }
        let id = v.id.clone();
        let on = s.shell.active_voice.as_deref() == Some(v.id.as_str());
        list = list.child(
            row()
                .key(format!("voice-{}", v.id))
                .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 { Color::TRANSPARENT })
                .hover(p.glass_hover)
                .focusable(true)
                .on_press(move |s: &mut AppState| {
                    super::voices::select(s, &id);
                    s.shell.voice_menu_open = false;
                })
                .child(text(v.name.clone()).font(ty::LABEL).color(p.text).grow(1.0).truncate())
                .child(badge(
                    p,
                    if v.trained { "Trained" } else { "Zero-shot" },
                    if v.trained { Tone::Success } else { Tone::Accent },
                ))
                .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));
    }
    let manage = Button::new("Manage voices")
        .ghost()
        .small()
        .key("menu-manage")
        .on_press(|s| set_screen(s, Screen::Voices))
        .build(p);
    let reload =
        icon_button(p, "menu-refresh", &icons::REFRESH, "Reload the voices from the data folder", refresh_voices);
    let create = Button::new("New voice")
        .primary()
        .small()
        .icon(&icons::PLUS)
        .key("menu-new")
        .on_press(|s| {
            s.shell.voice_menu_open = false;
            super::record::start_new_voice(s);
        })
        .build(p);
    let panel = col()
        .key("voice-menu")
        .w(290.0)
        .padding(8.0)
        .gap(6.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("voice-pill", Side::Bottom, Align::End, 8.0)
        .transition(rune::Transition::scale(0.98))
        .child(list)
        .child(row().w_full().gap(6.0).center_y().child(manage).child(el().grow(1.0)).child(reload).child(create));
    el().key("voice-menu-layer").pin(Some(0.0), Some(0.0), Some(0.0), Some(0.0)).child(scrim).child(panel)
}

fn engine_banner(s: &AppState, p: Palette) -> Option<El> {
    let (title, detail) = match &s.shell.engine {
        EngineStatus::Stopped { .. } if super::setuprun::running(s) => return None,
        EngineStatus::Stopped { code, detail } => (
            "The voice engine stopped".to_owned(),
            if detail.is_empty() {
                code.map(|c| format!("Exit code {c}.")).unwrap_or_default()
            } else {
                detail.clone()
            },
        ),
        EngineStatus::Unavailable { reason }
            if reason == NOT_INSTALLED || s.screen == Screen::Onboarding || super::setuprun::running(s) =>
        {
            return None;
        }
        EngineStatus::Unavailable { reason } => {
            ("The voice engine is not set up yet".to_owned(), format!("{reason} Run setup on the start screen."))
        }
        _ => return None,
    };
    let row_ = row()
        .key("engine-banner")
        .w_full()
        .px(14.0)
        .py(9.0)
        .gap(12.0)
        .center_y()
        .child(icon_el(&icons::ALERT, 16.0, p.warn))
        .child(
            col()
                .grow(1.0)
                .min_w(0.0)
                .gap(2.0)
                .child(text(title).font(ty::LABEL).color(p.text))
                .child(text(detail).font(ty::CAPTION).color(p.text_dim).wrap().max_lines(2)),
        )
        .child(
            Button::new("Retry").small().icon(&icons::REFRESH).key("banner-retry").on_press(restart_engine).build(p),
        );
    Some(el().w_full().px(16.0).child(glass_card(p).w_full().child(row_)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::protocol::Event;

    const WHY: &str = "not enough memory (RAM) for speech on the processor: it needs 11 GB";

    #[test]
    fn too_little_ram_is_explained_instead_of_ready() {
        let mut s = AppState::default();
        s.shell.engine = EngineStatus::Ready { device: Some("CPU".into()), tts: Some("loading".into()), rvc: None };
        let models = json!({"tts": "no_memory", "rvc": "ready", "tts_message": WHY});
        on_engine(&mut s, &EngineMsg::Event(Event { event: "models".into(), job: None, data: models }));
        assert_eq!(s.shell.tts_message.as_deref(), Some(WHY));
        let (help, facts) = engine_help(&s.shell.engine, true, s.shell.tts_message.as_deref(), false);
        assert!(help.starts_with("Speech cannot run on this computer"), "{help}");
        assert!(help.ends_with("\nNot enough memory (RAM) for speech on the processor: it needs 11 GB."), "{help}");
        assert_eq!(facts, ["Device: CPU", "Speech model: not enough memory (RAM)", "Voice conversion: ready"]);
        let ready = json!({"tts": "ready", "rvc": "ready"});
        on_engine(&mut s, &EngineMsg::Event(Event { event: "models".into(), job: None, data: ready }));
        assert_eq!(s.shell.tts_message, None);
    }
}