hex/src/rune_ui/onboarding_kit/live.rs
Kit Langton 877ffc71bc
fix(ui): translate onboarding and the menu bar, unclip meeting retention and Labs' unload menu (#1763)
* fix(ui): translate onboarding and the menu bar, wrap meeting retention, fit Labs' unload menu, and show only Reopen when the shortcut fails (t1548)

* test(ui): regenerate goldens for the onboarding, meetings and reopen changes (t1548)

* fix(i18n): build english() only on macOS, its one caller (t1548)

* test(ui): regenerate goldens after rebasing onto dev (t1548)
2026-11-12 22:47:49 -08:00

1020 lines
35 KiB
Rust

//! Hex's first run: the onboarding story, the one onboarding on every OS.
//! A new install (or an upgrade whose setup isn't ready) opens it at
//! launch, and Run setup again and `hex onboarding reset` replay it. The
//! window's tour ([`onboarding`](super::super::onboarding)) is the state
//! machine underneath: it starts the model download, asks for the
//! permissions, relaunches when macOS needs it, watches the practice
//! dictation, and records completion. This module shows the story's pages
//! over the window and feeds them that real state each frame.
//!
//! When the Hugging Face cache holds a compatible model, the download page
//! becomes the model step (`found_choice`): one list, Hex's recommended
//! model first and selected, then the models found. Picking ours downloads
//! it; picking a found one uses it in place, and the story moves on without
//! a download. Back on the next pages returns to the list. Nothing found
//! leaves the download page as it is, with the recommended model
//! downloading by itself.
use crate::desktop::i18n::tr;
use std::sync::Mutex;
use std::time::Instant;
use rune::{El, TextEdit, Transition, Tx, row, text};
use rune_kit::{Button, ButtonVariant};
use super::super::controls::{Paint, PushSize};
use super::super::found_choice::{self, ChoiceRow};
use super::super::paste_access::{self, PasteAccess};
use super::super::platform::Os;
use super::super::{Request, Ui, onboarding};
use super::fixture::{Language, Speech};
use super::permissions::{FLOAT_OFF, GRANTED_BEAT};
use super::pill::set_other_label;
use super::stories::{FRAME, Flow, Onboard, Step, advance_to};
use crate::desktop::onboarding::{
Input, ItemStatus, Practice, SetupItem, SetupStatus, Step as TourStep,
};
use crate::transcription::models::{
self as transcription_models, TranscriptionModelId, TranscriptionSelection,
};
/// How often the first run looks at the model on disk and the permissions.
const CHECK_EVERY: f64 = 0.25;
/// A download that gained no bytes for this long has stalled.
const STALL_AFTER: f64 = 30.0;
/// What the real first run reports to the story's pages.
pub(crate) struct Live {
/// Hex's own dictation records.
pub(crate) listening: bool,
/// The listener runs but its model, microphone, and shortcuts aren't up
/// yet, so the practice waits instead of inviting a hold.
pub(crate) warming: bool,
/// The model download stopped with an error.
pub(crate) failed: bool,
/// Why, in one line, such as a proxy or certificate (#894).
pub(crate) failure: Option<String>,
/// The download runs but gained nothing for [`STALL_AFTER`].
pub(crate) stalled: bool,
/// The download's bytes, and when they last grew.
progress: Option<(u64, f64)>,
/// A model file chosen with Use a model file… is being added.
pub(crate) using_file: bool,
pub(crate) microphone: ItemStatus,
pub(crate) accessibility: ItemStatus,
/// General's "Turn off the mic when not dictating" was on when the
/// first run opened, so the microphone opens only while you dictate.
pub(crate) release_microphone: bool,
/// Every permission is on and one applies only after Hex restarts.
pub(crate) restart: bool,
/// macOS asks for Microphone and Accessibility; Windows only shows the
/// Microphone row while its privacy switch is off.
pub(crate) accessibility_row: bool,
/// macOS 27 calls Accessibility "Device Control and Data Access".
pub(crate) accessibility_renamed: bool,
/// The shortcut listener failed after setup and Hex won't relaunch by
/// itself again: Reopen Hex.
pub(crate) reopen: bool,
/// macOS needed a restart and Hex couldn't relaunch itself.
pub(crate) relaunch_failed: bool,
/// The desktop's paste permission on GNOME and KDE Wayland: the
/// permissions page explains it and asks before the practice pastes.
pub(crate) paste: Option<PasteAccess>,
/// The model step: the models found on this computer, while it shows.
pub(crate) models: Vec<ChoiceRow>,
/// Where the model step stands.
pub(crate) model_step: ModelStep,
/// The pick is under way: ours downloading, or a found model ready.
pick_started: bool,
/// The scan for models on this computer hasn't answered yet.
scanning: bool,
pub(crate) practice: Practice,
/// The model and language this run downloads.
choice: TranscriptionSelection,
/// The other selection the language capsule switches to; `None` when
/// the system language recommends English.
alternate: Option<TranscriptionSelection>,
granted_at: Option<f64>,
mic_granted_at: Option<f64>,
checked: Option<Checked>,
/// A scene: the game deals the same messages every time.
pub(crate) fixture: bool,
/// Dictation streams send their live words to the practice field.
_live_words: crate::dictation::live_text::Demand,
}
/// The model step, shown only when the scan found a compatible model.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum ModelStep {
/// Nothing found (or not looked yet): the download page as always.
#[default]
None,
/// The list shows and holds the story until Continue.
Choosing,
/// Continued from the list; Back returns to it.
Chosen,
}
impl Live {
/// macOS keeps showing the mic in use: Hex holds it open between
/// dictations unless "Turn off the mic when not dictating" is on. A
/// listener that failed to start holds nothing.
pub(crate) fn mic_stays_open(&self) -> bool {
self.accessibility_row && !self.release_microphone && !self.reopen && !self.relaunch_failed
}
/// The story waits on the download page for the model step.
pub(crate) fn holds(&self) -> bool {
self.scanning
|| match self.model_step {
ModelStep::None => false,
ModelStep::Choosing => true,
ModelStep::Chosen => !self.pick_started,
}
}
/// The language capsule switches languages only when the system
/// language recommends a model other than English.
pub(crate) fn switches_language(&self) -> bool {
self.alternate.is_some()
}
}
/// The last look at the disk and macOS.
#[derive(Clone, Copy)]
struct Checked {
at: f64,
installed: bool,
status: SetupStatus,
}
impl Live {
/// The model can't be had here: its download failed or stalled, so
/// Continue without a model is offered (#894).
pub(crate) fn model_blocked(&self) -> bool {
self.failed || self.stalled
}
pub(crate) fn granted_for(&self, now: f64) -> bool {
self.granted_at
.is_some_and(|at| now - at >= GRANTED_BEAT + FLOAT_OFF)
}
pub(crate) fn mic_granted_for(&self, now: f64) -> bool {
self.mic_granted_at
.is_some_and(|at| now - at >= GRANTED_BEAT + FLOAT_OFF)
}
/// How far an allowed permission's card has floated off at `now`.
pub(crate) fn floated(&self, accessibility: bool, now: f64) -> f32 {
let at = if accessibility {
self.granted_at
} else {
self.mic_granted_at
};
at.map_or(0.0, |at| {
((now - at - GRANTED_BEAT) / FLOAT_OFF).clamp(0.0, 1.0) as f32
})
}
}
/// Where a fixture's clock starts.
const FIXTURE_START: f64 = 100.0;
/// The most one drawn frame moves the first run's clock: two 30 Hz frames.
const MAX_STEP: f64 = 1.0 / 15.0;
/// The first run's clock, which runs on drawn frames rather than the wall.
/// It stands still until the window draws its first frame, and a slow frame
/// moves it at most [`MAX_STEP`]. A cold launch spends most of a second on
/// its first frames (the GPU's pipelines, fonts and glyphs), and a beat's
/// first frame can be slow the same way; on the wall's time the opening
/// and the Launch Room's growth would play out unseen behind them and jump.
struct StoryClock {
/// Story seconds at `last`.
story: f64,
last: Option<Instant>,
}
impl StoryClock {
fn frame_drawn(&mut self, at: Instant) {
self.story = self.at(at);
self.last = Some(at);
}
/// Story seconds at `at`, after the last drawn frame.
fn at(&self, at: Instant) -> f64 {
self.story
+ self.last.map_or(0.0, |last| {
at.saturating_duration_since(last)
.as_secs_f64()
.min(MAX_STEP)
})
}
}
static STORY_CLOCK: Mutex<StoryClock> = Mutex::new(StoryClock {
story: 0.0,
last: None,
});
/// The window drew a frame.
pub(in crate::rune_ui) fn frame_drawn() {
if let Ok(mut clock) = STORY_CLOCK.lock() {
clock.frame_drawn(Instant::now());
}
}
/// Seconds on the first run's own clock. Fixtures keep the story's own
/// time, so a scene shows one settled moment.
fn clock(ui: &Ui) -> f64 {
if ui.is_fixture() {
return ui.first_run.as_ref().map_or(FIXTURE_START, |s| s.now);
}
STORY_CLOCK
.lock()
.map_or(0.0, |clock| clock.at(Instant::now()))
+ 1.0
}
/// Every permission is ready, the desktop's paste permission included
/// (or passed over), so the story needs no permissions page.
fn granted(status: SetupStatus, paste: Option<PasteAccess>) -> bool {
use crate::desktop::onboarding::PermissionState::Ready;
status.microphone == Ready
&& status.accessibility == Ready
&& paste.is_none_or(PasteAccess::settled)
}
fn english_language(selection: &TranscriptionSelection) -> bool {
selection.language == "en"
}
fn english_selection() -> TranscriptionSelection {
TranscriptionSelection {
model: TranscriptionModelId::ParakeetUnifiedEnglish,
language: "en".into(),
}
}
/// The other selection the language capsule offers: the model recommended
/// for the person's language while English is selected, English otherwise.
/// `None` when that recommendation is English too, so an English system has
/// nothing to switch to.
fn alternate_selection(
current: &TranscriptionSelection,
preferred: &str,
) -> Option<TranscriptionSelection> {
if english_language(current) {
let recommended = transcription_models::recommended_selection(preferred);
(!english_language(&recommended)).then_some(recommended)
} else {
Some(english_selection())
}
}
fn installed(ui: &Ui, selection: &TranscriptionSelection) -> bool {
transcription_models::validate(selection)
.is_ok_and(|model| ui.picker.installed(model, &selection.language))
}
/// Opens the first run over the tour, at the tour's step: at launch when
/// this run needs onboarding, and from Run setup again.
pub(in crate::rune_ui) fn open(ui: &mut Ui) {
let Some(tour_step) = ui.tour.as_ref().map(|tour| tour.flow.step()) else {
return;
};
if ui.first_run.is_some() {
return;
}
let choice = ui.settings.transcription.clone();
let wants = if english_language(&choice) {
Language::English
} else {
Language::Other
};
let alternate = alternate_selection(&choice, &ui.preferred_language());
let other = if english_language(&choice) {
alternate.as_ref()
} else {
Some(&choice)
};
// Replaces the previous run's label; an English-only run clears it.
set_other_label(other.map(|other| transcription_models::language_name(&other.language)));
let had_model = installed(ui, &choice);
let status = ui.platform.setup_status(had_model);
let mic_granted = status.microphone == crate::desktop::onboarding::PermissionState::Ready;
let granted = granted(status, ui.platform.paste);
let mut s = Onboard::new(Flow::FirstRun);
s.speech = Speech::AfterDownload;
s.toggle = ui.settings.shortcut_mode == crate::dictation::ShortcutMode::Toggle;
s.wants = wants;
s.caps = ui.settings.dictation_hotkey.keycaps();
s.had_model = had_model;
s.granted = granted;
s.mic_granted = mic_granted;
s.home = match ui.platform.caps.os {
Os::Macos => super::landing::Home::MenuBar,
Os::Windows => super::landing::Home::Tray,
Os::Linux => super::landing::Home::Launcher,
};
s.live = Some(Live {
listening: false,
warming: false,
failed: false,
failure: None,
stalled: false,
progress: None,
using_file: false,
microphone: ItemStatus::Todo,
accessibility: ItemStatus::Todo,
release_microphone: ui.settings.release_microphone_while_idle,
restart: false,
accessibility_row: ui.platform.caps.permissions,
accessibility_renamed: ui.platform.accessibility_renamed,
reopen: false,
relaunch_failed: false,
paste: ui.platform.paste,
models: Vec::new(),
model_step: ModelStep::None,
pick_started: false,
scanning: false,
practice: Practice::Waiting,
choice,
alternate,
granted_at: None,
mic_granted_at: None,
checked: None,
fixture: ui.is_fixture(),
_live_words: crate::dictation::live_text::demand(),
});
let now = clock(ui);
s.now = now;
match tour_step {
TourStep::Welcome => s.begin_live(now),
TourStep::Setup => s.resume_setup(),
TourStep::TryIt if had_model => s.jump_to_try(),
TourStep::TryIt => s.jump_to_waiting(),
TourStep::Done => s.jump_to_ready(),
}
ui.first_run = Some(s);
// The tour waits at setup, where it asks for permissions, while the
// story plays; with everything granted it goes on to the practice.
if tour_step == TourStep::Welcome {
onboarding::input(ui, Input::Continue);
}
}
/// A page of the first run, for scenes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::rune_ui) enum Page {
/// `"Setting up Hex"`, or the model step when models were found.
Download,
/// The demo, finished: `"With Hex"`'s happy ending.
Demo,
/// The first permission the run still asks for: the microphone, else
/// Accessibility (or the desktop's paste permission).
Permissions,
/// `"Almost ready"`: the model still downloads.
Waiting,
/// `"Your turn"`: the practice game.
Try,
Ready,
}
/// The page the first run shows, for the window tests (Linux only).
#[cfg(all(test, target_os = "linux"))]
pub(in crate::rune_ui) fn page(ui: &Ui) -> Option<Page> {
Some(match ui.first_run.as_ref()?.step {
Step::Pick | Step::Started => Page::Download,
Step::Parked | Step::YourTurn | Step::Hearing | Step::Heard | Step::Done => Page::Demo,
Step::Microphone | Step::Accessibility => Page::Permissions,
Step::Waiting => Page::Waiting,
Step::Try | Step::TryHearing | Step::TryHeard => Page::Try,
Step::Ready => Page::Ready,
})
}
/// Scenes: the first run over the tour a fixture walked, played on its own
/// clock to `page` as a person would see it, then held there.
pub(in crate::rune_ui) fn fixture(ui: &mut Ui, page: Page) {
ui.first_run = None;
open(ui);
if let Some(s) = ui.first_run.as_mut() {
// From the start, as a new install plays it, whatever the tour's step.
s.now = FIXTURE_START;
s.step = Step::Pick;
s.begin_live(FIXTURE_START);
}
fixture_resume(ui, page);
}
/// Scenes: plays a fixture's first run on from where it is to `page`.
pub(in crate::rune_ui) fn fixture_resume(ui: &mut Ui, page: Page) {
// One poll fills in what the tour reports.
let mut tx = Tx::default();
poll(ui, &mut tx);
let Some(s) = ui.first_run.as_mut() else {
return;
};
let reached = |s: &Onboard| match page {
Page::Download => matches!(s.step, Step::Pick | Step::Started),
Page::Demo => s.step == Step::Heard,
Page::Permissions => matches!(s.step, Step::Microphone | Step::Accessibility),
Page::Waiting => s.step == Step::Waiting,
Page::Try => s.step == Step::Try,
Page::Ready => s.step == Step::Ready,
};
if page == Page::Ready {
s.jump_to_ready();
}
for _ in 0..64 {
if reached(s) {
break;
}
let Some(next) = super::stories::first_run_next(s, s.now) else {
break;
};
s.now += next;
}
if page == Page::Try {
super::game::step(s, s.now);
}
// Everything that entered has settled; nothing more is due. The
// download's progress counts from here, so a scene never shows it
// stalled.
s.now += 10.0;
s.auto_due_at = None;
if let Some(live) = s.live.as_mut() {
live.progress = None;
}
poll(ui, &mut tx);
}
/// "Run setup again" and `hex onboarding reset`: forgets that onboarding
/// finished and opens it now. Settings, history, models, and permissions
/// stay as they are, so the run finds them ready and passes their steps.
pub(crate) fn restart(ui: &mut Ui, tx: &mut Tx) -> Result<(), String> {
if ui.live() {
crate::desktop::onboarding::reset().map_err(|error| format!("{error:#}"))?;
}
ui.select_pane(super::super::Pane::General, tx);
ui.first_run = None;
ui.tour = Some(onboarding::Tour::replay(&ui.settings, &ui.platform));
open(ui);
tx.settle();
if ui.first_run.is_none() {
return Err("Hex could not open onboarding".into());
}
Ok(())
}
/// Feeds the first run fresh state and moves it on; true while it shows.
pub(in crate::rune_ui) fn poll(ui: &mut Ui, tx: &mut Tx) -> bool {
if ui.first_run.is_none() {
return false;
}
let now = clock(ui);
let view = ui.tour.as_ref().map(|tour| tour.flow.view());
let tour_model = view.as_ref().map_or(ItemStatus::Todo, |view| view.model);
let offered = found_choice::offered(ui, tour_model);
let models = if offered {
found_choice::rows(ui, tour_model)
} else {
Vec::new()
};
let started = found_choice::started(ui, tour_model);
let scanning = ui.found.scanning();
let caps = ui.settings.dictation_hotkey.keycaps();
let toggle = ui.settings.shortcut_mode == crate::dictation::ShortcutMode::Toggle;
let release_microphone = ui.settings.release_microphone_while_idle;
let Some(choice) = ui
.first_run
.as_ref()
.and_then(|s| s.live.as_ref())
.map(|live| live.choice.clone())
else {
return false;
};
let model = transcription_models::validate(&choice).ok();
let warming = ui.view.as_ref().is_some_and(|view| view.listener.warming);
let (preparing, downloaded_bytes, errored) =
ui.view.as_ref().map_or((false, 0, false), |view| {
let t = &view.transcription;
(
model.is_some_and(|m| t.preparing == Some(m.id)),
t.downloaded_bytes,
t.error.is_some(),
)
});
let failure = super::super::model_import::download_failure(ui);
let using_file = super::super::model_import::using_file(ui);
// The disk and macOS checks run a few times a second, not every frame.
let checked = ui
.first_run
.as_ref()
.and_then(|s| s.live.as_ref())
.and_then(|live| live.checked)
// A fixture's clock stands still, so it looks every time.
.filter(|checked| !ui.is_fixture() && now - checked.at < CHECK_EVERY);
let checked = match checked {
Some(checked) => checked,
None => {
let installed = installed(ui, &choice);
Checked {
at: now,
installed,
status: ui.platform.setup_status(installed),
}
}
};
// A model picked from the list is the one Hex uses, whatever the
// language capsule last chose.
let (choice_installed, status) = (
checked.installed || tour_model == ItemStatus::Ready,
checked.status,
);
// Setup that is already ready never moves the tour past it by itself,
// and the tour watches the practice dictation only once it has.
if status.ready()
&& ui
.tour
.as_ref()
.is_some_and(|tour| tour.flow.step() == TourStep::Setup)
{
onboarding::input(ui, Input::Continue);
}
let asks_permissions = ui.platform.caps.permissions;
let login = super::login::of(&ui.platform);
let accessibility_renamed = ui.platform.accessibility_renamed;
let relaunch_failed = ui.platform.relaunch_failed;
let paste = ui.platform.paste;
let live_window = !ui.is_fixture();
let Some(s) = ui.first_run.as_mut() else {
return false;
};
if s.login.set(login, now) {
s.sfx.on_login(now);
}
let Some(live) = s.live.as_mut() else {
return false;
};
live.warming = warming;
live.checked = Some(checked);
// Linux and Windows ask for no permissions: both rows are ready.
if !asks_permissions {
live.microphone = ItemStatus::Ready;
live.accessibility = ItemStatus::Ready;
}
live.paste = paste;
// Permissions, as the tour's setup rows show them.
if let Some(view) = &view {
for row in &view.rows {
match row.item {
SetupItem::Microphone => live.microphone = row.status,
SetupItem::Accessibility => live.accessibility = row.status,
_ => {}
}
}
live.restart = view.restart;
if view.practice == Practice::TooShort && live.practice != Practice::TooShort {
s.taps = s.taps.saturating_add(1);
}
live.accessibility_renamed = accessibility_renamed;
live.relaunch_failed = relaunch_failed;
live.reopen = view.reopen;
live.practice = view.practice;
}
let mic_granted = status.microphone == crate::desktop::onboarding::PermissionState::Ready;
if mic_granted {
live.mic_granted_at.get_or_insert(now);
} else {
live.mic_granted_at = None;
}
// The model step: shown on the download page once the scan found
// something, and held there until Continue.
live.models = models;
live.pick_started = started;
live.scanning = scanning;
let downloading_page = matches!(s.step, Step::Pick | Step::Started);
match live.model_step {
ModelStep::None if offered && downloading_page => live.model_step = ModelStep::Choosing,
ModelStep::Choosing if !offered => live.model_step = ModelStep::None,
// A pick that failed asks again.
ModelStep::Chosen if downloading_page && tour_model == ItemStatus::Failed => {
live.model_step = ModelStep::Choosing;
}
_ => {}
}
if live.model_step == ModelStep::Chosen && downloading_page {
// A model already on this computer needs no download pill.
s.had_model = tour_model == ItemStatus::Ready;
}
let granted = granted(status, paste);
if granted {
live.granted_at.get_or_insert(now);
} else {
live.granted_at = None;
}
live.listening = live.practice == Practice::Listening;
// The model download.
live.failed = !choice_installed && !preparing && (errored || failure.is_some());
live.progress = (preparing && !choice_installed).then_some(match live.progress {
Some((bytes, since)) if bytes == downloaded_bytes => (bytes, since),
_ => (downloaded_bytes, now),
});
live.stalled = live
.progress
.is_some_and(|(_, since)| now - since >= STALL_AFTER);
live.failure = failure;
live.using_file = using_file;
s.granted = granted;
s.mic_granted = mic_granted;
s.caps = caps;
s.toggle = toggle;
live.release_microphone = release_microphone;
if let Some(download) = s.download.as_mut() {
if let Some(total) = model.and_then(|m| m.download_bytes()) {
download.total = total;
}
if choice_installed {
download.downloaded = download.total;
} else if preparing {
download.downloaded = downloaded_bytes.min(download.total.saturating_sub(1));
}
s.replay.show(download, now);
}
// Hex's state arrives between frames, so the first run keeps polling;
// a fixture shows one moment and stays still.
advance_to(s, now, tx);
let ready = s.step == Step::Ready;
if live_window {
tx.wake_after(FRAME);
}
// Hex is ready ends the tour's practice too, so a run quit on it
// resumes there rather than at the practice.
if ready
&& ui
.tour
.as_ref()
.is_some_and(|tour| tour.flow.step() == TourStep::TryIt)
{
onboarding::input(ui, Input::Skip);
}
true
}
/// The first run over the whole window, while it shows.
pub(in crate::rune_ui) fn overlay(ui: &Ui, p: Paint, reduced: bool) -> Option<El> {
let s = ui.first_run.as_ref()?;
s.reduced.set(reduced);
// Scenes are the release first run, without the replay strip.
let strip = (!ui.is_fixture())
.then(|| super::stories::strip(p, s))
.flatten();
Some(
super::flows::view(p, s)
.children(strip)
.key("first-run")
.role("dialog")
.label(tr("Setting up Hex"))
.absolute(0.0, 0.0)
.on_press(|_: &mut Ui| {}),
)
}
/// A story handler run on the window's first run.
pub(super) fn on_ui(f: fn(&mut Onboard)) -> impl Fn(&mut Ui) + 'static {
move |ui: &mut Ui| {
if let Some(s) = ui.first_run.as_mut() {
f(s);
}
}
}
pub(super) fn press_continue(ui: &mut Ui) {
if let Some(s) = ui.first_run.as_mut() {
s.move_on();
}
}
/// Skip on the demo or the practice: passes over that part to the next
/// step setup still needs. It never records completion; only Hex is ready
/// (or Continue without a model) does.
pub(in crate::rune_ui) fn skip(ui: &mut Ui) {
if let Some(s) = ui.first_run.as_mut() {
s.skip_optional();
}
}
/// "Continue without a model", once the download failed or stalled (#894):
/// onboarding finishes with no model, and Settings says so with Download
/// and Add model file…. Only offered once every permission is ready.
pub(in crate::rune_ui) fn continue_without_model(ui: &mut Ui) {
let offered = ui
.first_run
.as_ref()
.is_some_and(|s| s.granted && s.live.as_ref().is_some_and(Live::model_blocked));
if !offered {
return;
}
onboarding::close(ui, true);
}
/// "Start using Hex": closes the first run and the tour under it, and
/// records the tour finished once setup is ready.
pub(super) fn finish(ui: &mut Ui) {
let installed = ui.picker.selected_installed(&ui.settings);
let ready = ui.platform.setup_status(installed).ready();
onboarding::close(ui, ready);
}
fn choose(ui: &mut Ui, selection: &TranscriptionSelection) {
if transcription_models::validate(selection).is_ok() {
ui.send(Request::ChooseModel {
model: selection.model,
language: selection.language.clone(),
});
}
}
pub(super) fn cycle_language(ui: &mut Ui) {
let Some(s) = ui.first_run.as_mut() else {
return;
};
let Some(next) = s.live.as_ref().and_then(|live| live.alternate.clone()) else {
return;
};
s.cycle_language();
let Some(live) = s.live.as_mut() else {
return;
};
live.alternate = Some(std::mem::replace(&mut live.choice, next));
live.failed = false;
live.stalled = false;
live.progress = None;
live.checked = None;
let choice = live.choice.clone();
choose(ui, &choice);
}
/// Picks row `index` of the model step's list and starts it.
pub(super) fn pick_model(index: usize) -> impl Fn(&mut Ui) + 'static {
move |ui: &mut Ui| found_choice::pick(ui, index)
}
/// Continue on the model step: starts the selected row if none was picked,
/// and the story moves on once the pick is under way.
pub(in crate::rune_ui) fn continue_model(ui: &mut Ui) {
let model = ui
.tour
.as_ref()
.map_or(ItemStatus::Todo, |tour| tour.flow.view().model);
if found_choice::pending(ui, model) {
found_choice::start_selected(ui);
}
if let Some(live) = ui.first_run.as_mut().and_then(|s| s.live.as_mut()) {
live.model_step = ModelStep::Chosen;
}
if let Some(s) = ui.first_run.as_mut() {
s.move_on();
}
}
/// Back to the model step, to change the pick.
pub(super) fn back_to_models(ui: &mut Ui) {
if let Some(s) = ui.first_run.as_mut() {
s.back_to_download();
if let Some(live) = s.live.as_mut() {
live.model_step = ModelStep::Choosing;
}
}
}
/// "Reopen Hex" once the listener failed and Hex won't relaunch itself.
pub(super) fn reopen(ui: &mut Ui) {
onboarding::input(ui, Input::Reopen);
}
/// Hex's shortcut didn't start, and Reopen Hex: what a page shows instead
/// of asking for the shortcut until the listener is ready.
pub(super) fn recovery(p: Paint) -> El {
row()
.key("reopen")
.gap(10.0)
.center_y()
.child(
text(tr("Hex's shortcut didn't start."))
.key("why")
.font(super::landing::LEAD)
.color(p.muted()),
)
.child(
Button::new(tr("Reopen Hex"))
.variant(ButtonVariant::Neutral)
.on_press(reopen)
.build_push(p.k)
.key("reopen-hex"),
)
}
/// "Use a model file…" when the download is blocked: a GGUF chosen here is
/// imported and selected, and the first run moves on once it is ready.
pub(super) fn use_file(ui: &mut Ui) {
super::super::model_import::use_file(ui);
}
/// "Try again": retries the model the person picked from the list, else the
/// language capsule's choice.
pub(super) fn retry_download(ui: &mut Ui) {
let Some(live) = ui.first_run.as_mut().and_then(|s| s.live.as_mut()) else {
return;
};
live.failed = false;
live.stalled = false;
live.progress = None;
let choice = live.choice.clone();
match ui.found.picked {
Some(index) => found_choice::pick(ui, index),
None => choose(ui, &choice),
}
}
/// Allow on a permission row.
pub(super) fn allow(item: SetupItem) -> impl Fn(&mut Ui) + 'static {
move |ui: &mut Ui| onboarding::input(ui, Input::Grant(item))
}
/// Allow on the paste permission: the desktop's dialog opens.
pub(super) fn allow_paste(ui: &mut Ui) {
paste_access::ask(ui);
}
/// Continue after the desktop's paste permission was refused: the desktop
/// asks again at the first paste.
pub(super) fn paste_later(ui: &mut Ui) {
paste_access::later(ui);
if let Some(s) = ui.first_run.as_mut() {
s.move_on();
}
}
/// "Restart Hex" once macOS applies a grant only after a restart.
pub(super) fn restart_hex(ui: &mut Ui) {
onboarding::input(ui, Input::Restart);
}
pub(super) fn practice(ui: &mut Ui) -> &mut TextEdit {
match ui.first_run.as_mut() {
Some(s) => &mut s.practice,
// The field shows only with the first run.
None => Box::leak(Box::default()),
}
}
pub(super) fn practice_changed(ui: &mut Ui, tx: &mut Tx) {
if let Some(s) = ui.first_run.as_mut() {
s.on_practice_change(tx);
}
}
/// What the practice says in place of the shortcut invitation while the
/// listener loads its model, microphone, and shortcuts.
pub(super) fn warming_copy() -> &'static str {
tr("Getting Hex ready to listen…")
}
/// What the practice dictation's last try needs said.
pub(super) fn hint_copy(live: &Live) -> Option<&'static str> {
Some(match live.practice {
Practice::TooShort => tr("Keep holding the shortcut while you talk, then let go."),
Practice::NothingHeard => tr("Hex didn't hear any words. Try again a little louder."),
Practice::Failed => tr("That didn't work. Try again."),
Practice::Transcribing => tr("Typing what you said…"),
_ => return None,
})
}
/// The practice's `Use tap to start`: the shortcut starts and stops
/// dictation from now on, as General's setting would.
pub(super) fn use_toggle(ui: &mut Ui) {
ui.update(|settings| settings.shortcut_mode = crate::dictation::ShortcutMode::Toggle);
if let Some(s) = ui.first_run.as_mut() {
s.toggle = true;
s.practice.focused = true;
}
}
/// [`hint_copy`] under the practice field.
pub(super) fn hint(p: Paint, live: &Live) -> Option<El> {
if live.reopen {
return None;
}
let copy = hint_copy(live)?;
Some(
text(copy)
.key("practice-hint")
.font(p.k.ty.small)
.color(p.muted())
.transition(Transition::opacity()),
)
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};
fn selection(model: TranscriptionModelId, language: &str) -> TranscriptionSelection {
TranscriptionSelection {
model,
language: language.into(),
}
}
#[test]
fn the_language_switch_follows_the_system_language() {
let english = english_selection();
assert_eq!(
alternate_selection(&english, "en"),
None,
"an English system has no other language"
);
for model in [
TranscriptionModelId::CohereTranscribe,
TranscriptionModelId::WhisperLargeV3Turbo,
TranscriptionModelId::ParakeetV3,
] {
let current = selection(model, "en");
assert_eq!(
alternate_selection(&current, "en"),
None,
"{model:?} is English on an English system"
);
assert_eq!(
alternate_selection(&current, "fr"),
Some(transcription_models::recommended_selection("fr")),
"{model:?} still switches to the system's French recommendation"
);
}
for language in ["fr", "de"] {
let alternate =
alternate_selection(&english, language).expect("a v3-supported alternate");
assert_eq!(
alternate,
transcription_models::recommended_selection(language),
"{language} gets its own recommendation"
);
assert_eq!(alternate.model, TranscriptionModelId::ParakeetV3);
assert_eq!(alternate.language, language);
}
let japanese = alternate_selection(&english, "ja").expect("a Japanese alternate");
assert_eq!(
japanese,
transcription_models::recommended_selection("ja"),
"Japanese gets its own recommendation, not French"
);
assert_eq!(japanese.language, "ja");
assert_eq!(japanese.model, TranscriptionModelId::WhisperLargeV3Turbo);
assert_eq!(
alternate_selection(&japanese, "ja"),
Some(english),
"a non-English selection switches back to English"
);
}
#[test]
fn the_story_waits_for_the_first_frame_and_slow_frames_dont_skip_it() {
let open = Instant::now();
let mut clock = StoryClock {
story: 0.0,
last: None,
};
// A cold first frame takes most of a second: the story stands still.
assert_eq!(clock.at(open + Duration::from_millis(700)), 0.0);
let first = open + Duration::from_millis(700);
clock.frame_drawn(first);
assert_eq!(clock.story, 0.0);
// Frames at 60 Hz move it on the wall's time.
let frame = Duration::from_micros(16_667);
clock.frame_drawn(first + frame);
assert!((clock.story - frame.as_secs_f64()).abs() < 1e-9);
// A 400 ms frame moves it one step, and time between frames
// never runs ahead of the next frame.
let slow = first + frame + Duration::from_millis(400);
let between = clock.at(slow);
clock.frame_drawn(slow);
assert!((clock.story - (frame.as_secs_f64() + MAX_STEP)).abs() < 1e-9);
assert!(between <= clock.story);
}
}