Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
perf(desktop-gpui): skip the timeline rebuild while editing a frame
Pravine45a8df52c44
diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rsindex c9c031c45..790dc699d 100644--- a/apps/desktop-gpui/src/editor_window.rs+++ b/apps/desktop-gpui/src/editor_window.rs@@ -2276,8 +2276,7 @@ impl EditorWindow {/// the waveforms arrive separately and later, so whatever has landed is/// carried across.fn rebuild_timeline(&mut self) {- dismiss_indexed_sidebar_menu(&mut self.sidebar.menu);- self.text_menu = None;+ self.dismiss_transient_menus();let mic = std::mem::take(&mut self.timeline.mic_waveforms);let system = std::mem::take(&mut self.timeline.system_waveforms);let waveform_paths = self.timeline.waveform_paths.clone();@@ -2295,6 +2294,13 @@ impl EditorWindow {}}+ /// The transient popovers a project change closes, shared by the full+ /// rebuild and the frame-only path so the two cannot drift.+ fn dismiss_transient_menus(&mut self) {+ dismiss_indexed_sidebar_menu(&mut self.sidebar.menu);+ self.text_menu = None;+ }+/// `getMicWaveforms()` / `getSystemAudioWaveforms()` resolving/// (`ED/context.ts:1526-1539`). Plain state, not a resource: the decode/// runs in the background after the editor opens, so the waveform simply@@ -2419,12 +2425,36 @@ impl EditorWindow {}pub(crate) fn project_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ self.project_changed_inner(true, window, cx);+ }++ /// [`Self::project_changed`] for edits that only write `background.frame`.+ ///+ /// [`crate::editor_timeline::TimelineModel::build`] never reads the frame+ /// or the background (the style track draws a segment's name and enabled+ /// flag only), so a frame edit can skip the rebuild. The frame text fields+ /// call this once per keystroke; any edit that touches a field the timeline+ /// model reads must go through [`Self::project_changed`] instead.+ fn project_changed_without_timeline(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ self.project_changed_inner(false, window, cx);+ }++ fn project_changed_inner(+ &mut self,+ rebuild_timeline: bool,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {if !self.project_ready() {return;}self.synchronize_caption_track(false);self.history.record(&self.project);- self.rebuild_timeline();+ if rebuild_timeline {+ self.rebuild_timeline();+ } else {+ self.dismiss_transient_menus();+ }self.publish_project();self.schedule_save(window, cx);cx.notify();diff --git a/apps/desktop-gpui/src/editor_window/frame.rs b/apps/desktop-gpui/src/editor_window/frame.rsindex 30fd98399..1394bc614 100644--- a/apps/desktop-gpui/src/editor_window/frame.rs+++ b/apps/desktop-gpui/src/editor_window/frame.rs@@ -1,4 +1,6 @@-use cap_project::{FrameConfiguration, FrameStyle, FrameTheme, ProjectConfiguration};+use cap_project::{+ BackgroundConfiguration, FrameConfiguration, FrameStyle, FrameTheme, ProjectConfiguration,+};use gpui::{AppContext as _, Context, Entity, FontWeight, InteractiveElement, IntoElement, MouseButton,ParentElement, StatefulInteractiveElement as _, Styled, Window, div, point,@@ -120,18 +122,22 @@ enum FrameChange {}fn apply_frame_change(project: &mut ProjectConfiguration, change: FrameChange) -> bool {- let previous = project.background.frame.clone();- let frame = project- .background- .frame- .get_or_insert_with(Default::default);+ apply_background_frame_change(&mut project.background, change)+}++fn apply_background_frame_change(+ background: &mut BackgroundConfiguration,+ change: FrameChange,+) -> bool {+ let previous = background.frame.clone();+ let frame = background.frame.get_or_insert_with(Default::default);match change {FrameChange::Style(style) => frame.style = style,FrameChange::Theme(theme) => frame.theme = theme,FrameChange::Text(FrameField::Url, text) => frame.url = text,FrameChange::Text(FrameField::Title, text) => frame.title = text,}- project.background.frame != previous+ background.frame != previous}fn apply_targeted_frame_change(@@ -145,30 +151,24 @@ fn apply_targeted_frame_change(if !target.matches(project) {return false;}- let mut scoped = project.clone();let Some(segment) = project.timeline- .as_ref()- .and_then(|timeline| timeline.style_segments.get(target.index))+ .as_mut()+ .and_then(|timeline| timeline.style_segments.get_mut(target.index))else {return false;};- scoped.background = segment+ // The edit only ever touches the background, so clone that rather than the+ // whole project: the text fields send one of these per keystroke.+ let mut background = segment.overrides.background.clone().unwrap_or_else(|| project.background.clone());- if !apply_frame_change(&mut scoped, change) {+ if !apply_background_frame_change(&mut background, change) {return false;}- let Some(segment) = project- .timeline- .as_mut()- .and_then(|timeline| timeline.style_segments.get_mut(target.index))- else {- return false;- };- segment.overrides.background = Some(scoped.background);+ segment.overrides.background = Some(background);true}@@ -229,7 +229,7 @@ impl EditorWindow {{*target = next;}- self.project_changed(window, cx);+ self.project_changed_without_timeline(window, cx);}fn frame_style(&self) -> FrameStyle {@@ -728,6 +728,294 @@ mod tests {}}+ /// The pre-PR clone/fallback flow, kept test-only so the benchmark below+ /// can measure the clone it removed in the same run as the current one.+ /// It shares the current frame mutator, which behaves exactly like the+ /// pre-PR one.+ fn apply_targeted_frame_change_with_project_clone(+ project: &mut ProjectConfiguration,+ target: Option<&StyleFrameTarget>,+ change: FrameChange,+ ) -> bool {+ let Some(target) = target else {+ return apply_frame_change(project, change);+ };+ if !target.matches(project) {+ return false;+ }+ let mut scoped = project.clone();+ let Some(segment) = project+ .timeline+ .as_ref()+ .and_then(|timeline| timeline.style_segments.get(target.index))+ else {+ return false;+ };+ scoped.background = segment+ .overrides+ .background+ .clone()+ .unwrap_or_else(|| project.background.clone());+ if !apply_frame_change(&mut scoped, change) {+ return false;+ }+ let Some(segment) = project+ .timeline+ .as_mut()+ .and_then(|timeline| timeline.style_segments.get_mut(target.index))+ else {+ return false;+ };+ segment.overrides.background = Some(scoped.background);+ true+ }++ fn style_frame_project(timeline_segments: usize, with_override: bool) -> ProjectConfiguration {+ let mut project = ProjectConfiguration::default();+ project.timeline = Some(cap_project::TimelineConfiguration {+ segments: (0..timeline_segments)+ .map(|index| cap_project::TimelineSegment {+ timescale: 1.,+ start: index as f64,+ end: index as f64 + 1.,+ ..Default::default()+ })+ .collect(),+ transitions: Vec::new(),+ zoom_segments: Vec::new(),+ scene_segments: Vec::new(),+ mask_segments: Vec::new(),+ text_segments: Vec::new(),+ caption_segments: Vec::new(),+ keyboard_segments: Vec::new(),+ audio_segments: Vec::new(),+ style_segments: vec![cap_project::StyleSegment {+ overrides: cap_project::StyleOverrides {+ background: with_override.then(|| BackgroundConfiguration {+ frame: Some(FrameConfiguration {+ style: FrameStyle::MacOS,+ ..Default::default()+ }),+ padding: 77.5,+ ..Default::default()+ }),+ ..Default::default()+ },+ ..Default::default()+ }],+ image_segments: Vec::new(),+ camera3d_segments: Vec::new(),+ });+ project+ }++ fn style_frame_lanes(project: &ProjectConfiguration) -> crate::editor_timeline::TrackLanes {+ crate::editor_timeline::TrackLanes::from_project(project, false)+ }++ fn frame_change_cases() -> [fn() -> FrameChange; 4] {+ [+ || FrameChange::Style(FrameStyle::Windows),+ || FrameChange::Theme(FrameTheme::Light),+ || FrameChange::Text(FrameField::Title, "Changed title".into()),+ || FrameChange::Text(FrameField::Url, "https://example.com".into()),+ ]+ }++ fn median(samples: &mut Vec<f64>) -> f64 {+ assert!(samples.len() > 1, "need a warm-up and a sample");+ samples.remove(0);+ samples.sort_by(f64::total_cmp);+ samples[samples.len() / 2]+ }++ fn edit_frame_title(+ project: &mut ProjectConfiguration,+ target: &mut StyleFrameTarget,+ i: usize,+ j: usize,+ clone_project: bool,+ ) {+ let text = format!("Window title {i}-{j}");+ let changed = if clone_project {+ apply_targeted_frame_change_with_project_clone(+ project,+ Some(target),+ FrameChange::Text(FrameField::Title, text),+ )+ } else {+ apply_targeted_frame_change(+ project,+ Some(target),+ FrameChange::Text(FrameField::Title, text),+ )+ };+ if changed && let Some(next) = StyleFrameTarget::capture(project, target.index) {+ *target = next;+ }+ }++ /// One keystroke in a style frame's title field, with the old+ /// clone-the-project implementation and the current one measured in the+ /// same run, plus the timeline rebuild `project_changed` used to do.+ /// `cargo test -p cap-desktop-gpui --bin cap-gpui -- --ignored benchmark_style_frame_edit --nocapture`+ #[test]+ #[ignore = "manual style frame edit benchmark"]+ fn benchmark_style_frame_edit() {+ let mut cloned = style_frame_project(2_000, true);+ let mut borrowed = cloned.clone();+ let mut cloned_target = StyleFrameTarget::capture(&cloned, 0).expect("the style segment");+ let mut borrowed_target =+ StyleFrameTarget::capture(&borrowed, 0).expect("the style segment");++ let mut clone_samples = Vec::new();+ for i in 0..32 {+ let started = std::time::Instant::now();+ for j in 0..10 {+ edit_frame_title(&mut cloned, &mut cloned_target, i, j, true);+ }+ clone_samples.push(started.elapsed().as_secs_f64() * 1_000_000. / 10.);+ }+ let clone_edit = median(&mut clone_samples);++ let mut borrow_samples = Vec::new();+ for i in 0..32 {+ let started = std::time::Instant::now();+ for j in 0..10 {+ edit_frame_title(&mut borrowed, &mut borrowed_target, i, j, false);+ }+ borrow_samples.push(started.elapsed().as_secs_f64() * 1_000_000. / 10.);+ }+ let borrow_edit = median(&mut borrow_samples);++ assert_eq!(+ serde_json::to_value(&cloned).unwrap(),+ serde_json::to_value(&borrowed).unwrap(),+ "the old and new implementations must leave the same project"+ );++ // The other half of the old per-keystroke path: `project_changed`+ // rebuilt this model every time.+ let lanes = style_frame_lanes(&borrowed);+ let mut rebuild_samples = Vec::new();+ for _ in 0..16 {+ let started = std::time::Instant::now();+ for _ in 0..10 {+ drop(std::hint::black_box(+ crate::editor_timeline::TimelineModel::build_with_lanes(+ &borrowed, false, false, &lanes,+ ),+ ));+ }+ rebuild_samples.push(started.elapsed().as_secs_f64() * 1_000_000. / 10.);+ }+ let rebuild = median(&mut rebuild_samples);+ println!(+ "style_frame_edit timeline_segments=2000 clone_edit_us={clone_edit:.3} borrow_edit_us={borrow_edit:.3} timeline_rebuild_us={rebuild:.3}"+ );+ }++ #[test]+ fn a_frame_edit_does_not_change_the_timeline_model() {+ for with_override in [false, true] {+ for targeted in [false, true] {+ for change in frame_change_cases() {+ let mut project = style_frame_project(64, with_override);+ let target = StyleFrameTarget::capture(&project, 0).expect("the style segment");+ let lanes = style_frame_lanes(&project);+ let before = crate::editor_timeline::TimelineModel::build_with_lanes(+ &project, false, false, &lanes,+ );+ assert!(+ apply_targeted_frame_change(+ &mut project,+ targeted.then_some(&target),+ change(),+ ),+ "the frame change should apply \+ (override={with_override}, targeted={targeted})"+ );+ let after = crate::editor_timeline::TimelineModel::build_with_lanes(+ &project, false, false, &lanes,+ );+ assert_eq!(+ format!("{before:?}"),+ format!("{after:?}"),+ "a frame edit must not change anything the timeline model draws \+ (override={with_override}, targeted={targeted})"+ );+ }+ }+ }+ }++ #[test]+ fn the_targeted_frame_edit_matches_the_clone_the_project_flow() {+ for with_override in [false, true] {+ for change in frame_change_cases() {+ let mut cloned = style_frame_project(8, with_override);+ let mut borrowed = cloned.clone();+ let target = StyleFrameTarget::capture(&cloned, 0).expect("the style segment");+ assert_eq!(+ apply_targeted_frame_change_with_project_clone(+ &mut cloned,+ Some(&target),+ change(),+ ),+ apply_targeted_frame_change(&mut borrowed, Some(&target), change()),+ "the old and new implementations must agree (override={with_override})"+ );+ assert_eq!(+ serde_json::to_value(&cloned).unwrap(),+ serde_json::to_value(&borrowed).unwrap(),+ "the old and new implementations must leave the same project \+ (override={with_override})"+ );+ }+ }++ // A missing target takes the global-background path in both.+ let mut cloned = style_frame_project(8, false);+ let mut borrowed = cloned.clone();+ assert_eq!(+ apply_targeted_frame_change_with_project_clone(+ &mut cloned,+ None,+ FrameChange::Style(FrameStyle::Windows),+ ),+ apply_targeted_frame_change(+ &mut borrowed,+ None,+ FrameChange::Style(FrameStyle::Windows),+ )+ );+ assert_eq!(+ serde_json::to_value(&cloned).unwrap(),+ serde_json::to_value(&borrowed).unwrap()+ );++ // A stale target is a no-op in both.+ let mut cloned = style_frame_project(8, false);+ let mut borrowed = cloned.clone();+ let target = StyleFrameTarget::capture(&cloned, 0).expect("the style segment");+ cloned.timeline.as_mut().unwrap().style_segments[0].name = "Moved".into();+ borrowed.timeline.as_mut().unwrap().style_segments[0].name = "Moved".into();+ assert!(!apply_targeted_frame_change_with_project_clone(+ &mut cloned,+ Some(&target),+ FrameChange::Style(FrameStyle::Windows),+ ));+ assert!(!apply_targeted_frame_change(+ &mut borrowed,+ Some(&target),+ FrameChange::Style(FrameStyle::Windows),+ ));+ assert_eq!(+ serde_json::to_value(&cloned).unwrap(),+ serde_json::to_value(&borrowed).unwrap()+ );+ }+#[test]fn frame_changes_round_trip_and_undo_without_changing_the_background() {let mut project = ProjectConfiguration::default();