Merge the Stop draft into the Record draft with one surface model

Integration of the two meeting HUD drafts, for review of the whole path:
t1609 at 776efee1e (Record handoff) and meeting-stop-motion at 6b11440f9
(Stop to finished). Neither draft is replaced by this branch.

Beyond resolving the two conflicted files this adds the recording host's
surface model (meeting_capsules/stage.rs): the outline and each layer are
tracks stepped every frame from their own position and speed, so a change
of state bends the motion instead of restarting it.
This commit is contained in:
Kit Langton
2026-11-17 21:45:04 -08:00
26 changed files with 2783 additions and 386 deletions
+16 -2
View File
@@ -894,10 +894,24 @@ Record (offer, menu bar "Record Meeting", Meetings pane, or voice command)
│ │ `either_track_can_interrupt_the_release_in_place` (synthetic levels)
│ └── "Microphone is silent" (warning) or, for its first 10 s, "Started
│ automatically" shows beside the meter
├── Hover -> the pill reveals a panel: Stop opposite the meter and time
│ in its header, then Copy new, Copy all, Copy agent prompt; pointer
├── Hover -> the pill reveals four full-width actions beside the header:
│ Stop nearest the meter, Copy new, Copy all, Copy agent prompt; pointer
│ leaving -> eases back to rest (a held press keeps it open). A bottom
│ corner opens upward, its header nearest the screen edge
├── Stop -> the icon, label and whitespace use the same 242 × 44 pt row
│ and hover/focus bounds as the copies. The plain arrow stays put;
│ dragging the meter band repositions, dragging a row does not.
│ A click queues one stop immediately. The pill stays open and says
│ “Stopping…” with its waveform and elapsed time until capture ends.
│ The worker closing its sources, not the click, switches the header to
│ “Transcribing…”. Publication brings back the copies and Close on the
│ same surface; it does not wait for notes or a minimum animation time.
│ Short titles keep the open recording header's height. Longer ones
│ wrap at their final width (up to three lines). The timer keeps its
│ baseline. Notes grow from the outer edge, past the copy rows, without
│ moving a copy button away from the pointer.
│ A recorder failure yields to the Meetings error instead of showing a
│ finished transcript. Check: `stop_handoff_frames` (offscreen Rune).
├── Drag -> follows the pointer; release -> snaps to the corner nearest
│ its centre and saves recording_indicator_corner (window settings too)
├── Copy new -> copies the turns not yet copied or pasted, through
+1
View File
@@ -1117,6 +1117,7 @@ const TRANSLATIONS: &[(&str, [&str; 6])] = &[
("Markdown not saved: {}", ["Nie zapisano Markdown: {}", "未保存 Markdown:{}", "Markdown を保存できませんでした: {}", "Markdown nicht gespeichert: {}", "No se guardó el Markdown: {}", "Файл Markdown не збережено: {}"]),
("Open", ["Otwórz", "打开", "開く", "Öffnen", "Abrir", "Відкрити"]),
("Finalizing…", ["Kończenie…", "正在完成…", "仕上げ中…", "Wird abgeschlossen…", "Finalizando…", "Завершення…"]),
("Stopping…", ["Zatrzymywanie…", "正在停止…", "停止中…", "Wird gestoppt…", "Deteniendo…", "Зупинення…"]),
("Interrupted", ["Przerwano", "已中断", "中断", "Unterbrochen", "Interrumpido", "Перервано"]),
("Search meetings", ["Szukaj spotkań", "搜索会议", "会議を検索", "Besprechungen suchen", "Buscar reuniones", "Пошук зустрічей"]),
("No meetings match.", ["Brak pasujących spotkań.", "没有匹配的会议。", "一致する会議はありません。", "Keine passenden Besprechungen.", "No hay reuniones que coincidan.", "Відповідних зустрічей немає."]),
+1
View File
@@ -814,6 +814,7 @@ const TRANSLATIONS: &[(&str, &str)] = &[
("Markdown not saved: {}", "Markdown non enregistré : {}"),
("Open", "Ouvrir"),
("Finalizing…", "Finalisation…"),
("Stopping…", "Arrêt en cours…"),
("Failed", "Échec"),
("Interrupted", "Interrompue"),
("Search meetings", "Rechercher des réunions"),
+1
View File
@@ -817,6 +817,7 @@ const TRANSLATIONS: &[(&str, &str)] = &[
("Markdown not saved: {}", "Markdown não salvo: {}"),
("Open", "Abrir"),
("Finalizing…", "Finalizando…"),
("Stopping…", "Parando…"),
("Failed", "Falhou"),
("Interrupted", "Interrompida"),
("Search meetings", "Buscar reuniões"),
+1
View File
@@ -810,6 +810,7 @@ const TRANSLATIONS: &[(&str, &str)] = &[
("Markdown not saved: {}", "Markdown не сохранён: {}"),
("Open", "Открыть"),
("Finalizing…", "Завершение…"),
("Stopping…", "Остановка…"),
("Failed", "Ошибка"),
("Interrupted", "Прервано"),
("Search meetings", "Поиск встреч"),
+2 -1
View File
@@ -1084,12 +1084,13 @@ impl Pump {
tracing::info!(%app, "the call ended; the recording continues until Stop");
}
}
ControllerEvent::Stopping => {}
ControllerEvent::Transcribing => self.meeting_state = MeetingMenuState::Transcribing,
ControllerEvent::Finished(manifest) => {
tracing::info!(id = %manifest.id, "meeting transcript ready");
self.meeting_state = MeetingMenuState::Idle;
}
ControllerEvent::NotesStarted | ControllerEvent::NotesFinished(_) => {}
ControllerEvent::NotesProgress(_) | ControllerEvent::NotesFinished(_) => {}
ControllerEvent::Failed { title, error } => {
tracing::error!(%title, %error, "meeting failed");
self.meeting_state = MeetingMenuState::Idle;
+3
View File
@@ -397,6 +397,9 @@ impl Pump {
"Recording “{title}”; `hex meetings stop` stops and transcribes it"
))
}
(Some(ControllerEvent::Stopping), true) => {
ControlReply::done("Stopping the meeting recording")
}
(Some(ControllerEvent::Transcribing | ControllerEvent::Finished(_)), true) => {
ControlReply::done("Stopped recording; transcribing the meeting")
}
+2 -1
View File
@@ -187,6 +187,7 @@ fn follow(event: &ControllerEvent, window: &rune::AppHandle<Ui>) {
shown.clone_from(chapters);
}
}
ControllerEvent::Stopping => {}
ControllerEvent::Transcribing => *state = MeetingMenuState::Transcribing,
ControllerEvent::Finished(manifest) => {
tracing::info!(id = %manifest.id, "meeting transcript ready");
@@ -219,7 +220,7 @@ fn follow(event: &ControllerEvent, window: &rune::AppHandle<Ui>) {
| ControllerEvent::Reminder { .. }
| ControllerEvent::ReminderWithdrawn { .. }
| ControllerEvent::CallEndedWithdrawn
| ControllerEvent::NotesStarted
| ControllerEvent::NotesProgress(_)
| ControllerEvent::NotesFinished(_) => {}
}
}
+56 -25
View File
@@ -27,6 +27,7 @@ use call_switch::{
};
mod call_switch;
mod publication;
pub(crate) enum ControllerCommand {
Record(MeetingCandidate, Option<OfferId>),
@@ -90,6 +91,9 @@ pub(crate) enum ControllerEvent {
SourceWarning {
warning: Option<TrackWarning>,
},
/// Stop requested; the capture worker may still be closing its sources.
Stopping,
/// Both sources have stopped. The worker is preparing the final transcript.
Transcribing,
/// `auto_stop` when the recording stops on its own after
/// [`crate::meeting::detection::AUTO_STOP_GRACE`] (Stop when the
@@ -111,7 +115,7 @@ pub(crate) enum ControllerEvent {
ImportFailed {
error: String,
},
NotesStarted,
NotesProgress(String),
NotesFinished(Box<meeting::MeetingManifest>),
}
@@ -138,12 +142,11 @@ struct ActiveRecording {
}
impl ActiveRecording {
/// Ends this recording and its call's snooze as a hand stop does: a call
/// app back after leaving it is a new call (Always record starts again).
/// Request a stop and end the snooze; the worker confirms when capture ends.
fn end(&self, detector: &mut MeetingDetector, events: &SyncSender<ControllerEvent>) {
if !self.stop.swap(true, Ordering::Relaxed) {
detector.recording_stopped();
let _ = events.send(ControllerEvent::Transcribing);
let _ = events.send(ControllerEvent::Stopping);
}
}
}
@@ -906,6 +909,7 @@ fn poll_recording(
}
meeting::RecordingUpdate::Transcribing => {
active.end(detector, events);
let _ = events.send(ControllerEvent::Transcribing);
}
}
}
@@ -918,23 +922,19 @@ fn poll_recording(
let active = recording
.take()
.ok_or_else(|| eyre!("recording disappeared"))?;
let event = match active.worker.join() {
Ok(Ok(manifest)) => {
if manifest.status == meeting::MeetingStatus::Complete && meeting::notes_wanted() {
start_notes(manifest.id.clone(), events);
}
ControllerEvent::Finished(Box::new(manifest))
match active
.worker
.join()
.unwrap_or_else(|_| Err(eyre!("meeting recorder panicked")))
{
Ok(manifest) => publication::finished(manifest, events),
Err(error) => {
let _ = events.send(ControllerEvent::Failed {
title: active.title,
error: error.to_string(),
});
}
Ok(Err(error)) => ControllerEvent::Failed {
title: active.title,
error: error.to_string(),
},
Err(_) => ControllerEvent::Failed {
title: active.title,
error: "meeting recorder panicked".into(),
},
};
let _ = events.send(event);
}
}
// Stopped and transcribing: detection waits, but whether the call app
@@ -1397,12 +1397,14 @@ fn detect_meeting(
/// whether generation succeeds or fails.
pub(super) fn start_notes(id: String, events: &SyncSender<ControllerEvent>) {
let finished = events.clone();
if meeting::spawn_summary(id, move |result| {
if let Ok(manifest) = result {
let _ = finished.send(ControllerEvent::NotesFinished(Box::new(manifest)));
}
let pending = id.clone();
if meeting::spawn_summary(id.clone(), move |result| {
let _ = finished.send(match result {
Ok(manifest) => ControllerEvent::NotesFinished(Box::new(manifest)),
Err(_) => ControllerEvent::NotesProgress(pending),
});
}) {
let _ = events.send(ControllerEvent::NotesStarted);
let _ = events.send(ControllerEvent::NotesProgress(id));
}
}
@@ -1582,6 +1584,35 @@ mod tests {
}
}
#[test]
fn stop_request_is_not_a_capture_stopped_acknowledgment() {
let (events, read) = mpsc::sync_channel(4);
let mut active = active_recording(None, false, None);
let (updates, worker) = mpsc::sync_channel(1);
let (finish, wait) = mpsc::channel();
active.worker = thread::spawn(move || {
wait.recv().unwrap();
Err(eyre!("fixture"))
});
active.updates = worker;
let mut detector = MeetingDetector::default();
active.end(&mut detector, &events);
active.end(&mut detector, &events);
assert!(active.stop.load(Ordering::Relaxed));
assert!(matches!(read.try_recv(), Ok(ControllerEvent::Stopping)));
assert!(read.try_recv().is_err());
updates
.send(meeting::RecordingUpdate::Transcribing)
.unwrap();
let mut active = Some(active);
let mut browser = BrowserWatch::new(ContextSnapshot::capture_for_meeting);
poll_recording(&mut active, &mut detector, &mut browser, &events).unwrap();
assert!(matches!(read.try_recv(), Ok(ControllerEvent::Transcribing)));
assert!(read.try_recv().is_err());
finish.send(()).unwrap();
assert!(active.unwrap().worker.join().unwrap().is_err());
}
#[test]
fn keep_recording_disarms_the_call_switch_stop_too() {
let (events, _received) = mpsc::sync_channel(4);
+12
View File
@@ -0,0 +1,12 @@
//! Publish the transcript before starting optional notes. Even an immediate
//! notes result can then only update an existing meeting, never race its show.
use super::{ControllerEvent, SyncSender, meeting};
pub(super) fn finished(manifest: meeting::MeetingManifest, events: &SyncSender<ControllerEvent>) {
let notes = (manifest.status == meeting::MeetingStatus::Complete && meeting::notes_wanted())
.then(|| manifest.id.clone());
let _ = events.send(ControllerEvent::Finished(Box::new(manifest)));
if let Some(id) = notes {
super::start_notes(id, events);
}
}
+217 -113
View File
@@ -56,14 +56,18 @@ use crate::meeting::detection::{MeetingCandidate, OfferId};
use crate::meeting::watcher::{ControllerCommand, ControllerEvent};
use crate::meeting::{self, MeetingManifest, TranscriptEntry};
mod handoff;
mod offer;
#[path = "meeting_capsules/offer/surface.rs"]
mod offer_surface;
mod panel;
mod stage;
mod throw;
mod waveform;
use panel::{agent_prompt, hex_command, ready, ready_summary, recording};
use panel::{
agent_prompt, hex_command, ready, ready_window_size, recording, recording_window_size,
};
/// The offer, call ended, and ready capsules.
const MEETING_PANEL_WIDTH: f32 = 420.0;
@@ -94,7 +98,8 @@ const PANEL_RADIUS: f32 = 13.0;
/// Around the open panel's rows.
const PANEL_PAD: f32 = 5.0;
const HEADER_HEIGHT: f32 = 36.0;
const ROW_HEIGHT: f32 = 36.0;
const ROW_HEIGHT: f32 = 44.0;
const OPEN_HEADER: f32 = REST_HEIGHT + ROW_HEIGHT;
/// Concentric with the panel across [`PANEL_PAD`].
const ROW_RADIUS: f32 = PANEL_RADIUS - PANEL_PAD;
/// A row's icon and label inset; titles and summaries share it.
@@ -105,21 +110,27 @@ const FIRST_ROW_GAP: f32 = 2.0;
const NOTICE_HEIGHT: f32 = 20.0;
/// The ready panel's summary: Apple Intelligence's two sentences.
const SUMMARY_LINES: usize = 3;
const TITLE_LINES: usize = 3;
const TITLE_INSET: f32 = (REST_HEIGHT - 20.) / 2.;
const RESULT_HEADER_MAX: f32 = REST_HEIGHT + TITLE_LINES as f32 * 20. + 2. * TITLE_INSET;
const SUMMARY_LINE: f32 = 19.5;
/// The recording capsule's window at its largest: the open panel with a
/// notice.
/// One transparent window with room for the finished panel's longest summary.
const RECORDING_WINDOW: (f32, f32) = (
PANEL_WIDTH + 2.0 * CAPSULE_INSET,
HEADER_HEIGHT
+ NOTICE_HEIGHT
RESULT_HEADER_MAX
+ SUMMARY_LINE * SUMMARY_LINES as f32
+ ROW_PX
+ FIRST_ROW_GAP
+ 3.0 * ROW_HEIGHT
+ FIRST_ROW_GAP
+ PANEL_PAD
+ 2.0 * CAPSULE_INSET,
);
/// The clip opens under the pointer and retargets when it leaves.
/// The finished meeting's title and summary grow the panel on this.
const RECORDING_OPEN: Spring = Spring::new(0.42, 0.0);
const RECORDING_CLOSE: Spring = Spring::new(0.38, 0.0);
/// A start this quick never says "Starting…": the offer contracts straight
/// into the live pill.
const PENDING_LABEL_AFTER: f64 = 0.18;
/// How long a copy says "Copied".
const COPIED_FEEDBACK: Duration = Duration::from_millis(1_500);
const OFFER_TIMEOUT: Duration = Duration::from_secs(20);
@@ -151,6 +162,9 @@ enum Kind {
auto_stop: bool,
},
Ready(Box<MeetingManifest>),
Finalizing {
duration_ms: u64,
},
/// An automatic recording while the recording indicator is off.
AutoStarted {
title: String,
@@ -227,9 +241,10 @@ impl PillModel {
}
ControllerEvent::OfferWithdrawn(_)
| ControllerEvent::ReminderWithdrawn { .. }
| ControllerEvent::Stopping
| ControllerEvent::Chapters(_)
| ControllerEvent::ImportFailed { .. }
| ControllerEvent::NotesStarted
| ControllerEvent::NotesProgress(_)
| ControllerEvent::NotesFinished(_) => {}
}
}
@@ -257,6 +272,8 @@ enum LiveCopy {
/// transcript by the ticker, or the ready meeting's when it shows.
#[derive(Default)]
struct Live {
/// A swipe within a wide action row is not a click, even on release inside it.
row_swiped: bool,
entries: Vec<TranscriptEntry>,
/// What Copy new would copy now.
pending: meeting::PendingDelta,
@@ -280,6 +297,10 @@ struct Capsule {
/// Arms another 20 s if Cancel returns to an offer whose timer already fired.
rearm_offer: Option<offer::After>,
presentation: offer_surface::Presentation,
/// The recording host's outline and layers in motion.
stage: stage::Stage,
/// When the pointer opened the recording, for its rows' order of arrival.
opened: Option<f64>,
live: Live,
waveform: Option<Box<waveform::Listening>>,
commands: SyncSender<ControllerCommand>,
@@ -292,6 +313,8 @@ struct Capsule {
/// The pointer is over the recording pill (or holding it), or over the
/// ready panel.
hovered: bool,
/// The command was accepted, but the worker has not reported capture stopped.
stopping: bool,
/// A timeout arrived while the ready panel was hovered or the offer's
/// choices were open. Leaving closes the former; Cancel rearms the latter.
expired: bool,
@@ -343,8 +366,8 @@ impl Capsule {
}
if let (Some(resize), Some(Kind::Recording(shown))) = (&self.resize, &self.kind) {
resize(recording_window_size(
self.hovered,
panel::rest_width(shown),
self.hovered || self.stopping,
Some(shown),
));
}
}
@@ -387,6 +410,7 @@ impl Capsule {
&& ready.id == manifest.id
{
*ready = manifest;
#[cfg(target_os = "windows")]
if let Some(resize) = &self.resize {
resize(ready_window_size(ready));
}
@@ -510,8 +534,9 @@ impl Capsule {
return self.presentation.window();
}
match &self.kind {
Some(Kind::Finalizing { .. }) => RECORDING_WINDOW,
Some(Kind::Recording(shown)) => {
recording_window_size(self.hovered, panel::rest_width(shown))
recording_window_size(self.hovered || self.stopping, Some(shown))
}
Some(Kind::Ready(manifest)) => ready_window_size(manifest),
Some(Kind::Offer(..)) => self.presentation.window(),
@@ -577,39 +602,6 @@ impl Capsule {
}
}
/// The recording capsule's window. On Windows it is the size of what it
/// draws: the resting pill (including its timer and any notice), then the
/// open panel. Elsewhere it stays at its largest, and
/// only the `.hit()` pill takes the pointer.
#[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
fn recording_window_size(open: bool, rest_width: f32) -> (f32, f32) {
#[cfg(target_os = "windows")]
if !open {
let width = rest_width + 2.0 * CAPSULE_INSET;
return (width, REST_HEIGHT + 2.0 * CAPSULE_INSET);
}
RECORDING_WINDOW
}
/// The ready panel's window: its header, a summary while there is one or one
/// is being written, and the three copies.
fn ready_window_size(manifest: &MeetingManifest) -> (f32, f32) {
let summary = if ready_summary(manifest).is_some() {
SUMMARY_LINE * SUMMARY_LINES as f32 + ROW_PX + FIRST_ROW_GAP
} else {
0.0
};
(
PANEL_WIDTH + 2.0 * CAPSULE_INSET,
HEADER_HEIGHT
+ summary
+ 3.0 * ROW_HEIGHT
+ FIRST_ROW_GAP
+ PANEL_PAD
+ 2.0 * CAPSULE_INSET,
)
}
/// Where a corner's capsule window sits: its edge and margin, and its
/// alignment and inset along that edge, after a drag of (dx, dy) points.
fn corner_placement(
@@ -677,6 +669,8 @@ pub(crate) struct MeetingCapsules {
/// Bumped whenever the panel shows something new, so a stale timeout
/// doesn't close it.
generation: Arc<AtomicU64>,
/// Which finished/finalizing meeting still occupies the recording window.
finishing: Option<String>,
}
/// The recording capsule, rebuilt from its [`PillModel`] and the live Show
@@ -689,17 +683,6 @@ struct Pill {
}
impl Pill {
fn apply(&self, event: &ControllerEvent, inherit: bool) {
{
let mut model = self.lock();
model.apply(event, Instant::now());
self.reconcile_locked(&mut model, inherit);
}
if let ControllerEvent::RecordingStarted { id, .. } = event {
self.tick(id.clone());
}
}
fn keep_recording(&self) {
self.lock().keep_recording();
self.reconcile();
@@ -747,11 +730,12 @@ impl Pill {
place_capsule(&self.handle, corner, 0.0, 0.0);
// Windows: a shown pill starts at rest.
self.handle
.resize(recording_window_size(false, panel::rest_width(&recording)));
.resize(recording_window_size(false, Some(&recording)));
#[cfg(target_os = "windows")]
self.handle.set_input(rune::OverlayInput::All);
self.handle.update(move |capsule, tx| {
capsule.presentation = Default::default();
capsule.stage = Default::default();
capsule.corner = corner;
capsule.start_recording(recording, tx);
});
@@ -836,6 +820,8 @@ impl MeetingCapsules {
more_open: false,
rearm_offer: None,
presentation: Default::default(),
stage: Default::default(),
opened: None,
live: Live::default(),
waveform: None,
commands: commands.clone(),
@@ -844,6 +830,7 @@ impl MeetingCapsules {
resize: None,
choose: choose.clone(),
hovered: false,
stopping: false,
expired: false,
corner: MeetingIndicatorCorner::default(),
shift: None,
@@ -892,7 +879,7 @@ impl MeetingCapsules {
handle: overlay(
app,
"Hex meeting recording",
recording_window_size(false, REST_WIDTH),
recording_window_size(false, None),
true,
),
model: Arc::default(),
@@ -920,6 +907,7 @@ impl MeetingCapsules {
handoff: Default::default(),
pill,
generation: Arc::default(),
finishing: None,
}
}
@@ -932,7 +920,7 @@ impl MeetingCapsules {
} else if route == offer::Route::Close {
self.close_panel();
}
self.pill.apply(event, inherit);
self.advance_handoff(event, inherit);
match event {
ControllerEvent::Reminder { meeting, automatic } => {
// Unanswered, it closes without recording or snoozing
@@ -977,6 +965,10 @@ impl MeetingCapsules {
ControllerEvent::Starting(_) | ControllerEvent::Transcribing
if route != offer::Route::Ordinary => {}
ControllerEvent::Starting(_) | ControllerEvent::Transcribing => self.close_panel(),
ControllerEvent::Stopping => self.pill.handle.update(|c, tx| {
c.mark_stopping();
c.stir(tx);
}),
ControllerEvent::RecordingStarted {
title, automatic, ..
} => {
@@ -1009,10 +1001,10 @@ impl MeetingCapsules {
});
}
ControllerEvent::Finished(manifest) => {
self.show_panel(Kind::Ready(manifest.clone()), Some(READY_TIMEOUT));
let panel = self.finish_meeting(manifest);
// Copy new's hint reads the final transcript, off the main
// thread.
let (panel, id) = (self.panel.clone(), manifest.id.clone());
let id = manifest.id.clone();
std::thread::spawn(move || {
let entries = match meeting::TranscriptReader::default().read(&id) {
Ok(entries) => entries,
@@ -1032,15 +1024,19 @@ impl MeetingCapsules {
}
ControllerEvent::NotesFinished(manifest) => {
let manifest = manifest.clone();
self.panel
.update(move |capsule, _| capsule.refresh_ready(manifest));
let panel = if self.finishing.as_ref() == Some(&manifest.id) {
&self.pill.handle
} else {
&self.panel
};
panel.update(move |capsule, _| capsule.refresh_ready(manifest));
}
ControllerEvent::NotesProgress(id) => self.notes_progress(id),
ControllerEvent::Retitled { .. }
| ControllerEvent::SourceWarning { .. }
| ControllerEvent::Failed { .. }
| ControllerEvent::ImportFailed { .. }
| ControllerEvent::Chapters(_)
| ControllerEvent::NotesStarted => {}
| ControllerEvent::Chapters(_) => {}
}
}
@@ -1089,6 +1085,8 @@ impl MeetingCapsules {
panel.update(move |capsule, tx| {
capsule.kind = Some(kind);
capsule.presentation = presentation;
capsule.stage = Default::default();
capsule.opened = None;
capsule.more_open = false;
capsule.set_offer_timer(rearm);
capsule.live = Live::default();
@@ -1116,25 +1114,7 @@ impl MeetingCapsules {
});
}
if let Some(timeout) = timeout {
let (panel, current) = (self.panel.clone(), self.generation.clone());
std::thread::spawn(move || {
std::thread::sleep(timeout);
if current.load(Ordering::SeqCst) == generation {
panel.update(move |capsule, _| {
// Checked again when applied: a newer capsule may
// have been shown since.
if current.load(Ordering::SeqCst) != generation {
return;
}
// A ready panel waits for the pointer to leave it.
if capsule.hovered && matches!(capsule.kind, Some(Kind::Ready(_))) {
capsule.expired = true;
return;
}
capsule.close();
});
}
});
self.timeout(self.panel.clone(), generation, timeout);
}
}
@@ -1212,28 +1192,11 @@ fn dismiss_button(p: Paint) -> El {
.key("dismiss")
}
/// The overlay's frame hook: steps a glide into its corner, a frame at a
/// time, until it rests, and keeps a recording's waveform fed.
/// The overlay's frame hook: steps the surface, and a glide into its corner,
/// a frame at a time until they rest, and keeps a recording's waveform fed.
fn poll(capsule: &mut Capsule, now: f64, tx: &mut Tx) -> bool {
let changed = waveform::poll(capsule, now, tx);
if capsule.presentation.step_handoff(
matches!(capsule.kind, Some(Kind::Recording(_))),
capsule.reduced.get(),
now,
) {
tx.instant();
tx.wake_after(Duration::ZERO);
return true;
}
if matches!(capsule.kind, Some(Kind::Offer(..)))
&& capsule
.presentation
.step(capsule.more_open, capsule.reduced.get(), now)
{
tx.instant();
tx.wake_after(Duration::ZERO);
return true;
}
let mut changed = waveform::poll(capsule, now, tx);
changed |= capsule.step_stage(now, tx);
if !capsule.throw.gliding() {
return changed;
}
@@ -1248,6 +1211,128 @@ fn poll(capsule: &mut Capsule, now: f64, tx: &mut Tx) -> bool {
changed
}
impl Capsule {
/// Where the surface is heading for what the capsule shows now, and
/// whether its outline only follows the offer's own pages.
fn stage_target(&mut self, now: f64) -> Option<(stage::Target, bool)> {
use stage::{Outline, Target};
let pill = |w: f32| Outline {
w,
h: REST_HEIGHT,
radius: REST_HEIGHT / 2.0,
dark: 1.0,
};
let panel = |h: f32| Outline {
w: PANEL_WIDTH,
h,
radius: PANEL_RADIUS,
dark: 1.0,
};
let none = Target {
outline: pill(REST_WIDTH),
offer: false,
pending: None,
meter: false,
actions: None,
stop: true,
};
let target = match &self.kind {
Some(Kind::Offer(..)) if self.presentation.departing() => Target {
pending: Some(self.presentation.begun(now) + PENDING_LABEL_AFTER),
..none
},
Some(Kind::Offer(..)) => {
let target = Target {
outline: self.presentation.outline(self.reduced.get()),
offer: true,
..none
};
return Some((target, true));
}
Some(Kind::Recording(shown)) => {
let open = self.hovered || self.stopping;
if !open {
self.opened = None;
}
Target {
outline: if open {
panel(panel::open_height(shown))
} else {
pill(panel::rest_width(shown))
},
meter: true,
actions: open.then(|| *self.opened.get_or_insert(now)),
..none
}
}
// Capture has ended: Stop leaves, and the surface finishes its
// way to the open panel the finished meeting's layout grows from.
Some(Kind::Finalizing { .. } | Kind::Ready(_)) => Target {
outline: panel(panel::open_height_without_notice()),
meter: true,
actions: Some(self.opened.unwrap_or(f64::MIN)),
stop: false,
..none
},
_ => return None,
};
Some((target, false))
}
/// Steps the surface toward what the capsule shows; true while it moves.
fn step_stage(&mut self, now: f64, tx: &mut Tx) -> bool {
let reduced = self.reduced.get();
let paging = matches!(self.kind, Some(Kind::Offer(..)))
&& !self.presentation.departing()
&& self.presentation.step(self.more_open, reduced, now);
let Some((target, follow)) = self.stage_target(now) else {
self.stage = Default::default();
self.opened = None;
return false;
};
let moving = if follow {
self.stage.follow(&target, now);
if paging {
tx.instant();
}
paging
} else {
self.stage.step(&target, reduced, now)
};
if matches!(self.kind, Some(Kind::Recording(_))) {
self.presentation.arrived(&self.stage);
}
if moving {
tx.wake_after(Duration::ZERO);
}
moving && (follow || !self.stage.idling())
}
/// The surface as it rests for what the capsule shows now.
#[cfg(test)]
fn settle_stage(&mut self, now: f64) {
if self.hovered || self.stopping {
self.opened = Some(now - 10.0);
}
self.presentation.backdate(now - 10.0);
match self.stage_target(now) {
Some((target, _)) => self.stage.land(&target, now),
None => self.stage = Default::default(),
}
if matches!(self.kind, Some(Kind::Recording(_))) {
self.presentation.arrived(&self.stage);
}
}
/// A handler changed what the capsule shows: the surface starts toward
/// it in this frame, not at the next poll.
fn stir(&mut self, tx: &mut Tx) {
let now = tx.clock();
self.step_stage(now, tx);
tx.wake_after(Duration::ZERO);
}
}
fn view(capsule: &Capsule, cx: &mut Cx<Capsule>) -> El {
capsule.reduced.set(cx.is_reduced_motion());
view_body(capsule, cx).hover_motion_within(Anim::INSTANT, Anim::INSTANT)
@@ -1255,8 +1340,10 @@ fn view(capsule: &Capsule, cx: &mut Cx<Capsule>) -> El {
fn view_body(capsule: &Capsule, cx: &mut Cx<Capsule>) -> El {
// Recording and its summary stay dark; offers and reminders follow the host.
let dark =
matches!(capsule.kind, Some(Kind::Recording(_) | Kind::Ready(_))) || cx.system_dark();
let dark = matches!(
capsule.kind,
Some(Kind::Recording(_) | Kind::Finalizing { .. } | Kind::Ready(_))
) || cx.system_dark();
let p = Paint::new(dark, cx.env().scale);
if let Some(el) = offer_surface::transition(
capsule,
@@ -1270,6 +1357,7 @@ fn view_body(capsule: &Capsule, cx: &mut Cx<Capsule>) -> El {
};
let (dot, title, subtitle, actions) = match kind {
Kind::Recording(shown) => return recording(p, capsule, shown),
Kind::Finalizing { duration_ms } => return panel::finalizing(p, capsule, *duration_ms),
Kind::AutoStarted { title } => (
p.danger(),
tr("Recording automatically").to_owned(),
@@ -1594,6 +1682,8 @@ mod tests {
more_open,
rearm_offer: None,
presentation,
stage: Default::default(),
opened: None,
live: Live::default(),
waveform: None,
commands,
@@ -1602,6 +1692,7 @@ mod tests {
resize: None,
choose: Arc::new(move |choice| saved.lock().unwrap().push(choice)),
hovered: false,
stopping: false,
expired: false,
corner: MeetingIndicatorCorner::TopRight,
shift: None,
@@ -1615,6 +1706,9 @@ mod tests {
scale: 2.0,
};
let mut rt = crate::rune_ui::offscreen::runtime(capsule, view, size, env, text);
// The native overlay polls each frame; here only the surface steps,
// so no test reads the wall clock or the capture meter.
rt.poll = Some(|c: &mut Capsule, now, tx: &mut Tx| c.step_stage(now, tx));
rt.frame(0.0);
(rt, received, chosen)
}
@@ -1647,14 +1741,18 @@ mod tests {
}
}
fn advance_offer(rt: &mut Runtime<Capsule>, now: f64) {
rt.update(|c, tx| {
poll(c, now, tx);
tx.instant();
});
fn advance_offer(rt: &mut Runtime<Capsule>, _: f64) {
rt.frame(1.0 / 60.0);
}
/// Lands the hand-stepped surface, as `settle_all` lands Rune's tracks.
fn settle_stage(rt: &mut Runtime<Capsule>) {
rt.update(|c, tx| {
let now = tx.clock();
c.settle_stage(now);
});
}
#[test]
fn the_offer_menu_stays_usable_past_the_unanswered_deadline() {
let (mut rt, commands, chosen) = runtime(offer(slack_huddle()), false, true, PANEL);
@@ -2046,6 +2144,7 @@ mod tests {
let (x, y) = rt.find("pill").unwrap();
rt.pointer_move(x, y);
rt.frame(0.0);
settle_stage(rt);
rt.settle_all();
rt.frame(0.0);
}
@@ -2060,6 +2159,7 @@ mod tests {
span_ms: 4 * 60_000 + 59_000,
};
});
settle_stage(&mut rt);
rt.settle_all();
rt.frame(0.0);
// At rest, the meter and time, no actions.
@@ -2239,7 +2339,7 @@ mod tests {
}));
});
rt.frame(0.0);
let (x, y) = rt.find("header").unwrap();
let (x, y) = rt.find("meta").unwrap();
rt.pointer_move(x, y);
rt.pointer_down(x, y);
rt.pointer_move(x - 20.0, y + 30.0);
@@ -2390,6 +2490,7 @@ mod tests {
tx.instant();
});
let outer = |rt: &mut Runtime<Capsule>, window: (f32, f32)| {
settle_stage(rt);
rt.settle_all();
rt.frame(0.0);
let [x, y, _, h] = rt
@@ -2694,6 +2795,7 @@ mod tests {
let kind = call_ended();
assert_eq!(panel_width(&kind), CALL_ENDED.0);
let (mut rt, _, _) = runtime(kind, false, false, CALL_ENDED);
settle_stage(&mut rt);
rt.settle_all();
rt.frame(0.0);
let title = rt
@@ -2713,6 +2815,7 @@ mod tests {
include!("meeting_capsules/motion_fixture.rs");
include!("meeting_capsules/offer/proof.rs");
include!("meeting_capsules/replay_fixture.rs");
/// No `--snap` scene draws an overlay, so this renders the capsules to
/// PNGs in `HEX_CAPSULE_SNAPS` for review; without it, or a GPU, it skips.
@@ -2897,6 +3000,7 @@ mod tests {
rt: &mut Runtime<Capsule>,
size: (f32, f32),
) -> (u32, u32, Vec<u8>) {
settle_stage(rt);
rt.settle_all();
rt.frame(0.0);
let (w, h) = ((size.0 * 2.0) as u32, (size.1 * 2.0) as u32);
+160
View File
@@ -0,0 +1,160 @@
//! Ownership of the surface between the stop command and final publication.
use super::*;
impl Capsule {
pub(super) fn request_stop(&mut self) {
if !self.stopping
&& matches!(self.kind, Some(Kind::Recording(_)))
&& self.send(ControllerCommand::Stop)
{
self.mark_stopping();
}
}
pub(super) fn mark_stopping(&mut self) {
if matches!(self.kind, Some(Kind::Recording(_))) {
self.stopping = true;
#[cfg(target_os = "windows")]
self.fit_recording_window();
}
}
pub(super) fn capture_stopped(&mut self) {
if let Some(Kind::Recording(r)) = &self.kind {
self.kind = Some(Kind::Finalizing {
duration_ms: r.started.elapsed().as_millis() as u64,
});
#[cfg(target_os = "windows")]
if let Some(resize) = &self.resize {
resize((
RECORDING_WINDOW.0,
OPEN_HEADER + 3. * ROW_HEIGHT + FIRST_ROW_GAP + PANEL_PAD + 2. * CAPSULE_INSET,
));
}
}
}
pub(super) fn published(&mut self, manifest: Box<MeetingManifest>) {
self.live = Live::default();
self.kind = Some(Kind::Ready(manifest));
}
}
impl MeetingCapsules {
pub(super) fn advance_handoff(&mut self, event: &ControllerEvent, inherit: bool) {
// A new panel supersedes an old summary, and failure yields to the
// host's failure UI. Notes never take ownership or show a window.
if matches!(
event,
ControllerEvent::Starting(_)
| ControllerEvent::RecordingStarted { .. }
| ControllerEvent::Reminder { .. }
| ControllerEvent::Offer(..)
| ControllerEvent::Failed { .. }
) && self.finishing.take().is_some()
{
self.generation.fetch_add(1, Ordering::SeqCst);
self.pill.handle.update(|c, _| c.kind = None);
self.pill.handle.hide();
}
if let Some(id) = self.pill.apply(event, inherit) {
self.finishing = Some(id);
if matches!(event, ControllerEvent::Transcribing) {
self.pill.handle.update(|c, tx| {
c.capture_stopped();
c.stir(tx);
});
}
}
}
pub(super) fn notes_progress(&self, id: &str) {
let handle = if self.finishing.as_deref() == Some(id) {
&self.pill.handle
} else {
&self.panel
};
let id = id.to_owned();
handle.update_if(move |c, _| {
let Some(Kind::Ready(m)) = &c.kind else {
return false;
};
#[cfg(target_os = "windows")]
if m.id == id
&& let Some(resize) = &c.resize
{
resize(ready_window_size(m));
}
m.id == id
});
}
pub(super) fn finish_meeting(&mut self, manifest: &MeetingManifest) -> OverlayHandle<Capsule> {
if self.finishing.as_ref() != Some(&manifest.id) {
self.show_panel(Kind::Ready(Box::new(manifest.clone())), Some(READY_TIMEOUT));
return self.panel.clone();
}
let handle = self.pill.handle.clone();
let finished = Box::new(manifest.clone());
#[cfg(target_os = "windows")]
handle.resize(ready_window_size(&finished));
handle.update(move |c, tx| {
c.published(finished);
c.stir(tx);
});
let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
self.timeout(handle.clone(), generation, READY_TIMEOUT);
handle
}
}
impl Pill {
fn apply(&self, event: &ControllerEvent, inherit: bool) -> Option<String> {
// Relinquish the visible pill under the same lock as the ticker, so
// its last reconciliation cannot hide or restore a finalizing surface.
let mut model = self.lock();
let retain = match event {
ControllerEvent::Transcribing => model.shown.take(),
ControllerEvent::Finished(m) if model.shown.as_ref() == Some(&m.id) => {
model.shown.take()
}
_ => None,
};
model.apply(event, Instant::now());
self.reconcile_locked(&mut model, inherit);
drop(model);
if let ControllerEvent::RecordingStarted { id, .. } = event {
self.tick(id.clone());
}
retain
}
}
impl MeetingCapsules {
pub(super) fn timeout(
&self,
panel: OverlayHandle<Capsule>,
generation: u64,
timeout: Duration,
) {
let current = self.generation.clone();
std::thread::spawn(move || {
std::thread::sleep(timeout);
if current.load(Ordering::SeqCst) == generation {
panel.update(move |capsule, _| {
// Checked again when applied: a newer capsule may
// have been shown since.
if current.load(Ordering::SeqCst) != generation {
return;
}
// A ready panel waits for the pointer to leave it.
if capsule.hovered && matches!(capsule.kind, Some(Kind::Ready(_))) {
capsule.expired = true;
return;
}
capsule.close();
});
}
});
}
}
+560 -3
View File
@@ -40,6 +40,7 @@ fn recording_motion_frames() {
span_ms: 64_000,
};
});
settle_stage(&mut rt);
rt.settle_all();
rt.frame(0.0);
let mut renderer = offscreen::renderer(&gpu.device);
@@ -132,6 +133,151 @@ fn fixture_scope(capsule: &mut Capsule) {
capsule.waveform = Some(Box::new(wave));
}
/// Replay a Stop with a controlled controller/worker delay. This drives Rune's
/// actual press, layout, springs, text and recording compositor, not a movie of
/// the desktop. No controller thread, capture, audio device or settings store.
#[test]
fn stop_handoff_frames() {
use crate::rune_ui::offscreen;
use std::fmt::Write;
let Some(folder) = std::env::var_os("HEX_STOP_FRAMES") else {
return;
};
let folder = std::path::PathBuf::from(folder);
let gpu = rune::render::Gpu::try_new(rune::render::Gpu::instance(), None).unwrap();
let selected = std::env::var("HEX_STOP_CASE").ok();
for (name, stopped, published, notes, long, failed) in [
("short", 53, 55, 58, false, false),
("delayed", 68, 108, 138, false, false),
("localized", 60, 86, 118, true, false),
("failure", 60, 100, 118, false, true),
] {
if selected.as_deref().is_some_and(|s| s != name) {
continue;
}
let dir = folder.join(name);
std::fs::create_dir_all(&dir).unwrap();
let size = (RECORDING.0, RECORDING.1.ceil());
let (w, h) = ((size.0 * 2.) as u32, (size.1 * 2.) as u32);
let (mut rt, commands, _) = runtime(live_recording("ready-snap"), false, false, size);
rt.transparent = true;
rt.update(|c, tx| {
c.live.entries = call();
c.corner = MeetingIndicatorCorner::TopRight;
tx.instant();
});
rt.frame(0.);
let mut renderer = offscreen::renderer(&gpu.device);
let target = offscreen::target(&gpu.device, w, h);
let mut ink = waveform::Ink::default();
let mut trace = String::from("frame,key,x,y,w,h\n");
let mut pointer_trace = String::from("frame,x,y,cursor\n");
let mut point = None;
let start = Instant::now();
rt.state.waveform = Some(Box::new(waveform::Listening::new(start)));
for frame in 0..180 {
if let Some(Kind::Recording(shown)) = &mut rt.state.kind {
shown.started = Instant::now() - Duration::from_secs(258);
rt.state.waveform.as_mut().unwrap().sample(
start + Duration::from_secs_f64(frame as f64 / 60.),
fixture_levels(frame),
);
}
match frame {
12 => {
point = Some((225., 22.));
rt.pointer_move(225., 22.);
}
32 | 47 => {
let (x, y) = rt.find("stop").unwrap();
point = Some((x, y));
rt.pointer_move(x, y);
}
48 => {
let (x, y) = rt.find("stop").unwrap();
point = Some((x, y));
rt.pointer_down(x, y);
rt.pointer_up(x, y);
}
52 => rt.update(|c, _| c.mark_stopping()),
62 => {
point = None;
rt.pointer_leave();
}
f if f == stopped => rt.update(|c, _| c.capture_stopped()),
f if f == published && failed => rt.update(|c, tx| {
c.kind = None;
tx.instant();
}), // host opens Meetings with the failure
f if f == published => rt.update(|c, _| {
let Kind::Ready(mut m) = ready_transcript() else {
unreachable!()
};
m.duration_ms = Some(258_000);
if long {
m.title =
"Planification trimestrielle — lancement et préparation des équipes"
.into();
}
c.published(m);
}),
f if f == notes && !failed => rt.update(|c, _| {
let Kind::Ready(mut m) = ready_summarized() else {
unreachable!()
};
m.duration_ms = Some(258_000);
if long {
m.notes.as_mut().unwrap().title =
"Planification trimestrielle — lancement et préparation des équipes"
.into();
}
c.refresh_ready(m);
}),
_ => (),
}
rt.frame(1. / 60.);
if let Some((x, y)) = point {
writeln!(pointer_trace, "{frame},{x},{y},{:?}", rt.cursor()).unwrap();
}
if frame == 48 {
assert!(matches!(commands.try_recv(), Ok(ControllerCommand::Stop)));
}
for key in [
"pill",
"elapsed",
"stop",
"header",
"meeting-listening-field",
"title",
"summary",
"copy-new",
"copy-all",
"copy-prompt",
] {
if let Some(([x, y, w, h], _)) = rt.presented(key) {
writeln!(trace, "{frame},{key},{x},{y},{w},{h}").unwrap();
}
}
let rgba = paint_recording(&gpu, &mut renderer, &target, &mut rt, &mut ink);
// A retired hit target can still paint. Compare its trailing
// hover fill against the bare panel gutter on that scanline.
if frame == 47 || frame == 48 {
let scan = ((CAPSULE_INSET + REST_HEIGHT + ROW_HEIGHT / 2.) * 2.) as usize;
let pixel = |x: usize| rgba[4 * (scan * w as usize + x)];
assert_eq!(
pixel(460) != pixel(506),
frame == 47,
"Stop glyph at {frame}"
);
}
rune::render::write_png(&dir.join(format!("{frame:03}.png")), w, h, &rgba).unwrap();
}
std::fs::write(dir.join("trace.csv"), trace).unwrap();
std::fs::write(dir.join("pointer.csv"), pointer_trace).unwrap();
assert!(commands.try_recv().is_err(), "one Stop per handoff");
}
}
#[test]
fn a_light_host_draws_the_dark_recording_from_the_first_frame() {
use crate::rune_ui::offscreen;
@@ -253,6 +399,414 @@ fn paint_recording(
target.read(&gpu.device)
}
#[test]
fn stop_hits_its_center_edges_and_corners_but_not_its_neighbors() {
use MeetingIndicatorCorner::*;
for corner in [TopLeft, TopRight, BottomLeft, BottomRight] {
let (mut rt, commands, _) = runtime(live_recording("hit"), false, true, RECORDING);
rt.update(move |c, tx| {
c.corner = corner;
tx.instant();
});
rt.frame(0.);
open_recording(&mut rt);
let ([x, y, w, h], _) = rt.presented("stop").unwrap();
assert!(w >= 44. && h >= 44., "{corner:?}: {w}×{h}");
let ([_, cy, _, ch], _) = rt.presented("copy-new").unwrap();
assert!(y + h <= cy || y >= cy + ch);
let click = |rt: &mut Runtime<Capsule>, px, py| {
rt.pointer_down(px, py);
rt.pointer_up(px, py);
rt.frame(1. / 60.);
};
for (px, py) in [
(x - 0.5, y + h / 2.),
(x + w + 0.5, y + h / 2.),
(x + w / 2., y - 0.5),
(x + w / 2., y + h + 0.5),
] {
click(&mut rt, px, py);
assert!(commands.try_recv().is_err());
}
for px in [x + 0.25, x + w / 2., x + w - 0.25] {
for py in [y + 0.25, y + h / 2., y + h - 0.25] {
click(&mut rt, px, py);
assert!(
matches!(commands.try_recv(), Ok(ControllerCommand::Stop)),
"{corner:?} {px},{py} in {x},{y} {w}×{h}"
);
click(&mut rt, px, py);
assert!(commands.try_recv().is_err());
assert!(rt.find("elapsed").is_some());
rt.update(|c, tx| {
c.stopping = false;
c.hovered = true;
tx.instant();
});
rt.frame(0.);
}
}
rt.pointer_leave();
rt.frame(0.);
settle_stage(&mut rt);
rt.settle_all();
rt.frame(0.);
click(&mut rt, x + w / 2., y + h / 2.);
assert!(rt.find("stop").is_none() && commands.try_recv().is_err());
}
}
#[test]
fn stop_is_one_named_action_for_keyboard_and_accessibility() {
use rune::accesskit::Action;
for keyboard in [true, false] {
let (mut rt, commands, _) = runtime(live_recording("keys"), false, true, RECORDING);
assert!(!rt.accessibility_action("stop", Action::Click, None));
open_recording(&mut rt);
if keyboard {
assert!(rt.accessibility_action("stop", Action::Focus, None));
rt.frame(0.);
let space = rune::KeyEvent {
key: rune::Key::Text(" ".into()),
mods: Default::default(),
};
rt.key(space.clone());
rt.key_up(space);
} else {
assert!(rt.accessibility_action("stop", Action::Click, None));
}
rt.frame(0.);
assert!(matches!(commands.try_recv(), Ok(ControllerCommand::Stop)));
assert!(!rt.accessibility_action("stop", Action::Click, None));
assert!(commands.try_recv().is_err());
}
}
#[test]
fn localized_action_rows_share_their_geometry_and_arrow_in_every_corner() {
use crate::desktop::i18n;
use MeetingIndicatorCorner::*;
for &(code, _) in i18n::LANGUAGE_CHOICES.iter().filter(|(c, _)| c.is_some()) {
i18n::apply(code); // thread-local in tests, never a settings write
for corner in [TopLeft, TopRight, BottomLeft, BottomRight] {
let (mut rt, _, _) = runtime(live_recording("rows"), false, true, RECORDING);
rt.update(move |c, tx| {
c.corner = corner;
c.live.entries = call();
c.copy_new = Some(Arc::new(|_| {}));
tx.instant()
});
rt.frame(0.);
let ([_, _, w, h], _) = rt.presented("pill").unwrap();
assert_eq!((w, h), (148., 36.));
assert!(rt.find("stop").is_none());
open_recording(&mut rt);
for (key, name) in [
("stop", "Stop"),
("copy-new", "Copy new"),
("copy-all", "Copy all"),
("copy-prompt", "Copy agent prompt"),
] {
let nodes = rt.elements();
let (idx, row) = nodes
.iter()
.enumerate()
.find(|(_, e)| e.key.as_deref() == Some(key))
.unwrap();
let [x, y, w, h] = row.rect;
assert_eq!(
(x, w, h),
(CAPSULE_INSET + PANEL_PAD, 242., 44.),
"{code:?} {corner:?} {key}"
);
let child = |key| {
nodes
.iter()
.find(|e| e.parent == Some(idx) && e.key.as_deref() == Some(key))
.unwrap()
};
let [gx, gy, gw, gh] = child("glyph").rect;
assert_eq!((gx - x, gw, gh), (9., 16., 16.));
assert_eq!(gy + gh / 2., y + h / 2.);
let label = child("label");
assert_eq!(label.text.as_deref(), Some(tr(name)));
assert_eq!(label.rect[0] - x, 33.);
for px in [gx + gw / 2., label.rect[0] + 1., x + w - 1.] {
rt.pointer_move(px, y + h / 2.);
rt.frame(1. / 60.);
assert_eq!(
rt.cursor(),
Cursor::Default,
"{code:?} {corner:?} {key} {px}"
);
assert!(
rt.elements()
.iter()
.any(|e| e.key.as_deref() == Some(key) && e.hover > 0.)
);
}
}
}
}
i18n::apply(Some("en"));
}
#[test]
fn row_swipes_do_not_move_the_panel_or_fire_actions_but_small_clicks_work() {
let (mut rt, commands, _) = runtime(live_recording("ready-snap"), false, true, RECORDING);
let (send, shifts) = mpsc::channel();
rt.update(move |c, _| {
c.live.entries = call();
c.copy_new = Some(Arc::new(|_| {}));
c.shift = Some(Arc::new(move |_, dx, dy| send.send((dx, dy)).unwrap()));
});
rt.frame(0.);
open_recording(&mut rt);
for phase in 0..4 {
rt.update(|c, tx| {
match phase {
1 => c.capture_stopped(),
2 => {
let Kind::Ready(m) = ready_transcript() else {
unreachable!()
};
c.published(m)
}
3 => {
let Kind::Ready(m) = ready_summarized() else {
unreachable!()
};
c.refresh_ready(m)
}
_ => (),
};
tx.instant()
});
rt.frame(0.);
for key in ["stop", "copy-new", "copy-all", "copy-prompt"] {
let Some(([x, y, w, h], _)) = rt.presented(key) else {
continue;
};
for px in [x + 16., x + 35., x + w - 20.] {
let py = y + h / 2.;
rt.pointer_move(px, py);
rt.frame(0.);
assert_eq!(rt.cursor(), Cursor::Default);
rt.pointer_down(px, py);
rt.pointer_move(px + 10., py);
rt.frame(0.);
rt.pointer_up(px + 1., py);
rt.frame(0.);
assert!(
shifts.try_recv().is_err() && commands.try_recv().is_err(),
"{key} {phase}"
);
assert!(
rt.state.live.copied.is_none() && !rt.state.live.copying,
"{key} {phase}"
);
}
}
if phase == 0 {
for key in ["copy-prompt", "stop"] {
let (x, y) = rt.find(key).unwrap();
rt.pointer_down(x, y);
rt.pointer_move(x + 2., y + 1.);
rt.frame(0.);
rt.pointer_up(x + 2., y + 1.);
rt.frame(0.);
if key == "stop" {
assert!(matches!(commands.try_recv(), Ok(ControllerCommand::Stop)));
assert!(commands.try_recv().is_err());
} else {
assert!(rt.state.live.copied(LiveCopy::Prompt));
rt.state.live.copied = None;
}
assert!(shifts.try_recv().is_err());
}
}
}
tap(&mut rt, "dismiss");
assert!(rt.state.kind.is_none() && commands.try_recv().is_err());
}
#[test]
fn tab_focus_tracks_the_whole_action_row_without_changing_its_bounds() {
let (mut rt, commands, _) = runtime(live_recording("tab-rows"), false, true, RECORDING);
rt.update(|c, _| {
c.live.entries = call();
c.copy_new = Some(Arc::new(|_| {}));
});
rt.frame(0.);
open_recording(&mut rt);
for key in ["stop", "copy-new", "copy-all", "copy-prompt"] {
rt.key(rune::KeyEvent {
key: rune::Key::Tab,
mods: Default::default(),
});
rt.frame(0.);
let focused = rt
.elements()
.into_iter()
.find(|e| e.focus_visible && e.focused)
.unwrap();
assert_eq!(focused.key.as_deref(), Some(key));
assert_eq!(focused.rect[2..], [242., 44.]);
}
assert!(commands.try_recv().is_err());
}
#[test]
fn capture_end_and_publication_retarget_one_anchored_surface() {
use MeetingIndicatorCorner::*;
for (delay, reduced) in [(0, false), (90, false), (0, true), (90, true)] {
for corner in [TopLeft, TopRight, BottomLeft, BottomRight] {
let (mut rt, _, _) = runtime(live_recording("ready-snap"), false, true, RECORDING);
rt.reduced_motion = reduced;
rt.update(move |c, tx| {
c.corner = corner;
tx.instant();
});
rt.frame(0.);
let anchor = |rt: &Runtime<Capsule>| {
let ([x, y, w, h], opacity) = rt.presented("pill").unwrap();
assert!(w >= REST_WIDTH && h >= REST_HEIGHT && opacity > 0.99);
(
if corner.is_right() { x + w } else { x },
if corner.is_top() { y } else { y + h },
)
};
let (x, y) = anchor(&rt);
let (px, py) = rt.find("elapsed").unwrap();
rt.pointer_move(px, py);
for frame in 0..90 + delay {
if frame == 5 {
rt.update(|c, _| c.mark_stopping());
}
if frame == 7 {
rt.pointer_leave();
}
if frame == 12 {
rt.update(|c, _| c.capture_stopped());
}
if frame == 12 + delay {
rt.update(|c, _| {
let Kind::Ready(m) = ready_transcript() else {
unreachable!()
};
c.published(m);
});
}
if frame == 25 + delay {
rt.update(|c, _| {
let Kind::Ready(m) = ready_summarized() else {
unreachable!()
};
c.refresh_ready(m);
});
}
rt.frame(1. / 60.);
let (ax, ay) = anchor(&rt);
assert!(
(x - ax).abs() < 0.02 && (y - ay).abs() < 0.02,
"{corner:?} {frame}: {ax},{ay} vs {x},{y}"
);
assert_eq!(rt.find("meeting-listening-field").is_some(), frame < 12);
assert!(rt.find("elapsed").is_some());
assert_eq!(rt.find("dismiss").is_some(), frame >= 12 + delay);
}
}
}
}
/// Measure what Rune presented, not just Taffy's destination. In particular,
/// a transient but perfectly anchored 18 pt dip used to pass the anchor test.
#[test]
fn notes_grow_past_the_copies_without_a_height_dip_or_a_clock_hop() {
use MeetingIndicatorCorner::*;
for corner in [TopRight, BottomLeft, BottomRight, TopLeft] {
for (delay, reduced, long) in [
(1, false, false),
(60, false, false),
(2, false, true),
(1, true, true),
] {
let (mut rt, _, _) = runtime(live_recording("ready-snap"), false, true, RECORDING);
rt.reduced_motion = reduced;
rt.update(move |c, tx| {
c.corner = corner;
tx.instant();
});
rt.frame(0.);
open_recording(&mut rt);
let rect = |rt: &Runtime<Capsule>, k| rt.presented(k).unwrap().0;
let clock = rect(&rt, "elapsed");
let rows = ["copy-new", "copy-all", "copy-prompt"];
let at = rows.map(|k| rect(&rt, k));
let mut height = rect(&rt, "pill")[3];
let mut title_width = None;
rt.update(|c, _| c.mark_stopping());
for frame in 0..delay + 100 {
if frame == 1 {
rt.update(|c, _| c.capture_stopped());
}
if frame == 1 + delay {
rt.update(|c,_| {
let Kind::Ready(mut m) = ready_transcript() else { unreachable!() };
m.duration_ms = Some(258_000);
if long { m.title = "Planification trimestrielle — lancement et préparation des équipes".into(); }
c.published(m);
});
}
if frame == 4 + delay {
rt.update(|c,_| {
let Kind::Ready(mut m) = ready_summarized() else { unreachable!() };
m.duration_ms = Some(258_000);
if long { m.notes.as_mut().unwrap().title = "Planification trimestrielle — lancement et préparation des équipes".into(); }
c.refresh_ready(m);
});
}
rt.frame(1. / 60.);
let now = rect(&rt, "pill")[3];
assert!(
now >= height - 0.02,
"{corner:?} f{frame}: {height} → {now}"
);
height = now;
let t = rect(&rt, "elapsed");
assert!(
(t[1] - clock[1]).abs() < 0.02 && t[2..] == clock[2..],
"{corner:?} f{frame} timer {t:?} / {clock:?}"
);
assert!((t[0] - clock[0]).abs() < 0.02, "timer moved at {frame}");
if frame > delay {
let w = rect(&rt, "title")[2];
assert!(
(w - *title_width.get_or_insert(w)).abs() < 0.02,
"title wrapped at a moving width"
);
}
for (key, original) in rows.into_iter().zip(at) {
let row = rect(&rt, key);
assert_eq!(row[2..], original[2..]);
if !long {
assert!(
(row[1] - original[1]).abs() < 0.02,
"{corner:?} f{frame} {key}: {row:?} / {original:?}"
);
}
}
}
let header = rect(&rt, "header")[3];
assert!(if long {
header > OPEN_HEADER
} else {
(header - OPEN_HEADER).abs() < 0.02
});
}
}
}
#[test]
fn a_long_recording_keeps_its_timer_and_stop_inside_each_corner() {
use MeetingIndicatorCorner::*;
@@ -271,7 +825,8 @@ fn a_long_recording_keeps_its_timer_and_stop_inside_each_corner() {
}
tx.instant();
});
rt.settle_all();
settle_stage(&mut rt);
rt.settle_all();
rt.frame(0.);
let rect = |rt: &Runtime<Capsule>, key| {
rt.elements()
@@ -295,8 +850,10 @@ fn a_long_recording_keeps_its_timer_and_stop_inside_each_corner() {
rt.frame(1. / 60.);
}
assert_eq!(rt.find("elapsed"), Some(timer));
let [x, _, w, h] = rect(&rt, "stop");
assert!(w >= 44. && h >= 26. && (x + w <= sx || x >= tx + tw));
let [_, y, w, h] = rect(&rt, "stop");
let [_, my, _, mh] = rect(&rt, "meta");
assert_eq!((w, h), (PANEL_WIDTH - 2. * PANEL_PAD, ROW_HEIGHT));
assert!(y + h <= my || y >= my + mh);
tap(&mut rt, "stop");
assert!(matches!(received.try_recv(), Ok(ControllerCommand::Stop)));
}
+7 -2
View File
@@ -103,12 +103,14 @@ pub(super) fn actions(
})
.build_push(p.k),
};
face.key(key).on_press(move |c: &mut Capsule| {
face.key(key).on_press_tx(move |c: &mut Capsule, tx| {
if !c.presentation.inherits_offer_window()
&& c.more_open == choosing
&& matches!(c.kind, Some(Kind::Offer(shown, _)) if shown == id)
{
press(c);
// The surface answers in the frame of the press.
c.stir(tx);
}
})
};
@@ -179,10 +181,13 @@ impl Capsule {
self.waveform = Some(Box::new(waveform::Listening::new(Instant::now())));
self.live = Live::default();
self.hovered = false;
self.stopping = false;
self.expired = false;
self.throw.stop();
// Nothing here mounts with an entrance of its own: the surface
// carries the change.
tx.instant();
tx.wake_after(Duration::ZERO);
self.stir(tx);
}
pub(super) fn set_offer_timer(&mut self, timer: Option<After>) {
self.rearm_offer = timer;
+2 -1
View File
@@ -251,7 +251,8 @@ fn detected_offer_sheet() {
tx.instant()
});
rt.frame(0.);
rt.settle_all();
settle_stage(&mut rt);
rt.settle_all();
rt.frame(0.);
let w = (size.0 * 2.0) as u32;
let h = (size.1 * 2.0) as u32;
+149 -109
View File
@@ -4,6 +4,7 @@
use super::*;
use crate::calendar::CallProvider;
use crate::meeting::detection::MeetingSource;
use rune::Transition;
const ICON: f32 = 24.0;
const H: f32 = 28.0 + 2.0 * ACTIONS_INSET;
@@ -19,62 +20,82 @@ pub(super) struct Presentation {
v: f32,
last: Option<f64>,
pub(super) icon: Option<rune::Pixels>,
/// The offer Record was pressed on, until it has left the surface.
departure: Option<(OfferId, MeetingCandidate)>,
travel: Reveal,
live: Reveal,
/// When Record was pressed, on the surface's clock.
begun: Option<f64>,
/// The recording lives in the window its offer opened.
inherited: bool,
pub(super) hold_hover: bool,
pub(super) pointer: Option<(f32, f32)>,
}
#[derive(Default)]
struct Reveal {
at: Option<f64>,
t: f32,
}
impl Reveal {
fn step(&mut self, now: f64, spring: Spring) -> bool {
if self.t == 1. {
return false;
}
let dt = (now - *self.at.get_or_insert(now)).max(0.) as f32;
let t = spring.sample(0., 0., 1., dt).0;
self.t = if t >= 0.9995 { 1. } else { t };
true
}
}
impl Presentation {
pub(super) fn inherits_offer_window(&self) -> bool {
self.travel.at.is_some() || self.departure.is_some()
self.inherited || self.departure.is_some()
}
/// Record was pressed and the offer hasn't finished leaving.
pub(super) fn departing(&self) -> bool {
self.departure.is_some()
}
pub(super) fn begin(&mut self, id: OfferId, candidate: MeetingCandidate) {
self.departure = Some((id, candidate));
self.inherited = true;
self.hold_hover = true;
}
pub(super) fn begun(&mut self, now: f64) -> f64 {
*self.begun.get_or_insert(now)
}
#[cfg(test)]
pub(super) fn backdate(&mut self, now: f64) {
if self.departure.is_some() {
self.begun = Some(now);
}
}
/// The offer and "Starting…" have left a recording's surface: the
/// recording draws itself from here.
pub(super) fn arrived(&mut self, stage: &stage::Stage) {
use stage::Layer;
if !stage.presence(Layer::Offer).shows() && !stage.presence(Layer::Pending).shows() {
self.departure = None;
}
}
pub(super) fn blocks_hover(&mut self, inside: bool) -> bool {
if !inside {
self.hold_hover = false;
}
self.hold_hover
}
pub(super) fn step_handoff(&mut self, live: bool, reduced: bool, now: f64) -> bool {
if self.departure.is_none() {
return false;
/// The offer's outline between its two pages.
pub(super) fn outline(&self, reduced: bool) -> stage::Outline {
let (_, _, width) = self.page(reduced);
stage::Outline {
w: width,
h: H,
radius: rune_theme_opencode::kit(true).radius.md + ACTIONS_INSET,
dark: 0.0,
}
let moving = self.travel.step(
now,
if reduced {
Spring::new(0.16, 0.)
} else {
RECORDING_CLOSE
},
);
let lighting = live && self.live.step(now, Spring::new(0.18, 0.));
if self.travel.t == 1. && self.live.t == 1. {
self.departure = None;
}
moving || lighting
}
/// Which page shows, how much of it, and the shell's width around it.
fn page(&self, reduced: bool) -> (bool, f32, f32) {
let [ask, wide] = self.widths;
let split = if reduced { 0.5 } else { 0.69 };
let t = self.t;
let rules = t > split;
let alpha = (if rules {
(t - split) / (1.0 - split)
} else {
(split - t) / split
} * 1.45)
.min(1.0);
let fraction = if reduced {
if rules { 1.0 } else { 0.0 }
} else if wide < ask {
((t - split) / (1.0 - split)).max(0.)
} else {
(t / split).min(1.)
};
(rules, alpha, ask + (wide - ask) * fraction)
}
pub(super) fn for_kind(kind: &Kind, open: bool) -> Self {
let Kind::Offer(_, c) = kind else {
@@ -261,45 +282,47 @@ pub(super) fn transition(c: &Capsule, p: Paint, dark: Paint) -> Option<El> {
}
fn draw(p: Paint, dark: Paint, c: &Capsule, id: OfferId, candidate: &MeetingCandidate) -> El {
use stage::Layer;
let a = &c.presentation;
let [ask, wide] = a.widths;
let reduced = c.reduced.get();
let split = if reduced { 0.5 } else { 0.69 };
let t = a.t;
let rules = t > split;
let (rules, alpha, _) = a.page(reduced);
let i = usize::from(rules);
let alpha = (if rules {
(t - split) / (1.0 - split)
// Before its first step the surface is the offer at rest.
let o = c.stage.outline().unwrap_or_else(|| a.outline(reduced));
let offer = if c.stage.outline().is_some() {
c.stage.presence(Layer::Offer)
} else {
(split - t) / split
} * 1.45)
.min(1.0);
let fraction = if reduced {
if rules { 1.0 } else { 0.0 }
} else if wide < ask {
((t - split) / (1.0 - split)).max(0.)
} else {
(t / split).min(1.)
stage::Presence {
opacity: 1.0,
scale: 1.0,
blur: 0.0,
}
};
let from = ask + (wide - ask) * fraction;
let t = a.travel.t;
let g = if reduced { f32::from(t >= 0.5) } else { t };
let lerp = |from: f32, to: f32| from + (to - from) * g;
let pending = c.stage.presence(Layer::Pending);
let live = c.stage.presence(Layer::Meter);
let grid = |v: f32| (v * 64.).round() / 64.;
let w = grid(lerp(from, REST_WIDTH));
let h = grid(lerp(H, REST_HEIGHT));
let top = if c.corner.is_top() {
let (w, h) = (grid(o.w), grid(o.h));
let (right, top_corner) = (c.corner.is_right(), c.corner.is_top());
let top = if top_corner {
CAPSULE_INSET
} else {
a.window().1 - CAPSULE_INSET - h
};
let x = |width| {
if c.corner.is_right() {
if right {
a.window().0 - CAPSULE_INSET - width
} else {
CAPSULE_INSET
}
};
// Everything in the shell is laid out where it rests, measured from the
// saved corner: the outline moves over it and nothing rides its edges.
let from_corner = |width: f32, height: f32| {
(
if right { w - width } else { 0.0 },
if top_corner { 0.0 } else { h - height },
)
};
let (_, title, sub, actions) = offer::actions(p, id, candidate, rules);
let lines = col()
.w(a.lines[i])
@@ -320,9 +343,10 @@ fn draw(p: Paint, dark: Paint, c: &Capsule, id: OfferId, candidate: &MeetingCand
.font(p.k.ty.small)
.color(p.faint())
}));
let (page_x, page_y) = from_corner(a.widths[i], H);
let page = row()
.key("page")
.absolute(x(a.widths[i]) - x(w), (h - H) / 2.)
.absolute(page_x, page_y)
.w(a.widths[i])
.h(H)
.pl(START)
@@ -339,70 +363,85 @@ fn draw(p: Paint, dark: Paint, c: &Capsule, id: OfferId, candidate: &MeetingCand
.child(lines),
)
.child(row().key("actions").gap(8.0).children(actions))
.opacity(alpha * (1. - t * 3.).max(0.));
.transition(Transition::none())
.opacity(alpha * offer.opacity)
.scale(offer.scale)
.blur(offer.blur);
let page = if a.inherits_offer_window() || rules != c.more_open || alpha < 0.2 {
page.inert().a11y_hidden()
} else {
page
};
let radius = lerp(panel_radius(p), REST_HEIGHT * 0.5);
let label = match &c.kind {
Some(Kind::Recording(r)) => format!("{} · {}", tr("Recording"), r.title),
_ if a.inherits_offer_window() => tr("Starting…").to_owned(),
_ => title,
};
let mut shell = row()
// What a moving edge crosses fades under it; at rest the veil is nothing.
let (veil_x, veil_y) = c.stage.veil();
let mut veil = rune::el()
.key("veil")
.absolute(0., 0.)
.size(w, h)
.clip_fade_linear(
if right { veil_x } else { 0. },
if top_corner { 0. } else { veil_y },
if right { 0. } else { veil_x },
if top_corner { veil_y } else { 0. },
);
if offer.shows() {
veil = veil.child(page);
}
if pending.shows() {
let (px, py) = from_corner(REST_WIDTH, REST_HEIGHT);
veil = veil.child(
row()
.key("pending")
.absolute(px, py)
.size(REST_WIDTH, REST_HEIGHT)
.center()
.transition(Transition::none())
.opacity(pending.opacity)
.scale(pending.scale)
.blur(pending.blur)
.child(
text(tr("Starting…"))
.font(dark.k.ty.ui_medium)
.color(dark.muted()),
),
);
}
if live.shows()
&& let Some(Kind::Recording(r)) = &c.kind
{
// The recording's own header band, where it will draw it.
let (lx, ly) = from_corner(PANEL_WIDTH, REST_HEIGHT);
let band = row()
.key("live")
.absolute(lx, ly)
.size(PANEL_WIDTH, REST_HEIGHT)
.px(REST_PX)
.center_y()
.transition(Transition::none())
.opacity(live.opacity);
let band = if right { band.justify_end() } else { band };
veil = veil.child(band.child(panel::meter(dark, r)));
}
let shell = row()
.key("pill")
.role("status")
.label(label)
.absolute(x(w), top)
.w(w)
.h(h)
.radius(radius)
.fill(p.k.c.bg_base.mix(dark.k.c.bg_base, t))
.border(p.hair, p.k.c.border_base.mix(dark.k.c.border_base, t))
.clip_rounded(radius);
if t < 1. / 3. {
shell = shell.child(page);
}
let enter = ((t - 0.33) / 0.67).clamp(0., 1.);
if enter > 0. {
let layer = |key, opacity| {
let layer = row()
.key(key)
.absolute(0., 0.)
.size(w, h)
.px(REST_PX)
.center_y()
.opacity(opacity);
if c.corner.is_right() {
layer.justify_end()
} else {
layer
}
};
let live = a.live.t;
if live < 1. {
shell = shell.child(
row()
.key("pending")
.absolute(0., 0.)
.size(w, h)
.center()
.opacity(enter * (1. - live))
.child(
text(tr("Starting…"))
.font(dark.k.ty.ui_medium)
.color(dark.muted()),
),
);
}
if live > 0.
&& let Some(Kind::Recording(r)) = &c.kind
{
shell = shell.child(layer("live", enter * live).child(panel::meter(dark, r)));
}
}
.radius(o.radius)
.fill(p.k.c.bg_base.mix(dark.k.c.bg_base, o.dark))
.border(p.hair, p.k.c.border_base.mix(dark.k.c.border_base, o.dark))
.clip_rounded(o.radius)
// The stage steps every frame; nothing here eases a second time.
.motion(Spring::NONE)
.child(veil);
let radius = o.radius;
// Regions are rectangles. Inscribe bands in the rounded body rather
// than claiming the clear window, including its transparent corners.
let region = |y, h, inset| {
@@ -410,6 +449,7 @@ fn draw(p: Paint, dark: Paint, c: &Capsule, id: OfferId, candidate: &MeetingCand
.absolute(x(w) + inset, top + y)
.w(w - 2.0 * inset)
.h(h)
.motion(Spring::NONE)
.hit()
.a11y_hidden()
};
+476 -117
View File
@@ -2,7 +2,7 @@
//! rest, then Stop and the three copies, and the finished meeting's title
//! and summary over the same copies.
use rune::{Cursor, El, Icon, TextStyle, Tx, col, el, icon, row, text};
use rune::{Cursor, El, Icon, SpringPair, TextStyle, Transition, Tx, col, el, icon, row, text};
use rune_theme_opencode::icons;
use super::*;
@@ -67,7 +67,7 @@ pub(super) fn ready_summary(manifest: &MeetingManifest) -> Option<(String, bool)
/// The timer: elapsed while recording, the length once finished.
fn timer_style() -> TextStyle {
TextStyle::new(14.0, 600.0).mono().lh(18.0)
TextStyle::new(13.0, 500.0).mono().lh(18.0)
}
/// "4 min new", "Up to date", "Transcribing…", or ✓ Copied: what Copy new
@@ -119,8 +119,7 @@ fn copied_hint(p: Paint) -> El {
)
}
/// One of the panel's copies: an icon, its label, and on the right what it
/// would copy or that it just did. The first row is raised.
/// One action across its whole visible row, including the trailing whitespace.
#[allow(clippy::too_many_arguments)]
fn panel_row(
p: Paint,
@@ -130,6 +129,7 @@ fn panel_row(
hint: Option<El>,
first: bool,
enabled: bool,
presence: f32,
press: impl Fn(&mut Capsule, &mut Tx) + 'static,
) -> El {
let (ink, font) = if first {
@@ -144,8 +144,13 @@ fn panel_row(
.gap(8.0)
.center_y()
.radius(ROW_RADIUS)
.role("button")
.cursor(Cursor::Default)
.focus_ring(2., -2., p.k.c.border_focus)
// The surface steps each row's presence; nothing eases it twice.
.transition(Transition::none())
.label(label)
.child(icon(glyph, 16.0).color(ink))
.child(icon(glyph, 16.0).key("glyph").color(ink))
.child(
text(label.to_owned())
.key("label")
@@ -158,14 +163,39 @@ fn panel_row(
)
.children(hint);
let row_el = if first {
row_el.fill(p.k.c.layer_02).mb(FIRST_ROW_GAP)
row_el
.fill(p.k.c.layer_02)
.hover(p.k.c.hover)
.mb(FIRST_ROW_GAP)
} else {
row_el.hover(p.k.c.hover)
};
if enabled {
row_el.focusable(true).on_press_tx(press)
row_el
.focusable(true)
.no_window_drag()
// Rune buttons accept a release anywhere inside their rectangle.
// Track press travel only: no window move, drag item or grab cursor.
.on_drag(|c: &mut Capsule, d, tx| {
if d.phase == Phase::Down {
c.live.row_swiped = false;
}
c.live.row_swiped |= d.dx.hypot(d.dy) > 4.;
if d.phase == Phase::Up
&& (d.cancelled() || d.x < 0. || d.x >= d.w || d.y < 0. || d.y >= d.h)
{
c.live.row_swiped = false;
}
tx.live_only();
})
.on_press_tx(move |c: &mut Capsule, tx| {
if !std::mem::take(&mut c.live.row_swiped) {
press(c, tx);
}
})
.opacity(presence)
} else {
row_el.disabled(true).opacity(0.5)
row_el.disabled(true).opacity(0.5 * presence)
}
}
@@ -173,6 +203,7 @@ fn panel_row(
/// ready meeting.
fn copy_rows(p: Paint, capsule: &Capsule, recording: bool) -> Vec<El> {
let live = &capsule.live;
let presence = |row| capsule.action_presence(row).opacity;
// While recording, reading through the click can find speech the ticker
// hasn't shown yet.
let new_enabled = !live.copying
@@ -189,6 +220,7 @@ fn copy_rows(p: Paint, capsule: &Capsule, recording: bool) -> Vec<El> {
copy_new_hint(p, live, recording),
true,
new_enabled,
presence(1),
|c, tx| c.press_copy_new(tx),
),
panel_row(
@@ -199,6 +231,7 @@ fn copy_rows(p: Paint, capsule: &Capsule, recording: bool) -> Vec<El> {
copied(LiveCopy::All),
false,
!recording || !live.entries.is_empty(),
presence(2),
|c, tx| c.copy_all(tx),
),
panel_row(
@@ -209,6 +242,7 @@ fn copy_rows(p: Paint, capsule: &Capsule, recording: bool) -> Vec<El> {
copied(LiveCopy::Prompt),
false,
true,
presence(3),
|c, tx| c.copy_prompt(tx),
),
]
@@ -229,6 +263,24 @@ fn panel_body(p: Paint, title: &str) -> El {
.hit()
}
fn replace(c: &Capsule) -> Transition {
let (enter, exit) = if c.reduced.get() {
(0.18, 0.15)
} else {
(0.3, 0.25)
};
// A whole line replaced in place softens; under Reduce Motion it only fades.
if c.reduced.get() {
Transition::opacity()
} else {
Transition::blur(2.0)
}
.springs(SpringPair::new(
Spring::new(enter, 0.),
Spring::new(exit, 0.),
))
}
/// The finished meeting stays where its pill was; other panels take the saved corner.
pub(super) fn show_corner(
kind: &Kind,
@@ -272,34 +324,117 @@ fn in_corner(capsule: &Capsule, body: El) -> El {
/// The finished meeting: its title and length, the summary when there is
/// one, and the same copies as the recording.
pub(super) fn ready(p: Paint, capsule: &Capsule, manifest: &MeetingManifest) -> El {
let title = meeting::display_title(manifest);
let header = row()
.key("header")
.h(HEADER_HEIGHT)
.pl(PANEL_PAD + ROW_PX)
.pr(PANEL_PAD)
.gap(8.0)
.center_y()
.child(
text(title.clone())
.key("title")
.font(TextStyle::new(13.0, 600.0).lh(20.0))
.color(p.text())
.truncate()
.grow(1.0)
.min_w(0.0)
.a11y_hidden(),
result(
p,
capsule,
meeting::display_title(manifest),
manifest.duration_ms,
Some(manifest),
)
}
pub(super) fn finalizing(p: Paint, capsule: &Capsule, duration_ms: u64) -> El {
result(
p,
capsule,
tr("Transcribing…").to_owned(),
Some(duration_ms),
None,
)
}
fn result(
p: Paint,
capsule: &Capsule,
title: String,
duration: Option<u64>,
manifest: Option<&MeetingManifest>,
) -> El {
let top = capsule.corner.is_top();
let right = capsule.corner.is_right();
let label = handoff_label(p, capsule, &title, false);
let clock = duration.map(|duration| {
row()
.key("meter")
.h(REST_HEIGHT)
.gap(6.)
.center_y()
.transition(Transition::none())
// The field cools after capture ends; it never cuts. On the right
// it sits beside the time without moving it.
.children(match (capsule.waveform.is_some(), right) {
(true, true) => Some(waveform::slot().absolute(
-(waveform::WIDTH + 6.),
(REST_HEIGHT - crate::rune_hud::dot_scope::PLATE_HEIGHT) / 2.,
)),
(true, false) => Some(waveform::slot()),
(false, false) => Some(el().w(waveform::WIDTH)),
(false, true) => None,
})
.child(
text(meeting::format_duration(duration))
.key("elapsed")
.font(timer_style())
.color(p.muted()),
)
});
let close = row()
.key("close-slot")
.w(32.)
.h(REST_HEIGHT)
.center()
.children(manifest.map(|_| dismiss_button(p).transition(replace(capsule))));
let meta = meter_band();
let space = el().key("space").grow(1.);
let meta = if right {
meta.child(space).child(close).children(clock)
} else {
meta.children(clock).child(space).child(close)
};
// Stop leaves from where it was pressed while the title arrives.
let stop = capsule.stage.presence(stage::Layer::Action(0));
let label = if stop.shows() {
let ghost = panel_row(
p,
"stop",
&icons::STOP,
tr("Stopping…"),
None,
false,
false,
stop.opacity,
|_, _| {},
)
.children(manifest.duration_ms.map(|duration| {
text(meeting::format_duration(duration))
.key("duration")
.font(timer_style())
.color(p.muted())
}))
.child(dismiss_button(p));
let summary = ready_summary(manifest).map(|(summary, written)| {
.absolute(PANEL_PAD, 0.)
.w(PANEL_WIDTH - 2. * PANEL_PAD)
.blur(if capsule.reduced.get() {
0.
} else {
2. * (1. - stop.opacity)
})
.inert()
.a11y_hidden();
col().key("caption-slot").w_full().child(label).child(ghost)
} else {
label
};
let header = bands(top, meta, Some(label));
let summary = manifest.and_then(ready_summary).map(|(summary, written)| {
text(summary)
.key("summary")
// The words wipe on behind the growing edge, soft at their front.
.transition(if capsule.reduced.get() {
replace(capsule)
} else {
Transition::reveal(if top {
rune::Edge::Top
} else {
rune::Edge::Bottom
})
// Slower than the panel grows, so the edge is always ahead
// of the words and never cuts them.
.springs(SpringPair::new(Spring::new(0.6, 0.0), stage::EXIT))
})
.font(p.k.ty.text_small)
.color(if written { p.muted() } else { p.faint() })
.max_lines(SUMMARY_LINES)
@@ -307,21 +442,119 @@ pub(super) fn ready(p: Paint, capsule: &Capsule, manifest: &MeetingManifest) ->
.mt(2.0)
.mb(ROW_PX)
});
// Reveal the words within the growing surface, never over the copy buttons.
let summary = col().key("summary-lane").clip_rounded(0.).children(summary);
let rows = col()
.key("rows")
.px(PANEL_PAD)
.pb(PANEL_PAD)
.children(copy_rows(p, capsule, false));
let body = panel_body(p, &title)
.child(header)
.children(summary)
.child(rows)
.on_hover_change(|c: &mut Capsule, inside, _| c.set_hovered(inside))
.cursor(Cursor::Grab)
.on_drag(|c: &mut Capsule, drag, tx| c.drag(drag, tx));
let rows = if top {
rows.pb(PANEL_PAD)
} else {
rows.pt(PANEL_PAD)
};
let rows = if manifest.is_none() {
rows.disabled(true).opacity(0.48)
} else {
rows
};
let contents = col().key("panel-contents").w(PANEL_WIDTH);
// New notes grow from the free edge, not between the pointer and its
// copy row. A bottom corner mirrors the bands, not their reading order.
let contents = if top {
contents.child(header).child(rows).child(summary)
} else {
contents.child(summary).child(rows).child(header)
};
let body = panel_body(p, &title);
// A surface still on its way here keeps its own motion until it lands;
// from then on the panel's layout grows it for a title or a summary.
let arriving = capsule
.stage
.travelling()
.then(|| capsule.stage.outline())
.flatten();
let body = match arriving {
Some(o) => {
let grid = |v: f32| (v * 64.0).round() / 64.0;
let body = body
.size(grid(o.w), grid(o.h))
.radius(o.radius)
.clip_rounded(o.radius)
.motion(Spring::NONE);
let body = if right {
body.items_end()
} else {
body.items_start()
};
if top {
body.justify_start()
} else {
body.justify_end()
}
}
None => body.motion(RECORDING_OPEN),
};
let body = body
.child(contents)
.on_hover_change(|c: &mut Capsule, inside, _| c.set_hovered(inside));
in_corner(capsule, body)
}
/// A fast worker can report every phase within a few frames. Keep one text
/// run instead of leaving several fading titles in the same place. Only its
/// slot moves: the words wrap at their destination width from the first frame.
fn handoff_label(p: Paint, c: &Capsule, title: &str, stopping: bool) -> El {
let label = text(title.to_owned())
.key("title")
.w_full()
.motion(Spring::NONE)
.font(TextStyle::new(13., 600.).lh(20.))
.color(if stopping { p.muted() } else { p.text() });
let label = if stopping {
label.truncate_fade()
} else {
label.wrap_anywhere().max_lines(TITLE_LINES).a11y_hidden()
};
col()
.key("caption")
.min_w(0.)
.min_h(ROW_HEIGHT)
.py(TITLE_INSET)
.px(PANEL_PAD + ROW_PX)
.justify_center()
.transition(if stopping {
Transition::none()
} else {
replace(c)
})
.child(label)
}
// Only the meter band owns the window drag, never an ancestor of an action row.
fn meter_band() -> El {
row()
.key("meta")
.h(REST_HEIGHT)
.px(REST_PX)
.center_y()
.transition(Transition::none())
.cursor(Cursor::Default)
.on_drag(|c: &mut Capsule, d, tx| c.drag(d, tx))
}
fn bands(top: bool, meta: El, action: Option<El>) -> El {
let header = col()
.key("header")
.w(PANEL_WIDTH)
.transition(Transition::none());
if top {
header.child(meta).children(action)
} else {
header.children(action).child(meta)
}
}
/// Only grow the compact header for a notice or another minute digit.
/// Its 13 pt monospaced digits each occupy 8 pt at layout resolution.
pub(super) fn rest_width(shown: &Recording) -> f32 {
@@ -340,19 +573,93 @@ pub(super) fn meter(p: Paint, shown: &Recording) -> El {
let elapsed = meeting::format_duration(shown.started.elapsed().as_millis() as u64);
row()
.key("meter")
.h(REST_HEIGHT)
.gap(6.)
.center_y()
// The same meter in every state: it never arrives a second time.
.transition(Transition::none())
.child(waveform::slot())
.child(
text(elapsed)
.key("elapsed")
.font(TextStyle::new(13.0, 500.0).mono().lh(18.0))
.font(timer_style())
.color(p.muted()),
)
}
/// The open recording's height: its header, Stop, any notice and the copies.
pub(super) fn open_height(shown: &Recording) -> f32 {
open_height_without_notice()
+ if recording_notice(shown).is_some() {
NOTICE_HEIGHT
} else {
0.0
}
}
/// The open panel a finished meeting grows from.
pub(super) fn open_height_without_notice() -> f32 {
OPEN_HEADER + 3.0 * ROW_HEIGHT + FIRST_ROW_GAP + PANEL_PAD
}
/// How far short of the open panel's width its rows start to show.
const UNCOVER: f32 = 48.0;
/// What a moving edge of the surface crosses fades under it: the sides away
/// from the saved corner, by as much as the stage says they are moving.
fn veil(capsule: &Capsule, width: f32, height: f32) -> El {
let (x, y) = capsule.stage.veil();
let (right, top) = (capsule.corner.is_right(), capsule.corner.is_top());
el().key("veil")
.absolute(0.0, 0.0)
.size(width, height)
.clip_fade_linear(
if right { x } else { 0.0 },
if top { 0.0 } else { y },
if right { 0.0 } else { x },
if top { y } else { 0.0 },
)
}
impl Capsule {
/// How much of action row `row` (Stop, then the three copies) shows.
/// Whole wherever the surface isn't in motion.
pub(super) fn action_presence(&self, row: usize) -> stage::Presence {
let (Some(o), Some(Kind::Recording(shown))) = (self.stage.outline(), &self.kind) else {
return stage::Presence {
opacity: 1.0,
scale: 1.0,
blur: 0.0,
};
};
let mut presence = self.stage.presence(stage::Layer::Action(row));
// A row shows only as far as the outline has uncovered it, so an
// edge in flight never crosses words at full strength: across, as
// the far side clears the row's start; along, as the edge passes it.
let notice = if recording_notice(shown).is_some() {
NOTICE_HEIGHT
} else {
0.0
};
let near = match row {
0 => REST_HEIGHT,
1 => OPEN_HEADER + notice,
row => OPEN_HEADER + notice + FIRST_ROW_GAP + (row - 1) as f32 * ROW_HEIGHT,
};
let smooth = |t: f32| {
let t = t.clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
};
presence.opacity *=
smooth((o.w - (PANEL_WIDTH - UNCOVER)) / UNCOVER) * smooth((o.h - near) / ROW_HEIGHT);
presence
}
}
pub(super) fn recording(p: Paint, capsule: &Capsule, shown: &Recording) -> El {
let open = capsule.hovered;
let open = capsule.hovered || capsule.stopping;
// Rows that are leaving stay drawn until they have gone.
let actions = open || (0..stage::ACTIONS).any(|row| capsule.action_presence(row).shows());
let notice = recording_notice(shown);
let notice_text = |notice: Notice| {
text(notice.text().to_owned())
@@ -364,72 +671,74 @@ pub(super) fn recording(p: Paint, capsule: &Capsule, shown: &Recording) -> El {
};
let right = capsule.corner.is_right();
let top = capsule.corner.is_top();
let meter = meter(p, shown);
let accessory = if open {
Some(
row()
.key("stop")
.h(HEADER_HEIGHT - 2.0 * PANEL_PAD)
.px(ROW_PX)
.gap(6.0)
.center_y()
.radius(ROW_RADIUS)
.hover(p.k.c.hover)
.label(tr("Stop"))
.focusable(true)
.on_press(|c: &mut Capsule| {
c.send(ControllerCommand::Stop);
})
.child(icon(&icons::STOP, 12.0).color(p.muted()))
.child(
text(tr("Stop").to_owned())
.font(p.k.ty.text_xsmall)
.color(p.muted())
.a11y_hidden(),
),
)
let live = if capsule.stage.outline().is_some() {
capsule.stage.presence(stage::Layer::Meter).opacity
} else {
notice.map(notice_text)
1.0
};
let panel_height = HEADER_HEIGHT
+ 3.0 * ROW_HEIGHT
+ FIRST_ROW_GAP
+ PANEL_PAD
+ if notice.is_some() { NOTICE_HEIGHT } else { 0.0 };
let width = if open { PANEL_WIDTH } else { rest_width(shown) };
let height = if open { panel_height } else { REST_HEIGHT };
// The full-size layout exists before the first hover. Its origin cancels
// the moving clip's origin so neither the rows nor the meter ride its edge.
let header = row()
.key("header")
.absolute(
0.0,
if top {
0.0
let meter = meter(p, shown).opacity(live);
let accessory = notice.filter(|_| !open).map(notice_text);
let stop = capsule.action_presence(0);
let action = actions.then(|| {
// Pressed, the same row says so in place: its glyph and first
// letters stay where they were and it stops taking the pointer.
let stopping = capsule.stopping;
let row = panel_row(
p,
"stop",
&icons::STOP,
if stopping {
tr("Stopping…")
} else {
panel_height - HEADER_HEIGHT
tr("Stop")
},
None,
false,
!stopping && open && stop.takes_input(),
stop.opacity,
|c, tx| {
c.request_stop();
c.stir(tx);
},
)
.w(PANEL_WIDTH)
.h(HEADER_HEIGHT)
.center_y()
.gap(8.0);
.mx(PANEL_PAD);
if stopping || !open {
row.opacity(stop.opacity)
} else {
row
}
});
let panel_height = open_height(shown);
let (target_w, target_h, target_r) = if open {
(PANEL_WIDTH, panel_height, PANEL_RADIUS)
} else {
(rest_width(shown), REST_HEIGHT, REST_HEIGHT / 2.0)
};
// The stage owns the outline. Before its first step the pill is at rest.
let grid = |v: f32| (v * 64.0).round() / 64.0;
let (width, height, radius) = capsule
.stage
.outline()
.map_or((target_w, target_h, target_r), |o| {
(grid(o.w), grid(o.h), o.radius)
});
// The full-size layout exists before the first hover. Its origin cancels
// the moving clip's origin so neither the rows nor the meter ride its edge.
let header = meter_band();
let spacer = el().key("space").grow(1.0);
let header = if right {
header
.pl(if open { PANEL_PAD } else { REST_PX })
.pr(REST_PX)
.children(accessory)
.child(spacer)
.child(meter)
header.children(accessory).child(spacer).child(meter)
} else {
header
.pl(REST_PX)
.pr(if open { PANEL_PAD } else { REST_PX })
.child(meter)
.child(spacer)
.children(accessory)
header.child(meter).child(spacer).children(accessory)
};
let header = bands(top, header, action).absolute(
0.,
if top {
0.
} else {
panel_height - if actions { OPEN_HEADER } else { REST_HEIGHT }
},
);
let mut contents = col()
.key("panel-contents")
.size(PANEL_WIDTH, panel_height)
@@ -438,7 +747,7 @@ pub(super) fn recording(p: Paint, capsule: &Capsule, shown: &Recording) -> El {
if top { 0.0 } else { height - panel_height },
)
.child(header);
if open {
if actions {
if let Some(notice) = notice {
contents = contents.child(
row()
@@ -446,15 +755,16 @@ pub(super) fn recording(p: Paint, capsule: &Capsule, shown: &Recording) -> El {
.absolute(
0.0,
if top {
HEADER_HEIGHT
OPEN_HEADER
} else {
panel_height - HEADER_HEIGHT - NOTICE_HEIGHT
panel_height - OPEN_HEADER - NOTICE_HEIGHT
},
)
.w(PANEL_WIDTH)
.h(NOTICE_HEIGHT)
.px(PANEL_PAD + ROW_PX)
.center_y()
.opacity(stop.opacity)
.child(notice_text(notice)),
);
}
@@ -471,13 +781,9 @@ pub(super) fn recording(p: Paint, capsule: &Capsule, shown: &Recording) -> El {
.w(PANEL_WIDTH)
.px(PANEL_PAD)
.children(copy_rows(p, capsule, true));
contents = contents.child(rows);
// Leaving rows are drawn, not pressed.
contents = contents.child(if open { rows } else { rows.inert() });
}
let radius = if open {
PANEL_RADIUS
} else {
REST_HEIGHT / 2.0
};
let body = col()
.key("pill")
.role("status")
@@ -486,16 +792,14 @@ pub(super) fn recording(p: Paint, capsule: &Capsule, shown: &Recording) -> El {
.fill(p.k.c.bg_base)
.border(p.hair, p.k.c.border_base)
.size(width, height)
.child(contents)
.child(veil(capsule, width, height).child(contents))
.clip_rounded(radius)
.cursor(Cursor::Grab)
.motion(if open {
RECORDING_OPEN
} else {
RECORDING_CLOSE
// The stage steps every frame; nothing here eases a second time.
.motion(Spring::NONE)
.on_hover_change(|c: &mut Capsule, inside, tx| {
c.set_hovered(inside);
c.stir(tx);
})
.on_hover_change(|c: &mut Capsule, inside, _| c.set_hovered(inside))
.on_drag(|c: &mut Capsule, drag, tx| c.drag(drag, tx))
// Only the drawn pill takes the pointer; the rest of the window,
// as large as the open panel, lets clicks through. On Windows the
// window is only as large as the pill it draws instead.
@@ -561,3 +865,58 @@ pub(super) fn agent_prompt(hex: &str, id: &str, title: &str, recording: Option<u
),
}
}
/// The recording capsule's window. On Windows it is the size of what it
/// draws: the resting pill (as wide as the open panel while it says
/// `noticed`), then the open panel. Elsewhere it stays at its largest, and
/// only the `.hit()` pill takes the pointer.
#[cfg_attr(not(target_os = "windows"), allow(unused_variables))]
pub(super) fn recording_window_size(open: bool, shown: Option<&Recording>) -> (f32, f32) {
#[cfg(target_os = "windows")]
{
if !open {
let width = shown.map_or(REST_WIDTH, rest_width) + 2. * CAPSULE_INSET;
return (width, REST_HEIGHT + 2.0 * CAPSULE_INSET);
}
(
RECORDING_WINDOW.0,
OPEN_HEADER
+ 3. * ROW_HEIGHT
+ FIRST_ROW_GAP
+ PANEL_PAD
+ 2. * CAPSULE_INSET
+ if shown.and_then(recording_notice).is_some() {
NOTICE_HEIGHT
} else {
0.
},
)
}
#[cfg(not(target_os = "windows"))]
RECORDING_WINDOW
}
/// The ready panel's window: its header, a summary while there is one or one
/// is being written, and the three copies.
#[cfg(not(target_os = "windows"))]
pub(super) fn ready_window_size(_: &MeetingManifest) -> (f32, f32) {
RECORDING_WINDOW
}
#[cfg(target_os = "windows")]
pub(super) fn ready_window_size(manifest: &MeetingManifest) -> (f32, f32) {
let summary = if ready_summary(manifest).is_some() {
SUMMARY_LINE * SUMMARY_LINES as f32 + ROW_PX + FIRST_ROW_GAP
} else {
0.0
};
(
PANEL_WIDTH + 2.0 * CAPSULE_INSET,
RESULT_HEADER_MAX
+ summary
+ 3.0 * ROW_HEIGHT
+ FIRST_ROW_GAP
+ PANEL_PAD
+ 2.0 * CAPSULE_INSET,
)
}
@@ -0,0 +1,578 @@
// The whole recording host in one replay: an offer, Record, the live pill,
// its panel under the pointer, Stop and the finished meeting, on one runtime
// and one surface. `HEX_HUD_REPLAY=<dir>` writes every frame and a trace of
// the surface; without it only the trace's claims are checked.
/// One step of a replay's script.
#[derive(Clone, Copy)]
enum Cue {
Move(f32, f32),
Over(&'static str),
Leave,
Record,
Started,
Refused,
PressStop,
Stopped,
Published,
Notes,
}
struct Replay {
name: &'static str,
reduced: bool,
frames: usize,
/// Starts as a live recording rather than an offer.
live: bool,
cues: &'static [(usize, Cue)],
}
const REPLAYS: &[Replay] = &[
// The draft replay's schedule, frame for frame.
Replay {
name: "whole",
reduced: false,
frames: 555,
live: false,
cues: &[
(40, Cue::Over("record")),
(44, Cue::Record),
(60, Cue::Move(417., 82.)),
(96, Cue::Started),
(172, Cue::Move(432., 23.)),
(228, Cue::Over("stop")),
(276, Cue::Over("copy-new")),
(312, Cue::Over("copy-all")),
(336, Cue::Over("copy-prompt")),
(396, Cue::Over("stop")),
(404, Cue::PressStop),
(415, Cue::Move(214., 91.)),
(425, Cue::Stopped),
(470, Cue::Published),
(493, Cue::Notes),
],
},
Replay {
name: "fast",
reduced: false,
frames: 120,
live: false,
cues: &[
(20, Cue::Over("record")),
(24, Cue::Record),
(27, Cue::Started),
],
},
Replay {
name: "delayed",
reduced: false,
frames: 210,
live: false,
cues: &[
(20, Cue::Over("record")),
(24, Cue::Record),
(114, Cue::Started),
],
},
// The pointer comes and goes before anything has landed, Stop is pressed
// while the panel is still opening and the worker answers within frames.
Replay {
name: "interrupted",
reduced: false,
frames: 240,
live: true,
cues: &[
(12, Cue::Move(432., 23.)),
(20, Cue::Leave),
(27, Cue::Move(432., 23.)),
(33, Cue::Leave),
(60, Cue::Move(432., 23.)),
(74, Cue::PressStop),
(78, Cue::Leave),
(80, Cue::Stopped),
(84, Cue::Published),
(90, Cue::Notes),
],
},
Replay {
name: "failure",
reduced: false,
frames: 110,
live: false,
cues: &[
(20, Cue::Over("record")),
(24, Cue::Record),
(54, Cue::Refused),
],
},
Replay {
name: "reduced",
reduced: true,
frames: 330,
live: false,
cues: &[
(20, Cue::Over("record")),
(24, Cue::Record),
(40, Cue::Move(417., 82.)),
(60, Cue::Started),
(100, Cue::Move(432., 23.)),
(150, Cue::Over("stop")),
(170, Cue::PressStop),
(180, Cue::Move(214., 91.)),
(190, Cue::Stopped),
(230, Cue::Published),
(250, Cue::Notes),
],
},
];
/// Two people talking, with one pause in the long replay so the field is
/// seen going quiet and coming back.
fn replay_levels(replay: &Replay, frame: usize) -> [f32; 2] {
if replay.name == "whole" && (340..372).contains(&frame) {
return [0.0; 2];
}
let t = frame as f32 / 60.0;
let phrase = |speed: f32, beat: f32| ((t * speed).sin().abs() * (t * beat).cos().abs()).sqrt();
[
0.12 * phrase(13.0, 2.8).powi(3),
0.09 * phrase(6.3, 4.1).powi(3),
]
}
/// One frame of a replay as the surface presented it.
#[derive(Clone, Debug, Default)]
struct Shot {
phase: &'static str,
/// The surface: x, y, width, height.
pill: Option<[f32; 4]>,
velocity: (f32, f32),
veil: (f32, f32),
/// Offer, "Starting…", meter, then Stop and the three copies.
presence: [f32; 7],
pending: Option<[f32; 4]>,
elapsed: Option<[f32; 4]>,
glyph: Option<[f32; 4]>,
label: Option<([f32; 4], String)>,
title: Option<String>,
field: bool,
}
/// Plays `replay`, handing every frame to `each` once it is laid out.
fn play(
replay: &Replay,
mut each: impl FnMut(usize, &mut Runtime<Capsule>, &Shot),
) -> Vec<Shot> {
use stage::Layer;
let size = (500., 328.5);
let kind = if replay.live {
live_recording("replay")
} else {
offer(
provider_cases()
.into_iter()
.find(|(s, _)| *s == "meet")
.unwrap()
.1,
)
};
let (mut rt, commands, _) = runtime(kind, false, true, size);
rt.transparent = true;
rt.set_system_reduced_motion(replay.reduced);
rt.update(|c, tx| {
c.corner = MeetingIndicatorCorner::TopRight;
tx.instant();
});
rt.frame(0.);
let clock = Instant::now();
let at = |frame: usize| clock + Duration::from_secs_f64(frame as f64 / 60.);
if replay.live {
rt.state.waveform = Some(Box::new(waveform::Listening::new(clock)));
rt.state.live.entries = call();
}
let mut host = match rt.state.kind.as_ref() {
Some(Kind::Offer(id, _)) => offer::Host::Offered(*id),
_ => offer::Host::default(),
};
let mut live_since = replay.live.then_some(0usize);
let mut pressed = None;
let mut shots = Vec::new();
for frame in 0..replay.frames {
for (_, cue) in replay.cues.iter().filter(|(at, _)| *at == frame) {
match *cue {
Cue::Move(x, y) => rt.pointer_move(x, y),
Cue::Over(key) => {
let (x, y) = rt.find(key).unwrap_or_else(|| panic!("no {key} at {frame}"));
rt.pointer_move(x, y);
}
Cue::Leave => rt.pointer_leave(),
Cue::Record => {
let (x, y) = rt.find("record").unwrap();
rt.pointer_down(x, y);
rt.pointer_up(x, y);
pressed = Some(*cue);
}
Cue::Started => {
let event = started("replay");
assert_eq!(host.route(&event), offer::Route::Inherit);
let mut model = PillModel::default();
model.apply(&event, Instant::now());
let shown = model.pill(true).unwrap().clone();
rt.update(move |c, tx| {
c.start_recording(shown, tx);
c.live.entries = call();
});
rt.state.waveform = Some(Box::new(waveform::Listening::new(at(frame))));
live_since = Some(frame);
}
Cue::Refused => {
let event = ControllerEvent::Failed {
title: "Fixture".into(),
error: "Permission denied".into(),
};
assert_eq!(host.route(&event), offer::Route::Close);
rt.update(|c, _| c.close());
}
Cue::PressStop => {
// Wherever the pointer is, Stop is pressed where it is drawn.
let (x, y) = rt.find("stop").unwrap_or_else(|| panic!("no Stop at {frame}"));
rt.pointer_move(x, y);
rt.pointer_down(x, y);
rt.pointer_up(x, y);
pressed = Some(*cue);
}
Cue::Stopped => {
rt.update(|c, tx| {
c.capture_stopped();
c.stir(tx);
});
}
Cue::Published => rt.update(|c, tx| {
let Kind::Ready(mut m) = ready_transcript() else {
unreachable!()
};
m.duration_ms = Some(5_000);
c.published(m);
c.stir(tx);
}),
Cue::Notes => rt.update(|c, _| {
let Kind::Ready(mut m) = ready_summarized() else {
unreachable!()
};
m.duration_ms = Some(5_000);
c.refresh_ready(m);
}),
}
}
if let Some(since) = live_since {
// The app's clock tick: the time redraws without any other cause.
let run = if replay.live { 258_000 } else { 0 } + (frame - since) as u64 * 1000 / 60;
rt.update(move |c, _| {
if let Some(Kind::Recording(shown)) = &mut c.kind {
shown.started = Instant::now() - Duration::from_millis(run);
}
});
}
waveform::feed(&mut rt.state, at(frame), || replay_levels(replay, frame));
rt.frame(1. / 60.);
// A press is carried out in its own frame; nothing waits for motion.
match pressed.take() {
Some(Cue::Record) => {
let Ok(ControllerCommand::Record(_, Some(id))) = commands.try_recv() else {
panic!("Record not sent")
};
assert_eq!(
host.route(&ControllerEvent::Starting(Some(id))),
offer::Route::Keep
);
}
Some(_) => {
assert!(matches!(commands.try_recv(), Ok(ControllerCommand::Stop)));
assert!(rt.state.stopping, "Stop is true the frame it is pressed");
}
None => (),
}
assert!(commands.try_recv().is_err(), "an unasked command at {frame}");
let c = &rt.state;
let rect = |key: &str| rt.presented(key).map(|(rect, _)| rect);
let shot = Shot {
phase: match &c.kind {
None => "closed",
Some(Kind::Offer(..)) if c.presentation.departing() => "starting",
Some(Kind::Offer(..)) => "offer",
Some(Kind::Recording(_)) if c.stopping => "stopping",
Some(Kind::Recording(_)) => "recording",
Some(Kind::Finalizing { .. }) => "transcribing",
Some(Kind::Ready(m)) if m.notes.is_some() => "summary",
Some(Kind::Ready(_)) => "published",
_ => "other",
},
pill: rect("pill"),
velocity: c.stage.velocity(),
veil: c.stage.veil(),
presence: [
Layer::Offer,
Layer::Pending,
Layer::Meter,
Layer::Action(0),
Layer::Action(1),
Layer::Action(2),
Layer::Action(3),
]
.map(|layer| c.stage.presence(layer).opacity),
pending: rect("pending"),
elapsed: rect("elapsed"),
glyph: rt
.elements()
.into_iter()
.find(|e| e.key.as_deref() == Some("stop"))
.and(rect("glyph")),
label: rt.find("stop").and_then(|_| {
let stop = rt.presented("stop")?.0;
rt.elements()
.into_iter()
.filter(|e| e.key.as_deref() == Some("label"))
.find(|e| e.rect[1] >= stop[1] && e.rect[1] < stop[1] + stop[3])
.map(|e| (e.rect, e.text.unwrap_or_default()))
}),
title: rt
.elements()
.into_iter()
.find(|e| e.key.as_deref() == Some("title"))
.and_then(|e| e.text),
field: rt.find("meeting-listening-field").is_some(),
};
each(frame, &mut rt, &shot);
shots.push(shot);
}
shots
}
fn replay(name: &str) -> &'static Replay {
REPLAYS.iter().find(|r| r.name == name).unwrap()
}
/// The right and top edges of the surface never leave the saved corner.
fn anchored(shots: &[Shot]) {
for (frame, shot) in shots.iter().enumerate() {
let Some([x, y, w, _]) = shot.pill else {
continue;
};
assert!(
(x + w - (500. - CAPSULE_INSET)).abs() < 0.03 && (y - CAPSULE_INSET).abs() < 0.03,
"f{frame}: {:?}",
shot.pill
);
}
}
/// The drafts entered "Starting…" at the centre of a shell that was still
/// contracting, so the words rode 90 pt across the screen; and they showed it
/// for a start that took three frames.
#[test]
fn starting_keeps_its_place_and_a_quick_start_never_says_it() {
let shots = play(replay("delayed"), |_, _, _| {});
anchored(&shots);
// Its centre: it arrives a little small, about that point.
let seen: Vec<(f32, f32)> = shots
.iter()
.filter_map(|s| s.pending)
.map(|r| (r[0] + r[2] / 2., r[1] + r[3] / 2.))
.collect();
assert!(seen.len() > 60, "a slow start says Starting…");
let rest = (500. - CAPSULE_INSET - REST_WIDTH / 2., CAPSULE_INSET + REST_HEIGHT / 2.);
assert!(
seen.iter()
.all(|at| (at.0 - rest.0).abs() < 0.05 && (at.1 - rest.1).abs() < 0.05),
"Starting… moved: {:?} from {rest:?}",
seen.iter().find(|at| (at.0 - rest.0).abs() >= 0.05)
);
// It waits until the start has been slow, and leaves as the time arrives.
assert!(shots[24..34].iter().all(|s| s.presence[1] == 0.0));
let last = shots.last().unwrap();
assert_eq!((last.presence[1], last.presence[2]), (0.0, 1.0));
assert_eq!(last.pill.map(|r| (r[2], r[3])), Some((REST_WIDTH, REST_HEIGHT)));
let shots = play(replay("fast"), |_, _, _| {});
anchored(&shots);
assert!(shots.iter().all(|s| s.presence[1] == 0.0 && s.pending.is_none()));
// The offer contracts straight into the live pill, never growing back.
let widths: Vec<f32> = shots[24..].iter().filter_map(|s| s.pill).map(|r| r[2]).collect();
assert!(widths.windows(2).all(|w| w[1] <= w[0] + 0.02));
assert_eq!(*widths.last().unwrap(), REST_WIDTH);
}
/// The drafts opened the width and height on one spring and mounted every
/// row whole in the first frame, cut by the moving edges.
#[test]
fn the_panel_opens_width_first_and_its_rows_follow_in_order() {
let shots = play(replay("whole"), |_, _, _| {});
anchored(&shots);
let open = &shots[172..232];
let (mut led, mut ordered) = (0, 0);
for shot in open {
let [_, _, w, h] = shot.pill.unwrap();
let (dw, dh) = (
(w - REST_WIDTH) / (PANEL_WIDTH - REST_WIDTH),
(h - REST_HEIGHT) / (219. - REST_HEIGHT),
);
if dh > 0.02 && dh < 0.98 {
assert!(dw > dh, "the width trails at {w}×{h}");
led += 1;
}
let rows = &shot.presence[3..];
assert!(rows.windows(2).all(|p| p[0] >= p[1]), "{rows:?}");
ordered += usize::from(rows[0] > rows[3] && rows[3] > 0.0);
// A moving edge is soft; a resting one cuts nothing.
assert_eq!(shot.veil.0 > 0.0, shot.velocity.0 != 0.0 || shot.veil.0 > 0.0);
}
assert!(led > 8 && ordered > 4, "{led} {ordered}");
assert!(open[1].presence[6] == 0.0, "the last row waits its turn");
let rest = &shots[240];
assert_eq!((rest.veil, rest.velocity), ((0., 0.), (0., 0.)));
assert_eq!(rest.presence[3..], [1.0; 4]);
}
/// The drafts dropped Stop's glyph in the frame of the press and moved its
/// label 17 pt to restyle it. Then the field was cut the frame capture ended.
#[test]
fn stop_says_stopping_in_place_and_the_field_cools() {
let shots = play(replay("whole"), |_, _, _| {});
let (before, after) = (&shots[403], &shots[404]);
assert_eq!((before.phase, after.phase), ("recording", "stopping"));
assert_eq!(before.glyph, after.glyph);
assert!(after.glyph.is_some());
let (was, now) = (before.label.clone().unwrap(), after.label.clone().unwrap());
assert_eq!((was.1.as_str(), now.1.as_str()), ("Stop", "Stopping…"));
assert_eq!(was.0[..2], now.0[..2], "the label's first letters moved");
// Capture ends at 425: the field is still drawn, quieter each frame.
assert_eq!(shots[425].phase, "transcribing");
assert!(shots[425].field && shots[440].field);
assert!(shots[460].phase == "transcribing" && !shots[460].field);
// Stop leaves over several frames while the title arrives.
assert!(shots[426].presence[3] > 0.2 && shots[426].presence[3] < 1.0);
assert_eq!(shots[460].presence[3], 0.0);
// The time never moves through any of it.
let clock = shots[400].elapsed.unwrap();
for (frame, shot) in shots.iter().enumerate().skip(400) {
let now = shot.elapsed.unwrap();
assert!(
(now[0] - clock[0]).abs() < 0.03 && (now[1] - clock[1]).abs() < 0.03,
"f{frame}: {now:?}"
);
}
}
/// A pointer that comes and goes mid-flight turns the surface round from
/// where it is, at the speed it has; nothing restarts from rest.
#[test]
fn an_interrupted_panel_turns_round_without_a_stop_or_a_jump() {
let shots = play(replay("interrupted"), |_, _, _| {});
anchored(&shots);
let sizes: Vec<(f32, f32)> = shots
.iter()
.map(|s| s.pill.map(|r| (r[2], r[3])).unwrap())
.collect();
// No frame moves the edge by more than a frame of its peak speed, and
// its speed never changes by more than the spring can turn it.
for (frame, w) in sizes.windows(3).enumerate() {
let (a, b) = (w[1].1 - w[0].1, w[2].1 - w[1].1);
assert!(b.abs() < 20.0, "f{frame}: a {b} pt step");
assert!((b - a).abs() < 15.0, "f{frame}: speed {a} → {b}");
}
// Leaving at 20 reverses an opening panel: it carries on a little first.
assert!(sizes[20].1 > sizes[19].1 && sizes[24].1 < sizes[21].1);
let last = shots.last().unwrap();
assert_eq!(last.phase, "summary");
assert_eq!((last.veil, last.velocity), ((0., 0.), (0., 0.)));
}
#[test]
fn reduced_motion_lands_the_surface_and_only_fades() {
let shots = play(replay("reduced"), |_, _, _| {});
anchored(&shots);
for (frame, pair) in shots.windows(2).enumerate() {
assert_eq!(pair[1].veil, (0., 0.));
let (Some(a), Some(b)) = (pair[0].pill, pair[1].pill) else {
continue;
};
if pair[1].phase == "summary" || pair[1].phase == "offer" {
continue;
}
// The outline is either where it was or where it is going.
let rests = [
(REST_WIDTH, REST_HEIGHT),
(PANEL_WIDTH, 219.),
(a[2], a[3]),
];
assert!(
rests
.iter()
.any(|(w, h)| (b[2] - w).abs() < 0.03 && (b[3] - h).abs() < 0.03),
"f{frame}: {a:?} → {b:?}"
);
}
}
#[test]
fn hud_replay_frames() {
use crate::rune_ui::offscreen;
use std::fmt::Write;
let Some(root) = std::env::var_os("HEX_HUD_REPLAY") else {
return;
};
let root = std::path::PathBuf::from(root);
let only = std::env::var("HEX_HUD_CASE").ok();
let gpu = rune::render::Gpu::try_new(rune::render::Gpu::instance(), None).unwrap();
for replay in REPLAYS {
if only.as_deref().is_some_and(|name| name != replay.name) {
continue;
}
let dir = root.join(replay.name);
std::fs::create_dir_all(&dir).unwrap();
let (w, h) = (1000, 657);
let mut renderer = offscreen::renderer(&gpu.device);
let target = offscreen::target(&gpu.device, w, h);
let mut ink = waveform::Ink::default();
let shots = play(replay, |frame, rt, _| {
let pixels = if rt.state.kind.is_some() {
paint_recording(&gpu, &mut renderer, &target, rt, &mut ink)
} else {
vec![0; (w * h * 4) as usize]
};
rune::render::write_png(&dir.join(format!("{frame:03}.png")), w, h, &pixels).unwrap();
});
let mut trace = String::from(
"frame,phase,x,y,w,h,vw,vh,veil_x,veil_y,offer,pending,meter,stop,copy_new,copy_all,copy_prompt,pending_x,elapsed_x,elapsed_y,label_x,title,field\n",
);
for (frame, s) in shots.iter().enumerate() {
let [x, y, pw, ph] = s.pill.unwrap_or_default();
let p = s.presence;
let at = |r: Option<[f32; 4]>, i: usize| r.map_or(String::new(), |r| r[i].to_string());
writeln!(
trace,
"{frame},{},{x},{y},{pw},{ph},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}",
s.phase,
s.velocity.0,
s.velocity.1,
s.veil.0,
s.veil.1,
p[0],
p[1],
p[2],
p[3],
p[4],
p[5],
p[6],
at(s.pending, 0),
at(s.elapsed, 0),
at(s.elapsed, 1),
s.label.as_ref().map_or(String::new(), |l| l.0[0].to_string()),
s.title.clone().unwrap_or_default().replace(',', " "),
u8::from(s.field),
)
.unwrap();
}
std::fs::write(dir.join("trace.csv"), trace).unwrap();
}
}
+497
View File
@@ -0,0 +1,497 @@
//! The recording host's one surface. Its outline and the presence of what is
//! drawn in it are tracks stepped here: a change of state gives a track a new
//! target and the track bends toward it from where it is, at the speed it
//! has. Nothing restarts, and nothing waits for a track: the controller's
//! state is true the moment it arrives and the surface catches up.
//!
//! Content is laid out at its final size, anchored to the saved corner; only
//! the outline moves over it. While an edge moves, what it crosses fades
//! under it in proportion to the edge's speed, so nothing is cut hard in
//! flight and nothing is dimmed at rest.
use rune::Spring;
/// The outline: the body opens and closes on these, and the width leads.
const OPEN: Spring = Spring::new(0.42, 0.0);
const CLOSE: Spring = Spring::new(0.38, 0.0);
/// The width's share of the body's duration (0.37 beside 0.45).
const WIDTH_LEAD: f32 = 0.82;
/// What arrives, and what leaves (sooner).
pub(super) const ENTER: Spring = Spring::new(0.3, 0.0);
pub(super) const EXIT: Spring = Spring::new(0.25, 0.0);
/// Reduce Motion: no travel, a short fade.
pub(super) const REDUCED: Spring = Spring::new(0.18, 0.0);
/// Details follow the main change, most important first.
pub(super) const STAGGER: f64 = 0.04;
/// An edge at full speed fades this much of what it crosses.
const VEIL: f32 = 24.0;
/// Seconds of an edge's travel its fade covers.
const VEIL_REACH: f32 = 0.035;
/// The fade follows the edge's speed over this long, so it never pops on.
const VEIL_EASE: f32 = 0.05;
/// How far an arriving or leaving layer shrinks and softens.
const LAYER_SCALE: f32 = 0.96;
const LAYER_BLUR: f32 = 3.0;
/// One sprung value.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(super) struct Track {
pub(super) x: f32,
pub(super) v: f32,
}
impl Track {
pub(super) const fn at(x: f32) -> Self {
Self { x, v: 0.0 }
}
/// Bends toward `to` from where it is; true while it still moves.
/// `rest` is the distance that no longer shows.
fn step(&mut self, to: f32, spring: Spring, dt: f32, rest: f32) -> bool {
if self.x == to && self.v == 0.0 {
return false;
}
let (x, v) = spring.sample(self.x, self.v, to, dt);
*self = if (x - to).abs() < rest && v.abs() < rest * 20.0 {
Self::at(to)
} else {
Self { x, v }
};
true
}
}
/// Where the surface is heading.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Outline {
pub(super) w: f32,
pub(super) h: f32,
pub(super) radius: f32,
/// 0 follows the host's appearance; 1 is the recording's dark surface.
pub(super) dark: f32,
}
/// What can be drawn in the surface. Each has a presence from 0 to 1.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Layer {
/// The detected call and its actions.
Offer,
/// "Starting…", once a start has been slow enough to need saying.
Pending,
/// The listening field and timer.
Meter,
/// Stop and the three copies, in order of importance.
Action(usize),
}
pub(super) const ACTIONS: usize = 4;
const LAYERS: usize = 3 + ACTIONS;
impl Layer {
fn index(self) -> usize {
match self {
Layer::Offer => 0,
Layer::Pending => 1,
Layer::Meter => 2,
Layer::Action(row) => 3 + row.min(ACTIONS - 1),
}
}
}
/// The state a frame steps toward.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Target {
pub(super) outline: Outline,
pub(super) offer: bool,
/// Since when "Starting…" has been wanted.
pub(super) pending: Option<f64>,
pub(super) meter: bool,
/// Since when the actions have been wanted.
pub(super) actions: Option<f64>,
/// Stop is one of them. Once capture has ended it leaves and the copies stay.
pub(super) stop: bool,
}
impl Target {
fn wants(&self, layer: Layer, now: f64) -> bool {
match layer {
Layer::Offer => self.offer,
Layer::Pending => self.pending.is_some_and(|since| now >= since),
Layer::Meter => self.meter,
Layer::Action(row) => {
(row > 0 || self.stop)
&& self
.actions
.is_some_and(|since| now >= since + row as f64 * STAGGER)
}
}
}
}
/// A layer as it is drawn this frame.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Presence {
pub(super) opacity: f32,
pub(super) scale: f32,
pub(super) blur: f32,
}
impl Presence {
pub(super) fn shows(self) -> bool {
self.opacity > 0.0
}
/// Enough of it shows to act on.
pub(super) fn takes_input(self) -> bool {
self.opacity >= 0.5
}
}
#[derive(Default)]
pub(super) struct Stage {
/// Width, height, radius, dark. `None` until something shows: a surface
/// appears at rest, it doesn't animate its first frame.
outline: Option<[Track; 4]>,
layers: [Track; LAYERS],
last: Option<f64>,
/// When the outline last followed another motion.
followed: Option<f64>,
/// The outline itself is in flight, not only a layer.
travelling: bool,
waiting: bool,
veil: (f32, f32),
reduced: bool,
}
impl Stage {
pub(super) fn outline(&self) -> Option<Outline> {
self.outline.map(|[w, h, radius, dark]| Outline {
w: w.x,
h: h.x,
radius: radius.x,
dark: dark.x,
})
}
/// Points per second: how fast the width and height are changing.
#[cfg(test)]
pub(super) fn velocity(&self) -> (f32, f32) {
self.outline.map_or((0.0, 0.0), |[w, h, ..]| (w.v, h.v))
}
pub(super) fn resting(&self) -> bool {
self.last.is_none()
}
/// The outline is on its way somewhere.
pub(super) fn travelling(&self) -> bool {
self.travelling
}
/// How much of what the moving vertical and horizontal edges cross fades
/// under them: nothing at rest, more the faster they travel.
pub(super) fn veil(&self) -> (f32, f32) {
self.veil
}
fn ease_veil(&mut self, dt: f32) {
let Some([w, h, ..]) = self.outline else {
return;
};
let reach = |track: Track, size: f32| {
(track.v.abs() * VEIL_REACH)
.min(VEIL)
.min(size * 0.5)
.max(0.0)
};
let ease = 1.0 - (-dt / VEIL_EASE).exp();
let toward = |from: f32, to: f32| {
let next = from + (to - from) * ease;
if to == 0.0 && next < 0.05 { 0.0 } else { next }
};
self.veil = if self.reduced {
(0.0, 0.0)
} else {
(
toward(self.veil.0, reach(w, w.x)),
toward(self.veil.1, reach(h, h.x)),
)
};
}
pub(super) fn presence(&self, layer: Layer) -> Presence {
let p = self.layers[layer.index()].x.clamp(0.0, 1.0);
// The meter and the actions stay where they are: they only fade.
let soft = matches!(layer, Layer::Offer | Layer::Pending) && !self.reduced;
Presence {
opacity: p,
scale: if soft {
LAYER_SCALE + (1.0 - LAYER_SCALE) * p
} else {
1.0
},
blur: if soft { LAYER_BLUR * (1.0 - p) } else { 0.0 },
}
}
/// The surface as `target` describes it, at rest.
pub(super) fn land(&mut self, target: &Target, now: f64) {
let o = target.outline;
self.outline = Some([o.w, o.h, o.radius, o.dark].map(Track::at));
for layer in Self::layers() {
self.layers[layer.index()] = Track::at(f32::from(target.wants(layer, now)));
}
self.last = None;
self.travelling = false;
self.veil = (0.0, 0.0);
}
/// The outline follows something else's motion (the offer's own pages):
/// it takes that place and remembers the speed it arrived with, so a
/// change of state mid-way carries on from there.
pub(super) fn follow(&mut self, target: &Target, now: f64) {
let o = target.outline;
let to = [o.w, o.h, o.radius, o.dark];
let from = self.outline;
let dt = self.followed.replace(now).map(|last| (now - last) as f32);
self.land(target, now);
if let (Some(from), Some(dt), Some(tracks)) = (
from,
dt.filter(|dt| *dt > 0.0 && *dt < 0.1),
&mut self.outline,
) {
for ((track, from), to) in tracks.iter_mut().zip(from).zip(to) {
track.v = (to - from.x) / dt;
}
}
}
/// Steps every track toward `target`; true while anything still moves.
pub(super) fn step(&mut self, target: &Target, reduced: bool, now: f64) -> bool {
self.reduced = reduced;
self.followed = None;
let Some(tracks) = &mut self.outline else {
self.land(target, now);
return true;
};
let dt = self
.last
.map_or(1.0 / 60.0, |last| (now - last).clamp(0.0, 0.1) as f32);
let o = target.outline;
let mut moving = false;
if reduced {
let to = [o.w, o.h, o.radius, o.dark];
for (track, to) in tracks.iter_mut().zip(to) {
moving |= *track != Track::at(to);
*track = Track::at(to);
}
} else {
let body = if o.w * o.h >= tracks[0].x * tracks[1].x {
OPEN
} else {
CLOSE
};
let width = body.with_duration(body.duration * WIDTH_LEAD);
moving |= tracks[0].step(o.w, width, dt, 0.01);
moving |= tracks[1].step(o.h, body, dt, 0.01);
moving |= tracks[2].step(o.radius, body, dt, 0.01);
moving |= tracks[3].step(o.dark, body, dt, 0.002);
}
self.travelling = moving;
self.ease_veil(dt);
moving |= self.veil != (0.0, 0.0);
let mut waiting = false;
for layer in Self::layers() {
let wants = target.wants(layer, now);
let spring = match (reduced, wants) {
(true, _) => REDUCED,
(false, true) => ENTER,
(false, false) => EXIT,
};
moving |= self.layers[layer.index()].step(f32::from(wants), spring, dt, 0.002);
// A layer whose turn hasn't come keeps the clock running.
waiting |= !wants
&& match layer {
Layer::Pending => target.pending.is_some(),
Layer::Action(row) => target.actions.is_some() && (row > 0 || target.stop),
_ => false,
};
}
self.last = (moving || waiting).then_some(now);
self.waiting = waiting && !moving;
moving || waiting
}
/// Nothing drawn changed in the last step: a layer is only waiting its turn.
pub(super) fn idling(&self) -> bool {
self.waiting
}
fn layers() -> impl Iterator<Item = Layer> {
[Layer::Offer, Layer::Pending, Layer::Meter]
.into_iter()
.chain((0..ACTIONS).map(Layer::Action))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn target(w: f32, h: f32) -> Target {
Target {
outline: Outline {
w,
h,
radius: 13.0,
dark: 1.0,
},
offer: false,
pending: None,
meter: true,
actions: None,
stop: true,
}
}
#[test]
fn a_surface_appears_at_rest_and_moves_only_when_its_target_does() {
let mut stage = Stage::default();
assert!(stage.step(&target(148.0, 36.0), false, 0.0));
assert_eq!(stage.outline().unwrap().w, 148.0);
assert_eq!(stage.presence(Layer::Meter).opacity, 1.0);
assert!(!stage.step(&target(148.0, 36.0), false, 1.0 / 60.0));
assert!(stage.resting());
assert_eq!(stage.veil(), (0.0, 0.0));
}
/// The original discontinuity: a reversal restarted from rest, so the
/// edge stopped dead for a frame and the width and height moved as one.
#[test]
fn a_reversal_keeps_its_speed_and_the_width_leads() {
let mut stage = Stage::default();
let (rest, open) = (target(148.0, 36.0), target(252.0, 227.0));
stage.step(&rest, false, 0.0);
let mut now = 0.0;
let mut frame = |stage: &mut Stage, to: &Target| {
now += 1.0 / 60.0;
stage.step(to, false, now);
(stage.outline().unwrap(), stage.velocity())
};
let mut last = (148.0, 0.0);
for _ in 0..6 {
let (o, (vw, vh)) = frame(&mut stage, &open);
// Width leads: it has covered more of its way than the height.
assert!((o.w - 148.0) / 104.0 > (o.h - 36.0) / 191.0);
assert!(vw > 0.0 && vh > 0.0);
last = (o.w, vw);
}
// Reverse mid-flight: the edge carries on from the same place before
// it turns round. Restarting from rest would stop it dead here.
let (o, _) = frame(&mut stage, &rest);
assert!(
o.w > last.0 && o.w - last.0 < last.1 / 60.0,
"{} after {} at {} pt/s",
o.w,
last.0,
last.1
);
let mut widths = vec![o.w];
for _ in 0..90 {
widths.push(frame(&mut stage, &rest).0.w);
}
let peak = widths.iter().cloned().fold(0.0, f32::max);
let turn = widths.iter().position(|w| *w == peak).unwrap();
assert!(widths[turn..].windows(2).all(|w| w[1] <= w[0]));
assert_eq!(*widths.last().unwrap(), 148.0);
assert!(stage.resting());
}
#[test]
fn a_moving_edge_fades_what_it_crosses_and_a_resting_one_cuts_nothing() {
let mut stage = Stage::default();
stage.step(&target(148.0, 36.0), false, 0.0);
let open = target(252.0, 227.0);
let mut peak = (0.0f32, 0.0f32);
let mut last = (0.0, 0.0);
for frame in 1..=90 {
stage.step(&open, false, frame as f64 / 60.0);
let veil = stage.veil();
// The fade never pops: it grows and shrinks with the edge's speed.
assert!((veil.0 - last.0).abs() < 6.0 && (veil.1 - last.1).abs() < 6.0);
peak = (peak.0.max(veil.0), peak.1.max(veil.1));
last = veil;
}
assert!(peak.0 > 12.0 && peak.1 > 12.0 && peak.0 <= VEIL && peak.1 <= VEIL);
assert_eq!(stage.veil(), (0.0, 0.0));
}
#[test]
fn actions_arrive_in_order_and_leave_together() {
let mut stage = Stage::default();
stage.step(&target(148.0, 36.0), false, 0.0);
let open = Target {
actions: Some(0.0),
..target(252.0, 227.0)
};
for frame in 1..=6 {
stage.step(&open, false, frame as f64 / 60.0);
}
let shown: Vec<f32> = (0..ACTIONS)
.map(|row| stage.presence(Layer::Action(row)).opacity)
.collect();
assert!(shown.windows(2).all(|p| p[0] > p[1]), "{shown:?}");
assert!(stage.presence(Layer::Action(0)).blur == 0.0);
let closed = target(148.0, 36.0);
for frame in 7..=60 {
stage.step(&closed, false, frame as f64 / 60.0);
}
assert!((0..ACTIONS).all(|row| !stage.presence(Layer::Action(row)).shows()));
}
#[test]
fn a_fast_start_never_shows_the_pending_label() {
let mut stage = Stage::default();
let offer = Target {
offer: true,
meter: false,
..target(416.0, 44.0)
};
stage.step(&offer, false, 0.0);
let pending = Target {
pending: Some(0.18),
meter: false,
..target(148.0, 36.0)
};
for frame in 1..=3 {
assert!(stage.step(&pending, false, frame as f64 / 60.0));
assert!(!stage.presence(Layer::Pending).shows());
}
let live = target(148.0, 36.0);
for frame in 4..=90 {
stage.step(&live, false, frame as f64 / 60.0);
assert!(!stage.presence(Layer::Pending).shows());
}
assert_eq!(stage.presence(Layer::Meter).opacity, 1.0);
assert!(stage.resting());
}
#[test]
fn reduced_motion_lands_the_outline_and_keeps_a_short_fade() {
let mut stage = Stage::default();
stage.step(&target(148.0, 36.0), true, 0.0);
let open = Target {
actions: Some(0.0),
..target(252.0, 227.0)
};
assert!(stage.step(&open, true, 1.0 / 60.0));
assert_eq!(stage.outline().unwrap().w, 252.0);
assert_eq!(stage.veil(), (0.0, 0.0));
let fading = stage.presence(Layer::Action(0));
assert!(fading.opacity > 0.0 && fading.opacity < 1.0 && fading.scale == 1.0);
for frame in 2..=40 {
stage.step(&open, true, frame as f64 / 60.0);
}
assert_eq!(stage.presence(Layer::Action(ACTIONS - 1)).opacity, 1.0);
}
}
+42 -12
View File
@@ -8,9 +8,11 @@ use rune::compose::{Compositor, DeviceKey, Frame};
use std::time::{Duration, Instant};
const KEY: &str = "meeting-listening-field";
const WIDTH: f32 = 78.0;
pub(super) const WIDTH: f32 = 78.0;
const ATTACK: Spec = Spec::new(0.16, 0.0);
const RELEASE: Spec = Spec::new(0.55, 0.0);
/// After capture ends the field lets go and fades over this long.
const COOL: Duration = Duration::from_millis(450);
/// Dot scope's default -60 dBFS noise floor, in the capture meter's RMS units.
const FLOOR: f32 = 0.001;
@@ -18,6 +20,7 @@ pub(super) fn slot() -> rune::El {
rune::el()
.key(KEY)
.size(WIDTH, crate::rune_hud::dot_scope::PLATE_HEIGHT)
.transition(rune::Transition::none())
.a11y_hidden()
}
@@ -26,6 +29,9 @@ pub(super) struct Listening {
drawn: Option<DotFrame>,
last: Instant,
presence: Spring,
/// When capture ended: the field fades from then until it has gone.
cooling: Option<Instant>,
fade: f32,
reduced: bool,
}
@@ -60,6 +66,8 @@ impl Listening {
drawn: None,
last: now,
presence: Spring::at(0.0),
cooling: None,
fade: 1.0,
reduced: false,
}
}
@@ -246,21 +254,43 @@ fn either_track_lights_the_same_field_and_silence_parks_it() {
}
pub(super) fn poll(c: &mut Capsule, _: f64, tx: &mut rune::Tx) -> bool {
if !matches!(c.kind, Some(Kind::Recording(_))) {
return false;
}
let Some(wave) = c.waveform.as_mut() else {
let Some((changed, moving)) = feed(c, Instant::now(), meeting::track_levels) else {
return false;
};
let changed = wave.sample(Instant::now(), meeting::track_levels());
tx.wake_after(Duration::from_millis(if wave.presence.x > 0.0 {
16
} else {
50
}));
if c.waveform.is_some() {
tx.wake_after(Duration::from_millis(if moving { 16 } else { 50 }));
}
changed
}
/// One sample of the field at `now`: whether what it draws changed, and
/// whether it is still moving. Once capture has ended no level is read: the
/// field releases as it does on a pause, then goes.
pub(super) fn feed(
c: &mut Capsule,
now: Instant,
levels: impl FnOnce() -> [f32; 2],
) -> Option<(bool, bool)> {
let recording = matches!(c.kind, Some(Kind::Recording(_)));
let cooling = matches!(c.kind, Some(Kind::Finalizing { .. } | Kind::Ready(_)));
if !recording && !cooling {
return None;
}
let wave = c.waveform.as_mut()?;
let changed = wave.sample(now, if recording { levels() } else { [0.0; 2] });
if cooling {
let since = *wave.cooling.get_or_insert(now);
let t = now.saturating_duration_since(since).as_secs_f32() / COOL.as_secs_f32();
if t >= 1.0 {
c.waveform = None;
} else {
wave.fade = 1.0 - t * t * (3.0 - 2.0 * t);
}
return Some((true, true));
}
Some((changed, wave.presence.x > 0.0))
}
#[derive(Default)]
pub(super) struct Ink(Option<(DeviceKey, Painter)>);
@@ -306,7 +336,7 @@ impl Compositor<Capsule> for Ink {
let painter = &self.0.as_ref().unwrap().1;
// The field is composited after the UI, so it must inherit the
// header's presented opacity explicitly during the offer handoff.
drawn.pose.opacity = opacity;
drawn.pose.opacity = opacity * wave.fade;
let uniforms = painter.write(drawn, Default::default(), target, |buf, bytes| {
f.queue.write_buffer(buf, 0, bytes)
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 15 KiB