From 092d708850213f877619bb0bc37ab02a6876a6b4 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:52:49 +0000 Subject: [PATCH 1/8] feat(rendering): report the resting caption box with each editor frame --- crates/editor/src/editor.rs | 3 +- crates/editor/src/preparing_preview.rs | 3 +- crates/editor/src/preparing_preview/tests.rs | 1 + crates/rendering/src/layers/captions.rs | 243 ++++++++++++++++--- crates/rendering/src/lib.rs | 12 +- 5 files changed, 222 insertions(+), 40 deletions(-) diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs index 160f8f52a84..a3d560d4cdb 100644 --- a/crates/editor/src/editor.rs +++ b/crates/editor/src/editor.rs @@ -439,7 +439,7 @@ impl Renderer { layers.set_realtime_camera_effects(current.realtime); let render_start = Instant::now(); let input_frame_number = current.input.uniforms().frame_number; - let frame_layout = current.input.uniforms().frame_layout(); + let mut frame_layout = current.input.uniforms().frame_layout(); let render_result = match (output_format, current.input) { (EditorFrameFormat::Rgba, PendingRenderInput::Single(input)) => frame_renderer .render_immediate_with_timings( @@ -555,6 +555,7 @@ impl Renderer { #[cfg(target_os = "macos")] EditorFrameOutput::Surface(frame) => frame.frame_number, }; + frame_layout.caption = layers.caption_frame_box(); let callback_start = Instant::now(); (frame_cb)(frame, frame_layout); let callback_duration = callback_start.elapsed(); diff --git a/crates/editor/src/preparing_preview.rs b/crates/editor/src/preparing_preview.rs index f44b5a14d53..3e53852612d 100644 --- a/crates/editor/src/preparing_preview.rs +++ b/crates/editor/src/preparing_preview.rs @@ -685,7 +685,7 @@ async fn run_preview( cursor_cache.event_order(&cursor), ) }; - let layout = uniforms.frame_layout(); + let mut layout = uniforms.frame_layout(); let output = match options.frame_format { EditorFrameFormat::Rgba => renderer .render_immediate(frames, uniforms, &cursor, true, &mut layers) @@ -697,6 +697,7 @@ async fn run_preview( .await .map(EditorFrameOutput::Surface), }; + layout.caption = layers.caption_frame_box(); check_cursor_error(&constants)?; control.check()?; decoders.check()?; diff --git a/crates/editor/src/preparing_preview/tests.rs b/crates/editor/src/preparing_preview/tests.rs index 6e16a7f18c7..ac09af37c82 100644 --- a/crates/editor/src/preparing_preview/tests.rs +++ b/crates/editor/src/preparing_preview/tests.rs @@ -153,6 +153,7 @@ fn rendered_frame_identity_and_latest_sequence_are_both_required() { display: [0.0, 0.0, 160.0, 120.0], camera: None, output_size: [160, 120], + caption: None, }; let mut frame = cap_rendering::RenderedFrame { data: Arc::new(Vec::new()), diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs index c26e715b3e6..ed8a1141f72 100644 --- a/crates/rendering/src/layers/captions.rs +++ b/crates/rendering/src/layers/captions.rs @@ -101,6 +101,67 @@ pub struct CaptionOverlayLayout { pub position: CaptionPosition, } +/// The caption box on the latest frame at rest, before the bounce and pop +/// animations move it, in output-frame pixels (`[x0, y0, x1, y1]`). The +/// editor hit-tests and drags this box when the caption is placed manually. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CaptionFrameBox { + pub bounds: [f32; 4], + position: CaptionPosition, +} + +impl CaptionFrameBox { + pub fn new(bounds: [f32; 4], position: &str) -> Self { + Self { + bounds, + position: CaptionPosition::from_str(position), + } + } + + /// Whether this caption sits at the Manual position, through the + /// settings or its segment's own override. + pub fn is_manual(&self) -> bool { + self.position == CaptionPosition::Manual + } + + /// Whether this caption was laid out for the position setting `position`. + pub fn is_at(&self, position: &str) -> bool { + self.position == CaptionPosition::from_str(position) + } +} + +/// Top-left corner of a caption box of `box_size` at rest in a frame of +/// `frame` pixels. Manual placement centres the box on `manual`, a fraction +/// of the frame, and keeps the whole box inside the frame. +pub(crate) fn caption_box_origin( + position: CaptionPosition, + manual: Option>, + box_size: (f32, f32), + frame: (f32, f32), +) -> (f32, f32) { + let (box_width, box_height) = box_size; + let (width, height) = frame; + let margin = width * 0.05; + let max_left = (width - box_width).max(0.0); + let max_top = (height - box_height).max(0.0); + let manual = manual.filter(|_| position == CaptionPosition::Manual); + let left = match (position, manual) { + (_, Some(manual)) => { + (manual.x.clamp(0.0, 1.0) * width - box_width / 2.0).clamp(0.0, max_left) + } + (CaptionPosition::TopLeft | CaptionPosition::BottomLeft, _) => margin, + (CaptionPosition::TopRight | CaptionPosition::BottomRight, _) => { + (width - margin - box_width).max(0.0) + } + _ => ((width - box_width) / 2.0).max(0.0), + }; + let center_y = match manual { + Some(manual) => manual.y.clamp(0.0, 1.0) * height, + None => height * position.y_factor(), + }; + (left, (center_y - box_height / 2.0).clamp(0.0, max_top)) +} + /// The centre of the caption box last drawn, as fractions of the frame, with /// the position setting it was drawn for. Left and right presets align the /// box's edge to the margin, so where its centre lands depends on the box @@ -456,6 +517,7 @@ pub struct CaptionsLayer { output_size: (u32, u32), has_caption: bool, active_layout: Option, + frame_box: Option, } impl CaptionsLayer { @@ -597,6 +659,7 @@ impl CaptionsLayer { output_size: (0, 0), has_caption: false, active_layout: None, + frame_box: None, } } @@ -620,6 +683,7 @@ impl CaptionsLayer { ) { self.has_caption = false; self.active_layout = None; + self.frame_box = None; self.background_scissor = None; self.highlight_scissor = None; self.has_highlight = false; @@ -878,39 +942,12 @@ impl CaptionsLayer { let box_width = (text_width + padding * 2.0).min(available_width).max(1.0); let box_height = (text_height + padding * 2.0).min(height as f32).max(1.0); - let background_left = if position == CaptionPosition::Manual { - caption_data - .settings - .manual_position - .map(|manual_position| { - (manual_position.x.clamp(0.0, 1.0) * width as f32 - box_width / 2.0) - .clamp(0.0, (width as f32 - box_width).max(0.0)) - }) - .unwrap_or_else(|| ((width as f32 - box_width) / 2.0).max(0.0)) - } else { - match position { - CaptionPosition::TopLeft | CaptionPosition::BottomLeft => margin, - CaptionPosition::TopRight | CaptionPosition::BottomRight => { - (width as f32 - margin - box_width).max(0.0) - } - CaptionPosition::TopCenter | CaptionPosition::BottomCenter => { - ((width as f32 - box_width) / 2.0).max(0.0) - } - CaptionPosition::Manual => ((width as f32 - box_width) / 2.0).max(0.0), - } - }; - - let center_y = if position == CaptionPosition::Manual { - caption_data - .settings - .manual_position - .map(|manual_position| manual_position.y.clamp(0.0, 1.0) * height as f32) - .unwrap_or_else(|| height as f32 * CaptionPosition::BottomCenter.y_factor()) - } else { - height as f32 * position.y_factor() - }; - let base_background_top = - (center_y - box_height / 2.0).clamp(0.0, (height as f32 - box_height).max(0.0)); + let (background_left, base_background_top) = caption_box_origin( + position, + caption_data.settings.manual_position, + (box_width, box_height), + (width as f32, height as f32), + ); let background_top = (base_background_top + bounce_offset as f32) .clamp(0.0, (height as f32 - box_height).max(0.0)); @@ -1013,8 +1050,18 @@ impl CaptionsLayer { draw_box_height, ]; + let resting = [background_left, base_background_top, box_width, box_height]; self.active_layout = Some(CaptionOverlayLayout { rect, position }); - record_caption_center(position, rect, (width, height)); + self.frame_box = Some(CaptionFrameBox { + bounds: [ + resting[0], + resting[1], + resting[0] + resting[2], + resting[1] + resting[3], + ], + position, + }); + record_caption_center(position, resting, (width, height)); let background_uniforms = CaptionBackgroundUniforms { rect, @@ -1137,6 +1184,10 @@ impl CaptionsLayer { self.active_layout } + pub fn frame_box(&self) -> Option { + self.frame_box + } + pub fn render(&self, pass: &mut wgpu::RenderPass<'_>) { if !self.has_caption { return; @@ -1258,10 +1309,11 @@ fn calculate_caption_bounce(current_time: f64, start: f64, end: f64, fade_durati #[cfg(test)] mod tests { use super::{ - caption_center, caption_segment_effective_end, find_active_caption_segment, - find_active_word_index, word_byte_range, + CaptionFrameBox, CaptionPosition, caption_box_origin, caption_center, + caption_segment_effective_end, find_active_caption_segment, find_active_word_index, + word_byte_range, }; - use cap_project::{CaptionTrackSegment, CaptionWord}; + use cap_project::{CaptionTrackSegment, CaptionWord, XY}; fn segment(start: f64, end: f64, words: Vec) -> CaptionTrackSegment { CaptionTrackSegment { @@ -1287,6 +1339,123 @@ mod tests { } } + /// The caption box for a 24 px caption at 1080p is about this size; the + /// renderer scales the font with the frame height. + fn box_at(frame: (f32, f32)) -> (f32, f32) { + let scale = frame.1 / 1080.0; + (520.0 * scale, 60.0 * scale) + } + + fn normalised_center( + position: CaptionPosition, + manual: Option>, + frame: (f32, f32), + ) -> (f32, f32) { + let size = box_at(frame); + let (left, top) = caption_box_origin(position, manual, size, frame); + ( + (left + size.0 / 2.0) / frame.0, + (top + size.1 / 2.0) / frame.1, + ) + } + + /// A stored manual centre is a fraction of the output frame, so the same + /// project places its captions at the same spot at every export size. + #[test] + fn a_manual_caption_lands_on_the_same_fraction_at_every_resolution() { + let spots = [XY::new(0.5, 0.5), XY::new(0.3, 0.2), XY::new(0.62, 0.9)]; + for aspect in [ + [(1280.0, 720.0), (1920.0, 1080.0), (3840.0, 2160.0)], + [(720.0, 1280.0), (1080.0, 1920.0), (2160.0, 3840.0)], + [(720.0, 720.0), (1080.0, 1080.0), (2160.0, 2160.0)], + ] { + for spot in spots { + let centers = aspect + .map(|frame| normalised_center(CaptionPosition::Manual, Some(spot), frame)); + for center in centers { + assert!( + (center.0 - centers[0].0).abs() < 1e-5, + "{aspect:?} {spot:?}" + ); + assert!( + (center.1 - centers[0].1).abs() < 1e-5, + "{aspect:?} {spot:?}" + ); + } + } + } + let center = normalised_center( + CaptionPosition::Manual, + Some(XY::new(0.3, 0.2)), + (1920.0, 1080.0), + ); + assert!((center.0 - 0.3).abs() < 1e-6); + assert!((center.1 - 0.2).abs() < 1e-6); + } + + /// A centre near an edge keeps the whole box in the frame, in every + /// aspect, rather than cutting the caption off. + #[test] + fn a_manual_caption_near_an_edge_stays_inside_the_frame() { + for frame in [(1920.0, 1080.0), (1080.0, 1920.0), (1440.0, 1080.0)] { + let size = box_at(frame); + for spot in [ + XY::new(0.0, 0.0), + XY::new(1.0, 1.0), + XY::new(0.0, 1.0), + XY::new(-3.0, 7.0), + ] { + let (left, top) = + caption_box_origin(CaptionPosition::Manual, Some(spot), size, frame); + assert!( + left >= 0.0 && left + size.0 <= frame.0 + 1e-3, + "{frame:?} {spot:?}" + ); + assert!( + top >= 0.0 && top + size.1 <= frame.1 + 1e-3, + "{frame:?} {spot:?}" + ); + } + } + } + + /// The presets are unchanged by manual placement: a stored manual centre + /// does nothing until the position is Manual, and Manual without one is + /// the bottom-centre spot. + #[test] + fn presets_ignore_the_manual_centre() { + let frame = (1920.0, 1080.0); + let size = (400.0, 80.0); + let manual = Some(XY::new(0.1, 0.1)); + let expected = [ + (CaptionPosition::TopLeft, (96.0, 1080.0 * 0.08 - 40.0)), + (CaptionPosition::TopCenter, (760.0, 1080.0 * 0.08 - 40.0)), + (CaptionPosition::TopRight, (1424.0, 1080.0 * 0.08 - 40.0)), + (CaptionPosition::BottomLeft, (96.0, 1080.0 * 0.85 - 40.0)), + (CaptionPosition::BottomCenter, (760.0, 1080.0 * 0.85 - 40.0)), + (CaptionPosition::BottomRight, (1424.0, 1080.0 * 0.85 - 40.0)), + ]; + for (position, origin) in expected { + assert_eq!(caption_box_origin(position, manual, size, frame), origin); + assert_eq!(caption_box_origin(position, None, size, frame), origin); + } + assert_eq!( + caption_box_origin(CaptionPosition::Manual, None, size, frame), + caption_box_origin(CaptionPosition::BottomCenter, None, size, frame) + ); + } + + #[test] + fn the_frame_box_knows_its_placement() { + let manual = CaptionFrameBox::new([0.0, 0.0, 10.0, 10.0], "manual"); + assert!(manual.is_manual()); + assert!(manual.is_at("manual")); + let preset = CaptionFrameBox::new([0.0, 0.0, 10.0, 10.0], "top"); + assert!(!preset.is_manual()); + assert!(preset.is_at("top-center")); + assert!(!preset.is_at("bottom-center")); + } + /// A 400 px box against the 96 px left margin of a 1920 px frame is /// centred at 296 px, not at the 5% the preset table names. #[test] diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs index 4483aa781a3..e108918d844 100644 --- a/crates/rendering/src/lib.rs +++ b/crates/rendering/src/lib.rs @@ -75,7 +75,8 @@ pub use frame_pipeline::{GpuOutputFormat, Nv12RenderedFrame, RenderedFrame, Shar pub use frame_pipeline::{PendingSurface, RgbaToBgraSurfaceConverter}; pub use frame_windows::FrameWindows; pub use layers::{ - BackgroundTextureCache, clean_background_path, last_caption_center, new_font_system, + BackgroundTextureCache, CaptionFrameBox, clean_background_path, last_caption_center, + new_font_system, }; pub use managed_segment::{ ManagedRecordingSegmentDecoders, ManagedSegmentDecoderStatus, ManagedSegmentStopHandles, @@ -3653,6 +3654,9 @@ pub struct FrameLayout { pub display: [f32; 4], pub camera: Option<[f32; 4]>, pub output_size: [u32; 2], + /// Only the caption layer measures its box, so this is filled in after + /// the frame renders and stays `None` from [`ProjectUniforms::frame_layout`]. + pub caption: Option, } /// Unzoomed placement of the display card in output-frame pixels. Without a @@ -3682,6 +3686,7 @@ impl ProjectUniforms { display: self.display_outer_bounds, camera: self.camera.as_ref().map(|c| c.target_bounds), output_size: [self.output_size.0, self.output_size.1], + caption: None, } } @@ -8218,6 +8223,11 @@ fn join_layer(handle: std::thread::ScopedJoinHandle<'_, T>) -> T { } impl RendererLayers { + /// The caption box the last prepared frame drew, if any. + pub fn caption_frame_box(&self) -> Option { + self.overlays.as_ref()?.captions.frame_box() + } + pub fn reset_frame_state(&mut self) { self.display.reset_frame_state(); self.camera.reset_frame_state(); From 78acf2f9a71100bf410d0f4b0b9d345a493cd309 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:52:49 +0000 Subject: [PATCH 2/8] test(project): manual caption position loads from old projects and round-trips --- crates/project/src/configuration.rs | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs index bb0a0491097..64d7b3db71b 100644 --- a/crates/project/src/configuration.rs +++ b/crates/project/src/configuration.rs @@ -4803,6 +4803,57 @@ mod tests { assert_eq!(loaded.background.display_position, Some(XY::new(0.5, 0.4))); } + #[test] + fn manual_caption_position_loads_from_old_projects_and_round_trips() { + let dir = tempfile::tempdir().unwrap(); + + let mut value = serde_json::to_value(ProjectConfiguration::default()).unwrap(); + value["captions"] = serde_json::json!({ + "segments": [], + "settings": { "enabled": true, "position": "manual" }, + }); + std::fs::write( + dir.path().join("project-config.json"), + serde_json::to_string(&value).unwrap(), + ) + .unwrap(); + let old = ProjectConfiguration::load(dir.path()).unwrap(); + let settings = &old.captions.as_ref().unwrap().settings; + assert_eq!(settings.position, "manual"); + assert_eq!(settings.manual_position, None); + + value["captions"]["settings"]["manualPosition"] = serde_json::json!({ "x": 0.3, "y": 0.2 }); + std::fs::write( + dir.path().join("project-config.json"), + serde_json::to_string(&value).unwrap(), + ) + .unwrap(); + let tauri = ProjectConfiguration::load(dir.path()).unwrap(); + assert_eq!( + tauri.captions.as_ref().unwrap().settings.manual_position, + Some(XY::new(0.3, 0.2)) + ); + + let mut config = tauri; + config.captions.as_mut().unwrap().settings.manual_position = + Some(XY::new(0.423_7, 0.123_4)); + let saved = serde_json::to_value(&config).unwrap(); + assert_eq!( + saved["captions"]["settings"]["manualPosition"], + serde_json::json!({ "x": 0.423_7_f32, "y": 0.123_4_f32 }) + ); + std::fs::write( + dir.path().join("project-config.json"), + serde_json::to_string(&config).unwrap(), + ) + .unwrap(); + let reopened = ProjectConfiguration::load(dir.path()).unwrap(); + assert_eq!( + reopened.captions.as_ref().unwrap().settings.manual_position, + Some(XY::new(0.423_7, 0.123_4)) + ); + } + fn write_config_with_text_segment( project_path: &std::path::Path, font_size: f32, From 70617dc41b2b9574a6b9d308fdf39ddaf023d839 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:52:49 +0000 Subject: [PATCH 3/8] feat(desktop-gpui): drag, nudge and type the manual caption position --- apps/desktop-gpui/locales/de.toml | 2 + apps/desktop-gpui/locales/en.toml | 2 + apps/desktop-gpui/locales/es.toml | 2 + apps/desktop-gpui/locales/fr.toml | 2 + apps/desktop-gpui/locales/hi.toml | 2 + apps/desktop-gpui/locales/ja.toml | 2 + apps/desktop-gpui/locales/zh-CN.toml | 2 + apps/desktop-gpui/src/editor_canvas.rs | 298 +++++++++++++++++- apps/desktop-gpui/src/editor_panels.rs | 51 ++- apps/desktop-gpui/src/editor_tabs.rs | 221 +++++++++++-- apps/desktop-gpui/src/editor_window.rs | 46 ++- .../src/i18n/editor_shell_surface_tests.rs | 5 + 12 files changed, 596 insertions(+), 39 deletions(-) diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index 20701865b6e..dbbd169ccbc 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -2242,6 +2242,7 @@ purple = "Lila" [editor.canvas] camera = "Kamera" camera_follows_zoom = "Die Kameragröße folgt dem Zoom – zum Verschieben ziehen" +captions = "Untertitel" edit_zoom = "Zoom bearbeiten" image = "Bild" mask = "Maske" @@ -2500,6 +2501,7 @@ model_downloaded = "Modell {model} heruntergeladen" model_label = "Modell" position = "Position" regenerate = "Untertitel neu erstellen" +reset_position = "Position zurücksetzen" size_label = "Größe" style = "Stil" text_color = "Textfarbe" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index ff6f72e44b1..d3fc51f772b 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -2244,6 +2244,7 @@ purple = "Purple" [editor.canvas] camera = "Camera" camera_follows_zoom = "Camera size follows the zoom — drag to move" +captions = "Captions" edit_zoom = "Edit zoom" image = "Image" mask = "Mask" @@ -2502,6 +2503,7 @@ model_downloaded = "{model} model downloaded" model_label = "Model" position = "Position" regenerate = "Regenerate Captions" +reset_position = "Reset Position" size_label = "Size" style = "Style" text_color = "Text Color" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index 3156d6cb740..65f96b8b653 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -2242,6 +2242,7 @@ purple = "Morado" [editor.canvas] camera = "Cámara" camera_follows_zoom = "El tamaño de la cámara sigue al zoom; arrastra para moverla" +captions = "Subtítulos" edit_zoom = "Editar zoom" image = "Imagen" mask = "Máscara" @@ -2500,6 +2501,7 @@ model_downloaded = "Modelo {model} descargado" model_label = "Modelo" position = "Posición" regenerate = "Regenerar subtítulos" +reset_position = "Restablecer posición" size_label = "Tamaño" style = "Estilo" text_color = "Color del texto" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 16385c4743d..62b590f43a0 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -2242,6 +2242,7 @@ purple = "Violet" [editor.canvas] camera = "Caméra" camera_follows_zoom = "La taille de la caméra suit le zoom ; faites glisser pour la déplacer" +captions = "Sous-titres" edit_zoom = "Modifier le zoom" image = "Image" mask = "Masque" @@ -2500,6 +2501,7 @@ model_downloaded = "Modèle {model} téléchargé" model_label = "Modèle" position = "Position" regenerate = "Régénérer les sous-titres" +reset_position = "Réinitialiser la position" size_label = "Taille" style = "Style" text_color = "Couleur du texte" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index b8d7d9f0015..4fcd47b9525 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -2242,6 +2242,7 @@ purple = "बैंगनी" [editor.canvas] camera = "कैमरा" camera_follows_zoom = "कैमरे का आकार ज़ूम के साथ बदलता है; हिलाने के लिए खींचें" +captions = "कैप्शन" edit_zoom = "ज़ूम एडिट करें" image = "इमेज" mask = "मास्क" @@ -2500,6 +2501,7 @@ model_downloaded = "{model} मॉडल डाउनलोड हो गया" model_label = "मॉडल" position = "पोज़िशन" regenerate = "कैप्शन दोबारा बनाएँ" +reset_position = "पोज़िशन रीसेट करें" size_label = "आकार" style = "स्टाइल" text_color = "टेक्स्ट रंग" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index c04e300ea12..5e7231e8d09 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -2242,6 +2242,7 @@ purple = "パープル" [editor.canvas] camera = "カメラ" camera_follows_zoom = "カメラのサイズはズームに合わせて変わります。ドラッグで移動できます" +captions = "字幕" edit_zoom = "ズームを編集" image = "画像" mask = "マスク" @@ -2500,6 +2501,7 @@ model_downloaded = "{model}モデルをダウンロード済み" model_label = "モデル" position = "位置" regenerate = "字幕を再生成" +reset_position = "位置をリセット" size_label = "サイズ" style = "スタイル" text_color = "テキストの色" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 0d3ddef7591..38cbe1bb576 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -2242,6 +2242,7 @@ purple = "紫色" [editor.canvas] camera = "摄像头" camera_follows_zoom = "摄像头大小随缩放变化;拖动即可移动" +captions = "字幕" edit_zoom = "编辑缩放" image = "图片" mask = "遮罩" @@ -2500,6 +2501,7 @@ model_downloaded = "已下载“{model}”模型" model_label = "模型" position = "位置" regenerate = "重新生成字幕" +reset_position = "重置位置" size_label = "大小" style = "样式" text_color = "文字颜色" diff --git a/apps/desktop-gpui/src/editor_canvas.rs b/apps/desktop-gpui/src/editor_canvas.rs index a89bade62fd..488b6d3265e 100644 --- a/apps/desktop-gpui/src/editor_canvas.rs +++ b/apps/desktop-gpui/src/editor_canvas.rs @@ -46,7 +46,7 @@ use std::rc::Rc; use crate::i18n::tr; use crate::{editor_timeline::TrackKind, editor_window::EditorWindow}; use cap_project::{CameraXPosition, CameraYPosition, OverlayTrackKind, SceneMode, XY}; -use cap_rendering::FrameLayout; +use cap_rendering::{CaptionFrameBox, FrameLayout}; use gpui::{ AnyElement, Bounds, Context, CursorStyle, FontWeight, Hsla, InteractiveElement, IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, SharedString, @@ -104,6 +104,7 @@ pub enum SnapLineKind { Margin, ElementEdge, ElementCenter, + Third, } impl SnapLineKind { @@ -424,6 +425,84 @@ pub fn display_nudge_center( XY::new(x + rect.w / 2., y + rect.h / 2.) } +/// The caption safe area: the renderer's own 5% caption margin, applied to +/// both axes. +pub const CAPTION_SAFE_MARGIN: f64 = 0.05; + +/// Snap lines for a caption drag: the frame's edges and centre, its thirds, +/// the safe-area margins, and every other visible element. +pub fn caption_snap_targets(others: &[NormRect]) -> SnapTargets { + let mut targets = build_snap_targets(others, Some((CAPTION_SAFE_MARGIN, CAPTION_SAFE_MARGIN))); + for pos in [1. / 3., 2. / 3.] { + let line = SnapLine { + pos, + kind: SnapLineKind::Third, + reference: None, + }; + targets.v.push(line); + targets.h.push(line); + } + targets +} + +/// The caption box the renderer draws for a manual `center` and a box of +/// `size`, both normalised: centred on the point, then pushed back inside the +/// frame (`caption_box_origin` in `cap-rendering`). +pub fn caption_rest_rect(center: (f64, f64), size: (f64, f64)) -> NormRect { + let (w, h) = size; + NormRect { + x: (center.0 - w / 2.).clamp(0., (1. - w).max(0.)), + y: (center.1 - h / 2.).clamp(0., (1. - h).max(0.)), + w, + h, + } +} + +/// A caption drag keeps the whole box in the frame, the clamp the renderer +/// applies, so the stored centre is always the one drawn. +pub fn caption_drag_center( + rect: NormRect, + canvas: (f64, f64), + delta: (f64, f64), + targets: &SnapTargets, + shift: bool, +) -> (XY, Vec) { + camera_drag_center(rect, canvas, delta, targets, shift) +} + +/// One canvas pixel per arrow press, ten with Shift, inside the frame. +pub fn caption_nudge_center( + rect: NormRect, + canvas: (f64, f64), + direction: (f64, f64), + shift: bool, +) -> XY { + camera_nudge_center(rect, canvas, direction, shift) +} + +/// Where Manual placement centres the captions when no position is stored: +/// the bottom-centre spot the renderer falls back to. +pub const CAPTION_DEFAULT_CENTER: (f64, f64) = (0.5, 0.85); + +/// The caption box to hit-test on the canvas. Only a caption the renderer +/// placed manually gets one, so preset captions never take a click from the +/// elements under them. The size is the renderer's; the position comes from +/// the stored centre so a drag never waits on a frame. +pub fn caption_canvas_rect( + layout: &FrameLayout, + manual_position: Option>, +) -> Option { + let caption = layout.caption.filter(CaptionFrameBox::is_manual)?; + let drawn = norm_rect(caption.bounds, layout); + if drawn.w <= 0. || drawn.h <= 0. { + return None; + } + let center = manual_position.map_or(CAPTION_DEFAULT_CENTER, |position| { + (f64::from(position.x), f64::from(position.y)) + }); + Some(caption_rest_rect(center, (drawn.w, drawn.h))) +} + // --------------------------------------------------------------------------- // The live drag // --------------------------------------------------------------------------- @@ -447,6 +526,7 @@ pub enum CanvasSelection { Mask(usize), Text(usize), Image(usize), + Captions, } impl CanvasSelection { @@ -457,6 +537,7 @@ impl CanvasSelection { Self::Mask(_) => tr::editor::canvas::mask().into(), Self::Text(_) => tr::editor::canvas::text_item().into(), Self::Image(_) => tr::editor::canvas::image().into(), + Self::Captions => tr::editor::canvas::captions().into(), } } @@ -467,6 +548,7 @@ impl CanvasSelection { Self::Mask(index) => format!("canvas-mask-{index}").into(), Self::Text(index) => format!("canvas-text-{index}").into(), Self::Image(index) => format!("canvas-image-{index}").into(), + Self::Captions => "canvas-captions".into(), } } @@ -544,6 +626,16 @@ impl EditorWindow { self.canvas_overlay_visible() && !self.pane_scene() && self.camera_rect().is_some() } + fn caption_rect(&self) -> Option { + let layout = self.frame_layout.as_ref()?; + let captions = self.project.captions.as_ref()?; + caption_canvas_rect(layout, captions.settings.manual_position) + } + + fn show_captions(&self) -> bool { + self.canvas_overlay_visible() && self.caption_rect().is_some() + } + /// `displayDraggable()` (`:249`): the rendered display rect is /// zoom-transformed while a zoom segment is active, but a drag writes /// base-layout config, so it is locked rather than mismatched. @@ -649,6 +741,9 @@ impl EditorWindow { }); } } + if exclude == CanvasSelection::Captions { + return caption_snap_targets(&rects); + } let wants_margin = matches!(exclude, CanvasSelection::Display | CanvasSelection::Camera); build_snap_targets(&rects, wants_margin.then(|| classic_margin(layout))) } @@ -682,7 +777,8 @@ impl EditorWindow { CanvasSelection::Camera | CanvasSelection::Mask(_) | CanvasSelection::Text(_) - | CanvasSelection::Image(_) => true, + | CanvasSelection::Image(_) + | CanvasSelection::Captions => true, }; if !draggable { cx.notify(); @@ -717,6 +813,7 @@ impl EditorWindow { CanvasSelection::Display => self.display_draggable(), CanvasSelection::Camera => self.camera_resizable(), CanvasSelection::Mask(_) | CanvasSelection::Text(_) | CanvasSelection::Image(_) => true, + CanvasSelection::Captions => false, }; if !resizable { return; @@ -920,6 +1017,7 @@ impl EditorWindow { self.canvas_overlay_rect = Some(rect); self.write_overlay_rect(element, rect, cx); } + CanvasSelection::Captions => {} } let _ = (window, output_w, output_h); return; @@ -941,6 +1039,7 @@ impl EditorWindow { }; overlay_drag_center(bounds, size, delta, &targets, shift) } + CanvasSelection::Captions => caption_drag_center(start, size, delta, &targets, shift), }; self.snap_guides = guides; let optimistic = NormRect { @@ -961,6 +1060,7 @@ impl EditorWindow { self.canvas_overlay_rect = Some(optimistic); self.write_overlay_rect(element, optimistic, cx); } + CanvasSelection::Captions => self.write_caption_center(center, cx), } let _ = window; } @@ -1009,6 +1109,15 @@ impl EditorWindow { CanvasSelection::Image(index) => { tracing::info!(index, "canvas image drag"); } + CanvasSelection::Captions => tracing::info!( + position = ?self + .project + .captions + .as_ref() + .and_then(|captions| captions.settings.manual_position) + .map(|p| format!("{:.6},{:.6}", p.x, p.y)), + "canvas captions drag" + ), } } cx.notify(); @@ -1061,6 +1170,7 @@ impl EditorWindow { CanvasSelection::Mask(_) | CanvasSelection::Text(_) | CanvasSelection::Image(_) => { overlay_nudge_center(rect, direction, shift) } + CanvasSelection::Captions => caption_nudge_center(rect, size, direction, shift), }; let optimistic = NormRect { x: center.x - rect.w / 2., @@ -1080,6 +1190,7 @@ impl EditorWindow { self.canvas_overlay_rect = Some(optimistic); self.write_overlay_rect(selected, optimistic, cx); } + CanvasSelection::Captions => self.write_caption_center(center, cx), } self.schedule_save(window, cx); true @@ -1113,6 +1224,21 @@ impl EditorWindow { ); } + /// The manual caption centre. The placement setting itself is left alone: + /// the box only exists while the caption on screen is already manual, + /// whether through the setting or its segment's override. + fn write_caption_center(&mut self, center: XY, cx: &mut Context) { + let Some(captions) = self.project.captions.as_mut() else { + return; + }; + let next = XY::new(center.x as f32, center.y as f32); + if captions.settings.manual_position == Some(next) { + return; + } + captions.settings.manual_position = Some(next); + self.project_changed_live(cx); + } + fn write_canvas_style( &mut self, group: crate::editor_sidebar::StyleGroup, @@ -1207,6 +1333,7 @@ impl EditorWindow { h: segment.size.y, }) } + CanvasSelection::Captions => self.caption_rect(), } } @@ -1422,6 +1549,12 @@ impl EditorWindow { } } } + if self.show_captions() + && let Some(rect) = self.caption_rect() + { + layer = + layer.child(self.render_element_box(CanvasSelection::Captions, rect, (cw, ch), cx)); + } for guide in &self.snap_guides { let color = gpui::rgb(0xFF3B6B); layer = layer.child(match guide.axis { @@ -1474,7 +1607,9 @@ impl EditorWindow { CanvasSelection::Mask(_) | CanvasSelection::Text(_) | CanvasSelection::Image(_) => { (true, true, None) } + CanvasSelection::Captions => (true, false, None), }; + let has_handles = element != CanvasSelection::Captions; let left = rect.x as f32 * canvas.0; let top = rect.y as f32 * canvas.1; @@ -1598,7 +1733,10 @@ impl EditorWindow { (1, -1, CursorStyle::ResizeUpRightDownLeft), (-1, 1, CursorStyle::ResizeUpRightDownLeft), (1, 1, CursorStyle::ResizeUpLeftDownRight), - ] { + ] + .into_iter() + .filter(|_| has_handles) + { let hx = if dir_x < 0 { if flush.0 { 0. } else { -6. } } else if flush.2 { @@ -1955,6 +2093,7 @@ mod tests { display, camera: None, output_size: [width, height], + caption: None, } } @@ -2212,6 +2351,159 @@ mod tests { assert!((guide.start - 0.0).abs() < 1e-9); assert!((guide.end - 0.7).abs() < 1e-9); } + + fn caption_layout(width: u32, height: u32, bounds: [f32; 4], position: &str) -> FrameLayout { + FrameLayout { + caption: Some(CaptionFrameBox::new(bounds, position)), + ..layout(width, height, [0., 0., width as f32, height as f32]) + } + } + + fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 + } + + /// A preset caption gets no hit box at all, so a click on it reaches the + /// text, mask or screen underneath exactly as before. + #[test] + fn only_a_manual_caption_takes_clicks() { + let bounds = [700., 870., 1220., 930.]; + for preset in [ + "top-left", + "top-center", + "top-right", + "bottom-left", + "bottom-center", + "bottom-right", + ] { + let layout = caption_layout(1920, 1080, bounds, preset); + assert_eq!(caption_canvas_rect(&layout, Some(XY::new(0.5, 0.5))), None); + } + assert_eq!(caption_canvas_rect(&layout(1920, 1080, bounds), None), None); + let manual = caption_layout(1920, 1080, bounds, "manual"); + assert!(caption_canvas_rect(&manual, None).is_some()); + let empty = caption_layout(1920, 1080, [900., 900., 900., 900.], "manual"); + assert_eq!(caption_canvas_rect(&empty, None), None); + } + + /// The hit box is the renderer's box size at the stored centre, so it + /// covers the caption on screen and a click inside it lands. + #[test] + fn the_caption_hit_box_covers_the_drawn_caption() { + let canvas = Bounds { + origin: gpui::point(px(40.), px(20.)), + size: gpui::size(px(960.), px(540.)), + }; + let layout = caption_layout(1920, 1080, [576., 186., 1056., 246.], "manual"); + let rect = caption_canvas_rect(&layout, Some(XY::new(0.425, 0.2))).unwrap(); + assert!(near(rect.x, 576. / 1920.)); + assert!(near(rect.y, 186. / 1080.)); + assert!(near(rect.w, 480. / 1920.)); + assert!(near(rect.h, 60. / 1080.)); + assert!(rect_contains( + canvas, + rect, + gpui::point(px(40. + 0.425 * 960.), px(20. + 0.2 * 540.)) + )); + assert!(!rect_contains( + canvas, + rect, + gpui::point(px(40. + 0.425 * 960.), px(20. + 0.5 * 540.)) + )); + } + + /// No stored centre is the renderer's bottom-centre fallback, and a + /// centre near an edge is drawn pushed back inside the frame, in every + /// aspect. + #[test] + fn the_caption_rect_follows_the_renderer_clamp() { + let layout = caption_layout(1920, 1080, [700., 888., 1220., 948.], "manual"); + let rect = caption_canvas_rect(&layout, None).unwrap(); + assert!(near(rect.x + rect.w / 2., 0.5)); + assert!(near(rect.y + rect.h / 2., 0.85)); + + for (width, height) in [(1920, 1080), (1080, 1920), (1080, 1080), (1440, 1080)] { + let bounds = [0., 0., width as f32 * 0.4, height as f32 * 0.06]; + let layout = caption_layout(width, height, bounds, "manual"); + for spot in [XY::new(0., 0.), XY::new(1., 1.), XY::new(0.98, 0.01)] { + let rect = caption_canvas_rect(&layout, Some(spot)).unwrap(); + assert!(rect.x >= 0. && rect.x + rect.w <= 1. + 1e-9); + assert!(rect.y >= 0. && rect.y + rect.h <= 1. + 1e-9); + } + } + } + + /// A caption drag snaps to the frame centre, the thirds and the safe + /// margins, and shows the guide it snapped to. + #[test] + fn a_caption_drag_snaps_to_centre_thirds_and_safe_margins() { + let targets = caption_snap_targets(&[]); + let rect = NormRect { + x: 0.1, + y: 0.6, + w: 0.3, + h: 0.06, + }; + let canvas = (960., 540.); + + let to_centre = (0.5 - 0.25 - 3. / 960.) * 960.; + let (center, guides) = caption_drag_center(rect, canvas, (to_centre, 0.), &targets, false); + assert!(near(center.x, 0.5)); + assert!( + guides + .iter() + .any(|guide| guide.axis == GuideAxis::V && guide.kind == SnapLineKind::FrameCenter) + ); + + let to_third = (2. / 3. - 0.63 + 4. / 540.) * 540.; + let (center, guides) = caption_drag_center(rect, canvas, (0., to_third), &targets, false); + assert!(near(center.y, 2. / 3.)); + assert!( + guides + .iter() + .any(|guide| guide.axis == GuideAxis::H && guide.kind == SnapLineKind::Third) + ); + + let to_margin = (0.05 - 0.1 + 2. / 960.) * 960.; + let (center, guides) = caption_drag_center(rect, canvas, (to_margin, 0.), &targets, false); + assert!(near(center.x - rect.w / 2., CAPTION_SAFE_MARGIN)); + assert!( + guides + .iter() + .any(|guide| guide.axis == GuideAxis::V && guide.kind == SnapLineKind::Margin) + ); + + let (center, guides) = caption_drag_center(rect, canvas, (to_centre, 0.), &targets, true); + assert!(near(center.x, 0.25 + to_centre / 960.)); + assert!(guides.is_empty()); + } + + /// The stored centre after a drag or a nudge is always the one drawn: + /// the box cannot be pushed past an edge. + #[test] + fn a_caption_drag_and_nudge_keep_the_box_in_frame() { + let rect = NormRect { + x: 0.6, + y: 0.9, + w: 0.3, + h: 0.06, + }; + let targets = SnapTargets::default(); + let (center, _) = caption_drag_center(rect, (960., 540.), (900., 900.), &targets, true); + assert!(near(center.x, 1. - 0.15)); + assert!(near(center.y, 1. - 0.03)); + let (center, _) = caption_drag_center(rect, (960., 540.), (-2000., -900.), &targets, true); + assert!(near(center.x, 0.15)); + assert!(near(center.y, 0.03)); + + let center = caption_nudge_center(rect, (960., 540.), (-1., 0.), false); + assert!(near(center.x, 0.75 - 1. / 960.)); + let center = caption_nudge_center(rect, (960., 540.), (0., -1.), true); + assert!(near(center.y, 0.93 - 10. / 540.)); + let flush = NormRect { x: 0.7, ..rect }; + let center = caption_nudge_center(flush, (960., 540.), (1., 0.), true); + assert!(near(center.x, 0.85)); + } } fn rotate_point(point: (f64, f64), degrees: f64) -> (f64, f64) { diff --git a/apps/desktop-gpui/src/editor_panels.rs b/apps/desktop-gpui/src/editor_panels.rs index a7cca96368e..7392afc49ab 100644 --- a/apps/desktop-gpui/src/editor_panels.rs +++ b/apps/desktop-gpui/src/editor_panels.rs @@ -2794,6 +2794,9 @@ pub enum FieldKey { KeyboardStart(usize), KeyboardEnd(usize), SyncOffset(usize, OffsetKind), + /// The captions tab's manual centre, as a percentage of the frame. + CaptionManualX, + CaptionManualY, /// The crop dialog's four `BoundInput`s (`Editor.tsx:1199-1216`). They do /// not edit the project at all -- they drive the open cropper, which is /// why they are the one key whose value comes from outside @@ -2920,6 +2923,17 @@ impl EditorWindow { out.push_str(&ui::format_number(field.read(state.real()))); return Some(()); } + if matches!(key, FieldKey::CaptionManualX | FieldKey::CaptionManualY) { + let settings = crate::editor_tabs::caption_settings(&self.project); + let (x, y) = crate::editor_tabs::caption_manual_center(&settings); + let value = if key == FieldKey::CaptionManualX { + x + } else { + y + }; + out.push_str(&crate::editor_tabs::caption_percent_text(value)); + return Some(()); + } let timeline = self.project.timeline.as_ref()?; match key { FieldKey::StyleName(index) => out.push_str(&timeline.style_segments.get(index)?.name), @@ -3175,6 +3189,23 @@ impl EditorWindow { true }); } + FieldKey::CaptionManualX | FieldKey::CaptionManualY => { + if !final_commit { + return; + } + let Some(value) = ui::parse_number(&text) else { + return; + }; + let value = value.clamp(0., 100.) as f32; + let horizontal = key == FieldKey::CaptionManualX; + self.set_caption_placement(window, cx, move |settings| { + if horizontal { + crate::editor_tabs::set_caption_manual_center(settings, Some(value), None); + } else { + crate::editor_tabs::set_caption_manual_center(settings, None, Some(value)); + } + }); + } // The four `` boxes commit `onChange`, which // in Solid is the *change* event -- blur or Enter, not every // keystroke (`:4280-4290`). So they only write on a final commit. @@ -8306,11 +8337,21 @@ impl EditorWindow { } } None => match self.sidebar.tab { - crate::editor_sidebar::SidebarTab::Captions => colors.extend([ - ColorTarget::CaptionColor, - ColorTarget::CaptionBackground, - ColorTarget::CaptionHighlight, - ]), + crate::editor_sidebar::SidebarTab::Captions => { + colors.extend([ + ColorTarget::CaptionColor, + ColorTarget::CaptionBackground, + ColorTarget::CaptionHighlight, + ]); + if self + .project + .captions + .as_ref() + .is_some_and(|captions| captions.settings.position == "manual") + { + fields.extend([FieldKey::CaptionManualX, FieldKey::CaptionManualY]); + } + } crate::editor_sidebar::SidebarTab::Keyboard => { colors.extend([ColorTarget::KeyboardColor, ColorTarget::KeyboardBackground]) } diff --git a/apps/desktop-gpui/src/editor_tabs.rs b/apps/desktop-gpui/src/editor_tabs.rs index 3a49d8e5c14..9b989fed50e 100644 --- a/apps/desktop-gpui/src/editor_tabs.rs +++ b/apps/desktop-gpui/src/editor_tabs.rs @@ -563,6 +563,33 @@ pub fn caption_manual_center(settings: &CaptionSettings) -> (f32, f32) { ) } +/// The manual centre as the panel's percentage, to a tenth. +pub fn caption_percent_text(fraction: f32) -> String { + ui::format_number((f64::from(fraction) * 1000.).round() / 10.) +} + +/// "Reset position": Manual placement back on the default bottom-centre spot. +pub fn reset_caption_manual_center(settings: &mut CaptionSettings) { + let (x, y) = crate::editor_canvas::CAPTION_DEFAULT_CENTER; + settings.position = "manual".to_string(); + settings.manual_position = Some(cap_project::XY::new(x as f32, y as f32)); +} + +pub fn caption_at_default_center(settings: &CaptionSettings) -> bool { + let (x, y) = crate::editor_canvas::CAPTION_DEFAULT_CENTER; + caption_manual_center(settings) == (x as f32, y as f32) +} + +/// `STYLE_PRESET_KEYS` knocks the style preset to "custom" +/// (`CaptionsTab.tsx:157-172, 326-336`). Turning captions on, the export +/// toggle and placement are not style, so they keep the preset. +fn caption_reason_customises_style(reason: &str) -> bool { + !matches!( + reason, + "caption-enabled" | "caption-export" | "caption-position" | "caption-placement" + ) +} + pub fn set_caption_manual_center(settings: &mut CaptionSettings, x: Option, y: Option) { let (current_x, current_y) = caption_manual_center(settings); let fraction = |value: f32| (value / 100.).clamp(0., 1.); @@ -576,14 +603,24 @@ pub fn set_caption_manual_center(settings: &mut CaptionSettings, x: Option, /// Switching the caption position. Entering Manual from a preset seeds the /// manual centre from that preset (`updateCaptionPosition`, /// `CaptionsTab.tsx:380-394`); without it Manual drew bottom-centre and had -/// nothing to adjust. -pub fn set_caption_position(settings: &mut CaptionSettings, position: &str) { - set_caption_position_from(settings, position, cap_rendering::last_caption_center); +/// nothing to adjust. `on_screen` is the caption on the preview frame and +/// its centre; the renderer's last drawn caption is the fallback. +pub fn set_caption_position( + settings: &mut CaptionSettings, + position: &str, + on_screen: Option<(cap_rendering::CaptionFrameBox, (f32, f32))>, +) { + set_caption_position_from(settings, position, |preset| { + on_screen + .filter(|(caption, _)| caption.is_at(preset)) + .map(|(_, center)| center) + .or_else(|| cap_rendering::last_caption_center(preset)) + }); } -/// [`set_caption_position`] with the renderer's last drawn caption centre -/// supplied: left and right presets align the box's edge to a margin, so -/// only the drawn box says where its centre is. +/// [`set_caption_position`] with the drawn caption centre supplied: left and +/// right presets align the box's edge to a margin, so only the drawn box +/// says where its centre is. fn set_caption_position_from( settings: &mut CaptionSettings, position: &str, @@ -1067,8 +1104,16 @@ impl EditorWindow { let Some((value, _)) = CAPTION_POSITIONS.get(index) else { return; }; + let on_screen = self.frame_layout.and_then(|layout| { + let caption = layout.caption?; + let rect = crate::editor_canvas::norm_rect(caption.bounds, &layout); + Some(( + caption, + ((rect.x + rect.w / 2.) as f32, (rect.y + rect.h / 2.) as f32), + )) + }); self.set_caption_setting("caption-position", window, cx, move |settings| { - set_caption_position(settings, value) + set_caption_position(settings, value, on_screen) }); } SidebarMenu::CaptionAnimation => { @@ -1145,11 +1190,7 @@ impl EditorWindow { let apply = |project: &mut ProjectConfiguration| { with_caption_settings(project, |settings| { change(settings); - // `STYLE_PRESET_KEYS` knocks the grade to "custom" - // (`CaptionsTab.tsx:326-336`). Every setter routed through here - // is one of those keys except the two `enabled`-style ones, - // which are handled by their own call sites. - if reason != "caption-enabled" && reason != "caption-export" { + if caption_reason_customises_style(reason) { settings.preset = "custom".to_string(); } }) @@ -1161,6 +1202,17 @@ impl EditorWindow { } } + /// A caption placement write from the panel: no timeline rebuild, and + /// the style preset stays as it is. + pub(crate) fn set_caption_placement( + &mut self, + window: &mut Window, + cx: &mut Context, + change: impl FnOnce(&mut CaptionSettings), + ) { + self.set_caption_setting_inner(false, "caption-placement", window, cx, change); + } + pub(crate) fn set_keyboard_setting( &mut self, reason: &'static str, @@ -1304,9 +1356,15 @@ impl EditorWindow { window: &mut Window, cx: &mut Context, ) { + let reason = match slider { + CaptionSlider::ManualX | CaptionSlider::ManualY => "caption-placement", + CaptionSlider::Size + | CaptionSlider::BackgroundOpacity + | CaptionSlider::FadeDuration => "caption-slider", + }; self.set_caption_setting_inner( slider.changes_timeline_model(), - "caption-slider", + reason, window, cx, move |settings| match slider { @@ -3162,23 +3220,38 @@ impl EditorWindow { .flex() .flex_col() .gap(px(12.)) + .child(self.caption_position_row( + tr::editor::tabs::captions::horizontal_position(), + CaptionSlider::ManualX, + crate::editor_panels::FieldKey::CaptionManualX, + cx, + )) + .child(self.caption_position_row( + tr::editor::tabs::captions::vertical_position(), + CaptionSlider::ManualY, + crate::editor_panels::FieldKey::CaptionManualY, + cx, + )) .child( - self.slider_field( - tr::editor::tabs::captions::horizontal_position(), - SliderKey::Caption(CaptionSlider::ManualX), - "%", - cx, - ) - .into_any_element(), - ) - .child( - self.slider_field( - tr::editor::tabs::captions::vertical_position(), - SliderKey::Caption(CaptionSlider::ManualY), - "%", - cx, - ) - .into_any_element(), + div().flex().flex_row().justify_end().child( + ui::Button::plain( + &theme, + "caption-reset-position", + ui::ButtonVariant::Gray, + ui::ButtonSize::Sm, + ) + .label(tr::editor::tabs::captions::reset_position()) + .disabled(caption_at_default_center(&settings)) + .on_click(cx.listener( + |this, _, window, cx| { + this.set_caption_placement( + window, + cx, + reset_caption_manual_center, + ); + }, + )), + ), ) })) .child( @@ -3231,6 +3304,20 @@ impl EditorWindow { .into_any_element() } + /// A manual position row: label, slider, and the exact percentage to type. + fn caption_position_row( + &self, + name: impl Into, + slider: CaptionSlider, + field: crate::editor_panels::FieldKey, + cx: &mut Context, + ) -> AnyElement { + ui::Field::inline(&self.theme, name) + .child(self.slider_flex(SliderKey::Caption(slider), "%", cx)) + .value(self.render_number_field(field, "%", 56.)) + .into_any_element() + } + /// The five style presets (`CaptionsTab.tsx:1041-1075`), each previewing /// "Make it pop" in its own style with the third word emphasised. fn render_caption_presets( @@ -3861,6 +3948,22 @@ mod tests { ); } + /// The caption on the preview frame wins over the renderer's last drawn + /// one when it was drawn for the preset being left. + #[test] + fn manual_caption_position_starts_at_the_caption_on_screen() { + let mut settings = CaptionSettings { + position: "bottom-left".into(), + ..CaptionSettings::default() + }; + let on_screen = cap_rendering::CaptionFrameBox::new([0.; 4], "bottom-left"); + set_caption_position(&mut settings, "manual", Some((on_screen, (0.21, 0.84)))); + assert_eq!( + settings.manual_position.map(|xy| (xy.x, xy.y)), + Some((0.21, 0.84)) + ); + } + /// A 0.6.1 report: with the caption position set to Manual, the captions /// stayed bottom-centre and nothing could move them. Manual now starts /// where the preset drew them and the sliders move it. @@ -3892,7 +3995,7 @@ mod tests { assert_eq!(CaptionSlider::ManualY.read(&project), 100.); // Picking Manual again keeps the adjusted spot. - set_caption_position(&mut settings, "manual"); + set_caption_position(&mut settings, "manual", None); assert_eq!( settings.manual_position.map(|xy| (xy.x, xy.y)), Some((0.2, 1.0)) @@ -3911,6 +4014,64 @@ mod tests { ); } + #[test] + fn moving_the_captions_keeps_the_style_preset() { + for reason in ["caption-position", "caption-placement"] { + assert!(!caption_reason_customises_style(reason)); + } + for reason in ["caption-slider", "caption-font", "caption-animation"] { + assert!(caption_reason_customises_style(reason)); + } + } + + #[test] + fn reset_position_returns_manual_captions_to_bottom_centre() { + let mut settings = CaptionSettings { + position: "manual".into(), + manual_position: Some(cap_project::XY::new(0.2, 0.3)), + ..CaptionSettings::default() + }; + assert!(!caption_at_default_center(&settings)); + reset_caption_manual_center(&mut settings); + assert_eq!(settings.position, "manual"); + assert_eq!( + settings.manual_position.map(|xy| (xy.x, xy.y)), + Some((0.5, 0.85)) + ); + assert!(caption_at_default_center(&settings)); + + let unset = CaptionSettings { + position: "manual".into(), + ..CaptionSettings::default() + }; + assert!(caption_at_default_center(&unset)); + } + + /// The typed X and Y read back the way they were stored, to a tenth of + /// a percent, including centres a drag left between whole numbers. + #[test] + fn manual_position_fields_read_a_tenth_of_a_percent() { + assert_eq!(caption_percent_text(0.5), "50"); + assert_eq!(caption_percent_text(0.423_7), "42.4"); + assert_eq!(caption_percent_text(0.0), "0"); + assert_eq!(caption_percent_text(1.0), "100"); + assert_eq!(caption_percent_text(0.333_333_34), "33.3"); + + let mut settings = CaptionSettings { + position: "manual".into(), + ..CaptionSettings::default() + }; + set_caption_manual_center(&mut settings, Some(33.3), Some(150.)); + assert_eq!( + caption_percent_text(caption_manual_center(&settings).0), + "33.3" + ); + assert_eq!( + caption_percent_text(caption_manual_center(&settings).1), + "100" + ); + } + #[test] fn every_tab_slider_has_the_range_its_call_site_declares() { assert_eq!(CameraSlider::Size.limits(), (20., 80., 0.1)); diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index a899f906582..6f580359413 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -303,6 +303,18 @@ fn seeked_playhead(time: f64, frame: u32, playing: bool) -> f64 { if playing { time } else { frame_seconds(frame) } } +/// The part of a frame layout the canvas overlay draws from. A preset +/// caption has no box on the canvas, so a new caption under the playhead only +/// rebuilds the editor when it is placed manually. +fn canvas_hit_layout(layout: FrameLayout) -> FrameLayout { + FrameLayout { + caption: layout + .caption + .filter(cap_rendering::CaptionFrameBox::is_manual), + ..layout + } +} + fn frame_layout_requires_editor_invalidation( first_frame: bool, playing: bool, @@ -6626,7 +6638,8 @@ impl EditorWindow { } let handoff_target = self.transport.as_ref().and(self.ordinary_handoff_frame); let first_frame = self.latest_frame.is_none(); - let layout_changed = self.frame_layout != Some(frame.layout); + let layout_changed = + self.frame_layout.map(canvas_hit_layout) != Some(canvas_hit_layout(frame.layout)); if self.frame_layout.map(|layout| layout.output_size) != Some(frame.layout.output_size) { tracing::info!( output_size = ?frame.layout.output_size, @@ -14568,6 +14581,37 @@ mod tests { )); } + /// Scrubbing across preset captions changes only the caption box, which + /// the canvas never draws, so it costs no editor rebuild. A manual + /// caption's box is a canvas hit target, so its change does. + #[test] + fn only_a_manual_caption_box_changes_the_canvas_layout() { + let base = FrameLayout { + display: [0., 0., 1920., 1080.], + camera: None, + output_size: [1920, 1080], + caption: None, + }; + let preset = |bounds| FrameLayout { + caption: Some(cap_rendering::CaptionFrameBox::new(bounds, "bottom-center")), + ..base + }; + let manual = |bounds| FrameLayout { + caption: Some(cap_rendering::CaptionFrameBox::new(bounds, "manual")), + ..base + }; + assert_eq!(canvas_hit_layout(preset([0., 0., 10., 10.])), base); + assert_eq!( + canvas_hit_layout(preset([0., 0., 10., 10.])), + canvas_hit_layout(preset([5., 5., 50., 20.])) + ); + assert_ne!( + canvas_hit_layout(manual([0., 0., 10., 10.])), + canvas_hit_layout(manual([5., 5., 50., 20.])) + ); + assert_ne!(canvas_hit_layout(manual([0., 0., 10., 10.])), base); + } + /// Every failure `EditorInstance::new` would return, plus the one it would /// panic on, has to come back as a message. #[test] diff --git a/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs b/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs index 7ba482c4968..b88b446534b 100644 --- a/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs @@ -89,6 +89,7 @@ fn editor_shell_surfaces_match_the_literals_they_replaced() { tr::editor::canvas::camera_follows_zoom(), "Camera size follows the zoom — drag to move", ), + (tr::editor::canvas::captions(), "Captions"), (tr::editor::canvas::edit_zoom(), "Edit zoom"), (tr::editor::canvas::image(), "Image"), (tr::editor::canvas::mask(), "Mask"), @@ -579,6 +580,10 @@ fn editor_shell_surfaces_match_the_literals_they_replaced() { tr::editor::tabs::captions::regenerate(), "Regenerate Captions", ), + ( + tr::editor::tabs::captions::reset_position(), + "Reset Position", + ), (tr::editor::tabs::captions::size_label(), "Size"), (tr::editor::tabs::captions::style(), "Style"), (tr::editor::tabs::captions::text_color(), "Text Color"), From 0b3d89abb69cba5b5d91a3d1f7d5bd4dca916538 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:40:33 +0000 Subject: [PATCH 4/8] fix(desktop-gpui): the caption box takes the hover from the boxes under it --- apps/desktop-gpui/src/editor_canvas.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/apps/desktop-gpui/src/editor_canvas.rs b/apps/desktop-gpui/src/editor_canvas.rs index 488b6d3265e..a7201d1f4de 100644 --- a/apps/desktop-gpui/src/editor_canvas.rs +++ b/apps/desktop-gpui/src/editor_canvas.rs @@ -1660,6 +1660,13 @@ impl EditorWindow { }), ); + // The caption is drawn over every other element, so its box takes the + // pointer from the boxes under it; otherwise the screen box under it + // can win the hover and light up while the caption is the target. + if element == CanvasSelection::Captions { + box_el = box_el.occlude(); + } + if show { let label_left = (6. - left).max(6.); let label_top = if top >= 28. { -24. } else { (6. - top).max(6.) }; From cd8889568e0b75ebc15903c323305b60f190e02b Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:40:33 +0000 Subject: [PATCH 5/8] docs(desktop-gpui): document the manual caption position controls --- apps/desktop-gpui/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/desktop-gpui/README.md b/apps/desktop-gpui/README.md index 13093e19179..a94a8e46f8e 100644 --- a/apps/desktop-gpui/README.md +++ b/apps/desktop-gpui/README.md @@ -2006,6 +2006,7 @@ steps and side effects are the call site's. | | Uppercase / Active Word Highlight (+ Highlight Color, Style) | toggles, then a hex field and a select | — | `captions.settings.{uppercase,activeWordHighlight,highlightColor,highlightStyle}` | | | Background Settings → Color / Opacity | hex field + swatch, slider | 0–100 / 1 `%` | `captions.settings.{backgroundColor,backgroundOpacity}` | | | Position / Animation / Font Weight | three selects | — | `captions.settings.{position,fontWeight}`, `{fade,linger,wordTransition}Duration` | +| | Manual position → Horizontal / Vertical / Reset Position | shown while Position is Manual: slider plus a typed percentage per axis, and a reset to bottom centre. The caption on the preview is also a canvas element then: hover, select, drag with centre, thirds and safe-margin guides, arrow keys nudge 1px (10 with Shift) | 0–100 `%` | `captions.settings.manualPosition`, the caption box's centre as a fraction of the output frame | Two things in these tabs are honest dead ends rather than key paths, and both say so in the UI: From 733af27c0dbc5441783ed6ed686dbb3af2758bac Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 3 Nov 2026 16:53:55 +0000 Subject: [PATCH 6/8] chore(desktop-gpui): drop comments that restate the code --- apps/desktop-gpui/src/editor_canvas.rs | 3 --- apps/desktop-gpui/src/editor_panels.rs | 1 - apps/desktop-gpui/src/editor_tabs.rs | 5 ----- crates/rendering/src/layers/captions.rs | 1 - crates/rendering/src/lib.rs | 1 - 5 files changed, 11 deletions(-) diff --git a/apps/desktop-gpui/src/editor_canvas.rs b/apps/desktop-gpui/src/editor_canvas.rs index a7201d1f4de..49089712244 100644 --- a/apps/desktop-gpui/src/editor_canvas.rs +++ b/apps/desktop-gpui/src/editor_canvas.rs @@ -429,8 +429,6 @@ pub fn display_nudge_center( /// both axes. pub const CAPTION_SAFE_MARGIN: f64 = 0.05; -/// Snap lines for a caption drag: the frame's edges and centre, its thirds, -/// the safe-area margins, and every other visible element. pub fn caption_snap_targets(others: &[NormRect]) -> SnapTargets { let mut targets = build_snap_targets(others, Some((CAPTION_SAFE_MARGIN, CAPTION_SAFE_MARGIN))); for pos in [1. / 3., 2. / 3.] { @@ -470,7 +468,6 @@ pub fn caption_drag_center( camera_drag_center(rect, canvas, delta, targets, shift) } -/// One canvas pixel per arrow press, ten with Shift, inside the frame. pub fn caption_nudge_center( rect: NormRect, canvas: (f64, f64), diff --git a/apps/desktop-gpui/src/editor_panels.rs b/apps/desktop-gpui/src/editor_panels.rs index 7392afc49ab..013bfec57f7 100644 --- a/apps/desktop-gpui/src/editor_panels.rs +++ b/apps/desktop-gpui/src/editor_panels.rs @@ -2794,7 +2794,6 @@ pub enum FieldKey { KeyboardStart(usize), KeyboardEnd(usize), SyncOffset(usize, OffsetKind), - /// The captions tab's manual centre, as a percentage of the frame. CaptionManualX, CaptionManualY, /// The crop dialog's four `BoundInput`s (`Editor.tsx:1199-1216`). They do diff --git a/apps/desktop-gpui/src/editor_tabs.rs b/apps/desktop-gpui/src/editor_tabs.rs index 9b989fed50e..717a381f931 100644 --- a/apps/desktop-gpui/src/editor_tabs.rs +++ b/apps/desktop-gpui/src/editor_tabs.rs @@ -563,12 +563,10 @@ pub fn caption_manual_center(settings: &CaptionSettings) -> (f32, f32) { ) } -/// The manual centre as the panel's percentage, to a tenth. pub fn caption_percent_text(fraction: f32) -> String { ui::format_number((f64::from(fraction) * 1000.).round() / 10.) } -/// "Reset position": Manual placement back on the default bottom-centre spot. pub fn reset_caption_manual_center(settings: &mut CaptionSettings) { let (x, y) = crate::editor_canvas::CAPTION_DEFAULT_CENTER; settings.position = "manual".to_string(); @@ -1202,8 +1200,6 @@ impl EditorWindow { } } - /// A caption placement write from the panel: no timeline rebuild, and - /// the style preset stays as it is. pub(crate) fn set_caption_placement( &mut self, window: &mut Window, @@ -3304,7 +3300,6 @@ impl EditorWindow { .into_any_element() } - /// A manual position row: label, slider, and the exact percentage to type. fn caption_position_row( &self, name: impl Into, diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rs index ed8a1141f72..911d324f443 100644 --- a/crates/rendering/src/layers/captions.rs +++ b/crates/rendering/src/layers/captions.rs @@ -124,7 +124,6 @@ impl CaptionFrameBox { self.position == CaptionPosition::Manual } - /// Whether this caption was laid out for the position setting `position`. pub fn is_at(&self, position: &str) -> bool { self.position == CaptionPosition::from_str(position) } diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs index e108918d844..967f5cf1079 100644 --- a/crates/rendering/src/lib.rs +++ b/crates/rendering/src/lib.rs @@ -8223,7 +8223,6 @@ fn join_layer(handle: std::thread::ScopedJoinHandle<'_, T>) -> T { } impl RendererLayers { - /// The caption box the last prepared frame drew, if any. pub fn caption_frame_box(&self) -> Option { self.overlays.as_ref()?.captions.frame_box() } From 33e6fbdc7c31baf8a8aae256c640e9406caac19d Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:44:09 +0000 Subject: [PATCH 7/8] perf(desktop-gpui): a manual caption box only rebuilds the editor while the canvas overlay is live --- apps/desktop-gpui/src/editor_window.rs | 36 ++++++++++++++++---------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index 6f580359413..cc964f7698c 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -304,13 +304,15 @@ fn seeked_playhead(time: f64, frame: u32, playing: bool) -> f64 { } /// The part of a frame layout the canvas overlay draws from. A preset -/// caption has no box on the canvas, so a new caption under the playhead only -/// rebuilds the editor when it is placed manually. -fn canvas_hit_layout(layout: FrameLayout) -> FrameLayout { +/// caption has no box on the canvas, and the overlay only draws while the +/// player is hovered or dragged, so a new caption under the playhead only +/// rebuilds the editor when its box could be on screen. Hovering the player +/// rebuilds the editor anyway, which picks up the latest box. +fn canvas_hit_layout(layout: FrameLayout, overlay_live: bool) -> FrameLayout { FrameLayout { caption: layout .caption - .filter(cap_rendering::CaptionFrameBox::is_manual), + .filter(|caption| overlay_live && caption.is_manual()), ..layout } } @@ -6638,8 +6640,11 @@ impl EditorWindow { } let handoff_target = self.transport.as_ref().and(self.ordinary_handoff_frame); let first_frame = self.latest_frame.is_none(); - let layout_changed = - self.frame_layout.map(canvas_hit_layout) != Some(canvas_hit_layout(frame.layout)); + let overlay_live = self.player_panel_hovered || self.canvas_drag.is_some(); + let layout_changed = self + .frame_layout + .map(|layout| canvas_hit_layout(layout, overlay_live)) + != Some(canvas_hit_layout(frame.layout, overlay_live)); if self.frame_layout.map(|layout| layout.output_size) != Some(frame.layout.output_size) { tracing::info!( output_size = ?frame.layout.output_size, @@ -14583,7 +14588,8 @@ mod tests { /// Scrubbing across preset captions changes only the caption box, which /// the canvas never draws, so it costs no editor rebuild. A manual - /// caption's box is a canvas hit target, so its change does. + /// caption's box is a canvas hit target, so its change does while the + /// overlay is live, and not while the pointer is elsewhere. #[test] fn only_a_manual_caption_box_changes_the_canvas_layout() { let base = FrameLayout { @@ -14600,16 +14606,20 @@ mod tests { caption: Some(cap_rendering::CaptionFrameBox::new(bounds, "manual")), ..base }; - assert_eq!(canvas_hit_layout(preset([0., 0., 10., 10.])), base); + assert_eq!(canvas_hit_layout(preset([0., 0., 10., 10.]), true), base); assert_eq!( - canvas_hit_layout(preset([0., 0., 10., 10.])), - canvas_hit_layout(preset([5., 5., 50., 20.])) + canvas_hit_layout(preset([0., 0., 10., 10.]), true), + canvas_hit_layout(preset([5., 5., 50., 20.]), true) ); assert_ne!( - canvas_hit_layout(manual([0., 0., 10., 10.])), - canvas_hit_layout(manual([5., 5., 50., 20.])) + canvas_hit_layout(manual([0., 0., 10., 10.]), true), + canvas_hit_layout(manual([5., 5., 50., 20.]), true) + ); + assert_ne!(canvas_hit_layout(manual([0., 0., 10., 10.]), true), base); + assert_eq!( + canvas_hit_layout(manual([0., 0., 10., 10.]), false), + canvas_hit_layout(manual([5., 5., 50., 20.]), false) ); - assert_ne!(canvas_hit_layout(manual([0., 0., 10., 10.])), base); } /// Every failure `EditorInstance::new` would return, plus the one it would From 2acf210bf1eee7ee0310c83222d1a6d2a4568ad6 Mon Sep 17 00:00:00 2001 From: Richie McIlroy <33632126+richiemcilroy@users.noreply.github.com> Date: Tue, 3 Nov 2026 18:21:09 +0000 Subject: [PATCH 8/8] perf(desktop-gpui): read the manual caption fields without cloning the settings --- apps/desktop-gpui/src/editor_panels.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/desktop-gpui/src/editor_panels.rs b/apps/desktop-gpui/src/editor_panels.rs index 013bfec57f7..ac39856eb15 100644 --- a/apps/desktop-gpui/src/editor_panels.rs +++ b/apps/desktop-gpui/src/editor_panels.rs @@ -2923,8 +2923,9 @@ impl EditorWindow { return Some(()); } if matches!(key, FieldKey::CaptionManualX | FieldKey::CaptionManualY) { - let settings = crate::editor_tabs::caption_settings(&self.project); - let (x, y) = crate::editor_tabs::caption_manual_center(&settings); + let (x, y) = crate::editor_tabs::caption_manual_center( + &self.project.captions.as_ref()?.settings, + ); let value = if key == FieldKey::CaptionManualX { x } else {