mirror of
https://github.com/anomalyco/hex.git
synced 2026-11-28 13:02:21 +01:00
328 lines
12 KiB
Rust
328 lines
12 KiB
Rust
//! The live text plate (Labs): one click-through line
|
||
//! beside the recording HUD with what the dictation has said so far, on
|
||
//! every OS. It shows while a recording has text and hides when the
|
||
//! recording ends ([`crate::live_text`]); `rune_hud` says where the HUD is,
|
||
//! so the plate sits just past it, on the HUD's screen.
|
||
//!
|
||
//! The overlay is prewarmed: macOS keeps it drawn while hidden and refreshes
|
||
//! it before a reveal, so it never reappears with the last dictation's
|
||
//! words for a frame.
|
||
|
||
use std::sync::Arc;
|
||
use std::sync::atomic::{AtomicBool, Ordering};
|
||
|
||
use rune::{Anim, Cx, El, OverlayOptions, OverlayPlacement, OverlaySpec, ScreenEdge, row, text};
|
||
|
||
use super::controls::Paint;
|
||
use crate::transcription_engine::Partial;
|
||
|
||
/// The overlay's size: room for about a dozen words on one line.
|
||
pub(crate) const SIZE: (f32, f32) = (560.0, 44.0);
|
||
/// The plate's height inside the overlay.
|
||
const PLATE_H: f32 = 32.0;
|
||
/// The overlay's room around the plate, across its height.
|
||
const PAD: f32 = (SIZE.1 - PLATE_H) / 2.0;
|
||
|
||
#[derive(Default)]
|
||
pub(crate) struct Plate {
|
||
stable: String,
|
||
tentative: String,
|
||
}
|
||
|
||
/// Where the plate starts, just past the HUD.
|
||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||
pub(crate) enum Spot {
|
||
/// This far from the edge that the HUD is on, on the HUD's display
|
||
/// (`rune_hud::display`).
|
||
Edge(ScreenEdge, f32),
|
||
/// At `y` in Rune's global space (points from the primary display's
|
||
/// top-left, y down), centred on `x`; the plate hangs down from `y`
|
||
/// when `below`, else rises from it.
|
||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||
Global { x: f32, y: f32, below: bool },
|
||
}
|
||
|
||
impl Spot {
|
||
/// The overlay's placement for the plate to start at this spot.
|
||
fn placement(self) -> OverlayPlacement {
|
||
match self {
|
||
Self::Edge(edge, margin) => OverlayPlacement::Edge {
|
||
edge,
|
||
margin: margin - PAD,
|
||
align: rune::Align::Center,
|
||
inset: 0.0,
|
||
},
|
||
Self::Global { x, y, below } => OverlayPlacement::Rect {
|
||
x: x - SIZE.0 / 2.0,
|
||
y: if below { y - PAD } else { y - SIZE.1 + PAD },
|
||
width: SIZE.0,
|
||
height: SIZE.1,
|
||
},
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Where the plate goes. Called on the app's thread each time the plate
|
||
/// appears, so it may read the screen.
|
||
pub(crate) type Place = fn() -> Spot;
|
||
|
||
/// Adds the plate to the app. It shows only while a dictation publishes its
|
||
/// text (Labs › Live text, applied at once), so it's prewarmed only when
|
||
/// Live text is on at launch.
|
||
pub(crate) fn install<S: 'static>(app: &mut rune::App<S>, place: Place) {
|
||
let spec = OverlaySpec {
|
||
name: "Hex live text",
|
||
size: SIZE,
|
||
// Placed for real each time it appears.
|
||
edge: ScreenEdge::Top,
|
||
margin: 0.0,
|
||
align: rune::Align::Center,
|
||
inset: 0.0,
|
||
interactive: false,
|
||
view,
|
||
}
|
||
.options(OverlayOptions {
|
||
prewarm: crate::labs::live_text(),
|
||
#[cfg(not(target_os = "macos"))]
|
||
display: crate::rune_hud::display(),
|
||
..Default::default()
|
||
});
|
||
let overlay = app.overlay(spec, Plate::default());
|
||
let shown = Arc::new(AtomicBool::new(false));
|
||
crate::live_text::watch(move |partial| {
|
||
let partial = partial.filter(|partial| !is_blank(partial));
|
||
let Some(Partial { stable, tentative }) = partial.cloned() else {
|
||
if shown.swap(false, Ordering::AcqRel) {
|
||
// Hidden from the same queue that shows it, so a recording
|
||
// that ends as its plate appears never leaves it showing.
|
||
let handle = overlay.clone();
|
||
overlay.update(move |plate, tx| {
|
||
plate.stable.clear();
|
||
plate.tentative.clear();
|
||
tx.instant();
|
||
handle.hide();
|
||
});
|
||
}
|
||
return;
|
||
};
|
||
let appearing = !shown.swap(true, Ordering::AcqRel);
|
||
let handle = overlay.clone();
|
||
overlay.update(move |plate, tx| {
|
||
plate.stable = stable;
|
||
plate.tentative = tentative;
|
||
tx.instant();
|
||
if appearing {
|
||
// Placed and shown after the new words, so it appears
|
||
// where it belongs with them already drawn.
|
||
handle.set_placement(Some(place().placement()));
|
||
handle.show();
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
/// The model's first update often has no words yet.
|
||
fn is_blank(partial: &Partial) -> bool {
|
||
partial.stable.trim().is_empty() && partial.tentative.trim().is_empty()
|
||
}
|
||
|
||
fn view(plate: &Plate, cx: &mut Cx<Plate>) -> El {
|
||
let p = Paint::new(cx.system_dark(), cx.env().scale);
|
||
let c = &p.k.c;
|
||
let root = row()
|
||
.key("live-text")
|
||
.w_full()
|
||
.h_full()
|
||
.center()
|
||
.px(4.0)
|
||
.hover_motion_within(Anim::INSTANT, Anim::INSTANT);
|
||
if plate.stable.trim().is_empty() && plate.tentative.trim().is_empty() {
|
||
return root;
|
||
}
|
||
// The newest words stay in view: the start gives way with "…".
|
||
let line = row()
|
||
.key("line")
|
||
.min_w(0.0)
|
||
.shrink()
|
||
.child(
|
||
text(plate.stable.trim().to_owned())
|
||
.key("stable")
|
||
.truncate_head()
|
||
.font(p.k.ty.ui)
|
||
.color(p.text()),
|
||
)
|
||
.children((!plate.tentative.trim().is_empty()).then(|| {
|
||
text(plate.tentative.clone())
|
||
.key("tentative")
|
||
.truncate()
|
||
.font(p.k.ty.ui)
|
||
.color(p.faint())
|
||
}));
|
||
root.child(
|
||
row()
|
||
.key("plate")
|
||
.h(PLATE_H)
|
||
.max_w(SIZE.0 - 8.0)
|
||
.px(14.0)
|
||
.center_y()
|
||
.radius(PLATE_H / 2.0)
|
||
.fill(c.bg_base)
|
||
.border(p.hair, c.border_base)
|
||
.child(line),
|
||
)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use rune::Runtime;
|
||
use rune::text::TextSystem;
|
||
|
||
use super::*;
|
||
|
||
const SHORT: &str = "So the plan for today";
|
||
const LONG: &str = "So the plan for today is to finish the release notes, then check the \
|
||
streaming numbers on the M4, and after lunch we can review the onboarding flow together";
|
||
|
||
fn runtime(stable: &str, tentative: &str, dark: bool) -> Runtime<Plate> {
|
||
let plate = Plate {
|
||
stable: stable.into(),
|
||
tentative: tentative.into(),
|
||
};
|
||
let mut rt = crate::rune_ui::offscreen::runtime(
|
||
plate,
|
||
view,
|
||
SIZE,
|
||
rune::Env {
|
||
system_dark: dark,
|
||
scale: 2.0,
|
||
},
|
||
TextSystem::new(rune_theme_opencode::FONTS, rune_theme_opencode::FAMILIES),
|
||
);
|
||
rt.settle_all();
|
||
rt.frame(0.0);
|
||
rt
|
||
}
|
||
|
||
fn rect(rt: &Runtime<Plate>, key: &str) -> Option<[f32; 4]> {
|
||
rt.elements()
|
||
.into_iter()
|
||
.find(|e| !e.exiting && e.key.as_deref() == Some(key))
|
||
.map(|e| e.rect)
|
||
}
|
||
|
||
#[test]
|
||
fn a_short_line_hugs_its_words_in_the_middle() {
|
||
let rt = runtime(SHORT, "", false);
|
||
let [x, y, w, h] = rect(&rt, "plate").expect("the plate draws");
|
||
assert!(w < SIZE.0 / 2.0, "the plate hugs a short line: {w}");
|
||
assert!((x + w / 2.0 - SIZE.0 / 2.0).abs() < 1.0, "centred: {x} {w}");
|
||
assert!((y + h / 2.0 - SIZE.1 / 2.0).abs() < 1.0, "centred: {y} {h}");
|
||
assert!(rect(&rt, "tentative").is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn a_long_line_stays_inside_the_overlay_on_one_line() {
|
||
for tentative in ["", " together with the team"] {
|
||
let rt = runtime(LONG, tentative, true);
|
||
let [x, _, w, h] = rect(&rt, "plate").unwrap();
|
||
assert!(x >= 0.0 && x + w <= SIZE.0, "inside: {x} {w}");
|
||
assert_eq!(h, PLATE_H);
|
||
let [line_x, _, line_w, _] = rect(&rt, "line").unwrap();
|
||
assert!(
|
||
line_x + line_w <= x + w,
|
||
"the words fit the plate: {line_x} {line_w}"
|
||
);
|
||
let [_, _, _, line] = rect(&rt, "stable").unwrap();
|
||
assert!(line < PLATE_H, "one line: {line}");
|
||
assert_eq!(rect(&rt, "tentative").is_some(), !tentative.is_empty());
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn a_spot_places_the_plate_just_past_the_hud() {
|
||
assert_eq!(
|
||
Spot::Edge(ScreenEdge::Bottom, 50.0).placement(),
|
||
OverlayPlacement::Edge {
|
||
edge: ScreenEdge::Bottom,
|
||
margin: 50.0 - PAD,
|
||
align: rune::Align::Center,
|
||
inset: 0.0,
|
||
}
|
||
);
|
||
let rect = |below| match (Spot::Global {
|
||
x: 700.0,
|
||
y: 100.0,
|
||
below,
|
||
})
|
||
.placement()
|
||
{
|
||
OverlayPlacement::Rect { x, y, width, .. } => (x, y, width),
|
||
other => panic!("{other:?}"),
|
||
};
|
||
// Centred on the HUD; the plate's top edge at the spot when hanging
|
||
// below it, its bottom edge at the spot when rising above it.
|
||
assert_eq!(rect(true), (700.0 - SIZE.0 / 2.0, 100.0 - PAD, SIZE.0));
|
||
assert_eq!(
|
||
rect(false),
|
||
(700.0 - SIZE.0 / 2.0, 100.0 - PAD - PLATE_H, SIZE.0)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn no_words_draw_nothing() {
|
||
let rt = runtime(" ", "", false);
|
||
assert!(rect(&rt, "plate").is_none());
|
||
let blank = |stable: &str, tentative: &str| {
|
||
is_blank(&Partial {
|
||
stable: stable.into(),
|
||
tentative: tentative.into(),
|
||
})
|
||
};
|
||
assert!(blank("", ""));
|
||
assert!(blank(" ", " "));
|
||
assert!(!blank("", " so"));
|
||
assert!(!blank("so", ""));
|
||
}
|
||
|
||
/// Renders the plate to `HEX_LIVE_TEXT_SNAPS/live-text-*.png` in both
|
||
/// appearances, to look at.
|
||
#[test]
|
||
#[ignore = "set HEX_LIVE_TEXT_SNAPS to a folder; needs a GPU"]
|
||
fn snapshots() {
|
||
let folder = std::path::PathBuf::from(std::env::var("HEX_LIVE_TEXT_SNAPS").unwrap());
|
||
let gpu = rune::render::Gpu::try_new(rune::render::Gpu::instance(), None).unwrap();
|
||
for (name, stable, tentative) in [
|
||
("short", SHORT, ""),
|
||
("long", LONG, ""),
|
||
("tentative", SHORT, " is to finish"),
|
||
] {
|
||
for dark in [false, true] {
|
||
let mut rt = runtime(stable, tentative, dark);
|
||
let (w, h) = ((SIZE.0 * 2.0) as u32, (SIZE.1 * 2.0) as u32);
|
||
let mut renderer = crate::rune_ui::offscreen::renderer(&gpu.device);
|
||
let target = crate::rune_ui::offscreen::target(&gpu.device, w, h);
|
||
renderer.upload_images(&gpu.device, &gpu.queue, &mut rt.images);
|
||
renderer.prepare(
|
||
&gpu.device,
|
||
&gpu.queue,
|
||
&mut rt.text.atlas,
|
||
&rt.instances,
|
||
(w, h),
|
||
);
|
||
let mut encoder = gpu.device.create_command_encoder(&Default::default());
|
||
// A desktop grey behind the clear overlay.
|
||
let backdrop = if dark { 0.08 } else { 0.62 };
|
||
renderer.draw(
|
||
&mut encoder,
|
||
&target.view,
|
||
[backdrop, backdrop, backdrop, 1.0],
|
||
);
|
||
target.copy(&mut encoder);
|
||
gpu.queue.submit([encoder.finish()]);
|
||
let theme = if dark { "dark" } else { "light" };
|
||
let path = folder.join(format!("live-text-{name}-{theme}.png"));
|
||
rune::render::write_png(&path, w, h, &target.read(&gpu.device)).unwrap();
|
||
}
|
||
}
|
||
}
|
||
}
|