use std::time::{Duration, Instant}; use super::watch::{FIRST_FRAME, FirstFrame, HUD_BACKOFF, HUD_BACKOFF_MAX}; use super::*; use crate::rune_hud::dot_scope::Tuning; /// A capture's capsule sits at the screen's top, so a dictation during one /// shows at the bottom; Hidden still hides it (Labs › Dictate while /// annotating). #[test] fn a_dictation_during_a_capture_shows_at_the_bottom_clear_of_the_capsule() { use IndicatorPosition::{Bottom, Hidden, Top}; assert_eq!(place_during_capture(Top, true), Bottom); assert_eq!(place_during_capture(Bottom, true), Bottom); assert_eq!(place_during_capture(Hidden, true), Hidden); assert_eq!(place_during_capture(Top, false), Top); assert_eq!(place_during_capture(Bottom, false), Bottom); assert_eq!(place_during_capture(Hidden, false), Hidden); } #[test] fn dot_uniform_layout_matches_wgsl() { assert_eq!(std::mem::offset_of!(DotUniforms, dark), 60); assert_eq!(std::mem::offset_of!(DotUniforms, base), 64); assert_eq!(std::mem::offset_of!(DotUniforms, shadow), 128); assert_eq!(std::mem::offset_of!(DotUniforms, plate_layout), 144); assert_eq!(std::mem::offset_of!(DotUniforms, island), 160); assert_eq!(std::mem::offset_of!(DotUniforms, field), 176); } #[test] fn only_gnome_and_kde_on_wayland_keep_the_primary_display() { for desktops in ["GNOME", "ubuntu:GNOME", "KDE"] { assert!(keeps_primary_display(Some(desktops), true), "{desktops}"); assert!(!keeps_primary_display(Some(desktops), false), "{desktops}"); } for desktops in [None, Some("sway"), Some("XFCE")] { assert!(!keeps_primary_display(desktops, true)); assert!(!keeps_primary_display(desktops, false)); } } #[test] fn dot_scope_window_fits_the_largest_plate() { let largest = |key| { dot_scope::KNOBS .iter() .find(|knob| knob.key == key) .map(|knob| knob.max) .unwrap() }; let widest = largest("dot-width").max(largest("dot-processing-width")); assert!(widest + 24.0 <= WINDOW.0); // The plate's middle sits in the window's; its shadow reaches about // 16 pt below it. assert!(largest("dot-height") / 2.0 + 19.0 <= WINDOW.1 / 2.0); } /// A pose at `reveal`, the rest settled. fn revealed(reveal: f32) -> dot_scope::Pose { dot_scope::Pose { width: 112.0, height: 26.0, opacity: 1.0, scale: 1.0, softness: 0.0, cool: 0.0, fail: 0.0, glow: 0.0, grid: 1.0, live: 0.0, reveal, level: 0.0, clock: 0.0, done: 0.0, shift: 0.0, } } /// Labs' ears grow from the housing's height to the menu bar's as they open, /// so folded back (a window shown for the frame before it grows, or ordered /// out after it folded) they are the notch itself, with no black lip under /// the camera, and open they end on the bar's bottom edge. #[test] fn the_ears_grow_from_the_housing_to_the_menu_bar() { let ears = Island { notch: [185.0, 32.0], bar: 34.0, width: 253.0, top: -64.0, ears: true, }; let shape = |reveal| island_shape(ears, &revealed(reveal)); assert_eq!(shape(0.0)[1], 32.0, "folded, it is the housing"); assert_eq!(shape(0.0)[3], NOTCH_RADIUS, "with the notch's corners"); assert_eq!(shape(1.0)[1], 34.0, "open, it reaches the menu bar's edge"); assert_eq!(shape(1.0)[3], EARS_RADIUS); assert_eq!(shape(1.4)[1], 34.0, "a bounce past full stops there"); assert!( (shape(0.5)[1] - 33.0).abs() < 1e-6, "and halfway is halfway" ); // Without a menu bar to open to, it keeps the housing's height. let unmeasured = Island { bar: 0.0, ..ears }; assert_eq!(island_shape(unmeasured, &revealed(1.0))[1], 32.0); } /// The macOS HUD's window, which the captures use on every OS so they line /// up with the Metal reference frames. const CAPTURE_DOT_WINDOW: (f32, f32) = (320.0, 128.0); /// A dictation, as the listener reports it, at 60 fps: HUD Lab's synthetic /// voice for 3 s, then transcribing, processing, and done. fn schedule(model: &mut IndicatorModel, start: Instant) -> Vec { let mut events = vec![ (0.0, HudEvent::Started), (3.0, HudEvent::Submitted { job_id: 1 }), (3.6, HudEvent::Processing { job_id: 1 }), (4.4, HudEvent::JobCompleted { job_id: 1 }), ]; events.reverse(); (0..330) .map(|n| { let t = n as f32 / 60.0; let now = start + Duration::from_secs_f32(t); while events.last().is_some_and(|(at, _)| *at <= t) { model.handle(events.pop().unwrap().1, now, false); } if t < 3.0 { // A microphone's RMS for the demo voice's loudness. let rms = 10_f32.powf(dot_scope::demo_loudness(t) / 20.0); let meter = HudEvent::Meter { average: rms, peak: (rms * 3.0).min(1.0), }; model.handle(meter, now, false); } model.step(now, 1.0 / 60.0, false) }) .collect() } /// A 1512 × 982 point 14-inch MacBook Pro: a 32 pt housing under a 34 pt /// menu bar, 185 pt wide. fn macbook() -> crate::rune_hud::hud_placement::Screen { crate::rune_hud::hud_placement::Screen { frame: crate::rune_hud::hud_placement::Rect { x: 0.0, y: 0.0, width: 1512.0, height: 982.0, }, visible: crate::rune_hud::hud_placement::Rect { x: 0.0, y: 0.0, width: 1512.0, height: 948.0, }, safe_top: 32.0, aux_left: 663.5, aux_right: 663.5, bar: 24.0, } } /// An Apple Studio Display at its default 2560 × 1440 points: no notch, a /// 24 pt menu bar. fn studio_display() -> crate::rune_hud::hud_placement::Screen { crate::rune_hud::hud_placement::Screen { frame: crate::rune_hud::hud_placement::Rect { x: 0.0, y: 0.0, width: 2560.0, height: 1440.0, }, visible: crate::rune_hud::hud_placement::Rect { x: 0.0, y: 0.0, width: 2560.0, height: 1416.0, }, bar: 24.0, ..Default::default() } } /// Where `screen` puts the capture window for `tuning`'s placement. fn place_on( screen: &crate::rune_hud::hud_placement::Screen, tuning: Tuning, ) -> crate::rune_hud::hud_placement::Placed { let (width, height) = CAPTURE_DOT_WINDOW; let content = crate::rune_hud::hud_placement::Content { window: (f64::from(width), f64::from(height)), plate: (f64::from(width) - 24.0, f64::from(dot_scope::PLATE_HEIGHT)), island_spread: f64::from(tuning.island_spread), }; // `HEX_HUD_EARS=1` places Labs' notch indicator instead. if std::env::var("HEX_HUD_EARS").as_deref() == Ok("1") && let Some(placed) = crate::rune_hud::hud_placement::ears(screen, content) { return placed; } crate::rune_hud::hud_placement::place( tuning.placement, screen, content, false, crate::rune_hud::hud_placement::BOTTOM_OFFSET, ) } /// What the screen shows behind the window. #[derive(Clone, Copy)] struct Backdrop { /// How far the window's top sits below the screen's, pt. drop: f32, /// The menu bar's height. bar: f32, /// The notch's width and height, if any. notch: Option<(f32, f32)>, } fn backdrop( screen: &crate::rune_hud::hud_placement::Screen, placed: &crate::rune_hud::hud_placement::Placed, ) -> Backdrop { Backdrop { drop: (screen.frame.y + screen.frame.height - placed.top_left.1) as f32, bar: screen.bar_height() as f32, notch: screen .notch() .map(|notch| (notch.width as f32, notch.height as f32)), } } /// Renders a dictation through the real shaders offscreen, as PNG frames /// at 60 fps over a desktop colour, from a fixed schedule: /// /// ```sh /// HEX_HUD_FRAMES=/tmp/frames cargo test --bin hex rune_hud_frames -- --ignored /// ``` /// /// `HEX_HUD_TUNING` overrides Dot scope's tuning as JSON, such as /// `{"processing": "pulse", "placement": "notch"}`, placed on a 14-inch /// MacBook Pro, or with `HEX_HUD_SCREEN=studio` on a Studio Display (no /// notch); `HEX_HUD_EARS=1` draws Labs' notch indicator; `HEX_HUD_THEME=light` draws over a light desktop. `HEX_HUD_DUMP=` also writes /// every frame's shader inputs, for rendering the same frames elsewhere. #[test] #[ignore = "writes frames for a review clip"] fn rune_hud_frames() { let out = std::path::PathBuf::from(std::env::var("HEX_HUD_FRAMES").expect("HEX_HUD_FRAMES")); std::fs::create_dir_all(&out).unwrap(); let dark = std::env::var("HEX_HUD_THEME").as_deref() != Ok("light"); let mut fields = serde_json::to_value(Tuning::default()).unwrap(); if let Ok(json) = std::env::var("HEX_HUD_TUNING") { let overrides: serde_json::Value = serde_json::from_str(&json).unwrap(); for (key, value) in overrides.as_object().unwrap() { fields[key] = value.clone(); } } let tuning: Tuning = serde_json::from_value(fields).unwrap(); let start = Instant::now(); let screen = if std::env::var("HEX_HUD_SCREEN").as_deref() == Ok("studio") { studio_display() } else { macbook() }; let placed = place_on(&screen, tuning); let layout = placed.layout; let backdrop = backdrop(&screen, &placed); let mut model = IndicatorModel::new(tuning, start); model.set_island(layout.island); let frames = schedule(&mut model, start); let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); let adapter = block_on(instance.request_adapter(&Default::default())).expect("a GPU adapter"); // `HEX_HUD_BUFFERS=1` draws through the uniform buffer, as a device // without immediates does. let features = if std::env::var("HEX_HUD_BUFFERS").as_deref() == Ok("1") { wgpu::Features::empty() } else { adapter.features() & Painter::FEATURES }; let (device, queue) = block_on(adapter.request_device(&wgpu::DeviceDescriptor { required_features: features, required_limits: wgpu::Limits { max_immediate_size: if features.is_empty() { 0 } else { adapter.limits().max_immediate_size }, ..Default::default() }, ..Default::default() })) .unwrap(); let format = wgpu::TextureFormat::Rgba8Unorm; let gpu = Painter::new(&device, format); let scale = 2.0; let window = CAPTURE_DOT_WINDOW; let size = ((window.0 * scale) as u32, (window.1 * scale) as u32); let extent = wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: 1, }; let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, size: extent, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, format, usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }); let view = texture.create_view(&Default::default()); let row = (size.0 * 4).div_ceil(256) * 256; let readback = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: u64::from(row * size.1), usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false, }); let target = Target::whole(size, scale); let mut dump = Vec::new(); dump.extend(size.0.to_le_bytes()); dump.extend(size.1.to_le_bytes()); for (n, frame) in frames.iter().enumerate() { dump.extend(bytes(&DotUniforms::new(frame, layout, target))); let mut packed = packed_dots(frame); packed.resize(DOT_BYTES as usize, 0); dump.extend(packed); let mut encoder = device.create_command_encoder(&Default::default()); let uniforms = gpu.write(frame, layout, target, |buffer, data| { queue.write_buffer(buffer, 0, data) }); gpu.draw(&mut encoder, &view, &uniforms); encoder.copy_texture_to_buffer( texture.as_image_copy(), wgpu::TexelCopyBufferInfo { buffer: &readback, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: None, }, }, extent, ); queue.submit([encoder.finish()]); readback .slice(..) .map_async(wgpu::MapMode::Read, |result| result.unwrap()); device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); let mapped = readback.slice(..).get_mapped_range().unwrap(); let mut rgba = Vec::with_capacity((size.0 * size.1 * 4) as usize); for y in 0..size.1 { rgba.extend_from_slice(&mapped[(y * row) as usize..][..(size.0 * 4) as usize]); } drop(mapped); readback.unmap(); write_over_desktop( &out.join(format!("{n:04}.png")), size, scale, &rgba, dark, backdrop, ); } if let Ok(path) = std::env::var("HEX_HUD_DUMP") { std::fs::write(path, dump).unwrap(); } } /// Premultiplied RGBA over the desktop colour, the menu bar, and the notch /// (`backdrop`), as an RGB PNG. fn write_over_desktop( path: &std::path::Path, size: (u32, u32), scale: f32, rgba: &[u8], dark: bool, backdrop: Backdrop, ) { let (desktop, menu_bar): ([f32; 3], [f32; 3]) = if dark { ([0.11, 0.11, 0.13], [0.2, 0.2, 0.22]) } else { ([0.93, 0.93, 0.94], [0.98, 0.98, 0.98]) }; let behind = |x: u32, y: u32| { // In points from the screen's top middle. let px = (x as f32 + 0.5) / scale - size.0 as f32 / scale / 2.0; let py = (y as f32 + 0.5) / scale + backdrop.drop; if let Some((width, height)) = backdrop.notch { // The notch's bottom corners are rounded 8 pt. let radius = 8.0; let dx = (px.abs() - (width / 2.0 - radius)).max(0.0); let dy = (py - (height - radius)).max(0.0); if px.abs() <= width / 2.0 && py <= height && dx.hypot(dy) <= radius { return [0.0; 3]; } } if py < backdrop.bar { menu_bar } else { desktop } }; let rgb: Vec = rgba .chunks(4) .enumerate() .flat_map(|(i, p)| { let under = behind(i as u32 % size.0, i as u32 / size.0); let a = f32::from(p[3]) / 255.0; (0..3).map(move |c| { let v = f32::from(p[c]) / 255.0 + under[c] * (1.0 - a); (v * 255.0).round().clamp(0.0, 255.0) as u8 }) }) .collect(); let file = std::fs::File::create(path).unwrap(); let mut encoder = png::Encoder::new(file, size.0, size.1); encoder.set_color(png::ColorType::Rgb); encoder.set_depth(png::BitDepth::Eight); encoder .write_header() .unwrap() .write_image_data(&rgb) .unwrap(); } fn block_on(future: F) -> F::Output { let mut future = std::pin::pin!(future); let mut cx = std::task::Context::from_waker(std::task::Waker::noop()); loop { if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut cx) { return output; } std::thread::yield_now(); } } #[test] fn a_frame_less_start_hides_once() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 7); let early = first_frame.poll(start + Duration::from_millis(100), 7, None, None); assert!(early.hide.is_none()); assert_eq!(early.reason, None); let resolved = first_frame.poll(start + FIRST_FRAME, 7, None, Some("dx12 on Intel")); assert!(resolved.hide.is_some(), "the attempt presented nothing"); assert!( resolved .reason .as_deref() .is_some_and(|reason| reason.contains("presented no frame")), "{:?}", resolved.reason ); let after = first_frame.poll(start + FIRST_FRAME + Duration::from_secs(1), 7, None, None); assert!(after.hide.is_none()); } #[test] fn a_new_start_does_not_hide_on_the_previous_reason() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 0); assert!( first_frame .poll(start + FIRST_FRAME, 0, None, None) .hide .is_some() ); // The last known reason stays in Settings, but it can't hide the next // start before that start has had its own first-frame window. let next = start + FIRST_FRAME + Duration::from_millis(1); first_frame.start(next, 0); let tick = first_frame.poll(next + Duration::from_millis(250), 0, None, None); assert!(tick.hide.is_none()); assert!( tick.reason.is_some(), "the last attempt's reason still shows" ); let just_before = first_frame.poll(next + FIRST_FRAME - Duration::from_millis(1), 0, None, None); assert!(just_before.hide.is_none()); } #[test] fn a_second_start_while_pending_restarts_the_attempt() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 5); let second = start + Duration::from_millis(900); first_frame.start(second, 5); // 1.5 s after the first start is only 600 ms into the second. let early = first_frame.poll(start + FIRST_FRAME, 5, None, None); assert!( early.hide.is_none(), "the second start gets its own first-frame window" ); // The second attempt's baseline is its own: one frame since then presents. let resolved = first_frame.poll(second + FIRST_FRAME, 6, None, None); assert!(resolved.hide.is_none()); assert_eq!(resolved.reason, None); } #[test] fn an_overlay_failure_never_hides_on_its_own() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 0); // Rune clears the failure it replaced on the overlay thread; a poll right // after the start still sees the previous attempt's. A failure is only a // reason for Settings and the log: it never hides anything by itself. for at in [ Duration::from_millis(1), Duration::from_millis(250), FIRST_FRAME - Duration::from_millis(1), ] { let check = first_frame.poll(start + at, 0, Some("device lost"), None); assert!(check.hide.is_none()); assert_eq!(check.reason.as_deref(), Some("device lost")); } // Even after the attempt resolves, a failure still set doesn't hide on its // own: the frame that presented is what matters. let presented = first_frame.poll(start + FIRST_FRAME, 1, Some("device lost"), None); assert!(presented.hide.is_none()); assert_eq!(presented.reason.as_deref(), Some("device lost")); } #[test] fn an_attempt_hides_only_once() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 0); assert!( first_frame .poll(start + FIRST_FRAME, 0, None, None) .hide .is_some() ); assert!( first_frame .poll( start + FIRST_FRAME + Duration::from_millis(250), 0, None, None ) .hide .is_none() ); assert!( first_frame .poll( start + FIRST_FRAME + Duration::from_millis(500), 0, Some("device lost"), None ) .hide .is_none(), "a later failure doesn't hide the attempt again" ); } #[test] fn the_next_start_hides_again_after_a_hide() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 3); assert!( first_frame .poll(start + FIRST_FRAME, 3, None, None) .hide .is_some(), "the first attempt presented nothing" ); // A start during the backoff opens no attempt, so there is no second hide // to make: the blocked show builds nothing, and the HUD is shown nothing. let during = start + FIRST_FRAME + Duration::from_secs(1); assert!(!first_frame.start(during, 4), "the HUD is backing off"); assert!( first_frame .poll(during + FIRST_FRAME, 4, None, None) .hide .is_none(), "a refused start has no attempt to hide" ); // After the cooldown the recovery is per start: that one gets its own hide // if it is frame-less too. let next = start + FIRST_FRAME + HUD_BACKOFF; assert!(first_frame.start(next, 4), "the cooldown ended"); assert!( first_frame .poll(next + FIRST_FRAME, 4, None, None) .hide .is_some(), "the next attempt presented nothing either" ); } /// A recovery hide is queued for the runtime thread to apply on the overlay's /// own thread, so a dictation that starts in between must keep the HUD its own /// start asked for (#1793). #[test] fn a_stale_attempts_hide_leaves_a_newer_start_alone() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 4); let hide = first_frame .poll(start + FIRST_FRAME, 4, None, None) .hide .expect("the attempt presented nothing"); assert!(first_frame.should_apply_hide(hide, 4)); // A start during the backoff opens no attempt, so it does not take the HUD // over: the stale hide still applies to the attempt that decided it. That // is harmless, since the refused start shows nothing (#2175). let during = start + FIRST_FRAME + Duration::from_millis(120); assert!(!first_frame.start(during, 4), "the HUD is backing off"); assert!( first_frame.should_apply_hide(hide, 4), "no later attempt owns the HUD" ); // A stale hide can still land after the cooldown, once a later dictation // has opened its own attempt: that start re-asserts the HUD, so the stale // hide must not run. let next = start + FIRST_FRAME + HUD_BACKOFF; assert!(first_frame.start(next, 4), "the cooldown ended"); assert!( !first_frame.should_apply_hide(hide, 4), "a later start owns the HUD now" ); // That start's own frame-less attempt still hides, and only it. let next_hide = first_frame .poll(next + FIRST_FRAME, 4, None, None) .hide .expect("the new attempt presented nothing either"); assert_ne!(next_hide.attempt, hide.attempt, "each attempt has its tag"); assert!(first_frame.should_apply_hide(next_hide, 4)); } /// The hide is applied a turn after it is decided, and a HUD that presented its /// first frame in between is up: hiding it would take away the HUD the user is /// watching, and report a failure that did not happen (#1793). #[test] fn a_hide_is_dropped_when_a_frame_presented_after_the_poll() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 0); let hide = first_frame .poll(start + FIRST_FRAME, 0, None, None) .hide .expect("the attempt presented nothing"); // The first frame lands between the poll and the queued hide. assert!( !first_frame.should_apply_hide(hide, 1), "one frame since the poll means the HUD is drawing" ); // The same poll's hide still applies when nothing presented. assert!(first_frame.should_apply_hide(hide, 0)); } /// The poll runs every 250 ms, so a slow first frame can present just after its /// attempt resolved frame-less. The queued recovery hide must not run, and the /// backoff stays: the show was still too slow to trust, but the HUD it put up /// belongs to this recording (#2175). #[test] fn a_late_first_frame_keeps_its_backoff_and_its_hud() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 0); let failed = first_frame.poll(start + FIRST_FRAME, 0, None, None); let hide = failed.hide.expect("the attempt presented nothing"); assert_eq!(failed.backoff, Some(HUD_BACKOFF)); // The first frame presents before the hide, queued for Rune's thread, lands. assert!( !first_frame.should_apply_hide(hide, 1), "the HUD is drawing, only late" ); assert!(first_frame.backing_off(start + FIRST_FRAME + Duration::from_secs(1))); assert!(first_frame.failed(), "the show was still too slow to trust"); // A dictation during the backoff opens no attempt, so it shows nothing. assert!(!first_frame.start(start + FIRST_FRAME + Duration::from_secs(2), 1)); } /// A blocked show only stops Hex from creating one; it never takes down a HUD a /// late frame put up. A fresh start tears down whatever an older recording left, /// while building nothing (#2175). #[test] fn a_blocked_show_keeps_a_hud_that_is_up() { assert!( !blocked_show_hides(false, true), "a late frame keeps its HUD" ); assert!( blocked_show_hides(false, false), "nothing is up, so hide is harmless" ); assert!( blocked_show_hides(true, true), "a blocked fresh start tears down what an older recording left" ); assert!( blocked_show_hides(true, false), "a blocked fresh start hides what nothing shows" ); } /// A HUD that presented nothing is not rebuilt for at least a minute: the next /// show would make another window, swapchain and device on the thread that /// pumps Windows' messages (#2175). #[test] fn a_failed_show_backs_off_for_a_minute() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); assert!(first_frame.start(start, 0)); let failed = first_frame.poll(start + FIRST_FRAME, 0, None, None); assert_eq!(failed.backoff, Some(HUD_BACKOFF)); assert!(first_frame.backing_off(start + FIRST_FRAME)); assert!(first_frame.backing_off(start + FIRST_FRAME + HUD_BACKOFF - Duration::from_millis(1))); assert!(!first_frame.backing_off(start + FIRST_FRAME + HUD_BACKOFF)); assert!(first_frame.failed(), "its recording gets no further show"); assert_eq!(first_frame.failed_attempts(), 1); } /// A start during the cooldown shows nothing; the first start after it shows /// again. #[test] fn show_is_skipped_while_backing_off_and_allowed_after() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 0); let failed_at = start + FIRST_FRAME; first_frame.poll(failed_at, 0, None, None); assert!(!first_frame.start(failed_at + Duration::from_secs(30), 0)); assert!(!first_frame.start(failed_at + HUD_BACKOFF - Duration::from_millis(1), 0)); assert!( first_frame.start(failed_at + HUD_BACKOFF, 0), "the cooldown ended" ); assert!(!first_frame.backing_off(failed_at + HUD_BACKOFF)); } /// Each further failed attempt doubles the wait, up to half an hour. #[test] fn consecutive_failures_double_up_to_thirty_minutes() { let mut at = Instant::now(); let mut first_frame = FirstFrame::default(); let mut cooldowns = Vec::new(); for _ in 0..7 { assert!( first_frame.start(at, 0), "the cooldown ended before this start" ); let failed_at = at + FIRST_FRAME; let cooldown = first_frame .poll(failed_at, 0, None, None) .backoff .expect("a frame-less attempt backs off"); cooldowns.push(cooldown); at = failed_at + cooldown; } assert_eq!( cooldowns, [ HUD_BACKOFF, Duration::from_secs(2 * 60), Duration::from_secs(4 * 60), Duration::from_secs(8 * 60), Duration::from_secs(16 * 60), HUD_BACKOFF_MAX, HUD_BACKOFF_MAX, ] ); } /// A show that presents proves the HUD works: the backoff ends, and the next /// failure starts from the first cooldown again. #[test] fn a_success_resets_the_backoff() { let mut at = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(at, 0); assert_eq!( first_frame.poll(at + FIRST_FRAME, 0, None, None).backoff, Some(HUD_BACKOFF) ); at += FIRST_FRAME + HUD_BACKOFF; assert!(first_frame.start(at, 5)); let presented = first_frame.poll(at + FIRST_FRAME, 6, None, None); assert_eq!(presented.backoff, None); assert!(!first_frame.backing_off(at + FIRST_FRAME)); assert!(!first_frame.failed()); assert_eq!(first_frame.failed_attempts(), 0); at += FIRST_FRAME; first_frame.start(at, 6); assert_eq!( first_frame.poll(at + FIRST_FRAME, 6, None, None).backoff, Some(HUD_BACKOFF), "the failures start over" ); } /// A recording whose own attempt presented nothing asks for the HUD no more; /// only a later dictation's start can, and only after the cooldown. #[test] fn a_failed_attempt_gets_no_second_show_in_its_capture() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 0); assert!(!first_frame.failed()); first_frame.poll(start + FIRST_FRAME, 0, None, None); assert!(first_frame.failed()); assert!(!first_frame.start(start + FIRST_FRAME + Duration::from_secs(1), 0)); assert!(first_frame.failed()); assert!(first_frame.start(start + FIRST_FRAME + HUD_BACKOFF, 0)); assert!(!first_frame.failed()); } /// Settings keeps the last failure's reason while the HUD backs off. #[test] fn a_backing_off_hud_still_reports_its_last_failure() { let start = Instant::now(); let mut first_frame = FirstFrame::default(); first_frame.start(start, 0); first_frame.poll(start + FIRST_FRAME, 0, None, Some("dx12 on NVIDIA")); let during = first_frame.poll( start + FIRST_FRAME + Duration::from_secs(1), 0, None, Some("dx12 on NVIDIA"), ); assert_eq!(during.backoff, None, "only the resolving poll backs off"); assert!( during .reason .as_deref() .is_some_and(|reason| reason.contains("dx12 on NVIDIA")), "{:?}", during.reason ); assert!(first_frame.backing_off(start + FIRST_FRAME + Duration::from_secs(1))); } /// `reshow_due` is the recording's own recovery: a HUD Rune declined or Hex hid /// is asked for once, after its frames stop, and never again in that recording /// (#1793). #[test] fn a_recording_asks_again_only_when_its_frames_stop() { let stale = RESHOW_AFTER + Duration::from_millis(1); let fresh = Duration::from_millis(16); // Frames are coming: nothing to do. assert!(!reshow_due(Some(fresh), false)); // Frames stopped: ask, once. assert!(reshow_due(Some(stale), false)); assert!(!reshow_due(Some(stale), true)); // A start sets the clock, so a frame the previous dictation left can't make // it look late. assert!(!reshow_due(None, false)); // A recovery hide re-arms the ask and restarts the clock: the meter right // after it is not late, and the next stale one asks once more (#1793). assert!(!reshow_due(Some(Duration::ZERO), false)); assert!(reshow_due(Some(stale), false)); } /// A HUD as `install` builds it, without its overlay: the state `handle` /// touches, and no GPU or Rune. `shown` is what `Hud::reveal` records once Rune /// took the show; a HUD with no overlay can't ask it. fn hud(shown: bool) -> Hud { let presence = if shown { HudPresence::Shown { #[cfg(target_os = "macos")] placed: None, #[cfg(not(target_os = "macos"))] edge_placed: None, } } else { HudPresence::Hidden }; Hud { model: IndicatorModel::new(dot_scope::lab(), Instant::now()), drawn: None, layout: Layout::default(), position: IndicatorPosition::Top, this: None, presence, #[cfg(target_os = "macos")] shown: Arc::new(AtomicBool::new(shown)), reduce: false, animating: Arc::new(AtomicBool::new(false)), #[cfg(not(target_os = "macos"))] followed: None, #[cfg(not(target_os = "macos"))] gpu: Arc::default(), #[cfg(target_os = "windows")] watch: Arc::default(), #[cfg(any(target_os = "windows", test))] last_drawn: None, #[cfg(any(target_os = "windows", test))] armed: false, #[cfg(any(target_os = "windows", test))] polled_at: None, #[cfg(target_os = "windows")] stepped_at: None, #[cfg(target_os = "windows")] reshown: false, } } /// An armed timer draws the next level itself, so a meter only updates the /// model; a timer that isn't armed draws nothing, so the meter's update draws /// one frame. Loudness moves either way. #[test] fn an_armed_timer_draws_for_meters_and_a_stopped_one_lets_a_meter_draw() { let mut hud = hud(true); hud.armed = true; let draws = windows_pacing::meter_update( &mut hud, HudEvent::Meter { average: 0.5, peak: 0.8, }, ); assert!(!draws, "the armed timer's frame shows the level"); assert!((hud.model.loudness() - dot_scope::loudness(0.5)).abs() < f32::EPSILON); hud.armed = false; let draws = windows_pacing::meter_update( &mut hud, HudEvent::Meter { average: 0.1, peak: 0.2, }, ); assert!(draws, "nothing else draws the level, so this meter does"); assert!((hud.model.loudness() - dot_scope::loudness(0.1)).abs() < f32::EPSILON); } /// The timer arms from a start's own time, before any frame it draws, so the /// first frame after the show asks for the next one. It stops arming once no /// frame has drawn for `RESHOW_AFTER`: a show that fails draws nothing, and an /// always-asking timer would turn Rune's loop at 60 Hz with Hex idle. A hidden /// HUD arms nothing either. #[test] fn the_timer_arms_from_a_start_and_stops_when_frames_stop() { let mut hud = hud(true); hud.animating.store(true, Ordering::Release); // `handle(Started)` is where a start's arming reference comes from. hud.handle(HudEvent::Started); assert!( hud.last_drawn.is_some_and(|at| at.elapsed() < RESHOW_AFTER), "the start is the first reference" ); windows_pacing::poll(&mut hud, 0.0, &mut rune::Tx::default()); assert!(hud.armed, "the start's frame asks for the next"); // Frames stop: the reference ages past `RESHOW_AFTER`. hud.last_drawn = Some(Instant::now() - RESHOW_AFTER - Duration::from_millis(1)); windows_pacing::poll(&mut hud, 0.0, &mut rune::Tx::default()); assert!(!hud.armed, "a stale reference asks for nothing"); // Hidden, even a fresh reference arms nothing. hud.last_drawn = Some(Instant::now()); hud.set_presence(HudPresence::Hidden); windows_pacing::poll(&mut hud, 0.0, &mut rune::Tx::default()); assert!(!hud.armed); } /// Every start clears cached placement on every OS (and `reveal` calls /// `overlay.show()` unconditionally), so a start isn't gated to the OSes whose /// own recovery needed it and never leaves a stale placement standing (#873). #[test] fn a_start_clears_placement_on_every_os() { let mut hud = hud(true); #[cfg(target_os = "macos")] { hud.set_placed(place_on(&studio_display(), Tuning::default())); assert!(hud.placed().is_some()); } #[cfg(not(target_os = "macos"))] { if let HudPresence::Shown { edge_placed } = &mut hud.presence { *edge_placed = Some(IndicatorPosition::Top); } } hud.handle(HudEvent::Started); #[cfg(target_os = "macos")] assert!(hud.placed().is_none()); #[cfg(not(target_os = "macos"))] assert!(matches!( hud.presence, HudPresence::Shown { edge_placed: None } )); } /// Explicit 4-state lifecycle of `FirstFrame`: Idle -> Waiting -> Presented, /// Waiting -> Failed (with backoff and single hide) -> Waiting (carrying prior /// failure count and reason) -> Presented (clearing prior failure). #[test] fn first_frame_state_machine_transitions() { let t0 = Instant::now(); let mut ff = FirstFrame::default(); assert!(matches!(ff, FirstFrame::Idle)); assert!(!ff.failed()); assert!(!ff.backing_off(t0)); assert_eq!(ff.failed_attempts(), 0); let idle_poll = ff.poll(t0, 0, None, None); assert!(idle_poll.hide.is_none()); assert!(idle_poll.backoff.is_none()); assert!(idle_poll.reason.is_none()); // Idle -> Waiting (attempt 1) assert!(ff.start(t0, 10)); assert!(matches!( ff, FirstFrame::Waiting { attempt: 1, presents: 10, prior: None, .. } )); // Waiting -> Presented (attempt 1) let ok = ff.poll(t0 + FIRST_FRAME, 11, None, None); assert!(ok.hide.is_none()); assert!(ok.backoff.is_none()); assert!(ok.reason.is_none()); assert!(matches!(ff, FirstFrame::Presented { attempt: 1 })); assert!(!ff.failed()); assert_eq!(ff.failed_attempts(), 0); // Presented -> Waiting (attempt 2) -> Failed (attempt 2) let t1 = t0 + FIRST_FRAME; assert!(ff.start(t1, 11)); assert!(matches!(ff, FirstFrame::Waiting { attempt: 2, .. })); let fail = ff.poll(t1 + FIRST_FRAME, 11, None, Some("dx12")); let hide = fail .hide .expect("Waiting -> Failed emits one recovery hide"); assert_eq!(hide.attempt, 2); assert_eq!(fail.backoff, Some(HUD_BACKOFF)); assert!(matches!( ff, FirstFrame::Failed { attempt: 2, failures: 1, .. } )); assert!(ff.should_apply_hide(hide, 11)); // Failed during backoff refuses start and stays Failed let t_during = t1 + FIRST_FRAME + Duration::from_secs(5); assert!(!ff.start(t_during, 11)); assert!(matches!( ff, FirstFrame::Failed { attempt: 2, failures: 1, .. } )); // Failed after backoff -> Waiting (attempt 3), carrying prior failure let t2 = t1 + FIRST_FRAME + HUD_BACKOFF; assert!(ff.start(t2, 11)); assert!(matches!( ff, FirstFrame::Waiting { attempt: 3, prior: Some(_), .. } )); assert!(!ff.failed()); assert_eq!(ff.failed_attempts(), 1); assert!( !ff.should_apply_hide(hide, 11), "new attempt invalidates prior hide" ); // Prior reason stays visible while attempt 3 waits, without hiding. let mid = ff.poll(t2 + Duration::from_millis(100), 11, None, None); assert!(mid.hide.is_none()); assert!(mid.reason.is_some()); // Waiting (with prior) -> Presented clears consecutive failures & reason. let recovered = ff.poll(t2 + FIRST_FRAME, 12, None, None); assert!(recovered.hide.is_none()); assert!(recovered.reason.is_none()); assert!(matches!(ff, FirstFrame::Presented { attempt: 3 })); assert_eq!(ff.failed_attempts(), 0); } /// Rune runs a poll before the frame's render, so a stall longer than /// `RESHOW_AFTER` leaves the next poll looking at a stale `last_drawn` even /// though the frame it is part of draws: that frame is the one the previous /// poll drew. It must arm the next, or a HUD with no meters to restart it /// (Transcribing, Completed, Failed) freezes on screen and never fades out. #[test] fn a_frame_drawn_since_the_last_poll_keeps_the_timer_armed() { let mut hud = hud(true); hud.animating.store(true, Ordering::Release); let polled = Instant::now() - RESHOW_AFTER - RESHOW_AFTER; hud.polled_at = Some(polled); // Older than RESHOW_AFTER, but the frame drew after that poll. hud.last_drawn = Some(polled + Duration::from_millis(1)); assert!( hud.last_drawn .is_some_and(|at| at.elapsed() >= RESHOW_AFTER), "the reference is stale on its own" ); windows_pacing::poll(&mut hud, 0.0, &mut rune::Tx::default()); assert!(hud.armed, "a frame since the last poll keeps the timer"); // Nothing drew since the last poll and the reference is stale: stop. hud.last_drawn = Some(Instant::now() - RESHOW_AFTER - Duration::from_millis(1)); windows_pacing::poll(&mut hud, 0.0, &mut rune::Tx::default()); assert!(!hud.armed, "no frame since the last poll, and a stale one"); }