Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf: repaint mic meters only when their fill moves a device pixel
Richie McIlroy65d2e5cceccc
diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rsindex b5aebb1b2..26858c12a 100644--- a/apps/desktop-gpui/src/app_windows.rs+++ b/apps/desktop-gpui/src/app_windows.rs@@ -6356,23 +6356,6 @@ pub fn arm_target_mode(kind: crate::main_window::TargetType, cx: &mut App) {.ok();}-/// Repaint the bar between its once-a-second ticks -- the mic meter updates at-/// up to ~20Hz and the bar is never the active window.-pub fn refresh_controls_window(cx: &mut App) {- let level_db = crate::feeds::Feeds::global(cx).read(cx).mic_level_db;- if let Some(handle) = cx.global::<AppWindows>().controls {- handle- .update(cx, |controls, window, cx| {- if !controls.level_bar_moves(level_db, window.scale_factor()) {- return;- }- cx.notify();- window.refresh();- })- .ok();- }-}-fn camera_window_number(cx: &mut App) -> Option<isize> {let handle = cx.global::<AppWindows>().camera?;handlediff --git a/apps/desktop-gpui/src/controls_window.rs b/apps/desktop-gpui/src/controls_window.rsindex 4636cf7e0..b32e98985 100644--- a/apps/desktop-gpui/src/controls_window.rs+++ b/apps/desktop-gpui/src/controls_window.rs@@ -10,13 +10,13 @@use std::time::Duration;use gpui::{- Context, Entity, FontWeight, InteractiveElement as _, IntoElement, MouseButton,- ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled, Window, div,- prelude::FluentBuilder as _, px, svg,+ AppContext as _, Context, Entity, FontWeight, InteractiveElement as _, IntoElement,+ MouseButton, ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled,+ Window, div, prelude::FluentBuilder as _, px, svg,};use crate::{- feeds::{self, Feeds},+ feeds::Feeds,recording::RecordingMode,session::{Phase, RecordingSession},theme::Theme,@@ -33,9 +33,7 @@ pub struct ControlsWindow {/// platform, so the tick both notifies and asks for a frame explicitly._tick: gpui::Task<()>,ticking_live: bool,- /// The mic level bar's fill in device pixels as last drawn, `None` while- /// the bar is hidden.- drawn_level_px: std::cell::Cell<Option<u32>>,+ level_bar: Entity<ui::MicrophoneLevel>,}#[derive(Clone, Copy)]@@ -71,6 +69,15 @@ impl ControlsWindow {cx.notify();}).detach();+ let mic_level = Feeds::global(cx).read(cx).mic_level().clone();+ let level_bar = cx.new(|cx| {+ ui::MicrophoneLevel::new(+ ui::MicrophoneLevelKind::RecordingBar,+ &mic_level,+ window,+ cx,+ )+ });let mut this = Self {session,@@ -80,7 +87,7 @@ impl ControlsWindow {confirmation_pending: false,_tick: gpui::Task::ready(()),ticking_live: false,- drawn_level_px: std::cell::Cell::new(None),+ level_bar,};this.ticking_live = this.timer_is_live(cx);this._tick = Self::spawn_tick(window, cx);@@ -121,13 +128,6 @@ impl ControlsWindow {})}- /// Whether a new mic level would move the bar by at least a device pixel.- pub fn level_bar_moves(&self, db: f64, scale: f32) -> bool {- self.drawn_level_px- .get()- .is_some_and(|drawn| drawn != level_bar_px(db, scale))- }-/// `formatTime`: `M:SS`, hours folded into minutes the same way.fn format_elapsed(elapsed: Duration) -> String {let total = elapsed.as_secs();@@ -231,17 +231,21 @@ impl ControlsWindow {/// gray-10 track). In instant mode with a live mic it doubles as the mute/// button -- studio deliberately does not expose mute, since the mic is an/// editable track and muted spans would bake zeros in.- fn render_microphone(&self, scale: f32, cx: &mut Context<Self>) -> impl IntoElement {+ fn render_microphone(&self, cx: &mut Context<Self>) -> impl IntoElement {let theme = self.theme;let session = self.session.read(cx);let muted = session.mic_muted;let can_mute = session.mode() == Some(RecordingMode::Instant)&& session.has_microphone()&& matches!(session.phase, Phase::Recording { .. });- let level_db = Feeds::global(cx).read(cx).mic_level_db;- let level = feeds::bar_level(level_db);- self.drawn_level_px- .set((self.has_microphone && !muted).then(|| level_bar_px(level_db, scale)));+ self.level_bar.update(cx, |bar, cx| {+ bar.configure(+ self.has_microphone && !muted,+ theme.blue_9.into(),+ theme.gray_10.into(),+ cx,+ );+ });let icon = if !self.has_microphone || muted {"icons/mic-off.svg"@@ -277,26 +281,7 @@ impl ControlsWindow {}).child(svg().path(icon).size(px(20.)).text_color(icon_color)).when(self.has_microphone && !muted, |this| {- this.child(- div()- .absolute()- .bottom(px(4.))- .left(px(4.))- .right(px(4.))- .h(px(2.))- .rounded_full()- .overflow_hidden()- .bg(theme.gray_10)- .child(- div()- .absolute()- .left_0()- .top_0()- .bottom_0()- .w(gpui::relative(level as f32))- .bg(theme.blue_9),- ),- )+ this.child(self.level_bar.clone())})}@@ -376,7 +361,7 @@ impl ControlsWindow {.detach();}- fn render_bar(&mut self, scale: f32, cx: &mut Context<Self>) -> impl IntoElement {+ fn render_bar(&mut self, cx: &mut Context<Self>) -> impl IntoElement {let theme = self.theme;let session = self.session.read(cx);let paused = session.is_paused();@@ -434,7 +419,7 @@ impl ControlsWindow {.items_center().gap(px(2.)).flex_shrink_0()- .child(self.render_microphone(scale, cx))+ .child(self.render_microphone(cx)).child(self.action_button("pause",@@ -559,7 +544,7 @@ impl Render for ControlsWindow {.child(recording_issue_text(issue)),)})- .child(self.render_bar(window.scale_factor(), cx))+ .child(self.render_bar(cx))}}@@ -582,11 +567,6 @@ fn recording_issue_text(error: String) -> impl IntoElement + Styled {})}-/// The bar's track is 20pt wide.-fn level_bar_px(db: f64, scale: f32) -> u32 {- (feeds::bar_level(db) * 20.0 * f64::from(scale)).round() as u32-}-fn tick_delay(live: bool, elapsed: Duration) -> Duration {if live {until_next_second(elapsed)@@ -629,15 +609,4 @@ mod repaint_tests {Duration::from_secs(1));}-- #[test]- fn level_changes_under_a_device_pixel_do_not_move_the_bar() {- assert_eq!(level_bar_px(-30.0, 2.0), level_bar_px(-30.5, 2.0));- assert_ne!(level_bar_px(-30.0, 2.0), level_bar_px(-32.0, 2.0));- assert_eq!(level_bar_px(-30.0, 1.0), level_bar_px(-31.0, 1.0));- assert_ne!(level_bar_px(-30.0, 1.0), level_bar_px(-33.0, 1.0));- assert_eq!(level_bar_px(-96.0, 2.0), 0);- assert_eq!(level_bar_px(0.0, 1.0), 20);- assert_eq!(level_bar_px(0.0, 2.0), 40);- }}diff --git a/apps/desktop-gpui/src/feeds.rs b/apps/desktop-gpui/src/feeds.rsindex 17f195422..3aa69b05c 100644--- a/apps/desktop-gpui/src/feeds.rs+++ b/apps/desktop-gpui/src/feeds.rs@@ -688,8 +688,7 @@ pub struct Feeds {pub camera: Option<SelectedCamera>,/// Selected microphone name.pub microphone: Option<String>,- /// Rolling 200ms max of the mic level, in dB FS. `-96` when silent/absent.- pub mic_level_db: f64,+ mic_level: Entity<MicLevel>,mic_level_shown: Arc<std::sync::atomic::AtomicU64>,pub camera_error: Option<String>,camera_preview_parked: bool,@@ -729,12 +728,34 @@ pub struct SelectedCamera {struct FeedsGlobal(Entity<Feeds>);impl Global for FeedsGlobal {}+/// The live mic level: rolling 200ms max in dB FS, `-96` when absent. Kept+/// out of `Feeds` because windows read device state from `Feeds` in render,+/// so each of its notifies redraws them, and the level changes up to 20+/// times a second.+pub struct MicLevel {+ db: f64,+}++impl MicLevel {+ pub fn db(&self) -> f64 {+ self.db+ }++ fn set(&mut self, db: f64, cx: &mut Context<Self>) {+ if self.db != db {+ self.db = db;+ cx.notify();+ }+ }+}+impl Feeds {pub fn camera_input_pending(&self) -> bool {self.camera_input_pending}pub fn init(cx: &mut App) -> Entity<Self> {+ let mic_level = cx.new(|_| MicLevel { db: -96.0 });let feeds = cx.new(|_| Self {camera_actor: None,camera_preview_sender: None,@@ -754,7 +775,7 @@ impl Feeds {microphone_ready: None,camera: None,microphone: None,- mic_level_db: -96.0,+ mic_level,mic_level_shown: Arc::new(std::sync::atomic::AtomicU64::new((-96.0f64).to_bits())),camera_error: None,camera_preview_parked: false,@@ -1126,7 +1147,7 @@ impl Feeds {self.microphone_error = None;self.mic_input_pending = label.is_some();self.mic_input_released = false;- self.set_mic_level(-96.0);+ self.set_mic_level(-96.0, cx);let epoch = self.mic_epoch;let actor = self.ensure_mic_actor(cx);let gate = self.mic_input_gate.clone();@@ -1239,13 +1260,17 @@ impl Feeds {}).detach();}- self.set_mic_level(-96.0);+ self.set_mic_level(-96.0, cx);cx.notify();}- fn set_mic_level(&mut self, db: f64) {- self.mic_level_db = db;+ pub fn mic_level(&self) -> &Entity<MicLevel> {+ &self.mic_level+ }++ fn set_mic_level(&mut self, db: f64, cx: &mut Context<Self>) {self.mic_level_shown.store(db.to_bits(), Ordering::Release);+ self.mic_level.update(cx, |level, cx| level.set(db, cx));}fn ensure_camera_actor(&mut self, cx: &mut Context<Self>) -> ActorRef<CameraFeed> {@@ -1370,20 +1395,11 @@ impl Feeds {let _meter = meter;while wakes.recv_async().await.is_ok() {let level = f64::from_bits(latest.load(Ordering::Acquire));- let changed = this.update(cx, |this: &mut Feeds, cx| {- if this.mic_level_db == level {- return false;- }- this.set_mic_level(level);- cx.notify();- true- });- match changed {- Err(_) => return,- Ok(true) => {- cx.update(app_windows::refresh_controls_window);- }- Ok(false) => {}+ if this+ .update(cx, |this: &mut Feeds, cx| this.set_mic_level(level, cx))+ .is_err()+ {+ return;}}});@@ -1458,6 +1474,10 @@ pub(crate) fn camera_preview_image(Some((image, (width, height)))}+/// The quietest level any meter draws: `bar_level` bottoms out at -60 dB and+/// `picker_level` at -40 dB, so anything below looks identical everywhere.+const METER_FLOOR_DB: f64 = -60.0;+/// A 200ms max-hold window, coalesced to ~20 updates/s and quantized to/// 0.5dB (under a pixel on both level mappings).#[derive(Default)]@@ -1501,6 +1521,7 @@ impl MeterSender {let Some(level) = self.window.push(now, db) else {return;};+ let level = level.max(METER_FLOOR_DB);self.latest.store(level.to_bits(), Ordering::Release);if level.to_bits() != self.shown.load(Ordering::Acquire) {let _ = self.wake.try_send(());@@ -1700,6 +1721,44 @@ mod tests {assert!(wakes.try_recv().is_err());}+ #[test]+ fn input_below_every_meter_floor_never_wakes_the_ui() {+ use std::sync::atomic::AtomicU64;++ let shown = Arc::new(AtomicU64::new((-96.0f64).to_bits()));+ let latest = Arc::new(AtomicU64::new((-96.0f64).to_bits()));+ let (wake, wakes) = flume::bounded(1);+ let mut sender = MeterSender {+ window: MeterWindow::default(),+ shown: shown.clone(),+ latest: latest.clone(),+ wake,+ };+ let start = Instant::now();+ let at = |callback: u64| start + Duration::from_micros(callback * 10_667);++ sender.push(at(0), -72.0);+ assert_eq!(wakes.try_recv(), Ok(()));+ assert_eq!(+ f64::from_bits(latest.load(Ordering::Acquire)),+ METER_FLOOR_DB+ );++ shown.store(METER_FLOOR_DB.to_bits(), Ordering::Release);+ for callback in 1..400 {+ let db = -96.0 + (callback % 7) as f64 * 5.0;+ sender.push(at(callback), db);+ }+ assert!(wakes.try_recv().is_err());++ sender.push(at(400), -42.0);+ sender.push(at(410), -42.0);+ assert_eq!(wakes.try_recv(), Ok(()));+ assert_eq!(f64::from_bits(latest.load(Ordering::Acquire)), -42.0);+ assert_eq!(picker_level(METER_FLOOR_DB), picker_level(-96.0));+ assert_eq!(bar_level(METER_FLOOR_DB), bar_level(-96.0));+ }+#[test]fn preview_rejects_frames_queued_before_input_readiness() {let ready = cap_timestamp::Timestamps::now();diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rsindex a318d54a0..7a143d903 100644--- a/apps/desktop-gpui/src/main_window.rs+++ b/apps/desktop-gpui/src/main_window.rs@@ -792,6 +792,7 @@ pub struct MainWindow {camera_id: Option<recording::DeviceOrModelID>,microphone: Option<MicrophoneOption>,microphone_level: Entity<ui::MicrophoneLevel>,+ device_microphone_level: Entity<ui::MicrophoneLevel>,pending_device_restore: crate::store::RecordingInputSettings,device_restore_suspended: bool,device_format_target: Option<DeviceFormatTarget>,@@ -942,11 +943,20 @@ impl MainWindow {// Track the app-scoped feeds: the camera bubble's close button// deselects the camera there, and this window's selection has to- // follow. Repaints are gated to what is actually visible -- the mic- // meter notifies at ~20Hz and would otherwise repaint the home view- // for a level bar only the microphone picker shows.+ // follow. Repaints are gated to what is actually visible.let feeds = Feeds::global(cx);- let microphone_level = cx.new(|cx| ui::MicrophoneLevel::new(&feeds, window, cx));+ let mic_level = feeds.read(cx).mic_level().clone();+ let microphone_level = cx.new(|cx| {+ ui::MicrophoneLevel::new(+ ui::MicrophoneLevelKind::CaptureButton,+ &mic_level,+ window,+ cx,+ )+ });+ let device_microphone_level = cx.new(|cx| {+ ui::MicrophoneLevel::new(ui::MicrophoneLevelKind::DeviceRow, &mic_level, window, cx)+ });cx.observe(&feeds, |this: &mut Self, feeds, cx| {let feeds = feeds.read(cx);let camera_id = feeds.camera.as_ref().map(|camera| &camera.id);@@ -1075,6 +1085,7 @@ impl MainWindow {camera_id: None,microphone: None,microphone_level,+ device_microphone_level,pending_device_restore: crate::store::RecordingInputSettings::load(),device_restore_suspended: false,device_format_target: None,@@ -2709,7 +2720,26 @@ impl Render for MainWindow {&& self.microphone.is_some()&& self.session.read(cx).phase == Phase::Idle;self.microphone_level.update(cx, |meter, cx| {- meter.configure(meter_active, theme.blue_9.into(), cx);+ meter.configure(+ meter_active,+ theme.blue_9.into(),+ gpui::transparent_black(),+ cx,+ );+ });+ let device_meter_active = self.microphone.is_some()+ && matches!(self.panel, Some(Panel::Device(DeviceMenu::Microphone)));+ self.device_microphone_level.update(cx, |meter, cx| {+ meter.configure(+ device_meter_active,+ theme.blue_500.into(),+ if theme.is_dark() {+ gpui::hsla(0., 0., 1., 0.1)+ } else {+ gpui::hsla(0., 0., 0., 0.07)+ },+ cx,+ );});div()@@ -5158,9 +5188,7 @@ impl MainWindow {.map(|description| format!("Available: {description}"))},selected,- selected.then(|| {- feeds::picker_level(Feeds::global(cx).read(cx).mic_level_db)- }),+ selected.then(|| self.device_microphone_level.clone()),cx.listener(move |this, _, _window, cx| {if !this.device_changes_allowed(cx) {return;@@ -5874,10 +5902,9 @@ impl MainWindow {label: String,detail: Option<String>,selected: bool,- // `MicrophoneListItem`'s live level wash: a white 25% overlay whose- // right edge sits at `level * 100%` (1 = silence, the web app's- // orientation). Only the selected microphone row gets one.- audio_level: Option<f64>,+ // `MicrophoneListItem`'s live level bar. Only the selected+ // microphone row gets one.+ audio_level: Option<Entity<ui::MicrophoneLevel>>,on_click: impl Fn(&gpui::ClickEvent, &mut Window, &mut gpui::App) + 'static,) -> gpui::Stateful<gpui::Div> {let theme = self.theme;@@ -5930,26 +5957,7 @@ impl MainWindow {.child(detail)})).when_some(audio_level.filter(|_| selected), |this, level| {- this.child(- div()- .mt(px(3.))- .h(px(3.))- .w_full()- .rounded_full()- .overflow_hidden()- .bg(if theme.is_dark() {- gpui::hsla(0., 0., 1., 0.1)- } else {- gpui::hsla(0., 0., 0., 0.07)- })- .child(- div()- .h_full()- .rounded_full()- .bg(accent)- .w(gpui::relative(1. - level.clamp(0., 1.) as f32)),- ),- )+ this.child(level)}),).when(selected, |this| {diff --git a/apps/desktop-gpui/src/target_overlay.rs b/apps/desktop-gpui/src/target_overlay.rsindex 7c0bbd63f..e73ca5fc6 100644--- a/apps/desktop-gpui/src/target_overlay.rs+++ b/apps/desktop-gpui/src/target_overlay.rs@@ -370,8 +370,7 @@ impl TargetSelect {let Ok((icon_wanted, active, changed)) = this.update(cx, |this: &mut Self, cx| {let (display, window) = probe;- let microphone_fill =- crate::ui::MicrophoneLevel::fill(crate::feeds::Feeds::global(cx).read(cx));+ let microphone_fill = crate::ui::MicrophoneLevel::capture_fill(cx);let changed = this.cursor_display != display|| this.hovered_window != window|| this.microphone_fill != microphone_fill;diff --git a/apps/desktop-gpui/src/ui/microphone_level.rs b/apps/desktop-gpui/src/ui/microphone_level.rsindex 8bc64a3eb..2983941b2 100644--- a/apps/desktop-gpui/src/ui/microphone_level.rs+++ b/apps/desktop-gpui/src/ui/microphone_level.rs@@ -1,57 +1,132 @@use gpui::{- Context, Entity, Hsla, IntoElement, ParentElement as _, Render, Styled as _, Window, div,+ App, Context, Entity, Hsla, IntoElement, ParentElement as _, Render, Styled as _, Window, div,prelude::FluentBuilder as _, px,};-use crate::feeds::{self, Feeds};+use crate::feeds::{self, Feeds, MicLevel};+const RECORDING_BAR_TRACK_WIDTH: f32 = 20.;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum MicrophoneLevelKind {+ CaptureButton,+ DeviceRow,+ RecordingBar,+}++impl MicrophoneLevelKind {+ pub(crate) fn fill(self, db: f64) -> f32 {+ if !db.is_finite() {+ return 0.;+ }+ match self {+ Self::CaptureButton | Self::DeviceRow => (1. - feeds::picker_level(db)) as f32,+ Self::RecordingBar => feeds::bar_level(db) as f32,+ }+ }++ /// An upper bound on the fill's drawn width, in device pixels. The main+ /// window meters are never wider than the window itself.+ fn span(self, viewport_width: f32, scale: f32) -> f32 {+ match self {+ Self::CaptureButton | Self::DeviceRow => viewport_width * scale,+ Self::RecordingBar => RECORDING_BAR_TRACK_WIDTH * scale,+ }+ }++ fn shown(self, window: &Window) -> bool {+ match self {+ Self::RecordingBar => true,+ // Linux has no visibility query (`window_is_visible` is a stub),+ // and gating on focus would freeze the meter in a visible window.+ Self::CaptureButton | Self::DeviceRow => {+ !cfg!(any(target_os = "macos", target_os = "windows"))+ || crate::platform::window_is_visible(window)+ }+ }+ }+}++pub(crate) fn moves_a_device_pixel(drawn: f32, next: f32, span: f32) -> bool {+ (drawn * span).round() != (next * span).round()+}++/// A live mic level meter. It is its own view so a level change repaints+/// only when the meter would visibly move, without the window that hosts it+/// ever reading the level in render.pub(crate) struct MicrophoneLevel {+ kind: MicrophoneLevelKind,active: bool,+ level_db: f64,fill: f32,color: Hsla,+ track: Hsla,}impl MicrophoneLevel {- pub(crate) fn new(feeds: &Entity<Feeds>, window: &mut Window, cx: &mut Context<Self>) -> Self {- cx.observe_in(feeds, window, |this, feeds, window, cx| {- let visible = if cfg!(any(target_os = "macos", target_os = "windows")) {- crate::platform::window_is_visible(window)- } else {- window.is_window_active()- };- if this.active && visible {- let fill = Self::fill(feeds.read(cx));- if this.fill != fill {- this.fill = fill;- cx.notify();+ pub(crate) fn new(+ kind: MicrophoneLevelKind,+ level: &Entity<MicLevel>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> Self {+ cx.observe_in(level, window, |this, level, window, cx| {+ this.level_db = level.read(cx).db();+ if !this.active || !this.kind.shown(window) {+ return;+ }+ let fill = this.kind.fill(this.level_db);+ let span = this.kind.span(+ f32::from(window.viewport_size().width),+ window.scale_factor(),+ );+ if moves_a_device_pixel(this.fill, fill, span) {+ this.fill = fill;+ cx.notify();+ if this.kind == MicrophoneLevelKind::RecordingBar {+ window.refresh();}}}).detach();Self {+ kind,active: false,+ level_db: level.read(cx).db(),fill: 0.,color: gpui::transparent_black(),+ track: gpui::transparent_black(),}}- pub(crate) fn fill(feeds: &Feeds) -> f32 {- if feeds.microphone.is_some() && feeds.mic_level_db.is_finite() {- (1. - feeds::picker_level(feeds.mic_level_db)) as f32+ /// The capture-button fill for the current level, for surfaces that+ /// snapshot it outside render.+ pub(crate) fn capture_fill(cx: &App) -> f32 {+ let feeds = Feeds::global(cx).read(cx);+ if feeds.microphone.is_some() {+ MicrophoneLevelKind::CaptureButton.fill(feeds.mic_level().read(cx).db())} else {0.}}- pub(crate) fn configure(&mut self, active: bool, color: Hsla, cx: &mut Context<Self>) {+ pub(crate) fn configure(+ &mut self,+ active: bool,+ color: Hsla,+ track: Hsla,+ cx: &mut Context<Self>,+ ) {let fill = if active {- Self::fill(Feeds::global(cx).read(cx))+ self.kind.fill(self.level_db)} else {0.};- if self.active != active || self.color != color || self.fill != fill {+ if self.active != active || self.color != color || self.track != track || self.fill != fill+ {self.active = active;self.color = color;+ self.track = track;self.fill = fill;cx.notify();}@@ -74,6 +149,130 @@ impl MicrophoneLevel {impl Render for MicrophoneLevel {fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {- Self::snapshot(self.fill, self.color)+ match self.kind {+ MicrophoneLevelKind::CaptureButton => Self::snapshot(self.fill, self.color),+ MicrophoneLevelKind::DeviceRow => div()+ .mt(px(3.))+ .h(px(3.))+ .w_full()+ .rounded_full()+ .overflow_hidden()+ .bg(self.track)+ .child(+ div()+ .h_full()+ .rounded_full()+ .bg(self.color)+ .w(gpui::relative(self.fill)),+ ),+ MicrophoneLevelKind::RecordingBar => div()+ .absolute()+ .bottom(px(4.))+ .left(px(4.))+ .right(px(4.))+ .h(px(2.))+ .rounded_full()+ .overflow_hidden()+ .bg(self.track)+ .child(+ div()+ .absolute()+ .left_0()+ .top_0()+ .bottom_0()+ .w(gpui::relative(self.fill))+ .bg(self.color),+ ),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn px_moved(kind: MicrophoneLevelKind, from_db: f64, to_db: f64, span: f32) -> bool {+ moves_a_device_pixel(kind.fill(from_db), kind.fill(to_db), span)+ }++ #[test]+ fn a_level_change_of_a_device_pixel_or_more_repaints() {+ let span = MicrophoneLevelKind::CaptureButton.span(320., 2.);+ assert!(px_moved(+ MicrophoneLevelKind::CaptureButton,+ -30.,+ -20.,+ span+ ));+ assert!(px_moved(+ MicrophoneLevelKind::CaptureButton,+ -96.,+ -39.,+ span+ ));+ assert!(px_moved(MicrophoneLevelKind::DeviceRow, -12., -10., span));+ assert!(moves_a_device_pixel(0.5, 0.5 + 1. / span, span));+ }++ #[test]+ fn a_sub_pixel_level_change_does_not_repaint() {+ let span = MicrophoneLevelKind::CaptureButton.span(320., 2.);+ assert!(!moves_a_device_pixel(0.5, 0.5 + 0.4 / span, span));+ assert!(!moves_a_device_pixel(0.25, 0.25, span));+ assert!(!px_moved(+ MicrophoneLevelKind::CaptureButton,+ -20.,+ -20.25,+ 40.+ ));+ }++ #[test]+ fn levels_below_the_visible_range_never_repaint() {+ let span = MicrophoneLevelKind::CaptureButton.span(4096., 3.);+ for db in [-96., -72., -60., -55.5, -48., -40.5, -40.] {+ assert!(!px_moved(+ MicrophoneLevelKind::CaptureButton,+ -96.,+ db,+ span+ ));+ assert!(!px_moved(MicrophoneLevelKind::DeviceRow, -96., db, span));+ }+ let span = MicrophoneLevelKind::RecordingBar.span(0., 2.);+ for db in [-96., -80., -60.5, -60.] {+ assert!(!px_moved(MicrophoneLevelKind::RecordingBar, -96., db, span));+ }+ assert!(px_moved(+ MicrophoneLevelKind::RecordingBar,+ -96.,+ -58.,+ span+ ));+ }++ #[test]+ fn the_recording_bar_repaints_per_device_pixel_of_its_track() {+ let kind = MicrophoneLevelKind::RecordingBar;+ assert!(!px_moved(kind, -30., -30.5, kind.span(0., 2.)));+ assert!(px_moved(kind, -30., -32., kind.span(0., 2.)));+ assert!(!px_moved(kind, -30., -31., kind.span(0., 1.)));+ assert!(px_moved(kind, -30., -33., kind.span(0., 1.)));+ assert_eq!(kind.fill(-96.) * kind.span(0., 2.), 0.);+ assert_eq!(kind.fill(0.) * kind.span(0., 1.), 20.);+ assert_eq!(kind.fill(0.) * kind.span(0., 2.), 40.);+ }++ #[test]+ fn fills_match_the_existing_level_mappings() {+ assert_eq!(MicrophoneLevelKind::CaptureButton.fill(-96.), 0.);+ assert_eq!(MicrophoneLevelKind::CaptureButton.fill(0.), 1.);+ assert_eq!(MicrophoneLevelKind::DeviceRow.fill(-40.), 0.);+ assert_eq!(MicrophoneLevelKind::RecordingBar.fill(-60.), 0.);+ assert_eq!(MicrophoneLevelKind::RecordingBar.fill(-30.), 0.5);+ assert_eq!(+ MicrophoneLevelKind::CaptureButton.fill(f64::NEG_INFINITY),+ 0.+ );}}diff --git a/apps/desktop-gpui/src/ui/mod.rs b/apps/desktop-gpui/src/ui/mod.rsindex e69609d4b..13bd5ec2c 100644--- a/apps/desktop-gpui/src/ui/mod.rs+++ b/apps/desktop-gpui/src/ui/mod.rs@@ -89,7 +89,7 @@ pub use field::{Field, Subfield};pub use kbd::{KbdChip, KbdSize, kbd_symbol};#[allow(unused_imports)]pub use menu::{Menu, MenuItem, MenuKey, MenuState};-pub(crate) use microphone_level::MicrophoneLevel;+pub(crate) use microphone_level::{MicrophoneLevel, MicrophoneLevelKind};#[allow(unused_imports)]pub use number_field::{NumberChange, NumberField, NumberFieldState, NumberLimits, format_number, parse_number,