From 68b7a464098a1b84cf97e4a2e92fb114f508511c Mon Sep 17 00:00:00 2001 From: Aatman Jain Date: Sat, 28 Nov 2026 00:08:05 +0000 Subject: [PATCH 1/6] feat(desktop-gpui): export a Studio recording as a step-by-step guide Adds Steps to the editor's Export page. It writes a folder with guide.md, guide.json and one PNG per step: a step for each click, double-click, right-click, drag and marker, with the narration spoken around it and a screenshot cropped to where it happened, the spot ringed. - cap-steps (new crate, no gpui or ffmpeg): step detection, narration, crop and ring, Markdown and JSON. - steps_export: reads a project's cursor events, markers and caption words through the timeline and the recorder's track offsets, grabs each frame from the screen track, and moves the finished guide into place. - editor_export: the Steps format, its stage, sidebar and progress, and a CAP_GPUI_AUTO_EXPORT_STEPS hook. - Strings in all seven locales. --- .github/workflows/ci.yml | 2 +- apps/desktop-gpui/Cargo.lock | 11 + apps/desktop-gpui/Cargo.toml | 3 +- apps/desktop-gpui/locales/de.toml | 19 + apps/desktop-gpui/locales/en.toml | 19 + apps/desktop-gpui/locales/es.toml | 19 + apps/desktop-gpui/locales/fr.toml | 19 + apps/desktop-gpui/locales/hi.toml | 19 + apps/desktop-gpui/locales/ja.toml | 19 + apps/desktop-gpui/locales/zh-CN.toml | 19 + apps/desktop-gpui/src/app_windows.rs | 8 + apps/desktop-gpui/src/editor_export.rs | 520 ++++++++- .../src/editor_export/steps_tests.rs | 131 +++ .../src/i18n/editor_shell_surface_tests.rs | 38 + apps/desktop-gpui/src/main.rs | 1 + apps/desktop-gpui/src/steps_export.rs | 494 +++++++++ apps/desktop-gpui/src/steps_export/tests.rs | 542 ++++++++++ apps/desktop-gpui/steps/Cargo.toml | 12 + apps/desktop-gpui/steps/src/detect.rs | 182 ++++ apps/desktop-gpui/steps/src/document.rs | 191 ++++ apps/desktop-gpui/steps/src/frame.rs | 223 ++++ apps/desktop-gpui/steps/src/lib.rs | 98 ++ apps/desktop-gpui/steps/src/narration.rs | 82 ++ .../click_position_uses_latest_move.json | 25 + .../steps/tests/scenarios/double_click.json | 20 + .../steps/tests/scenarios/drag.json | 21 + .../scenarios/intro_before_first_step.json | 32 + .../scenarios/long_press_is_a_click.json | 15 + .../tests/scenarios/marker_headings.json | 35 + .../marker_without_clicks_is_a_note.json | 30 + .../narration_announce_then_act.json | 40 + .../narration_pause_splits_sentences.json | 36 + .../narration_prefers_the_coming_step.json | 32 + .../steps/tests/scenarios/no_events.json | 9 + .../scenarios/press_without_release.json | 20 + .../tests/scenarios/repeated_clicks.json | 37 + .../steps/tests/scenarios/right_click.json | 25 + .../steps/tests/scenarios/single_click.json | 16 + .../tests/scenarios/stop_click_dropped.json | 20 + .../steps/tests/scenarios/two_spots_fast.json | 25 + .../scenarios/unlabeled_marker_note.json | 13 + apps/desktop-gpui/steps/tests/spec.rs | 995 ++++++++++++++++++ 42 files changed, 4099 insertions(+), 18 deletions(-) create mode 100644 apps/desktop-gpui/src/editor_export/steps_tests.rs create mode 100644 apps/desktop-gpui/src/steps_export.rs create mode 100644 apps/desktop-gpui/src/steps_export/tests.rs create mode 100644 apps/desktop-gpui/steps/Cargo.toml create mode 100644 apps/desktop-gpui/steps/src/detect.rs create mode 100644 apps/desktop-gpui/steps/src/document.rs create mode 100644 apps/desktop-gpui/steps/src/frame.rs create mode 100644 apps/desktop-gpui/steps/src/lib.rs create mode 100644 apps/desktop-gpui/steps/src/narration.rs create mode 100644 apps/desktop-gpui/steps/tests/scenarios/click_position_uses_latest_move.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/double_click.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/drag.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/intro_before_first_step.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/long_press_is_a_click.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/marker_headings.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/marker_without_clicks_is_a_note.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/narration_announce_then_act.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/narration_pause_splits_sentences.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/narration_prefers_the_coming_step.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/no_events.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/press_without_release.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/repeated_clicks.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/right_click.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/single_click.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/stop_click_dropped.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/two_spots_fast.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/unlabeled_marker_note.json create mode 100644 apps/desktop-gpui/steps/tests/spec.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82a8d9ba6dd..779b05223c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -408,7 +408,7 @@ jobs: cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-gpui-kernels cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-glass cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-i18n-build - cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-notes -p cap-calendar -p cap-meetings -p cap-meeting-platform -p cap-notes-ui -p cap-diarize + cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-notes -p cap-calendar -p cap-meetings -p cap-meeting-platform -p cap-notes-ui -p cap-diarize -p cap-steps # Cap only builds gpui's crates as dependencies, so their own tests never run # in the app jobs above. Run the ones covering Cap's patches against real diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock index a4a261efef7..9ca8ae3ca99 100644 --- a/apps/desktop-gpui/Cargo.lock +++ b/apps/desktop-gpui/Cargo.lock @@ -1595,6 +1595,7 @@ dependencies = [ "cap-project", "cap-recording", "cap-rendering", + "cap-steps", "cap-timestamp", "cap-utils", "cap-verify", @@ -2120,6 +2121,16 @@ dependencies = [ "workspace-hack", ] +[[package]] +name = "cap-steps" +version = "0.1.0" +dependencies = [ + "image 0.25.10", + "serde", + "serde_json", + "tiny-skia", +] + [[package]] name = "cap-timestamp" version = "0.1.0" diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml index 95c94a185ff..437c7f15190 100644 --- a/apps/desktop-gpui/Cargo.toml +++ b/apps/desktop-gpui/Cargo.toml @@ -5,7 +5,7 @@ # gpui's tree does not want. [workspace] resolver = "2" -members = [".", "kernels", "i18n-build", "glass", "notes", "notes-ui", "calendar", "meetings", "meeting-platform", "diarize"] +members = [".", "kernels", "i18n-build", "glass", "notes", "notes-ui", "calendar", "meetings", "meeting-platform", "diarize", "steps"] [package] name = "cap-desktop-gpui" @@ -35,6 +35,7 @@ cap-calendar = { path = "calendar" } cap-diarize = { path = "diarize" } cap-notes = { path = "notes" } cap-notes-ui = { path = "notes-ui" } +cap-steps = { path = "steps" } iana-time-zone = "0.1" # gpui — the wingleeio/zed fork Comet ships. The pinned rev carries f596cde # ("destination alpha on transparent windows: Porter-Duff OVER, not additive"), diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index c7fb57662f5..b98a745f8e2 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -2728,6 +2728,25 @@ refining_size = "Größe wird präzisiert…" refining_time = "Dauer wird präzisiert…" unavailable = "Nicht verfügbar" +[editor.export.steps] +caption_click = "Klicken Sie auf die markierte Stelle." +caption_double_click = "Doppelklicken Sie auf die markierte Stelle." +caption_drag = "Ziehen Sie entlang des Pfeils." +caption_repeat = "Klicken Sie {number}-mal auf die markierte Stelle." +caption_right_click = "Klicken Sie mit der rechten Maustaste auf die markierte Stelle." +caption_step = "Schritt {number}" +count = { one = "{count} Schritt", other = "{count} Schritte" } +cta = "Schritte exportieren" +exported = "Schritte exportiert" +exporting = "Schritte werden geschrieben" +file_only = "Schritte werden als Anleitung in einem Ordner gespeichert." +finding = "Schritte werden gesucht…" +folder = "{name} Schritte" +format = "Schritte" +guide = "Ein Screenshot für jeden Klick, jedes Ziehen und jeden Marker, mit dem, was Sie dazu gesagt haben. Gespeichert als Markdown mit Bildern, dazu eine JSON-Kopie für Tools und Agenten." +more = { one = "und {count} weiterer Schritt", other = "und {count} weitere Schritte" } +none = "Diese Aufnahme enthält keine Klicks oder Marker. Klicken Sie sich durch das, was Sie zeigen, oder fügen Sie Marker hinzu: Jeder wird zu einem Schritt." + [editor.export.tracks] aligned = "Spuren folgen Ihren Schnitten und Ihrer Geschwindigkeit und passen in jedem Videoeditor zusammen. Video wird ohne Hintergrund und Effekte exportiert." audio_detail = "WAV · 48 kHz" diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index a259d731926..70a76ee4272 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -2730,6 +2730,25 @@ refining_size = "Refining size…" refining_time = "Refining time…" unavailable = "Unavailable" +[editor.export.steps] +caption_click = "Click the highlighted spot." +caption_double_click = "Double-click the highlighted spot." +caption_drag = "Drag along the arrow." +caption_repeat = { text = "Click the highlighted spot {number} times.", context = "Written into an exported guide for a step that clicks one place several times; {number} is 2 or more." } +caption_right_click = "Right-click the highlighted spot." +caption_step = { text = "Step {number}", context = "Heading of one step in an exported guide." } +count = { one = "{count} step", other = "{count} steps", context = "How many steps an exported guide has." } +cta = "Export Steps" +exported = "Steps exported" +exporting = "Writing steps" +file_only = "Steps are saved as a guide in a folder." +finding = "Finding steps…" +folder = { text = "{name} Steps", context = "Name of the folder an exported guide is saved in; {name} is the recording's name." } +format = { text = "Steps", context = "Export format: a step-by-step guide with a screenshot for each click." } +guide = "One screenshot for each click, drag and marker, with what you said around it. Saved as Markdown and images, with a JSON copy for tools and agents." +more = { one = "and {count} more step", other = "and {count} more steps", context = "Closes a list that shows only the first steps of a guide." } +none = "No clicks or markers in this recording. Click through what you are showing, or add markers, and each one becomes a step." + [editor.export.tracks] aligned = "Tracks follow your cuts and speed, so they line up in any video editor. Video comes out clean, without background or effects." audio_detail = "WAV · 48 kHz" diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index dbd580d5c7f..2fbd8719dbb 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -2728,6 +2728,25 @@ refining_size = "Ajustando tamaño…" refining_time = "Ajustando tiempo…" unavailable = "No disponible" +[editor.export.steps] +caption_click = "Haz clic en el punto resaltado." +caption_double_click = "Haz doble clic en el punto resaltado." +caption_drag = "Arrastra siguiendo la flecha." +caption_repeat = "Haz clic {number} veces en el punto resaltado." +caption_right_click = "Haz clic derecho en el punto resaltado." +caption_step = "Paso {number}" +count = { one = "{count} paso", other = "{count} pasos" } +cta = "Exportar pasos" +exported = "Pasos exportados" +exporting = "Escribiendo los pasos" +file_only = "Los pasos se guardan como una guía en una carpeta." +finding = "Buscando pasos…" +folder = "{name} Pasos" +format = "Pasos" +guide = "Una captura por cada clic, arrastre y marcador, con lo que dijiste en ese momento. Se guarda como Markdown con imágenes, y con una copia en JSON para herramientas y agentes." +more = { one = "y {count} paso más", other = "y {count} pasos más" } +none = "No hay clics ni marcadores en esta grabación. Haz clic en lo que muestras, o añade marcadores, y cada uno se convertirá en un paso." + [editor.export.tracks] aligned = "Las pistas siguen tus cortes y tu velocidad, así que encajan en cualquier editor de vídeo. El vídeo sale limpio, sin fondo ni efectos." audio_detail = "WAV · 48 kHz" diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index b71e0f82c8d..ec436815aa4 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -2728,6 +2728,25 @@ refining_size = "Affinage de la taille…" refining_time = "Affinage de la durée…" unavailable = "Indisponible" +[editor.export.steps] +caption_click = "Cliquez sur le point en surbrillance." +caption_double_click = "Double-cliquez sur le point en surbrillance." +caption_drag = "Faites glisser le long de la flèche." +caption_repeat = "Cliquez {number} fois sur le point en surbrillance." +caption_right_click = "Faites un clic droit sur le point en surbrillance." +caption_step = "Étape {number}" +count = { one = "{count} étape", other = "{count} étapes" } +cta = "Exporter les étapes" +exported = "Étapes exportées" +exporting = "Écriture des étapes" +file_only = "Les étapes sont enregistrées sous forme de guide dans un dossier." +finding = "Recherche des étapes…" +folder = "{name} Étapes" +format = "Étapes" +guide = "Une capture pour chaque clic, glissement et repère, avec ce que vous avez dit à ce moment-là. Enregistré en Markdown avec des images, et avec une copie JSON pour les outils et les agents." +more = { one = "et {count} autre étape", other = "et {count} autres étapes" } +none = "Aucun clic ni repère dans cet enregistrement. Cliquez sur ce que vous montrez, ou ajoutez des repères : chacun devient une étape." + [editor.export.tracks] aligned = "Les pistes suivent vos coupes et votre vitesse, et s'alignent dans n'importe quel logiciel de montage. La vidéo sort propre, sans arrière-plan ni effets." audio_detail = "WAV · 48 kHz" diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index c6562cae7a1..352a8c726a8 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -2728,6 +2728,25 @@ refining_size = "साइज़ सटीक किया जा रहा ह refining_time = "समय सटीक किया जा रहा है…" unavailable = "उपलब्ध नहीं" +[editor.export.steps] +caption_click = "हाइलाइट की गई जगह पर क्लिक करें।" +caption_double_click = "हाइलाइट की गई जगह पर डबल-क्लिक करें।" +caption_drag = "तीर के साथ ड्रैग करें।" +caption_repeat = "हाइलाइट की गई जगह पर {number} बार क्लिक करें।" +caption_right_click = "हाइलाइट की गई जगह पर राइट-क्लिक करें।" +caption_step = "चरण {number}" +count = { one = "{count} चरण", other = "{count} चरण" } +cta = "चरण एक्सपोर्ट करें" +exported = "चरण एक्सपोर्ट हो गए" +exporting = "चरण लिखे जा रहे हैं" +file_only = "चरण एक फ़ोल्डर में गाइड के रूप में सेव होते हैं।" +finding = "चरण खोजे जा रहे हैं…" +folder = "{name} चरण" +format = "चरण" +guide = "हर क्लिक, ड्रैग और मार्कर के लिए एक स्क्रीनशॉट, साथ में वह जो आपने उस समय कहा। Markdown और इमेज के रूप में सेव होता है, टूल और एजेंट के लिए JSON कॉपी के साथ।" +more = { one = "और {count} चरण", other = "और {count} चरण" } +none = "इस रिकॉर्डिंग में कोई क्लिक या मार्कर नहीं है। जो दिखा रहे हैं उस पर क्लिक करें, या मार्कर जोड़ें, और हर एक एक चरण बन जाएगा।" + [editor.export.tracks] aligned = "ट्रैक आपके कट और स्पीड के हिसाब से चलते हैं, इसलिए किसी भी वीडियो एडिटर में एक साथ मेल खाते हैं। वीडियो बिना बैकग्राउंड या इफ़ेक्ट के साफ़ निकलता है।" audio_detail = "WAV · 48 kHz" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index dbaf6c62104..499fd862025 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -2728,6 +2728,25 @@ refining_size = "サイズを精査中…" refining_time = "時間を精査中…" unavailable = "利用不可" +[editor.export.steps] +caption_click = "ハイライトされた箇所をクリックします。" +caption_double_click = "ハイライトされた箇所をダブルクリックします。" +caption_drag = "矢印に沿ってドラッグします。" +caption_repeat = "ハイライトされた箇所を{number}回クリックします。" +caption_right_click = "ハイライトされた箇所を右クリックします。" +caption_step = "ステップ{number}" +count = { other = "{count}ステップ" } +cta = "ステップを書き出す" +exported = "ステップを書き出しました" +exporting = "ステップを書き出し中" +file_only = "ステップはガイドとしてフォルダに保存されます。" +finding = "ステップを検出中…" +folder = "{name} ステップ" +format = "ステップ" +guide = "クリック、ドラッグ、マーカーごとにスクリーンショットを1枚、その前後に話した内容と一緒に保存します。Markdownと画像で書き出し、ツールやエージェント向けのJSONも付きます。" +more = { other = "ほか{count}ステップ" } +none = "この録画にはクリックもマーカーもありません。見せたい操作をクリックするか、マーカーを追加すると、それぞれがステップになります。" + [editor.export.tracks] aligned = "各トラックはカットや速度の変更に沿うため、どの動画編集ソフトでも揃います。映像は背景やエフェクトなしで書き出されます。" audio_detail = "WAV · 48 kHz" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 2389e04f45c..4c77429f7d7 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -2728,6 +2728,25 @@ refining_size = "正在精确估算大小…" refining_time = "正在精确估算用时…" unavailable = "不可用" +[editor.export.steps] +caption_click = "点击高亮的位置。" +caption_double_click = "双击高亮的位置。" +caption_drag = "沿箭头拖动。" +caption_repeat = "点击高亮的位置 {number} 次。" +caption_right_click = "右键点击高亮的位置。" +caption_step = "步骤 {number}" +count = { other = "{count} 个步骤" } +cta = "导出步骤" +exported = "步骤已导出" +exporting = "正在写入步骤" +file_only = "步骤会以指南的形式保存到一个文件夹中。" +finding = "正在查找步骤…" +folder = "{name} 步骤" +format = "步骤" +guide = "每次点击、拖动和标记各生成一张截图,并附上你当时说的话。保存为 Markdown 和图片,另附一份供工具和智能体使用的 JSON。" +more = { other = "还有 {count} 个步骤" } +none = "这段录制中没有点击或标记。点击你要演示的内容,或添加标记,每一个都会成为一个步骤。" + [editor.export.tracks] aligned = "各轨道会跟随你的剪辑和速度,在任何视频编辑软件中都能对齐。视频不含背景和效果。" audio_detail = "WAV · 48 kHz" diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs index 82686f87b0e..dbb43dd035f 100644 --- a/apps/desktop-gpui/src/app_windows.rs +++ b/apps/desktop-gpui/src/app_windows.rs @@ -6376,7 +6376,11 @@ async fn drive_auto_export(handle: WindowHandle, cx: &mut gpui::As if flags.contains(&"tracks") { export.use_tracks(None); } + if flags.contains(&"steps") { + export.use_steps(); + } } + view.refresh_steps(window, cx); cx.notify(); }); return; @@ -6400,6 +6404,10 @@ async fn drive_auto_export(handle: WindowHandle, cx: &mut gpui::As view.open_export(window, cx); let tracks = std::env::var("CAP_GPUI_AUTO_EXPORT_TRACKS").ok(); if let Some(export) = view.export.as_mut() + && std::env::var_os("CAP_GPUI_AUTO_EXPORT_STEPS").is_some() + { + export.use_steps(); + } else if let Some(export) = view.export.as_mut() && let Some(tracks) = tracks.as_deref() { export.use_tracks(Some(tracks)); diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs index 664ea8ce09c..324f73850f8 100644 --- a/apps/desktop-gpui/src/editor_export.rs +++ b/apps/desktop-gpui/src/editor_export.rs @@ -29,6 +29,7 @@ use gpui::{ use crate::editor_window::EditorWindow; use crate::i18n::tr; use crate::sign_in::{SignIn, SignInEvent, SignInOrigin, SignInOutcome}; +use crate::steps_export::StepsError; use crate::store::{self, ExportPrefs}; use crate::ui; use crate::{library, platform}; @@ -40,6 +41,7 @@ const STAGE_PADDING_X: f32 = 24.; /// padding: everything on the stage that is not the preview itself. const STAGE_VERTICAL_CHROME: f32 = 16. + 22. + 14. + 18. + STATS_HEIGHT + 20.; const STATS_HEIGHT: f32 = 44.; +const STEP_ROWS_SHOWN: usize = 7; const SEGMENT_HEIGHT: f32 = 26.; const COMPRESSION_PRESETS: [(ExportCompression, fn() -> &'static str); 4] = [ ( @@ -106,10 +108,11 @@ pub enum ExportFormatKind { Gif, Tracks, Audio, + Steps, } impl ExportFormatKind { - const ALL: [Self; 3] = [Self::Mp4, Self::Gif, Self::Tracks]; + const ALL: [Self; 4] = [Self::Mp4, Self::Gif, Self::Tracks, Self::Steps]; fn label(self) -> &'static str { match self { @@ -117,6 +120,7 @@ impl ExportFormatKind { Self::Gif => "GIF", Self::Tracks => tr::editor::export::tracks::format(), Self::Audio => tr::editor::export::audio::format(), + Self::Steps => tr::editor::export::steps::format(), } } @@ -138,6 +142,7 @@ impl ExportFormatKind { Self::Gif => "Gif", Self::Tracks => "Tracks", Self::Audio => "Audio", + Self::Steps => "Steps", } } @@ -146,6 +151,7 @@ impl ExportFormatKind { "Gif" => Self::Gif, "Tracks" => Self::Tracks, "Audio" => Self::Audio, + "Steps" => Self::Steps, _ => Self::Mp4, } } @@ -190,6 +196,52 @@ fn track_options( .collect() } +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct StepRow { + pub number: usize, + pub time: String, + pub text: String, + pub heading: Option, +} + +fn steps_folder_name(pretty_name: &str) -> String { + let reserved = tr::editor::export::steps::folder("").len(); + tr::editor::export::steps::folder(export_name_stem(pretty_name, reserved)) +} + +fn steps_captions() -> cap_steps::Captions { + cap_steps::Captions { + step: tr::editor::export::steps::caption_step("{number}"), + click: tr::editor::export::steps::caption_click().into(), + double_click: tr::editor::export::steps::caption_double_click().into(), + right_click: tr::editor::export::steps::caption_right_click().into(), + drag: tr::editor::export::steps::caption_drag().into(), + repeat: tr::editor::export::steps::caption_repeat("{count}"), + } +} + +fn step_rows(guide: &cap_steps::Guide, captions: &cap_steps::Captions) -> Vec { + guide + .steps + .iter() + .enumerate() + .map(|(index, step)| StepRow { + number: index + 1, + time: cap_steps::timestamp(step.time), + text: cap_steps::instruction(step, captions), + heading: step.heading.clone(), + }) + .collect() +} + +fn steps_failure(error: &StepsError) -> String { + match error { + StepsError::NoSteps => tr::editor::export::steps::none().into(), + StepsError::Cancelled => String::new(), + StepsError::Failed(error) => error.clone(), + } +} + fn track_label(kind: TrackKind) -> &'static str { match kind { TrackKind::Screen => tr::editor::export::tracks::screen(), @@ -440,6 +492,10 @@ pub struct ExportUi { /// exporting sound once does not change what the next video export /// opens with. saved_format: ExportFormatKind, + /// What the Steps format would write, for its stage. `None` until the + /// recording has been read. + pub steps: Option>, + steps_task: Option>, } /// What the project renders from: its output size before any export scaling @@ -599,6 +655,8 @@ impl ExportUi { _ => AudioExportFormat::Mp3, }, saved_format: ExportFormatKind::from_slug(&prefs.format), + steps: None, + steps_task: None, } } @@ -615,7 +673,11 @@ impl ExportUi { fn set_track_options(&mut self, options: Vec) { self.tracks = selected_tracks(&options, &self.excluded_tracks); self.track_options = options; - if self.format == ExportFormatKind::Tracks && self.track_options.is_empty() { + if matches!( + self.format, + ExportFormatKind::Tracks | ExportFormatKind::Steps + ) && self.track_options.is_empty() + { self.format = ExportFormatKind::Mp4; } } @@ -641,6 +703,14 @@ impl ExportUi { } } + /// Switches to a step-by-step guide, for the `CAP_GPUI_AUTO_EXPORT*` + /// hooks. + pub(crate) fn use_steps(&mut self) { + self.format = ExportFormatKind::Steps; + self.set_destination(ExportDestination::File); + self.cursor_only = false; + } + fn toggle_track(&mut self, kind: TrackKind) { if let Some(index) = self.tracks.iter().position(|track| *track == kind) { self.tracks.remove(index); @@ -1114,7 +1184,38 @@ impl EditorWindow { .to_vec() } + pub(crate) fn refresh_steps(&mut self, window: &mut Window, cx: &mut Context) { + let Some(ui) = self.export.as_mut() else { + return; + }; + if ui.format != ExportFormatKind::Steps || ui.steps.is_some() || ui.steps_task.is_some() { + return; + } + let project_path = self.project_path.clone(); + let project = self.project.clone(); + let captions = steps_captions(); + ui.steps_task = Some(cx.spawn_in(window, async move |this, cx| { + let rows = cx + .background_executor() + .spawn(async move { + let meta = RecordingMeta::load_for_project(&project_path).ok()?; + let guide = crate::steps_export::project_guide(&meta, &project); + Some(step_rows(&guide, &captions)) + }) + .await + .unwrap_or_default(); + let _ = this.update(cx, |this, cx| { + if let Some(ui) = this.export.as_mut() { + ui.steps = Some(rows); + ui.steps_task = None; + } + cx.notify(); + }); + })); + } + fn refresh_export_preview(&mut self, window: &mut Window, cx: &mut Context) { + self.refresh_steps(window, cx); let path = self.project_path.clone(); let time = self.preview_or_playhead(); let instance = self.instance.clone(); @@ -1284,6 +1385,10 @@ impl EditorWindow { self.start_audio_export(pretty_name, window, cx); return; } + if ui.format == ExportFormatKind::Steps { + self.start_steps_export(pretty_name, window, cx); + return; + } if ui.destination == ExportDestination::Link { let sign_in = SignIn::global(cx); if sign_in.read(cx).is_pending() { @@ -1716,6 +1821,156 @@ impl EditorWindow { })); } + fn start_steps_export( + &mut self, + pretty_name: String, + window: &mut Window, + cx: &mut Context, + ) { + let project_path = self.project_path.clone(); + let project = self.project.clone(); + let Some(ui) = self.export.as_mut() else { + return; + }; + let folder_name = steps_folder_name(&pretty_name); + let captions = steps_captions(); + ui.cancel = Arc::new(AtomicBool::new(false)); + let cancel = ui.cancel.clone(); + ui.phase = ExportPhase::ChoosingFile; + ui.error = None; + ui.rendered = 0; + ui.total_frames = 0; + ui.output_path = None; + cx.notify(); + + ui.export_task = Some(cx.spawn_in(window, async move |this, cx| { + let chosen: Result, String> = + match std::env::var_os("CAP_GPUI_AUTO_EXPORT") { + Some(path) => Ok(Some(PathBuf::from(path))), + None => { + #[cfg(target_os = "macos")] + { + platform::try_save_file_panel(&folder_name, &[]) + } + #[cfg(not(target_os = "macos"))] + { + Ok(platform::save_file_panel_async(&folder_name, &[], cx).await) + } + } + }; + let folder = match chosen { + Ok(Some(path)) => path, + Ok(None) => { + let _ = this.update_in(cx, |this, window, cx| { + if let Some(ui) = this.export.as_mut() + && Arc::ptr_eq(&ui.cancel, &cancel) + { + ui.phase = ExportPhase::Idle; + } + cx.notify(); + this.finish_requested_export_close(window, cx); + }); + return; + } + Err(error) => { + tracing::warn!( + error, + "Save dialog unavailable; keeping the steps in the project output folder" + ); + project_path.join("output").join(&folder_name) + } + }; + let started = this.update(cx, |this, cx| { + let Some(ui) = this.export.as_mut() else { + return false; + }; + if !Arc::ptr_eq(&ui.cancel, &cancel) || cancel.load(Ordering::Relaxed) { + ui.phase = ExportPhase::Idle; + cx.notify(); + return false; + } + ui.phase = ExportPhase::Starting; + cx.notify(); + true + }); + if !started.unwrap_or(false) { + let _ = this.update_in(cx, |this, window, cx| { + this.finish_requested_export_close(window, cx) + }); + return; + } + + let (progress_tx, progress_rx) = flume::unbounded::<(usize, usize)>(); + let export_cancel = cancel.clone(); + let export_folder = folder.clone(); + let started_at = std::time::Instant::now(); + let export = cx.background_executor().spawn(async move { + let meta = RecordingMeta::load_for_project(&project_path) + .map_err(|error| StepsError::Failed(error.to_string()))?; + crate::steps_export::export_steps( + &meta, + &project, + &pretty_name, + &export_folder, + &captions, + &export_cancel, + &move |done, total| { + let _ = progress_tx.send((done, total)); + }, + ) + }); + + loop { + if let Some((done, total)) = progress_rx.try_iter().last() { + let _ = this.update(cx, |this, cx| { + if let Some(ui) = this.export.as_mut() { + ui.rendered = done.min(u32::MAX as usize) as u32; + ui.total_frames = total.min(u32::MAX as usize) as u32; + ui.phase = ExportPhase::Rendering; + } + cx.notify(); + }); + } + if progress_rx.is_disconnected() { + break; + } + cx.background_executor() + .timer(Duration::from_millis(50)) + .await; + } + + let result = export.await; + let _ = this.update(cx, |this, cx| { + let Some(ui) = this.export.as_mut() else { + return; + }; + match result { + Ok(files) => { + tracing::info!( + folder = %folder.display(), + files = files.len(), + elapsed_ms = started_at.elapsed().as_millis() as u64, + "editor steps export completed" + ); + crate::app_sounds::play_notification(); + ui.phase = ExportPhase::Done; + ui.output_path = Some(folder); + } + Err(StepsError::Cancelled) => ui.phase = ExportPhase::Idle, + Err(error) => { + tracing::error!(?error, "editor steps export failed"); + ui.phase = ExportPhase::Failed; + ui.error = Some(steps_failure(&error)); + } + } + cx.notify(); + }); + let _ = this.update_in(cx, |this, window, cx| { + this.finish_requested_export_close(window, cx) + }); + })); + } + fn start_audio_export( &mut self, pretty_name: String, @@ -2472,6 +2727,8 @@ impl EditorWindow { .min_h_0() .child(if ui.format == ExportFormatKind::Tracks { self.render_tracks_stage(ui).into_any_element() + } else if ui.format == ExportFormatKind::Steps { + self.render_steps_stage(ui).into_any_element() } else if ui.format == ExportFormatKind::Audio { self.render_audio_stage(ui).into_any_element() } else { @@ -2904,13 +3161,213 @@ impl EditorWindow { ) } + fn render_steps_stage(&self, ui: &ExportUi) -> impl IntoElement { + let theme = self.theme; + let editor = theme.editor; + let duration = self.total_duration(); + let folder = steps_folder_name( + self.summary() + .map(|summary| summary.pretty_name.as_str()) + .filter(|name| !name.trim().is_empty()) + .unwrap_or("Cap Recording"), + ); + let found = ui.steps.as_deref(); + let count = found.map_or(0, <[StepRow]>::len); + + let row = |step: &StepRow| { + let text = if step.text.is_empty() { + step.heading.clone().unwrap_or_default() + } else { + step.text.clone() + }; + div() + .flex() + .flex_row() + .items_center() + .gap(px(12.)) + .h(px(34.)) + .child( + div() + .flex_none() + .w(px(26.)) + .h(px(22.)) + .rounded(px(6.)) + .bg(Hsla::from(editor.ctl)) + .flex() + .items_center() + .justify_center() + .text_size(px(11.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(editor.text_2)) + .child(step.number.to_string()), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(12.5)) + .text_color(Hsla::from(editor.text_1)) + .truncate() + .child(text), + ) + .child( + div() + .flex_none() + .text_size(px(11.)) + .text_color(Hsla::from(editor.text_3)) + .child(step.time.clone()), + ) + }; + let note = |text: String| { + div() + .py(px(10.)) + .text_size(px(12.)) + .text_color(Hsla::from(editor.text_3)) + .child(text) + }; + + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .bg(Hsla::from(editor.stage)) + .pt(px(16.)) + .px(px(STAGE_PADDING_X)) + .pb(px(20.)) + .child( + div() + .h(px(22.)) + .flex() + .flex_row() + .items_center() + .text_size(px(12.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(editor.text_2)) + .child(tr::editor::export::steps::format()), + ) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .items_center() + .justify_center() + .gap(px(12.)) + .pt(px(14.)) + .pb(px(18.)) + .child( + div() + .w_full() + .max_w(px(640.)) + .flex() + .flex_col() + .p(px(16.)) + .rounded(px(12.)) + .bg(Hsla::from(editor.card)) + .shadow(editor.card_shadow()) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(8.)) + .pb(px(8.)) + .mb(px(4.)) + .border_b_1() + .border_color(Hsla::from(editor.line)) + .child( + svg() + .path("icons/folder.svg") + .size(px(16.)) + .flex_none() + .text_color(Hsla::from(editor.text_2)), + ) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(editor.text_1)) + .truncate() + .child(folder), + ), + ) + .children( + found + .unwrap_or_default() + .iter() + .take(STEP_ROWS_SHOWN) + .map(row), + ) + .when(found.is_none(), |card| { + card.child(note(tr::editor::export::steps::finding().into())) + }) + .when(found.is_some() && count == 0, |card| { + card.child(note(tr::editor::export::steps::none().into())) + }) + .when(count > STEP_ROWS_SHOWN, |card| { + card.child(note(tr::editor::export::steps::more( + count - STEP_ROWS_SHOWN, + ))) + }), + ) + .child( + div() + .w_full() + .max_w(px(640.)) + .px(px(4.)) + .text_size(px(11.)) + .text_color(Hsla::from(editor.text_3)) + .child(tr::editor::export::steps::guide()), + ), + ) + .child( + div().flex().flex_row().justify_center().child( + div() + .h(px(STATS_HEIGHT)) + .min_w(px(420.)) + .flex() + .flex_row() + .rounded(px(10.)) + .bg(Hsla::from(editor.card)) + .shadow(editor.card_shadow()) + .child(export_stat( + &theme, + tr::editor::export::stats::duration(), + Some(format_duration(duration)), + false, + )) + .child(export_stat( + &theme, + tr::editor::export::steps::format(), + found.map(|_| tr::editor::export::steps::count(count)), + true, + )) + .child(export_stat( + &theme, + tr::editor::export::tracks::files(), + Some(if count == 0 { + tr::editor::export::stats::unavailable().into() + } else { + tr::editor::export::tracks::file_count(count + 2) + }), + true, + )), + ), + ) + } + fn render_export_sidebar(&self, ui: &ExportUi, cx: &mut Context) -> impl IntoElement { let theme = self.theme; let editor = theme.editor; let transparent = has_transparent_background(&self.project); let tracks_mode = ui.format == ExportFormatKind::Tracks; let audio_mode = ui.format == ExportFormatKind::Audio; - let link_disabled = transparent || ui.cursor_only || tracks_mode; + let steps_mode = ui.format == ExportFormatKind::Steps; + let link_disabled = transparent || ui.cursor_only || tracks_mode || steps_mode; let resolutions = self.export_resolutions(ui); let fps_options = self.export_fps_options(ui); @@ -2943,10 +3400,10 @@ impl EditorWindow { .when(tracks_mode, |this| { this.child(self.export_tracks_field(ui, cx)) }) - .when(!tracks_mode && !audio_mode, |this| { + .when(!tracks_mode && !audio_mode && !steps_mode, |this| { this.child(self.export_resolution_field(ui, &resolutions, cx)) }) - .when(!audio_mode, |this| { + .when(!audio_mode && !steps_mode, |this| { this.child(self.export_fps_field(ui, fps_options, cx)) }) .when( @@ -2957,7 +3414,7 @@ impl EditorWindow { ui.format == ExportFormatKind::Gif && !ui.cursor_only, |this| this.child(self.export_gif_quality_field(ui, cx)), ) - .when(!tracks_mode && !audio_mode, |this| { + .when(!tracks_mode && !audio_mode && !steps_mode, |this| { this.child(div().h(px(1.)).flex_none().bg(Hsla::from(editor.line))) .child(self.export_advanced(ui, cx)) }), @@ -2989,6 +3446,11 @@ impl EditorWindow { Some("icons/music.svg"), true, ), + ExportDestination::File if ui.format == ExportFormatKind::Steps => ( + tr::editor::export::steps::cta(), + Some("icons/file-text.svg"), + true, + ), ExportDestination::File => ( tr::editor::export::cta::file(), Some("icons/folder.svg"), @@ -3017,8 +3479,10 @@ impl EditorWindow { true, ), }; - let busy = - ui.phase.is_busy() || (ui.format == ExportFormatKind::Tracks && ui.tracks.is_empty()); + let busy = ui.phase.is_busy() + || (ui.format == ExportFormatKind::Tracks && ui.tracks.is_empty()) + || (ui.format == ExportFormatKind::Steps + && ui.steps.as_ref().is_none_or(|steps| steps.is_empty())); let (bg, hover_bg, text) = if primary { ( Hsla::from(editor.accent), @@ -3102,7 +3566,10 @@ impl EditorWindow { .disabled( (*dest == ExportDestination::Link && link_disabled) || (*dest == ExportDestination::Clipboard - && ui.format == ExportFormatKind::Tracks), + && matches!( + ui.format, + ExportFormatKind::Tracks | ExportFormatKind::Steps + )), ); option.icon = Some(dest.icon().into()); option @@ -3117,7 +3584,11 @@ impl EditorWindow { return; }; if let Some(ui) = this.export.as_mut() { - if ui.format == ExportFormatKind::Tracks && dest != ExportDestination::File { + if matches!( + ui.format, + ExportFormatKind::Tracks | ExportFormatKind::Steps + ) && dest != ExportDestination::File + { return; } if dest == ExportDestination::Link @@ -3145,6 +3616,8 @@ impl EditorWindow { .text_color(Hsla::from(editor.text_3)) .child(if ui.format == ExportFormatKind::Tracks { tr::editor::export::tracks::file_only() + } else if ui.format == ExportFormatKind::Steps { + tr::editor::export::steps::file_only() } else if ui.cursor_only { tr::editor::export::link_unavailable_cursor() } else { @@ -3288,6 +3761,7 @@ impl EditorWindow { ExportFormatKind::Gif => cursor_only, ExportFormatKind::Tracks => no_tracks, ExportFormatKind::Audio => false, + ExportFormatKind::Steps => no_tracks, }; self.export_section(tr::editor::export::section::format(), "icons/video.svg") .child( @@ -3989,6 +4463,9 @@ impl EditorWindow { ExportPhase::Rendering if ui.format == ExportFormatKind::Audio => { tr::editor::export::audio::exporting() } + ExportPhase::Rendering if ui.format == ExportFormatKind::Steps => { + tr::editor::export::steps::exporting() + } ExportPhase::Rendering if ui.cursor_only => { tr::editor::export::phase::rendering_cursor() } @@ -4017,6 +4494,9 @@ impl EditorWindow { ExportPhase::Done if ui.format == ExportFormatKind::Audio => { tr::editor::export::audio::exported() } + ExportPhase::Done if ui.format == ExportFormatKind::Steps => { + tr::editor::export::steps::exported() + } ExportPhase::Done => tr::editor::export::phase::complete(), ExportPhase::Failed if ui.clipboard_retry_path().is_some() => { tr::editor::export::phase::clipboard_failed() @@ -4203,11 +4683,16 @@ impl EditorWindow { ui::ButtonVariant::Gray, ui::ButtonSize::Md, ) - .label(if ui.format == ExportFormatKind::Tracks { - tr::editor::export::tracks::open_folder() - } else { - tr::editor::export::done::open_file() - }) + .label( + if matches!( + ui.format, + ExportFormatKind::Tracks | ExportFormatKind::Steps + ) { + tr::editor::export::tracks::open_folder() + } else { + tr::editor::export::done::open_file() + }, + ) .on_click(move |_, _, cx| { if let Some(path) = &path { library::open_with_system(path, cx); @@ -4518,7 +5003,7 @@ fn normalize_export_options(ui: &mut ExportUi, transparent: bool) { if ui.format == ExportFormatKind::Tracks { ui.set_destination(ExportDestination::File); } - if ui.format == ExportFormatKind::Audio { + if matches!(ui.format, ExportFormatKind::Audio | ExportFormatKind::Steps) { ui.set_destination(ExportDestination::File); ui.cursor_only = false; } @@ -4722,6 +5207,9 @@ fn export_progress( } } +#[cfg(test)] +mod steps_tests; + #[cfg(test)] mod tests { use gpui::{Render, VisualTestContext, point, size}; diff --git a/apps/desktop-gpui/src/editor_export/steps_tests.rs b/apps/desktop-gpui/src/editor_export/steps_tests.rs new file mode 100644 index 00000000000..2442499b3fd --- /dev/null +++ b/apps/desktop-gpui/src/editor_export/steps_tests.rs @@ -0,0 +1,131 @@ +use cap_steps::{Action, Captions, Guide, Point, Step}; + +use super::{ + ExportDestination, ExportFormatKind, ExportUi, normalize_export_options, step_rows, + steps_captions, steps_failure, steps_folder_name, +}; +use crate::steps_export::StepsError; +use crate::store::ExportPrefs; + +fn prefs(format: &str, export_to: &str) -> ExportPrefs { + ExportPrefs { + format: format.into(), + fps: 30, + export_to: export_to.into(), + resolution: "720p".into(), + compression: "Maximum".into(), + optimize_filesize: false, + cursor_only: true, + custom_bpp: None, + force_ffmpeg_decoder: false, + advanced_open: false, + organization_id: None, + turbo: false, + gif_quality: None, + excluded_tracks: None, + resolution_from_source: false, + fps_from_source: false, + audio_format: None, + enhance_quality: false, + link_compression: None, + link_custom_bpp: None, + } +} + +fn step(time: f64, action: Action, narration: &str, heading: Option<&str>, repeat: u32) -> Step { + Step { + time, + frame_time: time, + action, + position: (action != Action::Note).then(|| Point::new(0.5, 0.5)), + drag_to: (action == Action::Drag).then(|| Point::new(0.7, 0.7)), + repeat, + heading: heading.map(str::to_string), + narration: narration.to_string(), + } +} + +#[test] +fn steps_is_offered_for_recordings_with_a_screen() { + assert!(ExportFormatKind::options(false, false).contains(&ExportFormatKind::Steps)); + assert!(!ExportFormatKind::options(true, false).contains(&ExportFormatKind::Steps)); + assert!(!ExportFormatKind::options(true, true).contains(&ExportFormatKind::Steps)); + assert!(!ExportFormatKind::Steps.writes_video()); + assert_eq!( + ExportFormatKind::from_slug(ExportFormatKind::Steps.slug()), + ExportFormatKind::Steps + ); + assert_eq!(ExportFormatKind::Steps.label(), "Steps"); +} + +#[test] +fn steps_are_saved_to_a_folder_whatever_was_chosen_before() { + for destination in ["link", "clipboard", "file"] { + let mut ui = ExportUi::from_preferences(prefs("Steps", destination)); + assert_eq!(ui.format, ExportFormatKind::Steps); + normalize_export_options(&mut ui, false); + assert_eq!(ui.destination, ExportDestination::File, "{destination}"); + assert!(!ui.cursor_only, "{destination}"); + } +} + +#[test] +fn the_automation_hook_switches_to_steps() { + let mut ui = ExportUi::from_preferences(prefs("Mp4", "link")); + ui.use_steps(); + assert_eq!(ui.format, ExportFormatKind::Steps); + assert_eq!(ui.destination, ExportDestination::File); + assert!(!ui.cursor_only); +} + +#[test] +fn the_steps_folder_is_named_after_the_recording() { + assert_eq!(steps_folder_name("Sprint 1/2"), "Sprint 12 Steps"); + assert_eq!(steps_folder_name(" "), "Cap Recording Steps"); + let long = steps_folder_name(&"a".repeat(300)); + assert!(long.len() <= 255, "{}", long.len()); + assert!(long.ends_with(" Steps"), "{long}"); + assert!(long.starts_with("aaaa"), "{long}"); +} + +#[test] +fn the_guide_is_written_in_the_apps_own_words() { + assert_eq!(steps_captions(), Captions::default()); +} + +#[test] +fn the_stage_lists_each_step_by_what_the_reader_does() { + let guide = Guide { + intro: String::new(), + steps: vec![ + step(4.2, Action::Click, "Open the team page.", None, 1), + step(9.0, Action::Click, "", Some("Invite"), 3), + step(75.0, Action::Note, "", None, 1), + step(80.0, Action::Drag, "", None, 1), + ], + }; + let rows = step_rows(&guide, &Captions::default()); + assert_eq!(rows.len(), 4); + assert_eq!(rows[0].number, 1); + assert_eq!(rows[0].time, "0:04"); + assert_eq!(rows[0].text, "Open the team page."); + assert_eq!(rows[0].heading, None); + assert_eq!(rows[1].number, 2); + assert_eq!(rows[1].text, "Click the highlighted spot 3 times."); + assert_eq!(rows[1].heading.as_deref(), Some("Invite")); + assert_eq!(rows[2].time, "1:15"); + assert_eq!(rows[2].text, ""); + assert_eq!(rows[3].number, 4); + assert_eq!(rows[3].text, "Drag along the arrow."); +} + +#[test] +fn a_recording_without_steps_says_how_to_get_some() { + let message = steps_failure(&StepsError::NoSteps); + assert!(message.contains("click"), "{message}"); + assert!(message.contains("marker"), "{message}"); + assert_eq!( + steps_failure(&StepsError::Failed("disk full".into())), + "disk full" + ); +} 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 25c79b4f23c..8a7571e9cc2 100644 --- a/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs @@ -64,6 +64,11 @@ const FORMATTED: &[&str] = &[ "editor.export.stats.output_value", "editor.export.tracks.file_count", "editor.export.tracks.video_detail", + "editor.export.steps.caption_repeat", + "editor.export.steps.caption_step", + "editor.export.steps.count", + "editor.export.steps.folder", + "editor.export.steps.more", "editor.tabs.captions.download", "editor.tabs.captions.downloading", "editor.tabs.captions.generate_failed", @@ -1546,6 +1551,39 @@ fn editor_shell_surfaces_match_the_literals_they_replaced() { "Separate tracks are only recorded in Studio Mode.", ), (tr::editor::export::tracks::system_audio(), "System audio"), + ( + tr::editor::export::steps::caption_click(), + "Click the highlighted spot.", + ), + ( + tr::editor::export::steps::caption_double_click(), + "Double-click the highlighted spot.", + ), + ( + tr::editor::export::steps::caption_drag(), + "Drag along the arrow.", + ), + ( + tr::editor::export::steps::caption_right_click(), + "Right-click the highlighted spot.", + ), + (tr::editor::export::steps::cta(), "Export Steps"), + (tr::editor::export::steps::exported(), "Steps exported"), + (tr::editor::export::steps::exporting(), "Writing steps"), + ( + tr::editor::export::steps::file_only(), + "Steps are saved as a guide in a folder.", + ), + (tr::editor::export::steps::finding(), "Finding steps…"), + (tr::editor::export::steps::format(), "Steps"), + ( + tr::editor::export::steps::guide(), + "One screenshot for each click, drag and marker, with what you said around it. Saved as Markdown and images, with a JSON copy for tools and agents.", + ), + ( + tr::editor::export::steps::none(), + "No clicks or markers in this recording. Click through what you are showing, or add markers, and each one becomes a step.", + ), (tr::editor::canvas::shape(), "Shape"), (tr::editor::timeline::track::shape(), "Shape"), ( diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index f7bbc2c5021..58bff5c9f31 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -117,6 +117,7 @@ mod single_instance; #[cfg(debug_assertions)] mod snapshot; mod startup; +mod steps_export; mod store; mod style_presets; mod target_overlay; diff --git a/apps/desktop-gpui/src/steps_export.rs b/apps/desktop-gpui/src/steps_export.rs new file mode 100644 index 00000000000..52c99eb08f2 --- /dev/null +++ b/apps/desktop-gpui/src/steps_export.rs @@ -0,0 +1,494 @@ +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; + +use cap_project::{ + CursorEvents, ProjectConfiguration, RecordingMeta, StudioRecordingMeta, TimelineConfiguration, +}; +use cap_steps::{ + ButtonEvent, Captions, Document, DocumentStep, Marker, Point, PointerMove, Recording, Size, + Word, +}; + +pub(crate) const GUIDE_FILE: &str = "guide.md"; +pub(crate) const GUIDE_DATA_FILE: &str = "guide.json"; +pub(crate) const STEP_IMAGES_FOLDER: &str = "steps"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum StepsError { + NoSteps, + Cancelled, + Failed(String), +} + +const STOP_CLICK_WINDOW: f64 = 1.0; +const OUTSIDE_FRAME: f64 = 0.001; +const MAX_FRAME_LEAD: f64 = 1.0; + +/// One recording segment. Cursor events are on the recording's clock, the +/// timeline's source time starts at the segment's latest track start, and +/// the screen file at the screen's own start (`segment_video_timing` in +/// cap-rendering): `event_offset` and `screen_offset` are those two gaps. +struct Clip { + display: PathBuf, + cursor: CursorEvents, + event_offset: f64, + screen_offset: f64, +} + +fn clips(meta: &RecordingMeta) -> Vec { + match meta.studio_meta() { + Some(StudioRecordingMeta::MultipleSegments { inner }) => inner + .segments + .iter() + .map(|segment| { + let latest_start = segment.latest_start_time(); + Clip { + display: meta.path(&segment.display.path), + cursor: segment.cursor_events(meta), + event_offset: latest_start.unwrap_or(0.0), + screen_offset: latest_start + .zip(segment.display.start_time) + .map_or(0.0, |(latest, screen)| latest - screen), + } + }) + .collect(), + Some(StudioRecordingMeta::SingleSegment { segment }) => vec![Clip { + display: meta.path(&segment.display.path), + cursor: segment + .cursor + .as_ref() + .and_then(|cursor| CursorEvents::load_from_file(&meta.path(cursor)).ok()) + .unwrap_or_default(), + event_offset: 0.0, + screen_offset: 0.0, + }], + None => Vec::new(), + } +} + +fn media_duration(path: &Path) -> f64 { + ffmpeg::format::input(path) + .map(|input| input.duration().max(0) as f64 / f64::from(ffmpeg::ffi::AV_TIME_BASE)) + .unwrap_or(0.0) +} + +fn source_length(clip: &Clip) -> f64 { + (media_duration(&clip.display) - clip.screen_offset).max(0.0) +} + +fn pointer_at(path: &[(f64, Point)], time: f64) -> Option { + let after = path.partition_point(|(moved, _)| *moved <= time); + path.get(after.saturating_sub(1)) + .map(|(_, position)| *position) +} + +fn outside_frame(position: Point) -> bool { + let inside = -OUTSIDE_FRAME..=1.0 + OUTSIDE_FRAME; + !inside.contains(&position.x) || !inside.contains(&position.y) +} + +/// A project that was never edited has no timeline, and plays its clips +/// back to back. +enum Playback<'a> { + Edited(&'a TimelineConfiguration), + BackToBack(Vec<(f64, f64)>), +} + +impl<'a> Playback<'a> { + fn new(project: &'a ProjectConfiguration, clips: &[Clip]) -> Self { + match &project.timeline { + Some(timeline) => Self::Edited(timeline), + None => { + let mut start = 0.0; + Self::BackToBack( + clips + .iter() + .map(|clip| { + let length = source_length(clip); + let span = (start, length); + start += length; + span + }) + .collect(), + ) + } + } + } + + fn duration(&self) -> f64 { + match self { + Self::Edited(timeline) => timeline.duration(), + Self::BackToBack(spans) => spans.iter().map(|(_, length)| length).sum(), + } + } + + fn output_time(&self, clip: u32, source_time: f64) -> Option { + match self { + Self::Edited(timeline) => timeline.output_time_for_source(clip, source_time), + Self::BackToBack(spans) => spans + .get(clip as usize) + .filter(|(_, length)| (0.0..=*length).contains(&source_time)) + .map(|(start, _)| start + source_time), + } + } + + fn source(&self, output_time: f64) -> Option<(u32, f64)> { + match self { + Self::Edited(timeline) => timeline.source_for_output_time(output_time), + Self::BackToBack(spans) => spans + .iter() + .enumerate() + .rfind(|(_, (start, _))| *start <= output_time) + .map(|(index, (start, length))| (index as u32, (output_time - start).min(*length))), + } + } +} + +fn caption_words(timeline: &TimelineConfiguration) -> Vec { + let mut words = Vec::new(); + for caption in &timeline.caption_segments { + if !caption.words.is_empty() { + words.extend(caption.words.iter().map(|word| Word { + start: f64::from(word.start), + end: f64::from(word.end), + text: word.text.clone(), + })); + continue; + } + let spoken: Vec<&str> = caption.text.split_whitespace().collect(); + let each = (caption.end - caption.start) / spoken.len().max(1) as f64; + words.extend(spoken.iter().enumerate().map(|(index, text)| Word { + start: caption.start + each * index as f64, + end: caption.start + each * (index + 1) as f64, + text: (*text).to_string(), + })); + } + words +} + +#[cfg(test)] +pub(crate) fn recording_events( + meta: &RecordingMeta, + project: &ProjectConfiguration, +) -> Result { + let clips = clips(meta); + Ok(events(project, &clips, &Playback::new(project, &clips)).0) +} + +pub(crate) fn project_guide( + meta: &RecordingMeta, + project: &ProjectConfiguration, +) -> cap_steps::Guide { + let clips = clips(meta); + guide(project, &clips, &Playback::new(project, &clips)).1 +} + +/// The guide and the duration of the video it follows. The stop click is +/// already gone from the events (judged against the recording itself), so +/// the guide is built without a duration: an end the timeline trimmed would +/// otherwise cost a real click its step. +fn guide( + project: &ProjectConfiguration, + clips: &[Clip], + playback: &Playback, +) -> (f64, cap_steps::Guide) { + let (mut recording, anchors) = events(project, clips, playback); + let duration = std::mem::replace(&mut recording.duration, f64::INFINITY); + recording.moves.extend(anchors); + (duration, cap_steps::build_guide(&recording)) +} + +/// Returns the events and, for every button event, where the pointer was: +/// a click is placed from the uncut pointer path, because the pointer may +/// have reached it in footage the timeline cut. +fn events( + project: &ProjectConfiguration, + clips: &[Clip], + playback: &Playback, +) -> (Recording, Vec) { + let mut recording = Recording { + duration: playback.duration(), + ..Recording::default() + }; + let mut anchors = Vec::new(); + for (index, clip) in clips.iter().enumerate() { + let clip_index = index as u32; + let source_time = |time_ms: f64| time_ms / 1000.0 - clip.event_offset; + let mut path: Vec<(f64, Point)> = clip + .cursor + .moves + .iter() + .filter(|event| event.time_ms.is_finite() && event.x.is_finite() && event.y.is_finite()) + .map(|event| (source_time(event.time_ms), Point::new(event.x, event.y))) + .collect(); + path.sort_by(|a, b| a.0.total_cmp(&b.0)); + let last_press = if index + 1 == clips.len() { + Some(source_length(clip)) + .filter(|length| *length > 0.0) + .map_or(f64::INFINITY, |length| length - STOP_CLICK_WINDOW) + } else { + f64::INFINITY + }; + + recording + .moves + .extend(path.iter().filter_map(|&(time, position)| { + Some(PointerMove { + time: playback.output_time(clip_index, time)?, + position, + }) + })); + for event in &clip.cursor.clicks { + let time = source_time(event.time_ms); + let position = pointer_at(&path, time); + if event.down && (time > last_press || position.is_some_and(outside_frame)) { + continue; + } + let Some(time) = playback.output_time(clip_index, time) else { + continue; + }; + recording.buttons.push(ButtonEvent { + time, + button: event.cursor_num, + down: event.down, + }); + anchors.extend(position.map(|position| PointerMove { time, position })); + } + } + recording.moves.sort_by(|a, b| a.time.total_cmp(&b.time)); + recording.buttons.sort_by(|a, b| a.time.total_cmp(&b.time)); + + recording.markers = project + .markers + .iter() + .filter_map(|marker| { + Some(Marker { + time: playback.output_time(marker.recording_clip, marker.time)?, + label: marker.label.clone(), + }) + }) + .collect(); + recording.markers.sort_by(|a, b| a.time.total_cmp(&b.time)); + if let Some(timeline) = &project.timeline { + recording.words = caption_words(timeline); + } + (recording, anchors) +} + +fn settle( + shown: &mut ffmpeg::frame::Video, + next: &mut ffmpeg::frame::Video, + have_shown: &mut bool, + target: i64, +) -> bool { + let timestamp = next.timestamp().or_else(|| next.pts()); + if *have_shown && timestamp.is_some_and(|timestamp| timestamp > target) { + return true; + } + std::mem::swap(shown, next); + *have_shown = true; + timestamp.is_none_or(|timestamp| timestamp >= target) +} + +fn frame_at(path: &Path, seconds: f64) -> Result<(Size, Vec), String> { + use ffmpeg::rescale::{Rescale, TIME_BASE}; + + let mut input = ffmpeg::format::input(path).map_err(|error| error.to_string())?; + let stream = input + .streams() + .best(ffmpeg::media::Type::Video) + .ok_or("No video stream found")?; + let stream_index = stream.index(); + let time_base = stream.time_base(); + let stream_start = match stream.start_time() { + ffmpeg::ffi::AV_NOPTS_VALUE => 0, + timestamp => timestamp, + }; + let target = ((seconds.max(0.0) * 1_000_000.0) as i64) + .rescale((1, 1_000_000), time_base) + .saturating_add(stream_start); + let mut decoder = ffmpeg::codec::context::Context::from_parameters(stream.parameters()) + .map_err(|error| error.to_string())? + .decoder() + .video() + .map_err(|error| error.to_string())?; + if seconds > 0.0 { + let position = target.rescale(time_base, TIME_BASE); + input + .seek(position, ..position) + .map_err(|error| format!("Failed to seek to {seconds:.3}s: {error}"))?; + } + + let mut shown = ffmpeg::frame::Video::empty(); + let mut next = ffmpeg::frame::Video::empty(); + let mut have_shown = false; + let mut settled = false; + for (stream, packet) in input.packets() { + if stream.index() != stream_index || decoder.send_packet(&packet).is_err() { + continue; + } + while !settled && decoder.receive_frame(&mut next).is_ok() { + settled = settle(&mut shown, &mut next, &mut have_shown, target); + } + if settled { + break; + } + } + if !settled && decoder.send_eof().is_ok() { + while !settled && decoder.receive_frame(&mut next).is_ok() { + settled = settle(&mut shown, &mut next, &mut have_shown, target); + } + } + if !have_shown { + return Err(format!("No frame at {seconds:.3}s in {}", path.display())); + } + + let (width, height) = (shown.width(), shown.height()); + let mut scaler = ffmpeg::software::scaling::context::Context::get( + shown.format(), + width, + height, + ffmpeg::format::Pixel::RGBA, + width, + height, + ffmpeg::software::scaling::flag::Flags::BILINEAR, + ) + .map_err(|error| error.to_string())?; + let mut rgba = ffmpeg::frame::Video::empty(); + scaler + .run(&shown, &mut rgba) + .map_err(|error| error.to_string())?; + let stride = rgba.stride(0); + let row_bytes = width as usize * 4; + let data = rgba.data(0); + let mut pixels = Vec::with_capacity(row_bytes * height as usize); + for row in 0..height as usize { + pixels.extend_from_slice(&data[row * stride..row * stride + row_bytes]); + } + Ok((Size { width, height }, pixels)) +} + +/// Blocking. The screenshots come from the screen track itself, not the +/// styled video, so they are sharp and carry no cursor but the ring. The +/// guide is written beside `folder` and moved in only once it is whole, so +/// a cancelled or failed export leaves an earlier guide there untouched. +pub(crate) fn export_steps( + meta: &RecordingMeta, + project: &ProjectConfiguration, + title: &str, + folder: &Path, + captions: &Captions, + cancel: &AtomicBool, + progress: &(dyn Fn(usize, usize) + Send + Sync), +) -> Result, StepsError> { + let clips = clips(meta); + let playback = Playback::new(project, &clips); + let (duration, guide) = guide(project, &clips, &playback); + if guide.steps.is_empty() { + return Err(StepsError::NoSteps); + } + let name = folder + .file_name() + .ok_or_else(|| StepsError::Failed("The guide needs a folder to be saved in".into()))? + .to_string_lossy(); + let staging = folder.with_file_name(format!(".{name}.{}", crate::store::new_uuid_v4())); + let output = Output { + title, + captions, + cancel, + progress, + }; + let written = write_guide(&staging, &clips, &playback, guide, duration, &output) + .and_then(|names| publish(&staging, folder, &names).map_err(StepsError::Failed)); + let _ = std::fs::remove_dir_all(&staging); + written +} + +struct Output<'a> { + title: &'a str, + captions: &'a Captions, + cancel: &'a AtomicBool, + progress: &'a (dyn Fn(usize, usize) + Send + Sync), +} + +fn write_guide( + staging: &Path, + clips: &[Clip], + playback: &Playback, + guide: cap_steps::Guide, + duration: f64, + output: &Output, +) -> Result, StepsError> { + let cancelled = || { + if output.cancel.load(Ordering::Relaxed) { + Err(StepsError::Cancelled) + } else { + Ok(()) + } + }; + cancelled()?; + std::fs::create_dir_all(staging.join(STEP_IMAGES_FOLDER)) + .map_err(|error| StepsError::Failed(error.to_string()))?; + let total = guide.steps.len(); + let mut names = vec![GUIDE_FILE.to_string(), GUIDE_DATA_FILE.to_string()]; + let mut steps = Vec::with_capacity(total); + for (index, step) in guide.steps.into_iter().enumerate() { + cancelled()?; + let image = format!( + "{STEP_IMAGES_FOLDER}/{}", + cap_steps::image_name(index + 1, total) + ); + let pressed = playback.source(step.time); + playback + .source(step.frame_time) + .filter(|(clip, time)| { + pressed.is_none_or(|(pressed_clip, pressed_time)| { + *clip == pressed_clip && (0.0..=MAX_FRAME_LEAD).contains(&(pressed_time - time)) + }) + }) + .or(pressed) + .and_then(|(clip, time)| Some((clips.get(clip as usize)?, time))) + .ok_or_else(|| format!("Step {} is not on the timeline", index + 1)) + .and_then(|(clip, time)| frame_at(&clip.display, time + clip.screen_offset)) + .and_then(|(size, rgba)| { + cap_steps::render_step_image(&rgba, size, &step) + .ok_or_else(|| "The screen frame could not be read".to_string()) + }) + .and_then(|image| cap_steps::encode_png(&image)) + .and_then(|png| std::fs::write(staging.join(&image), png).map_err(|e| e.to_string())) + .map_err(StepsError::Failed)?; + names.push(image.clone()); + steps.push(DocumentStep { step, image }); + (output.progress)(index + 1, total); + } + cancelled()?; + + let document = Document { + title: output.title.to_string(), + duration, + intro: guide.intro, + steps, + }; + std::fs::write( + staging.join(GUIDE_FILE), + cap_steps::markdown(&document, output.captions), + ) + .and_then(|()| std::fs::write(staging.join(GUIDE_DATA_FILE), cap_steps::json(&document))) + .map_err(|error| StepsError::Failed(error.to_string()))?; + Ok(names) +} + +fn publish(staging: &Path, folder: &Path, names: &[String]) -> Result, String> { + if folder.exists() { + std::fs::create_dir_all(folder.join(STEP_IMAGES_FOLDER)).map_err(|e| e.to_string())?; + for name in names { + std::fs::rename(staging.join(name), folder.join(name)).map_err(|e| e.to_string())?; + } + } else { + std::fs::rename(staging, folder).map_err(|e| e.to_string())?; + } + Ok(names.iter().map(|name| folder.join(name)).collect()) +} + +#[cfg(test)] +mod tests; diff --git a/apps/desktop-gpui/src/steps_export/tests.rs b/apps/desktop-gpui/src/steps_export/tests.rs new file mode 100644 index 00000000000..f9050c062e3 --- /dev/null +++ b/apps/desktop-gpui/src/steps_export/tests.rs @@ -0,0 +1,542 @@ +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::AtomicBool; + +use cap_project::{ + CaptionTrackSegment, CaptionWord, ProjectConfiguration, RecordingMeta, TimelineMarker, +}; +use cap_steps::{Action, Captions, Point, Size, Step, crop_for}; +use cap_verify::fixture::{FixtureSpec, SegmentSpec, Timing, VideoTrackSpec, write_fixture}; +use serde_json::json; + +use super::{ + GUIDE_DATA_FILE, GUIDE_FILE, STEP_IMAGES_FOLDER, StepsError, export_steps, recording_events, +}; + +const FRAME: Size = Size { + width: 1280, + height: 720, +}; +const LENGTH: f64 = 8.0; +const CAP_BLUE: [u8; 3] = [0x47, 0x85, 0xFF]; + +struct Project { + _root: tempfile::TempDir, + folder: PathBuf, + meta: RecordingMeta, + config: ProjectConfiguration, +} + +/// A real studio project: an 8 s 1280x720 screen track, and a cursor file +/// with one left click per `(seconds, x, y)`, the pointer arriving 200 ms +/// before each press. +fn project(clicks: &[(f64, f64, f64)]) -> Project { + project_with(clicks, |_| {}) +} + +/// The same project, with `patch` applied to its `recording-meta.json`. +fn project_with(clicks: &[(f64, f64, f64)], patch: impl FnOnce(&mut serde_json::Value)) -> Project { + let root = tempfile::tempdir().unwrap(); + let bundle = root.path().join("steps.cap"); + let spec = FixtureSpec { + name: "Invite a teammate".into(), + segments: vec![SegmentSpec { + display: VideoTrackSpec::new( + FRAME.width, + FRAME.height, + 30, + Timing::Constant { duration: LENGTH }, + ), + camera: None, + mic: None, + system_audio: None, + }], + }; + write_fixture(&spec, &bundle).unwrap(); + + let mut moves = Vec::new(); + let mut presses = Vec::new(); + for &(seconds, x, y) in clicks { + let at = seconds * 1000.0; + moves.push(json!({ + "active_modifiers": [], "cursor_id": "0", "time_ms": at - 200.0, "x": x, "y": y + })); + for (offset, down) in [(0.0, true), (80.0, false)] { + presses.push(json!({ + "active_modifiers": [], "cursor_num": 1, "cursor_id": "0", + "time_ms": at + offset, "down": down + })); + } + } + let cursor = "content/segments/segment-0/cursor.json"; + std::fs::write( + bundle.join(cursor), + serde_json::to_vec(&json!({ "clicks": presses, "moves": moves })).unwrap(), + ) + .unwrap(); + let meta_path = bundle.join("recording-meta.json"); + let mut meta: serde_json::Value = + serde_json::from_slice(&std::fs::read(&meta_path).unwrap()).unwrap(); + meta["segments"][0]["cursor"] = cursor.into(); + patch(&mut meta); + std::fs::write(&meta_path, serde_json::to_vec_pretty(&meta).unwrap()).unwrap(); + + Project { + folder: root.path().join("guide"), + meta: RecordingMeta::load_for_project(&bundle).unwrap(), + config: ProjectConfiguration::load(&bundle).unwrap(), + _root: root, + } +} + +fn export(project: &Project) -> Result, StepsError> { + export_steps( + &project.meta, + &project.config, + "Invite a teammate", + &project.folder, + &Captions::default(), + &AtomicBool::new(false), + &|_, _| {}, + ) +} + +fn read_png(path: &Path) -> image::RgbaImage { + image::load_from_memory_with_format(&std::fs::read(path).unwrap(), image::ImageFormat::Png) + .unwrap() + .to_rgba8() +} + +fn click_step(x: f64, y: f64) -> Step { + Step { + time: 0.0, + frame_time: 0.0, + action: Action::Click, + position: Some(Point::new(x, y)), + drag_to: None, + repeat: 1, + heading: None, + narration: String::new(), + } +} + +fn caption(start: f64, end: f64, text: &str, words: &[(f32, f32, &str)]) -> CaptionTrackSegment { + CaptionTrackSegment { + id: format!("caption-{start}"), + start, + end, + text: text.into(), + words: words + .iter() + .map(|&(start, end, text)| CaptionWord { + text: text.into(), + start, + end, + }) + .collect(), + fade_duration_override: None, + linger_duration_override: None, + position_override: None, + color_override: None, + background_color_override: None, + font_size_override: None, + } +} + +#[test] +fn events_come_out_in_seconds_at_their_positions() { + let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); + let recording = recording_events(&project.meta, &project.config).unwrap(); + + assert!((recording.duration - LENGTH).abs() < 0.2, "{recording:?}"); + assert_eq!(recording.buttons.len(), 4); + assert!((recording.buttons[0].time - 2.0).abs() < 1e-6); + assert_eq!(recording.buttons[0].button, cap_steps::LEFT_BUTTON); + assert!(recording.buttons[0].down); + assert!((recording.buttons[1].time - 2.08).abs() < 1e-6); + assert!(!recording.buttons[1].down); + assert_eq!(recording.moves.len(), 2); + assert!((recording.moves[0].time - 1.8).abs() < 1e-6); + assert_eq!(recording.moves[0].position, Point::new(0.25, 0.5)); +} + +#[test] +fn events_in_cut_footage_are_dropped_and_the_rest_shift() { + let mut project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); + let timeline = project.config.timeline.as_mut().unwrap(); + timeline.segments[0].start = 3.0; + timeline.segments[0].end = 7.0; + let recording = recording_events(&project.meta, &project.config).unwrap(); + + assert!((recording.duration - 4.0).abs() < 1e-6, "{recording:?}"); + assert_eq!(recording.buttons.len(), 2, "{recording:?}"); + assert!((recording.buttons[0].time - 1.0).abs() < 1e-6); + assert_eq!(recording.moves.len(), 1); + assert!((recording.moves[0].time - 0.8).abs() < 1e-6); +} + +#[test] +fn a_faster_clip_brings_its_events_closer() { + let mut project = project(&[(4.0, 0.75, 0.25)]); + project.config.timeline.as_mut().unwrap().segments[0].timescale = 2.0; + let recording = recording_events(&project.meta, &project.config).unwrap(); + + assert!( + (recording.duration - LENGTH / 2.0).abs() < 0.2, + "{recording:?}" + ); + assert!((recording.buttons[0].time - 2.0).abs() < 1e-6); +} + +#[test] +fn markers_and_captions_are_read_in_timeline_time() { + let mut project = project(&[(4.0, 0.5, 0.5)]); + let mut marker = TimelineMarker::new(0, 3.5); + marker.label = "Setup".into(); + let mut cut = TimelineMarker::new(0, 1.0); + cut.label = "Cut away".into(); + project.config.markers = vec![cut, marker]; + let timeline = project.config.timeline.as_mut().unwrap(); + timeline.segments[0].start = 3.0; + timeline.caption_segments = vec![ + caption( + 0.2, + 0.9, + "Open the menu.", + &[(0.2, 0.4, "Open"), (0.4, 0.5, "the"), (0.5, 0.9, "menu.")], + ), + caption(2.0, 3.0, "Then save", &[]), + ]; + let recording = recording_events(&project.meta, &project.config).unwrap(); + + assert_eq!(recording.markers.len(), 1, "{recording:?}"); + assert_eq!(recording.markers[0].label, "Setup"); + assert!((recording.markers[0].time - 0.5).abs() < 1e-6); + let words: Vec<&str> = recording + .words + .iter() + .map(|word| word.text.as_str()) + .collect(); + assert_eq!(words, ["Open", "the", "menu.", "Then", "save"]); + assert!((recording.words[0].start - 0.2).abs() < 1e-4); + assert!((recording.words[2].end - 0.9).abs() < 1e-4); + assert!((recording.words[3].start - 2.0).abs() < 1e-4); + assert!((recording.words[3].end - 2.5).abs() < 1e-4); + assert!((recording.words[4].end - 3.0).abs() < 1e-4); +} + +#[test] +fn export_writes_the_guide_its_data_and_one_image_per_step() { + let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25), (6.0, 0.5, 0.9)]); + let files = export(&project).unwrap(); + + let images = project.folder.join(STEP_IMAGES_FOLDER); + assert_eq!( + files, + vec![ + project.folder.join(GUIDE_FILE), + project.folder.join(GUIDE_DATA_FILE), + images.join("step-01.png"), + images.join("step-02.png"), + images.join("step-03.png"), + ] + ); + for file in &files { + assert!(file.is_file(), "{}", file.display()); + } + + let guide = std::fs::read_to_string(project.folder.join(GUIDE_FILE)).unwrap(); + assert!(guide.starts_with("# Invite a teammate\n"), "{guide}"); + for number in 1..=3 { + assert!( + guide.contains(&format!("![Step {number}](steps/step-0{number}.png)")), + "{guide}" + ); + } + assert!(guide.contains("### Step 2 · 0:04"), "{guide}"); + + let data: serde_json::Value = + serde_json::from_slice(&std::fs::read(project.folder.join(GUIDE_DATA_FILE)).unwrap()) + .unwrap(); + assert_eq!(data["title"], "Invite a teammate"); + assert_eq!(data["steps"].as_array().unwrap().len(), 3); + assert_eq!(data["steps"][1]["action"], "click"); + assert_eq!(data["steps"][1]["image"], "steps/step-02.png"); + + let crop = crop_for(&click_step(0.25, 0.5), FRAME); + let image = read_png(&images.join("step-01.png")); + assert_eq!((image.width(), image.height()), (crop.width, crop.height)); +} + +#[test] +fn each_click_is_ringed_where_it_happened() { + let clicks = [(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]; + let project = project(&clicks); + export(&project).unwrap(); + + for (index, &(_, x, y)) in clicks.iter().enumerate() { + let image = read_png( + &project + .folder + .join(STEP_IMAGES_FOLDER) + .join(format!("step-0{}.png", index + 1)), + ); + let crop = crop_for(&click_step(x, y), FRAME); + let cx = x * f64::from(FRAME.width) - f64::from(crop.x); + let cy = y * f64::from(FRAME.height) - f64::from(crop.y); + let radius = (f64::from(crop.width) * 0.022).max(14.0); + for turn in 0..8 { + let angle = f64::from(turn) * std::f64::consts::FRAC_PI_4; + let pixel = image.get_pixel( + (cx + radius * angle.cos()).round() as u32, + (cy + radius * angle.sin()).round() as u32, + ); + assert!( + pixel.0[..3] + .iter() + .zip(CAP_BLUE) + .all(|(channel, blue)| (i32::from(*channel) - i32::from(blue)).abs() <= 24), + "step {} turn {turn}: {pixel:?}", + index + 1 + ); + } + } +} + +#[test] +fn screenshots_come_from_their_own_moments() { + let project = project(&[(2.0, 0.5, 0.5), (6.0, 0.5, 0.5)]); + export(&project).unwrap(); + let images = project.folder.join(STEP_IMAGES_FOLDER); + assert_ne!( + read_png(&images.join("step-01.png")).into_raw(), + read_png(&images.join("step-02.png")).into_raw() + ); +} + +#[test] +fn narration_and_headings_reach_the_guide() { + let mut project = project(&[(4.0, 0.5, 0.5)]); + let mut marker = TimelineMarker::new(0, 1.0); + marker.label = "Setup".into(); + project.config.markers = vec![marker]; + project.config.timeline.as_mut().unwrap().caption_segments = vec![caption( + 2.5, + 3.6, + "Open the team page.", + &[ + (2.5, 2.8, "Open"), + (2.8, 2.9, "the"), + (2.9, 3.2, "team"), + (3.2, 3.6, "page."), + ], + )]; + export(&project).unwrap(); + + let guide = std::fs::read_to_string(project.folder.join(GUIDE_FILE)).unwrap(); + assert!( + guide.contains("## Setup\n\n### Step 1 · 0:04\n\nOpen the team page.\n\n![Step 1]"), + "{guide}" + ); +} + +#[test] +fn a_recording_with_nothing_clicked_or_marked_has_no_steps() { + let project = project(&[]); + assert_eq!(export(&project), Err(StepsError::NoSteps)); + assert!(!project.folder.join(GUIDE_FILE).exists()); +} + +#[test] +fn a_cancelled_export_stops_without_a_guide() { + let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); + let result = export_steps( + &project.meta, + &project.config, + "Invite a teammate", + &project.folder, + &Captions::default(), + &AtomicBool::new(true), + &|_, _| {}, + ); + assert_eq!(result, Err(StepsError::Cancelled)); + assert!(!project.folder.join(GUIDE_FILE).exists()); +} + +#[test] +fn progress_counts_every_screenshot() { + let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25), (6.0, 0.5, 0.9)]); + let seen = Mutex::new(Vec::new()); + export_steps( + &project.meta, + &project.config, + "Invite a teammate", + &project.folder, + &Captions::default(), + &AtomicBool::new(false), + &|done, total| seen.lock().unwrap().push((done, total)), + ) + .unwrap(); + + let seen = seen.into_inner().unwrap(); + assert_eq!(seen.last(), Some(&(3, 3)), "{seen:?}"); + assert!(seen.iter().all(|&(_, total)| total == 3), "{seen:?}"); + assert!( + seen.windows(2).all(|pair| pair[0].0 <= pair[1].0), + "{seen:?}" + ); +} + +fn step_image(project: &Project, number: usize) -> Vec { + read_png( + &project + .folder + .join(STEP_IMAGES_FOLDER) + .join(format!("step-0{number}.png")), + ) + .into_raw() +} + +fn guide_data(project: &Project) -> serde_json::Value { + serde_json::from_slice(&std::fs::read(project.folder.join(GUIDE_DATA_FILE)).unwrap()).unwrap() +} + +/// Cursor events are on the recording's clock; the timeline starts at the +/// latest track start, and the screen file at the screen's own start. +#[test] +fn track_start_offsets_place_clicks_and_their_screenshots() { + let offset = project_with(&[(3.0, 0.5, 0.5)], |meta| { + meta["segments"][0]["display"]["start_time"] = 0.2.into(); + meta["segments"][0]["mic"] = + json!({ "path": "content/segments/segment-0/mic.ogg", "start_time": 0.5 }); + }); + let recording = recording_events(&offset.meta, &offset.config).unwrap(); + assert!( + (recording.buttons[0].time - 2.5).abs() < 1e-6, + "{recording:?}" + ); + assert!( + (recording.moves[0].time - 2.3).abs() < 1e-6, + "{recording:?}" + ); + export(&offset).unwrap(); + + let plain = project(&[(2.8, 0.5, 0.5)]); + export(&plain).unwrap(); + assert_eq!(step_image(&offset, 1), step_image(&plain, 1)); +} + +#[test] +fn a_click_outside_the_recorded_area_is_not_a_step() { + let project = project(&[(2.0, 1.3, 0.5), (4.0, 0.5, 0.5), (5.5, 0.4, -0.2)]); + export(&project).unwrap(); + let data = guide_data(&project); + let steps = data["steps"].as_array().unwrap(); + assert_eq!(steps.len(), 1, "{data}"); + assert!((steps[0]["time"].as_f64().unwrap() - 4.0).abs() < 1e-6); +} + +#[test] +fn a_click_after_a_cut_is_ringed_where_the_pointer_was() { + let mut project = project(&[(3.1, 0.75, 0.25)]); + project.config.timeline.as_mut().unwrap().segments[0].start = 3.0; + export(&project).unwrap(); + let data = guide_data(&project); + let position = &data["steps"][0]["position"]; + assert!( + (position["x"].as_f64().unwrap() - 0.75).abs() < 1e-6, + "{data}" + ); + assert!( + (position["y"].as_f64().unwrap() - 0.25).abs() < 1e-6, + "{data}" + ); +} + +#[test] +fn a_click_right_after_a_cut_shows_footage_from_after_the_cut() { + let mut cut = project(&[(5.02, 0.5, 0.5)]); + let timeline = cut.config.timeline.as_mut().unwrap(); + let mut second = timeline.segments[0].clone(); + timeline.segments[0].end = 2.0; + second.start = 5.0; + timeline.segments.push(second); + export(&cut).unwrap(); + + let whole = project(&[(5.06, 0.5, 0.5)]); + export(&whole).unwrap(); + assert_eq!(step_image(&cut, 1), step_image(&whole, 1)); +} + +#[test] +fn the_stop_click_is_judged_by_the_recording_not_the_trimmed_timeline() { + let mut trimmed = project(&[(4.5, 0.5, 0.5)]); + trimmed.config.timeline.as_mut().unwrap().segments[0].end = 5.0; + export(&trimmed).unwrap(); + assert_eq!(guide_data(&trimmed)["steps"].as_array().unwrap().len(), 1); + + let stopped = project(&[(7.5, 0.5, 0.5)]); + assert_eq!(export(&stopped), Err(StepsError::NoSteps)); +} + +#[test] +fn a_cancelled_re_export_leaves_the_earlier_guide_as_it_was() { + let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25), (6.0, 0.5, 0.9)]); + let files = export(&project).unwrap(); + let before: Vec> = files + .iter() + .map(|file| std::fs::read(file).unwrap()) + .collect(); + let listing = |folder: &Path| { + let mut names: Vec<_> = std::fs::read_dir(folder) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + names.sort(); + names + }; + let beside = listing(project.folder.parent().unwrap()); + let inside = listing(&project.folder.join(STEP_IMAGES_FOLDER)); + + let cancel = AtomicBool::new(false); + let result = export_steps( + &project.meta, + &project.config, + "A different title", + &project.folder, + &Captions::default(), + &cancel, + &|done, _| { + if done == 1 { + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + } + }, + ); + assert_eq!(result, Err(StepsError::Cancelled)); + for (file, bytes) in files.iter().zip(&before) { + assert_eq!(&std::fs::read(file).unwrap(), bytes, "{}", file.display()); + } + assert_eq!(listing(project.folder.parent().unwrap()), beside); + assert_eq!(listing(&project.folder.join(STEP_IMAGES_FOLDER)), inside); +} + +#[test] +fn cancelling_during_the_last_screenshot_still_cancels() { + let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); + let cancel = AtomicBool::new(false); + let result = export_steps( + &project.meta, + &project.config, + "Invite a teammate", + &project.folder, + &Captions::default(), + &cancel, + &|done, total| { + if done == total { + cancel.store(true, std::sync::atomic::Ordering::Relaxed); + } + }, + ); + assert_eq!(result, Err(StepsError::Cancelled)); + assert!(!project.folder.join(GUIDE_FILE).exists()); +} diff --git a/apps/desktop-gpui/steps/Cargo.toml b/apps/desktop-gpui/steps/Cargo.toml new file mode 100644 index 00000000000..d6c47ada5e4 --- /dev/null +++ b/apps/desktop-gpui/steps/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "cap-steps" +version = "0.1.0" +edition = "2024" +license = "AGPL-3.0" +publish = false + +[dependencies] +image = { version = "0.25.1", default-features = false, features = ["png"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tiny-skia = "0.11" diff --git a/apps/desktop-gpui/steps/src/detect.rs b/apps/desktop-gpui/steps/src/detect.rs new file mode 100644 index 00000000000..25f5038cec4 --- /dev/null +++ b/apps/desktop-gpui/steps/src/detect.rs @@ -0,0 +1,182 @@ +use std::collections::HashMap; + +use crate::{ + Action, ButtonEvent, Guide, LEFT_BUTTON, Marker, Point, PointerMove, RIGHT_BUTTON, Recording, + Step, +}; + +const FRAME_LEAD: f64 = 0.05; +const SAME_SPOT: f64 = 0.02; +const DOUBLE_CLICK_GAP: f64 = 0.5; +const REPEAT_GAP: f64 = 1.0; +const STOP_CLICK_WINDOW: f64 = 1.0; +const DRAG_TRAVEL: f64 = 0.03; + +struct Press { + time: f64, + button: u8, + position: Option, + drag_to: Option, +} + +pub fn build_guide(recording: &Recording) -> Guide { + let moves = pointer_path(&recording.moves); + let mut presses = presses(&recording.buttons, &moves); + if recording.duration.is_finite() && recording.duration > 0.0 { + presses.retain(|press| press.time <= recording.duration - STOP_CLICK_WINDOW); + } + let steps = with_markers(pointer_steps(&presses), &recording.markers); + crate::narration::attach(recording, steps) +} + +fn with_markers(mut steps: Vec, markers: &[Marker]) -> Vec { + let mut markers: Vec<&Marker> = markers + .iter() + .filter(|marker| marker.time.is_finite()) + .collect(); + markers.sort_by(|a, b| a.time.total_cmp(&b.time)); + + let mut notes = Vec::new(); + for (index, marker) in markers.iter().enumerate() { + let until = markers + .get(index + 1) + .map_or(f64::INFINITY, |next| next.time); + let label = marker.label.trim(); + let heading = (!label.is_empty()).then(|| label.to_string()); + match steps + .iter_mut() + .find(|step| step.time >= marker.time && step.time < until) + { + Some(step) => step.heading = heading, + None => notes.push(Step { + time: marker.time, + frame_time: marker.time.max(0.0), + action: Action::Note, + position: None, + drag_to: None, + repeat: 1, + heading, + narration: String::new(), + }), + } + } + steps.extend(notes); + steps.sort_by(|a, b| a.time.total_cmp(&b.time)); + steps +} + +fn same_spot(a: Option, b: Option) -> bool { + match (a, b) { + (Some(a), Some(b)) => a.distance(b) <= SAME_SPOT, + (None, None) => true, + _ => false, + } +} + +fn pointer_steps(presses: &[Press]) -> Vec { + let mut steps = Vec::new(); + let mut index = 0; + while let Some(first) = presses.get(index) { + let mut count = 1; + let mut previous = first.time; + while let Some(next) = presses.get(index + count) { + let continues = next.button == first.button + && first.drag_to.is_none() + && next.drag_to.is_none() + && next.time - previous <= REPEAT_GAP + && same_spot(first.position, next.position); + if !continues { + break; + } + previous = next.time; + count += 1; + } + let double = + count == 2 && first.button == LEFT_BUTTON && previous - first.time <= DOUBLE_CLICK_GAP; + steps.push(Step { + time: first.time, + frame_time: (first.time - FRAME_LEAD).max(0.0), + action: if first.drag_to.is_some() { + Action::Drag + } else if double { + Action::DoubleClick + } else if first.button == RIGHT_BUTTON { + Action::RightClick + } else { + Action::Click + }, + position: first.position, + drag_to: first.drag_to, + repeat: if double { 1 } else { count as u32 }, + heading: None, + narration: String::new(), + }); + index += count; + } + steps +} + +fn pointer_path(moves: &[PointerMove]) -> Vec { + let mut path: Vec = moves + .iter() + .filter(|event| { + event.time.is_finite() && event.position.x.is_finite() && event.position.y.is_finite() + }) + .map(|event| PointerMove { + time: event.time, + position: Point::new( + event.position.x.clamp(0.0, 1.0), + event.position.y.clamp(0.0, 1.0), + ), + }) + .collect(); + path.sort_by(|a, b| a.time.total_cmp(&b.time)); + path +} + +fn position_at(path: &[PointerMove], time: f64) -> Option { + let after = path.partition_point(|event| event.time <= time); + path.get(after.saturating_sub(1)) + .map(|event| event.position) +} + +fn presses(buttons: &[ButtonEvent], path: &[PointerMove]) -> Vec { + let mut events: Vec<&ButtonEvent> = buttons + .iter() + .filter(|event| event.time.is_finite()) + .collect(); + events.sort_by(|a, b| a.time.total_cmp(&b.time)); + + let mut found: Vec = Vec::new(); + let mut held: HashMap = HashMap::new(); + for event in events { + if event.down { + held.insert(event.button, found.len()); + found.push(Press { + time: event.time, + button: event.button, + position: position_at(path, event.time), + drag_to: None, + }); + } else if let Some(index) = held.remove(&event.button) { + let press = &mut found[index]; + if travelled(path, press, event.time) > DRAG_TRAVEL { + press.drag_to = position_at(path, event.time); + } + } + } + found +} + +fn travelled(path: &[PointerMove], press: &Press, released: f64) -> f64 { + let Some(start) = press.position else { + return 0.0; + }; + let from = path.partition_point(|event| event.time < press.time); + let to = path.partition_point(|event| event.time <= released); + path.get(from..to) + .unwrap_or_default() + .iter() + .map(|event| event.position.distance(start)) + .fold(0.0, f64::max) +} diff --git a/apps/desktop-gpui/steps/src/document.rs b/apps/desktop-gpui/steps/src/document.rs new file mode 100644 index 00000000000..c37337f6080 --- /dev/null +++ b/apps/desktop-gpui/steps/src/document.rs @@ -0,0 +1,191 @@ +use serde::Serialize; + +use crate::{Action, Point, Step}; + +#[derive(Clone, Debug, PartialEq)] +pub struct DocumentStep { + pub step: Step, + pub image: String, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Document { + pub title: String, + pub duration: f64, + pub intro: String, + pub steps: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Captions { + pub step: String, + pub click: String, + pub double_click: String, + pub right_click: String, + pub drag: String, + pub repeat: String, +} + +impl Default for Captions { + fn default() -> Self { + Self { + step: "Step {number}".into(), + click: "Click the highlighted spot.".into(), + double_click: "Double-click the highlighted spot.".into(), + right_click: "Right-click the highlighted spot.".into(), + drag: "Drag along the arrow.".into(), + repeat: "Click the highlighted spot {count} times.".into(), + } + } +} + +pub fn image_name(index: usize, total: usize) -> String { + let digits = total.max(index).to_string().len().max(2); + format!("step-{index:0digits$}.png") +} + +pub fn timestamp(seconds: f64) -> String { + let total = if seconds.is_finite() && seconds > 0.0 { + seconds as u64 + } else { + 0 + }; + let (hours, minutes, seconds) = (total / 3600, total / 60 % 60, total % 60); + if hours > 0 { + format!("{hours}:{minutes:02}:{seconds:02}") + } else { + format!("{minutes}:{seconds:02}") + } +} + +/// Narration is speech, not Markdown: anything in it that Markdown would +/// read as formatting is kept as the character it is. +fn escape(text: &str) -> String { + let numbered = text + .find(|character: char| !character.is_ascii_digit()) + .filter(|end| *end > 0 && text[*end..].starts_with(['.', ')'])); + let mut escaped = String::with_capacity(text.len()); + for (index, character) in text.char_indices() { + let special = matches!( + character, + '\\' | '`' | '*' | '_' | '[' | ']' | '<' | '>' | '&' | '~' + ) || (index == 0 && matches!(character, '#' | '-' | '+')) + || numbered == Some(index); + if special { + escaped.push('\\'); + } + escaped.push(if character.is_control() { + ' ' + } else { + character + }); + } + escaped +} + +fn action_caption(step: &Step, captions: &Captions) -> Option { + match step.action { + Action::Click if step.repeat > 1 => { + Some(captions.repeat.replace("{count}", &step.repeat.to_string())) + } + Action::Click => Some(captions.click.clone()), + Action::DoubleClick => Some(captions.double_click.clone()), + Action::RightClick => Some(captions.right_click.clone()), + Action::Drag => Some(captions.drag.clone()), + Action::Note => None, + } +} + +pub fn instruction(step: &Step, captions: &Captions) -> String { + let narration = step.narration.trim(); + if narration.is_empty() { + action_caption(step, captions).unwrap_or_default() + } else { + narration.to_string() + } +} + +pub fn markdown(document: &Document, captions: &Captions) -> String { + let mut blocks = vec![format!("# {}", escape(document.title.trim()))]; + let intro = document.intro.trim(); + if !intro.is_empty() { + blocks.push(escape(intro)); + } + for (index, entry) in document.steps.iter().enumerate() { + let step = &entry.step; + if let Some(heading) = step + .heading + .as_deref() + .map(str::trim) + .filter(|heading| !heading.is_empty()) + { + blocks.push(format!("## {}", escape(heading))); + } + let label = captions.step.replace("{number}", &(index + 1).to_string()); + blocks.push(format!("### {label} · {}", timestamp(step.time))); + let narration = step.narration.trim(); + let action = action_caption(step, captions); + if narration.is_empty() { + blocks.extend(action); + } else { + blocks.push(escape(narration)); + if step.action != Action::Click || step.repeat > 1 { + blocks.extend(action.map(|action| format!("_{action}_"))); + } + } + blocks.push(format!("![{label}]({})", entry.image)); + } + let mut text = blocks.join("\n\n"); + text.push('\n'); + text +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct GuideData<'a> { + title: &'a str, + duration: f64, + intro: &'a str, + steps: Vec>, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct StepData<'a> { + index: usize, + time: f64, + action: Action, + position: Option, + drag_to: Option, + repeat: u32, + heading: Option<&'a str>, + narration: &'a str, + image: &'a str, +} + +pub fn json(document: &Document) -> String { + let data = GuideData { + title: &document.title, + duration: document.duration, + intro: &document.intro, + steps: document + .steps + .iter() + .enumerate() + .map(|(index, entry)| StepData { + index: index + 1, + time: entry.step.time, + action: entry.step.action, + position: entry.step.position, + drag_to: entry.step.drag_to, + repeat: entry.step.repeat, + heading: entry.step.heading.as_deref(), + narration: &entry.step.narration, + image: &entry.image, + }) + .collect(), + }; + let mut text = serde_json::to_string_pretty(&data).unwrap_or_default(); + text.push('\n'); + text +} diff --git a/apps/desktop-gpui/steps/src/frame.rs b/apps/desktop-gpui/steps/src/frame.rs new file mode 100644 index 00000000000..bb0a498a0e5 --- /dev/null +++ b/apps/desktop-gpui/steps/src/frame.rs @@ -0,0 +1,223 @@ +use tiny_skia::{FillRule, Paint, PathBuilder, PixmapMut, Stroke, Transform}; + +use crate::{Point, Step}; + +const CROP_SHARE: f64 = 0.5; +const MIN_CROP_WIDTH: u32 = 960; +const CROP_ASPECT: f64 = 16.0 / 10.0; +const DRAG_MARGIN: f64 = 0.08; +const RING_SHARE: f64 = 0.022; +const MIN_RING_RADIUS: f64 = 14.0; +const HIGHLIGHT: [u8; 3] = [0x47, 0x85, 0xFF]; +const HIGHLIGHT_FILL_ALPHA: u8 = 46; +const HALO_ALPHA: u8 = 230; +const HALO_WIDTH: f32 = 1.5; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Size { + pub width: u32, + pub height: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Rect { + pub x: u32, + pub y: u32, + pub width: u32, + pub height: u32, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StepImage { + pub size: Size, + pub rgba: Vec, +} + +fn even_down(value: u32) -> u32 { + value & !1 +} + +fn even_up(value: u32) -> u32 { + value.saturating_add(1) & !1 +} + +pub fn crop_for(step: &Step, frame: Size) -> Rect { + let whole = Rect { + x: 0, + y: 0, + width: frame.width, + height: frame.height, + }; + let Some(from) = step.position else { + return whole; + }; + if frame.width < 2 || frame.height < 2 { + return whole; + } + let to = step.drag_to.unwrap_or(from); + let (frame_width, frame_height) = (f64::from(frame.width), f64::from(frame.height)); + let room = 1.0 - 2.0 * DRAG_MARGIN; + let needed_width = ((from.x - to.x).abs() * frame_width / room).ceil(); + let needed_height = ((from.y - to.y).abs() * frame_height / room).ceil(); + + let standard = ((frame_width * CROP_SHARE).round() as u32).max(MIN_CROP_WIDTH.min(frame.width)); + let width = even_up( + standard + .max(needed_width as u32) + .max((needed_height * CROP_ASPECT).ceil() as u32), + ) + .min(even_down(frame.width)); + let tall_enough = + even_down((f64::from(width) / CROP_ASPECT) as u32).max(even_up(needed_height as u32)); + let height = tall_enough.min(even_down(frame.height)); + + let centre_x = (from.x + to.x) / 2.0 * frame_width; + let centre_y = (from.y + to.y) / 2.0 * frame_height; + let place = |centre: f64, length: u32, limit: u32| { + ((centre - f64::from(length) / 2.0).round().max(0.0) as u32).min(limit - length) + }; + Rect { + x: place(centre_x, width, frame.width), + y: place(centre_y, height, frame.height), + width, + height, + } +} + +/// `None` when the buffer is not a whole RGBA frame of that size. +pub fn render_step_image(frame_rgba: &[u8], frame: Size, step: &Step) -> Option { + let row_bytes = (frame.width as usize).checked_mul(4)?; + let expected = row_bytes.checked_mul(frame.height as usize)?; + if expected == 0 || frame_rgba.len() != expected { + return None; + } + let crop = crop_for(step, frame); + let mut rgba = Vec::with_capacity(crop.width as usize * crop.height as usize * 4); + for row in crop.y..crop.y + crop.height { + let start = row as usize * row_bytes + crop.x as usize * 4; + rgba.extend_from_slice(&frame_rgba[start..start + crop.width as usize * 4]); + } + let mut image = StepImage { + size: Size { + width: crop.width, + height: crop.height, + }, + rgba, + }; + if let Some(position) = step.position { + let in_crop = |point: Point| { + ( + (point.x * f64::from(frame.width) - f64::from(crop.x)) as f32, + (point.y * f64::from(frame.height) - f64::from(crop.y)) as f32, + ) + }; + highlight(&mut image, in_crop(position), step.drag_to.map(in_crop)); + } + Some(image) +} + +fn paint(alpha: u8, colour: [u8; 3]) -> Paint<'static> { + let mut paint = Paint::default(); + paint.set_color_rgba8(colour[0], colour[1], colour[2], alpha); + paint.anti_alias = true; + paint +} + +/// A ring that leaves what is inside it readable, with a pale edge so it +/// still shows on a blue interface. +fn highlight(image: &mut StepImage, centre: (f32, f32), drag_to: Option<(f32, f32)>) { + let radius = (f64::from(image.size.width) * RING_SHARE).max(MIN_RING_RADIUS) as f32; + let width = (radius * 0.25).max(4.0); + let Some(mut pixmap) = + PixmapMut::from_bytes(&mut image.rgba, image.size.width, image.size.height) + else { + return; + }; + let Some(ring) = PathBuilder::from_circle(centre.0, centre.1, radius) else { + return; + }; + let identity = Transform::identity(); + if let Some(to) = drag_to { + arrow(&mut pixmap, centre, to, radius, width); + } + pixmap.fill_path( + &ring, + &paint(HIGHLIGHT_FILL_ALPHA, HIGHLIGHT), + FillRule::Winding, + identity, + None, + ); + if let Some(edge) = + PathBuilder::from_circle(centre.0, centre.1, radius + width / 2.0 + HALO_WIDTH / 2.0) + { + let stroke = Stroke { + width: HALO_WIDTH, + ..Stroke::default() + }; + pixmap.stroke_path(&edge, &paint(HALO_ALPHA, [255; 3]), &stroke, identity, None); + } + let stroke = Stroke { + width, + ..Stroke::default() + }; + pixmap.stroke_path(&ring, &paint(255, HIGHLIGHT), &stroke, identity, None); +} + +fn arrow(pixmap: &mut PixmapMut, from: (f32, f32), to: (f32, f32), radius: f32, width: f32) { + let (dx, dy) = (to.0 - from.0, to.1 - from.1); + let length = dx.hypot(dy); + let head = width * 3.5; + if length <= radius + head { + return; + } + let (ux, uy) = (dx / length, dy / length); + let neck = (to.0 - ux * head, to.1 - uy * head); + let half = head * 0.6; + + let mut shaft = PathBuilder::new(); + shaft.move_to(from.0 + ux * radius, from.1 + uy * radius); + shaft.line_to(neck.0, neck.1); + let mut tip = PathBuilder::new(); + tip.move_to(to.0, to.1); + tip.line_to(neck.0 - uy * half, neck.1 + ux * half); + tip.line_to(neck.0 + uy * half, neck.1 - ux * half); + tip.close(); + let (Some(shaft), Some(tip)) = (shaft.finish(), tip.finish()) else { + return; + }; + + let identity = Transform::identity(); + let pale = paint(HALO_ALPHA, [255; 3]); + let blue = paint(255, HIGHLIGHT); + let edge = Stroke { + width: width + HALO_WIDTH * 2.0, + ..Stroke::default() + }; + pixmap.stroke_path(&shaft, &pale, &edge, identity, None); + let edge = Stroke { + width: HALO_WIDTH * 2.0, + ..Stroke::default() + }; + pixmap.stroke_path(&tip, &pale, &edge, identity, None); + let line = Stroke { + width, + ..Stroke::default() + }; + pixmap.stroke_path(&shaft, &blue, &line, identity, None); + pixmap.fill_path(&tip, &blue, FillRule::Winding, identity, None); +} + +pub fn encode_png(image: &StepImage) -> Result, String> { + use ::image::ImageEncoder; + + let mut png = Vec::new(); + ::image::codecs::png::PngEncoder::new(&mut png) + .write_image( + &image.rgba, + image.size.width, + image.size.height, + ::image::ExtendedColorType::Rgba8, + ) + .map_err(|error| error.to_string())?; + Ok(png) +} diff --git a/apps/desktop-gpui/steps/src/lib.rs b/apps/desktop-gpui/steps/src/lib.rs new file mode 100644 index 00000000000..10da0b77eb8 --- /dev/null +++ b/apps/desktop-gpui/steps/src/lib.rs @@ -0,0 +1,98 @@ +//! Everything here is in output time, the seconds a viewer sees, and in +//! positions normalised to the recorded frame. Reading a project and decoding +//! its frames is the app's side. + +mod detect; +mod document; +mod frame; +mod narration; + +use serde::{Deserialize, Serialize}; + +pub use detect::build_guide; +pub use document::{ + Captions, Document, DocumentStep, image_name, instruction, json, markdown, timestamp, +}; +pub use frame::{Rect, Size, StepImage, crop_for, encode_png, render_step_image}; + +pub const LEFT_BUTTON: u8 = 1; +pub const RIGHT_BUTTON: u8 = 2; + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Point { + pub x: f64, + pub y: f64, +} + +impl Point { + pub fn new(x: f64, y: f64) -> Self { + Self { x, y } + } + + pub fn distance(self, other: Self) -> f64 { + (self.x - other.x).hypot(self.y - other.y) + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PointerMove { + pub time: f64, + pub position: Point, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ButtonEvent { + pub time: f64, + pub button: u8, + pub down: bool, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Marker { + pub time: f64, + pub label: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Word { + pub start: f64, + pub end: f64, + pub text: String, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Recording { + pub duration: f64, + pub moves: Vec, + pub buttons: Vec, + pub markers: Vec, + pub words: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum Action { + Click, + DoubleClick, + RightClick, + Drag, + Note, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Step { + pub time: f64, + pub frame_time: f64, + pub action: Action, + pub position: Option, + pub drag_to: Option, + pub repeat: u32, + pub heading: Option, + pub narration: String, +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Guide { + pub intro: String, + pub steps: Vec, +} diff --git a/apps/desktop-gpui/steps/src/narration.rs b/apps/desktop-gpui/steps/src/narration.rs new file mode 100644 index 00000000000..1ee75ee6127 --- /dev/null +++ b/apps/desktop-gpui/steps/src/narration.rs @@ -0,0 +1,82 @@ +use crate::{Guide, Recording, Step, Word}; + +const SENTENCE_PAUSE: f64 = 1.0; +const EARLIER_STEP_WEIGHT: f64 = 1.5; +const INTRO_LEAD: f64 = 4.0; + +struct Sentence { + start: f64, + end: f64, + text: String, +} + +/// People mostly announce what they are about to do, so a step that has +/// already happened counts as further away than one still to come. +pub(crate) fn attach(recording: &Recording, mut steps: Vec) -> Guide { + let first_step = steps.first().map(|step| step.time); + let mut intro: Vec = Vec::new(); + for sentence in sentences(&recording.words) { + let introduces = first_step.is_none_or(|first| sentence.end < first - INTRO_LEAD); + match nearest(&steps, &sentence) { + Some(index) if !introduces => { + let narration = &mut steps[index].narration; + if !narration.is_empty() { + narration.push(' '); + } + narration.push_str(&sentence.text); + } + _ => intro.push(sentence.text), + } + } + Guide { + intro: intro.join(" "), + steps, + } +} + +fn sentences(words: &[Word]) -> Vec { + let mut words: Vec<&Word> = words + .iter() + .filter(|word| { + word.start.is_finite() && word.end.is_finite() && !word.text.trim().is_empty() + }) + .collect(); + words.sort_by(|a, b| a.start.total_cmp(&b.start)); + + let mut found: Vec = Vec::new(); + let mut open = false; + for word in words { + let text = word.text.trim(); + match found.last_mut() { + Some(sentence) if open && word.start - sentence.end <= SENTENCE_PAUSE => { + sentence.text.push(' '); + sentence.text.push_str(text); + sentence.end = sentence.end.max(word.end); + } + _ => found.push(Sentence { + start: word.start, + end: word.end.max(word.start), + text: text.to_string(), + }), + } + open = !text.ends_with(['.', '!', '?']); + } + found +} + +fn nearest(steps: &[Step], sentence: &Sentence) -> Option { + let mut best: Option<(usize, f64)> = None; + for (index, step) in steps.iter().enumerate() { + let distance = if step.time > sentence.end { + step.time - sentence.end + } else if step.time < sentence.start { + (sentence.start - step.time) * EARLIER_STEP_WEIGHT + } else { + 0.0 + }; + if best.is_none_or(|(_, closest)| distance <= closest) { + best = Some((index, distance)); + } + } + best.map(|(index, _)| index) +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/click_position_uses_latest_move.json b/apps/desktop-gpui/steps/tests/scenarios/click_position_uses_latest_move.json new file mode 100644 index 00000000000..2625b086023 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/click_position_uses_latest_move.json @@ -0,0 +1,25 @@ +{ + "about": "A click is where the pointer last was, or where it first appears when it had not moved yet.", + "duration": 10, + "moves": [[1.0, 0.1, 0.1], [2.0, 0.5, 0.5], [2.5, 0.9, 0.9]], + "buttons": [ + [0.5, 1, true], + [0.58, 1, false], + [2.2, 1, true], + [2.28, 1, false] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 0.5, + "at": [0.1, 0.1] + }, + { + "action": "click", + "time": 2.2, + "at": [0.5, 0.5] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/double_click.json b/apps/desktop-gpui/steps/tests/scenarios/double_click.json new file mode 100644 index 00000000000..e5dcb5ad302 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/double_click.json @@ -0,0 +1,20 @@ +{ + "about": "Two quick clicks on one spot are a double-click, not two steps.", + "duration": 10, + "moves": [[1.0, 0.3, 0.3], [2.9, 0.4, 0.55]], + "buttons": [ + [3.0, 1, true], + [3.08, 1, false], + [3.25, 1, true], + [3.33, 1, false] + ], + "expect": { + "steps": [ + { + "action": "doubleClick", + "time": 3.0, + "at": [0.4, 0.55] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/drag.json b/apps/desktop-gpui/steps/tests/scenarios/drag.json new file mode 100644 index 00000000000..ec8c25295e2 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/drag.json @@ -0,0 +1,21 @@ +{ + "about": "Pressing, moving and releasing is a drag from where it started to where it ended.", + "duration": 15, + "moves": [ + [5.0, 0.2, 0.3], + [6.1, 0.3, 0.35], + [6.4, 0.5, 0.5], + [6.8, 0.6, 0.6] + ], + "buttons": [[6.0, 1, true], [6.9, 1, false]], + "expect": { + "steps": [ + { + "action": "drag", + "time": 6.0, + "at": [0.2, 0.3], + "to": [0.6, 0.6] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/intro_before_first_step.json b/apps/desktop-gpui/steps/tests/scenarios/intro_before_first_step.json new file mode 100644 index 00000000000..b24b420a2de --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/intro_before_first_step.json @@ -0,0 +1,32 @@ +{ + "about": "What is said long before the first step introduces the guide.", + "duration": 20, + "moves": [[11.5, 0.5, 0.5]], + "buttons": [[12.0, 1, true], [12.08, 1, false]], + "words": [ + [0.5, 0.8, "Hi,"], + [0.8, 1.1, "this"], + [1.1, 1.4, "is"], + [1.4, 1.7, "a"], + [1.7, 2.0, "quick"], + [2.0, 2.3, "tour"], + [2.3, 2.6, "of"], + [2.6, 2.9, "the"], + [2.9, 3.2, "billing"], + [3.2, 3.5, "page."], + [10.8, 11.2, "Click"], + [11.2, 11.6, "invoices."] + ], + "expect": { + "intro": ["quick tour of the billing page."], + "steps": [ + { + "action": "click", + "time": 12.0, + "at": [0.5, 0.5], + "says": ["Click invoices."], + "not_says": ["tour"] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/long_press_is_a_click.json b/apps/desktop-gpui/steps/tests/scenarios/long_press_is_a_click.json new file mode 100644 index 00000000000..574093808ab --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/long_press_is_a_click.json @@ -0,0 +1,15 @@ +{ + "about": "Holding the button without moving is a click, not a drag.", + "duration": 10, + "moves": [[2.5, 0.5, 0.5], [3.5, 0.505, 0.5]], + "buttons": [[3.0, 1, true], [4.2, 1, false]], + "expect": { + "steps": [ + { + "action": "click", + "time": 3.0, + "at": [0.5, 0.5] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/marker_headings.json b/apps/desktop-gpui/steps/tests/scenarios/marker_headings.json new file mode 100644 index 00000000000..376c0c39887 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/marker_headings.json @@ -0,0 +1,35 @@ +{ + "about": "A labelled marker heads the steps that follow it.", + "duration": 20, + "markers": [[1.0, "Create a project"], [10.0, "Invite your team"]], + "moves": [[2.5, 0.2, 0.2], [5.5, 0.4, 0.4], [11.5, 0.7, 0.7]], + "buttons": [ + [3.0, 1, true], + [3.08, 1, false], + [6.0, 1, true], + [6.08, 1, false], + [12.0, 1, true], + [12.08, 1, false] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 3.0, + "at": [0.2, 0.2], + "heading": "Create a project" + }, + { + "action": "click", + "time": 6.0, + "at": [0.4, 0.4] + }, + { + "action": "click", + "time": 12.0, + "at": [0.7, 0.7], + "heading": "Invite your team" + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/marker_without_clicks_is_a_note.json b/apps/desktop-gpui/steps/tests/scenarios/marker_without_clicks_is_a_note.json new file mode 100644 index 00000000000..71c79a36541 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/marker_without_clicks_is_a_note.json @@ -0,0 +1,30 @@ +{ + "about": "A marker with nothing clicked after it is a step of its own: a screenshot of that moment.", + "duration": 20, + "markers": [[2.0, "Dashboard overview"], [8.0, "Open settings"]], + "moves": [[9.0, 0.9, 0.1]], + "buttons": [[9.5, 1, true], [9.58, 1, false]], + "words": [ + [2.2, 2.525, "This"], + [2.525, 2.85, "is"], + [2.85, 3.175, "the"], + [3.175, 3.5, "dashboard."] + ], + "expect": { + "steps": [ + { + "action": "note", + "time": 2.0, + "heading": "Dashboard overview", + "says": ["This is the dashboard."] + }, + { + "action": "click", + "time": 9.5, + "at": [0.9, 0.1], + "heading": "Open settings", + "silent": true + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/narration_announce_then_act.json b/apps/desktop-gpui/steps/tests/scenarios/narration_announce_then_act.json new file mode 100644 index 00000000000..4693c357155 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/narration_announce_then_act.json @@ -0,0 +1,40 @@ +{ + "about": "Each sentence goes with the step it was spoken around.", + "duration": 15, + "moves": [[3.5, 0.3, 0.3], [8.5, 0.6, 0.2]], + "buttons": [ + [4.0, 1, true], + [4.08, 1, false], + [9.0, 1, true], + [9.08, 1, false] + ], + "words": [ + [2.0, 2.35, "First,"], + [2.35, 2.7, "open"], + [2.7, 3.05, "the"], + [3.05, 3.4, "settings."], + [6.2, 6.48, "Then"], + [6.48, 6.76, "pick"], + [6.76, 7.04, "the"], + [7.04, 7.32, "export"], + [7.32, 7.6, "tab."] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 4.0, + "at": [0.3, 0.3], + "says": ["First, open the settings."], + "not_says": ["export"] + }, + { + "action": "click", + "time": 9.0, + "at": [0.6, 0.2], + "says": ["Then pick the export tab."], + "not_says": ["settings"] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/narration_pause_splits_sentences.json b/apps/desktop-gpui/steps/tests/scenarios/narration_pause_splits_sentences.json new file mode 100644 index 00000000000..f4de0c44ac0 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/narration_pause_splits_sentences.json @@ -0,0 +1,36 @@ +{ + "about": "Without punctuation, a pause ends the sentence.", + "duration": 10, + "moves": [[2.0, 0.3, 0.3], [5.4, 0.6, 0.6]], + "buttons": [ + [2.3, 1, true], + [2.38, 1, false], + [5.6, 1, true], + [5.68, 1, false] + ], + "words": [ + [1.0, 1.333, "open"], + [1.333, 1.667, "the"], + [1.667, 2.0, "menu"], + [4.5, 4.9, "choose"], + [4.9, 5.3, "export"] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 2.3, + "at": [0.3, 0.3], + "says": ["open the menu"], + "not_says": ["choose"] + }, + { + "action": "click", + "time": 5.6, + "at": [0.6, 0.6], + "says": ["choose export"], + "not_says": ["menu"] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/narration_prefers_the_coming_step.json b/apps/desktop-gpui/steps/tests/scenarios/narration_prefers_the_coming_step.json new file mode 100644 index 00000000000..8c27fd6d4ad --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/narration_prefers_the_coming_step.json @@ -0,0 +1,32 @@ +{ + "about": "A sentence between two steps belongs to the one it announces, even when the earlier one is a little closer.", + "duration": 12, + "moves": [[3.0, 0.2, 0.2], [7.0, 0.8, 0.8]], + "buttons": [ + [3.5, 1, true], + [3.58, 1, false], + [7.6, 1, true], + [7.68, 1, false] + ], + "words": [ + [5.0, 5.333, "Now"], + [5.333, 5.667, "click"], + [5.667, 6.0, "save."] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 3.5, + "at": [0.2, 0.2], + "silent": true + }, + { + "action": "click", + "time": 7.6, + "at": [0.8, 0.8], + "says": ["Now click save."] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/no_events.json b/apps/desktop-gpui/steps/tests/scenarios/no_events.json new file mode 100644 index 00000000000..9270d71a8aa --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/no_events.json @@ -0,0 +1,9 @@ +{ + "about": "With nothing clicked or marked there are no steps, and the narration is the intro.", + "duration": 8, + "words": [[1.0, 1.5, "Just"], [1.5, 2.0, "talking."]], + "expect": { + "intro": ["Just talking."], + "steps": [] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/press_without_release.json b/apps/desktop-gpui/steps/tests/scenarios/press_without_release.json new file mode 100644 index 00000000000..2a09db65e2f --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/press_without_release.json @@ -0,0 +1,20 @@ +{ + "about": "A press whose release was cut is still a click; a release on its own is nothing.", + "duration": 12, + "moves": [[0.5, 0.3, 0.3], [5.5, 0.7, 0.7]], + "buttons": [[1.0, 1, false], [3.0, 1, true], [6.0, 1, true], [6.1, 1, false]], + "expect": { + "steps": [ + { + "action": "click", + "time": 3.0, + "at": [0.3, 0.3] + }, + { + "action": "click", + "time": 6.0, + "at": [0.7, 0.7] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/repeated_clicks.json b/apps/desktop-gpui/steps/tests/scenarios/repeated_clicks.json new file mode 100644 index 00000000000..7a6236e8e88 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/repeated_clicks.json @@ -0,0 +1,37 @@ +{ + "about": "Clicking one control again and again is one step that says how many times; a later click there is its own step.", + "duration": 20, + "moves": [ + [4.5, 0.8, 0.2], + [5.65, 0.801, 0.2], + [7.05, 0.8, 0.201], + [11.5, 0.8, 0.2] + ], + "buttons": [ + [5.0, 1, true], + [5.08, 1, false], + [5.7, 1, true], + [5.78, 1, false], + [6.4, 1, true], + [6.48, 1, false], + [7.1, 1, true], + [7.18, 1, false], + [12.0, 1, true], + [12.08, 1, false] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 5.0, + "at": [0.8, 0.2], + "repeat": 4 + }, + { + "action": "click", + "time": 12.0, + "at": [0.8, 0.2] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/right_click.json b/apps/desktop-gpui/steps/tests/scenarios/right_click.json new file mode 100644 index 00000000000..917af974033 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/right_click.json @@ -0,0 +1,25 @@ +{ + "about": "The secondary button is a right-click; choosing from its menu is a separate click.", + "duration": 10, + "moves": [[1.5, 0.7, 0.7], [3.2, 0.72, 0.78]], + "buttons": [ + [2.0, 2, true], + [2.1, 2, false], + [3.5, 1, true], + [3.58, 1, false] + ], + "expect": { + "steps": [ + { + "action": "rightClick", + "time": 2.0, + "at": [0.7, 0.7] + }, + { + "action": "click", + "time": 3.5, + "at": [0.72, 0.78] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/single_click.json b/apps/desktop-gpui/steps/tests/scenarios/single_click.json new file mode 100644 index 00000000000..a4b302f8a75 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/single_click.json @@ -0,0 +1,16 @@ +{ + "about": "One click is one step, placed where the pointer last was.", + "duration": 12, + "moves": [[0, 0.2, 0.2], [3.0, 0.5, 0.4], [3.9, 0.62, 0.48]], + "buttons": [[4.0, 1, true], [4.08, 1, false]], + "expect": { + "steps": [ + { + "action": "click", + "time": 4.0, + "at": [0.62, 0.48], + "silent": true + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/stop_click_dropped.json b/apps/desktop-gpui/steps/tests/scenarios/stop_click_dropped.json new file mode 100644 index 00000000000..9884f0910a5 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/stop_click_dropped.json @@ -0,0 +1,20 @@ +{ + "about": "The click that stops the recording, in its last second, is not a step.", + "duration": 10, + "moves": [[3.0, 0.4, 0.4], [9.3, 0.97, 0.01]], + "buttons": [ + [4.0, 1, true], + [4.08, 1, false], + [9.6, 1, true], + [9.68, 1, false] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 4.0, + "at": [0.4, 0.4] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/two_spots_fast.json b/apps/desktop-gpui/steps/tests/scenarios/two_spots_fast.json new file mode 100644 index 00000000000..0af06e015aa --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/two_spots_fast.json @@ -0,0 +1,25 @@ +{ + "about": "Quick clicks in different places are separate steps.", + "duration": 10, + "moves": [[2.8, 0.2, 0.2], [3.4, 0.7, 0.7]], + "buttons": [ + [3.0, 1, true], + [3.08, 1, false], + [3.6, 1, true], + [3.68, 1, false] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 3.0, + "at": [0.2, 0.2] + }, + { + "action": "click", + "time": 3.6, + "at": [0.7, 0.7] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/unlabeled_marker_note.json b/apps/desktop-gpui/steps/tests/scenarios/unlabeled_marker_note.json new file mode 100644 index 00000000000..18e83c03427 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/unlabeled_marker_note.json @@ -0,0 +1,13 @@ +{ + "about": "A marker without a name still captures its moment.", + "duration": 12, + "markers": [[5.0, ""]], + "expect": { + "steps": [ + { + "action": "note", + "time": 5.0 + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/spec.rs b/apps/desktop-gpui/steps/tests/spec.rs new file mode 100644 index 00000000000..4a2b1781af7 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/spec.rs @@ -0,0 +1,995 @@ +use std::path::Path; + +use cap_steps::{ + Action, ButtonEvent, Captions, Document, DocumentStep, Guide, LEFT_BUTTON, Marker, Point, + PointerMove, Recording, Rect, Size, Step, Word, build_guide, crop_for, encode_png, image_name, + json, markdown, render_step_image, timestamp, +}; +use serde::Deserialize; + +const TIME_TOLERANCE: f64 = 0.15; +const POSITION_TOLERANCE: f64 = 0.01; +const CAP_BLUE: [u8; 3] = [0x47, 0x85, 0xFF]; + +#[derive(Deserialize)] +struct Scenario { + #[allow(dead_code)] + about: String, + duration: f64, + #[serde(default)] + moves: Vec<(f64, f64, f64)>, + #[serde(default)] + buttons: Vec<(f64, u8, bool)>, + #[serde(default)] + markers: Vec<(f64, String)>, + #[serde(default)] + words: Vec<(f64, f64, String)>, + expect: Expect, +} + +#[derive(Deserialize)] +struct Expect { + #[serde(default)] + intro: Vec, + steps: Vec, +} + +#[derive(Deserialize)] +struct ExpectStep { + action: Action, + time: f64, + #[serde(default)] + at: Option<(f64, f64)>, + #[serde(default)] + to: Option<(f64, f64)>, + #[serde(default = "once")] + repeat: u32, + #[serde(default)] + heading: Option, + #[serde(default)] + says: Vec, + #[serde(default)] + not_says: Vec, + #[serde(default)] + silent: bool, +} + +fn once() -> u32 { + 1 +} + +impl Scenario { + fn recording(&self) -> Recording { + Recording { + duration: self.duration, + moves: self + .moves + .iter() + .map(|&(time, x, y)| PointerMove { + time, + position: Point::new(x, y), + }) + .collect(), + buttons: self + .buttons + .iter() + .map(|&(time, button, down)| ButtonEvent { time, button, down }) + .collect(), + markers: self + .markers + .iter() + .map(|(time, label)| Marker { + time: *time, + label: label.clone(), + }) + .collect(), + words: self + .words + .iter() + .map(|(start, end, text)| Word { + start: *start, + end: *end, + text: text.clone(), + }) + .collect(), + } + } +} + +fn describe(guide: &Guide) -> String { + let mut out = format!("intro: {:?}\n", guide.intro); + for (index, step) in guide.steps.iter().enumerate() { + out.push_str(&format!( + " {}. {:?} t={:.2} at={:?} to={:?} x{} heading={:?} says={:?}\n", + index + 1, + step.action, + step.time, + step.position, + step.drag_to, + step.repeat, + step.heading, + step.narration + )); + } + out +} + +fn near(point: Option, expected: Option<(f64, f64)>) -> bool { + match (point, expected) { + (None, None) => true, + (Some(point), Some((x, y))) => { + (point.x - x).abs() <= POSITION_TOLERANCE && (point.y - y).abs() <= POSITION_TOLERANCE + } + _ => false, + } +} + +fn says(narration: &str, fragment: &str) -> bool { + narration.to_lowercase().contains(&fragment.to_lowercase()) +} + +fn judge(text: &str) -> Result<(), String> { + let scenario: Scenario = serde_json::from_str(text).map_err(|error| error.to_string())?; + let guide = build_guide(&scenario.recording()); + let mut problems = Vec::new(); + for fragment in &scenario.expect.intro { + if !says(&guide.intro, fragment) { + problems.push(format!("the intro should say {fragment:?}")); + } + } + if scenario.expect.intro.is_empty() && !guide.intro.is_empty() { + problems.push("the intro should be empty".to_string()); + } + if guide.steps.len() != scenario.expect.steps.len() { + problems.push(format!( + "expected {} steps, got {}", + scenario.expect.steps.len(), + guide.steps.len() + )); + } + for (index, (step, expected)) in guide.steps.iter().zip(&scenario.expect.steps).enumerate() { + let number = index + 1; + if step.action != expected.action { + problems.push(format!( + "step {number} should be {:?}, got {:?}", + expected.action, step.action + )); + } + if (step.time - expected.time).abs() > TIME_TOLERANCE { + problems.push(format!( + "step {number} should be at {:.2}s, got {:.2}s", + expected.time, step.time + )); + } + if !near(step.position, expected.at) { + problems.push(format!( + "step {number} should be at {:?}, got {:?}", + expected.at, step.position + )); + } + if !near(step.drag_to, expected.to) { + problems.push(format!( + "step {number} should drag to {:?}, got {:?}", + expected.to, step.drag_to + )); + } + if step.repeat != expected.repeat { + problems.push(format!( + "step {number} should repeat {} times, got {}", + expected.repeat, step.repeat + )); + } + if step.heading != expected.heading { + problems.push(format!( + "step {number} should be headed {:?}, got {:?}", + expected.heading, step.heading + )); + } + for fragment in &expected.says { + if !says(&step.narration, fragment) { + problems.push(format!("step {number} should say {fragment:?}")); + } + } + for fragment in &expected.not_says { + if says(&step.narration, fragment) { + problems.push(format!("step {number} should not say {fragment:?}")); + } + } + if expected.silent && !step.narration.is_empty() { + problems.push(format!("step {number} should have no narration")); + } + } + if problems.is_empty() { + Ok(()) + } else { + Err(format!("{}\n{}", problems.join("\n"), describe(&guide))) + } +} + +macro_rules! scenarios { + ($($name:ident),* $(,)?) => { + $( + #[test] + fn $name() { + let text = include_str!(concat!("scenarios/", stringify!($name), ".json")); + if let Err(problems) = judge(text) { + panic!("{problems}"); + } + } + )* + }; +} + +scenarios!( + single_click, + double_click, + repeated_clicks, + drag, + right_click, + stop_click_dropped, + narration_announce_then_act, + narration_prefers_the_coming_step, + narration_pause_splits_sentences, + intro_before_first_step, + marker_headings, + marker_without_clicks_is_a_note, + unlabeled_marker_note, + press_without_release, + click_position_uses_latest_move, + no_events, + two_spots_fast, + long_press_is_a_click, +); + +/// Scores a folder of scenario files of your own: set +/// `CAP_STEPS_EXTRA_SCENARIOS` to it. Without the variable this does nothing. +#[test] +fn extra_scenarios() { + let Some(folder) = std::env::var_os("CAP_STEPS_EXTRA_SCENARIOS") else { + return; + }; + let mut files: Vec<_> = std::fs::read_dir(Path::new(&folder)) + .expect("the scenario folder should be readable") + .filter_map(|entry| entry.ok().map(|entry| entry.path())) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension == "json") + }) + .collect(); + files.sort(); + let mut failures = 0; + for file in &files { + let text = std::fs::read_to_string(file).expect("the scenario should be readable"); + if let Err(problems) = judge(&text) { + failures += 1; + println!("FAIL {}\n{problems}", file.display()); + } else { + println!("ok {}", file.display()); + } + } + println!("EXTRA_SCENARIO_TOTAL={}", files.len()); + println!("EXTRA_SCENARIO_FAILURES={failures}"); + assert_eq!(failures, 0, "{failures} of {} scenarios fail", files.len()); +} + +fn click_at(time: f64, x: f64, y: f64) -> Recording { + Recording { + duration: time + 10.0, + moves: vec![PointerMove { + time: 0.0, + position: Point::new(x, y), + }], + buttons: vec![ + ButtonEvent { + time, + button: LEFT_BUTTON, + down: true, + }, + ButtonEvent { + time: time + 0.08, + button: LEFT_BUTTON, + down: false, + }, + ], + ..Recording::default() + } +} + +#[test] +fn the_frame_is_taken_just_before_the_press() { + let guide = build_guide(&click_at(4.0, 0.5, 0.5)); + assert_eq!(guide.steps.len(), 1); + assert!((guide.steps[0].frame_time - 3.95).abs() < 1e-9); + + let guide = build_guide(&click_at(0.02, 0.5, 0.5)); + assert_eq!(guide.steps.len(), 1); + assert_eq!(guide.steps[0].frame_time, 0.0); +} + +#[test] +fn a_note_is_framed_at_its_marker() { + let guide = build_guide(&Recording { + duration: 20.0, + markers: vec![Marker { + time: 6.5, + label: "Overview".into(), + }], + ..Recording::default() + }); + assert_eq!(guide.steps.len(), 1); + assert_eq!(guide.steps[0].action, Action::Note); + assert_eq!(guide.steps[0].frame_time, 6.5); +} + +#[test] +fn events_out_of_order_still_give_steps_in_time_order() { + let mut recording = click_at(8.0, 0.2, 0.2); + recording.duration = 30.0; + recording.moves.push(PointerMove { + time: 2.5, + position: Point::new(0.7, 0.7), + }); + recording.moves.push(PointerMove { + time: 5.0, + position: Point::new(0.2, 0.2), + }); + recording.buttons.push(ButtonEvent { + time: 3.1, + button: LEFT_BUTTON, + down: false, + }); + recording.buttons.push(ButtonEvent { + time: 3.0, + button: LEFT_BUTTON, + down: true, + }); + let guide = build_guide(&recording); + assert_eq!(guide.steps.len(), 2); + assert!((guide.steps[0].time - 3.0).abs() < 1e-9); + assert!((guide.steps[1].time - 8.0).abs() < 1e-9); + assert!(near(guide.steps[0].position, Some((0.7, 0.7)))); + assert!(near(guide.steps[1].position, Some((0.2, 0.2)))); +} + +#[test] +fn broken_numbers_are_ignored_not_fatal() { + let mut recording = click_at(4.0, 0.5, 0.5); + recording.moves.push(PointerMove { + time: f64::NAN, + position: Point::new(0.1, 0.1), + }); + recording.moves.push(PointerMove { + time: 3.0, + position: Point::new(f64::INFINITY, 0.1), + }); + recording.buttons.push(ButtonEvent { + time: f64::NAN, + button: LEFT_BUTTON, + down: true, + }); + recording.words.push(Word { + start: f64::NAN, + end: 1.0, + text: "lost".into(), + }); + let guide = build_guide(&recording); + assert_eq!(guide.steps.len(), 1); + assert!(near(guide.steps[0].position, Some((0.5, 0.5)))); + assert!(!says(&guide.steps[0].narration, "lost")); + assert!(!says(&guide.intro, "lost")); +} + +#[test] +fn positions_outside_the_frame_are_pulled_onto_it() { + let guide = build_guide(&click_at(4.0, 1.2, -0.1)); + assert_eq!(guide.steps.len(), 1); + assert!(near(guide.steps[0].position, Some((1.0, 0.0)))); +} + +fn step(action: Action, position: Option<(f64, f64)>, drag_to: Option<(f64, f64)>) -> Step { + Step { + time: 4.0, + frame_time: 3.95, + action, + position: position.map(|(x, y)| Point::new(x, y)), + drag_to: drag_to.map(|(x, y)| Point::new(x, y)), + repeat: 1, + heading: None, + narration: String::new(), + } +} + +const RETINA: Size = Size { + width: 3024, + height: 1964, +}; +const HD: Size = Size { + width: 1280, + height: 720, +}; + +#[test] +fn without_a_position_the_crop_is_the_whole_frame() { + assert_eq!( + crop_for(&step(Action::Note, None, None), RETINA), + Rect { + x: 0, + y: 0, + width: 3024, + height: 1964 + } + ); +} + +#[test] +fn a_click_is_cropped_to_half_the_frame_at_16_by_10() { + assert_eq!( + crop_for(&step(Action::Click, Some((0.5, 0.5)), None), RETINA), + Rect { + x: 756, + y: 510, + width: 1512, + height: 944 + } + ); +} + +#[test] +fn a_crop_is_never_narrower_than_960_pixels() { + assert_eq!( + crop_for(&step(Action::Click, Some((0.5, 0.5)), None), HD), + Rect { + x: 160, + y: 60, + width: 960, + height: 600 + } + ); +} + +#[test] +fn a_small_frame_is_cropped_across_its_full_width() { + let frame = Size { + width: 800, + height: 600, + }; + assert_eq!( + crop_for(&step(Action::Click, Some((0.5, 0.5)), None), frame), + Rect { + x: 0, + y: 50, + width: 800, + height: 500 + } + ); +} + +#[test] +fn a_crop_near_an_edge_stays_inside_the_frame() { + assert_eq!( + crop_for(&step(Action::Click, Some((0.99, 0.01)), None), RETINA), + Rect { + x: 1512, + y: 0, + width: 1512, + height: 944 + } + ); + assert_eq!( + crop_for(&step(Action::Click, Some((0.0, 1.0)), None), RETINA), + Rect { + x: 0, + y: 1020, + width: 1512, + height: 944 + } + ); +} + +#[test] +fn a_short_drag_is_cropped_around_its_middle() { + assert_eq!( + crop_for( + &step(Action::Drag, Some((0.45, 0.5)), Some((0.55, 0.5))), + RETINA + ), + Rect { + x: 756, + y: 510, + width: 1512, + height: 944 + } + ); +} + +#[test] +fn a_long_drag_widens_the_crop_to_hold_both_ends() { + let drags = [ + ((0.1, 0.5), (0.9, 0.5)), + ((0.2, 0.1), (0.3, 0.9)), + ((0.05, 0.05), (0.95, 0.95)), + ((0.6, 0.7), (0.1, 0.2)), + ]; + for (from, to) in drags { + let crop = crop_for(&step(Action::Drag, Some(from), Some(to)), RETINA); + assert!(crop.x + crop.width <= RETINA.width, "{crop:?}"); + assert!(crop.y + crop.height <= RETINA.height, "{crop:?}"); + assert!(crop.width >= 1512 && crop.height >= 944, "{crop:?}"); + let full = crop.width == RETINA.width && crop.height == RETINA.height; + for (x, y) in [from, to] { + let px = x * f64::from(RETINA.width); + let py = y * f64::from(RETINA.height); + let margin_x = if full || crop.width == RETINA.width { + 0.0 + } else { + 0.08 * f64::from(crop.width) + }; + let margin_y = if full || crop.height == RETINA.height { + 0.0 + } else { + 0.08 * f64::from(crop.height) + }; + let left_free = crop.x == 0; + let right_free = crop.x + crop.width == RETINA.width; + let top_free = crop.y == 0; + let bottom_free = crop.y + crop.height == RETINA.height; + assert!( + px >= f64::from(crop.x) + if left_free { 0.0 } else { margin_x } - 1.0, + "{from:?} to {to:?}: {crop:?}" + ); + assert!( + px <= f64::from(crop.x + crop.width) - if right_free { 0.0 } else { margin_x } + + 1.0, + "{from:?} to {to:?}: {crop:?}" + ); + assert!( + py >= f64::from(crop.y) + if top_free { 0.0 } else { margin_y } - 1.0, + "{from:?} to {to:?}: {crop:?}" + ); + assert!( + py <= f64::from(crop.y + crop.height) - if bottom_free { 0.0 } else { margin_y } + + 1.0, + "{from:?} to {to:?}: {crop:?}" + ); + } + } +} + +fn gradient(size: Size) -> Vec { + let mut pixels = Vec::with_capacity((size.width * size.height * 4) as usize); + for y in 0..size.height { + for x in 0..size.width { + pixels.extend_from_slice(&[(x % 251) as u8, (y % 241) as u8, 0, 255]); + } + } + pixels +} + +fn gray(size: Size) -> Vec { + [128, 128, 128, 255].repeat((size.width * size.height) as usize) +} + +fn pixel(image: &cap_steps::StepImage, x: f64, y: f64) -> [u8; 4] { + let x = (x.round() as u32).min(image.size.width - 1); + let y = (y.round() as u32).min(image.size.height - 1); + let index = ((y * image.size.width + x) * 4) as usize; + [ + image.rgba[index], + image.rgba[index + 1], + image.rgba[index + 2], + image.rgba[index + 3], + ] +} + +fn is_cap_blue(pixel: [u8; 4]) -> bool { + pixel[..3] + .iter() + .zip(CAP_BLUE) + .all(|(channel, blue)| (i32::from(*channel) - i32::from(blue)).abs() <= 24) +} + +fn ring_radius(crop: Rect) -> f64 { + (f64::from(crop.width) * 0.022).max(14.0) +} + +#[test] +fn the_step_image_is_the_cropped_frame() { + let click = step(Action::Click, Some((0.25, 0.75)), None); + let crop = crop_for(&click, HD); + let image = render_step_image(&gradient(HD), HD, &click).expect("an image"); + assert_eq!( + image.size, + Size { + width: crop.width, + height: crop.height + } + ); + assert_eq!(image.rgba.len(), (crop.width * crop.height * 4) as usize); + for (x, y) in [(0, 0), (crop.width - 1, 0), (0, crop.height - 1)] { + assert_eq!( + pixel(&image, f64::from(x), f64::from(y)), + [ + ((crop.x + x) % 251) as u8, + ((crop.y + y) % 241) as u8, + 0, + 255 + ] + ); + } +} + +#[test] +fn the_click_is_ringed_in_cap_blue() { + for position in [(0.5, 0.5), (0.25, 0.75), (0.9, 0.2)] { + let click = step(Action::Click, Some(position), None); + let crop = crop_for(&click, HD); + let image = render_step_image(&gray(HD), HD, &click).expect("an image"); + let cx = position.0 * f64::from(HD.width) - f64::from(crop.x); + let cy = position.1 * f64::from(HD.height) - f64::from(crop.y); + let radius = ring_radius(crop); + for turn in 0..8 { + let angle = f64::from(turn) * std::f64::consts::FRAC_PI_4; + let sample = pixel(&image, cx + radius * angle.cos(), cy + radius * angle.sin()); + assert!(is_cap_blue(sample), "{position:?} turn {turn}: {sample:?}"); + } + } +} + +#[test] +fn what_was_clicked_stays_visible_inside_the_ring() { + let click = step(Action::Click, Some((0.5, 0.5)), None); + let crop = crop_for(&click, HD); + let image = render_step_image(&gray(HD), HD, &click).expect("an image"); + let centre = pixel( + &image, + f64::from(crop.width) / 2.0, + f64::from(crop.height) / 2.0, + ); + assert!(!is_cap_blue(centre), "{centre:?}"); + for channel in ¢re[..3] { + assert!((i32::from(*channel) - 128).abs() <= 40, "{centre:?}"); + } +} + +#[test] +fn pixels_away_from_the_ring_are_untouched() { + let click = step(Action::Click, Some((0.5, 0.5)), None); + let crop = crop_for(&click, HD); + let image = render_step_image(&gray(HD), HD, &click).expect("an image"); + let radius = ring_radius(crop); + let cx = f64::from(crop.width) / 2.0; + let cy = f64::from(crop.height) / 2.0; + for turn in 0..8 { + let angle = f64::from(turn) * std::f64::consts::FRAC_PI_4; + assert_eq!( + pixel( + &image, + cx + 3.0 * radius * angle.cos(), + cy + 3.0 * radius * angle.sin() + ), + [128, 128, 128, 255] + ); + } +} + +#[test] +fn a_drag_is_drawn_as_a_line_between_its_ends() { + let drag = step(Action::Drag, Some((0.4, 0.4)), Some((0.6, 0.6))); + let crop = crop_for(&drag, HD); + let image = render_step_image(&gray(HD), HD, &drag).expect("an image"); + let middle = pixel( + &image, + 0.5 * f64::from(HD.width) - f64::from(crop.x), + 0.5 * f64::from(HD.height) - f64::from(crop.y), + ); + assert!(is_cap_blue(middle), "{middle:?}"); +} + +#[test] +fn a_note_is_the_frame_as_it_was() { + let frame = gradient(HD); + let image = render_step_image(&frame, HD, &step(Action::Note, None, None)).expect("an image"); + assert_eq!(image.size, HD); + assert_eq!(image.rgba, frame); +} + +#[test] +fn a_frame_of_the_wrong_length_gives_no_image() { + let click = step(Action::Click, Some((0.5, 0.5)), None); + assert!(render_step_image(&[0; 16], HD, &click).is_none()); + assert!( + render_step_image( + &[], + Size { + width: 0, + height: 0 + }, + &click + ) + .is_none() + ); +} + +#[test] +fn step_images_are_written_as_png() { + let click = step(Action::Click, Some((0.5, 0.5)), None); + let image = render_step_image(&gradient(HD), HD, &click).expect("an image"); + let png = encode_png(&image).expect("a png"); + let decoded = image::load_from_memory_with_format(&png, image::ImageFormat::Png) + .expect("a readable png") + .to_rgba8(); + assert_eq!(decoded.width(), image.size.width); + assert_eq!(decoded.height(), image.size.height); + assert_eq!(decoded.into_raw(), image.rgba); +} + +#[test] +fn image_names_are_zero_padded() { + assert_eq!(image_name(1, 9), "step-01.png"); + assert_eq!(image_name(12, 12), "step-12.png"); + assert_eq!(image_name(7, 120), "step-007.png"); +} + +#[test] +fn timestamps_read_like_a_player() { + assert_eq!(timestamp(4.2), "0:04"); + assert_eq!(timestamp(75.0), "1:15"); + assert_eq!(timestamp(3725.0), "1:02:05"); + assert_eq!(timestamp(-3.0), "0:00"); + assert_eq!(timestamp(f64::NAN), "0:00"); +} + +fn document_step( + index: usize, + time: f64, + action: Action, + narration: &str, + heading: Option<&str>, +) -> DocumentStep { + DocumentStep { + step: Step { + time, + frame_time: time, + action, + position: (action != Action::Note).then(|| Point::new(0.5, 0.5)), + drag_to: (action == Action::Drag).then(|| Point::new(0.6, 0.6)), + repeat: 1, + heading: heading.map(str::to_string), + narration: narration.to_string(), + }, + image: format!("steps/{}", image_name(index, 2)), + } +} + +#[test] +fn markdown_lays_out_the_title_the_intro_and_each_step() { + let document = Document { + title: "Invite a teammate".into(), + duration: 12.0, + intro: "A quick tour of the team page.".into(), + steps: vec![ + document_step(1, 4.2, Action::Click, "Open the team page.", None), + document_step(2, 9.0, Action::Click, "", None), + ], + }; + assert_eq!( + markdown(&document, &Captions::default()), + "# Invite a teammate\n\ + \n\ + A quick tour of the team page.\n\ + \n\ + ### Step 1 · 0:04\n\ + \n\ + Open the team page.\n\ + \n\ + ![Step 1](steps/step-01.png)\n\ + \n\ + ### Step 2 · 0:09\n\ + \n\ + Click the highlighted spot.\n\ + \n\ + ![Step 2](steps/step-02.png)\n" + ); +} + +#[test] +fn markdown_opens_a_section_at_each_heading() { + let document = Document { + title: "Setup".into(), + duration: 30.0, + intro: String::new(), + steps: vec![ + document_step(1, 3.0, Action::Click, "Sign in.", Some("Create a project")), + document_step(2, 14.0, Action::Note, "", Some("Invite your team")), + ], + }; + assert_eq!( + markdown(&document, &Captions::default()), + "# Setup\n\ + \n\ + ## Create a project\n\ + \n\ + ### Step 1 · 0:03\n\ + \n\ + Sign in.\n\ + \n\ + ![Step 1](steps/step-01.png)\n\ + \n\ + ## Invite your team\n\ + \n\ + ### Step 2 · 0:14\n\ + \n\ + ![Step 2](steps/step-02.png)\n" + ); +} + +#[test] +fn markdown_names_the_action_when_narration_alone_would_not() { + let mut double = document_step(1, 3.0, Action::DoubleClick, "Open the file.", None); + let mut repeated = document_step(2, 6.0, Action::Click, "Go forward a few pages.", None); + repeated.step.repeat = 3; + let right = document_step(1, 8.0, Action::RightClick, "", None); + let dragged = document_step(2, 9.0, Action::Drag, "Move the slider.", None); + let captions = Captions::default(); + + double.image = "steps/step-01.png".into(); + let text = markdown( + &Document { + title: "T".into(), + duration: 10.0, + intro: String::new(), + steps: vec![double, repeated], + }, + &captions, + ); + assert!( + text.contains("Open the file.\n\n_Double-click the highlighted spot._\n\n![Step 1]"), + "{text}" + ); + assert!( + text.contains( + "Go forward a few pages.\n\n_Click the highlighted spot 3 times._\n\n![Step 2]" + ), + "{text}" + ); + + let text = markdown( + &Document { + title: "T".into(), + duration: 10.0, + intro: String::new(), + steps: vec![right, dragged], + }, + &captions, + ); + assert!( + text.contains("### Step 1 · 0:08\n\nRight-click the highlighted spot.\n\n![Step 1]"), + "{text}" + ); + assert!( + text.contains("Move the slider.\n\n_Drag along the arrow._\n\n![Step 2]"), + "{text}" + ); +} + +#[test] +fn markdown_uses_the_captions_it_is_given() { + let captions = Captions { + step: "Schritt {number}".into(), + click: "Klicke auf die markierte Stelle.".into(), + double_click: "Doppelklicke auf die markierte Stelle.".into(), + right_click: "Rechtsklicke auf die markierte Stelle.".into(), + drag: "Ziehe entlang des Pfeils.".into(), + repeat: "Klicke {count}-mal auf die markierte Stelle.".into(), + }; + let mut repeated = document_step(2, 6.0, Action::Click, "", None); + repeated.step.repeat = 4; + let text = markdown( + &Document { + title: "T".into(), + duration: 10.0, + intro: String::new(), + steps: vec![document_step(1, 3.0, Action::Click, "", None), repeated], + }, + &captions, + ); + assert!( + text.contains("### Schritt 1 · 0:03\n\nKlicke auf die markierte Stelle.\n\n![Schritt 1]"), + "{text}" + ); + assert!( + text.contains("Klicke 4-mal auf die markierte Stelle."), + "{text}" + ); +} + +#[test] +fn narration_cannot_break_the_markdown() { + let document = Document { + title: "Use *bold* ".into(), + duration: 10.0, + intro: "#1 priority".into(), + steps: vec![document_step( + 1, + 3.0, + Action::Click, + "Type *bold* into [here]_now with `code` and a \\ slash", + Some("Step [one]"), + )], + }; + let text = markdown(&document, &Captions::default()); + assert!(text.starts_with("# Use \\*bold\\* \\\n"), "{text}"); + assert!(text.contains("\n\\#1 priority\n"), "{text}"); + assert!(text.contains("\n## Step \\[one\\]\n"), "{text}"); + assert!( + text.contains( + "Type \\*bold\\* into \\ \\[here\\]\\_now with \\`code\\` and a \\\\ slash" + ), + "{text}" + ); +} + +#[test] +fn narration_that_looks_like_a_list_a_fence_or_an_entity_stays_text() { + let said = |narration: &str| { + markdown( + &Document { + title: "T".into(), + duration: 10.0, + intro: String::new(), + steps: vec![document_step(1, 3.0, Action::Click, narration, None)], + }, + &Captions::default(), + ) + }; + assert!(said("1. Open settings").contains("\n1\\. Open settings\n")); + assert!(said("12) then save").contains("\n12\\) then save\n")); + assert!(said("3 files are listed.").contains("\n3 files are listed.\n")); + assert!(said("~~~ fenced").contains("\n\\~\\~\\~ fenced\n")); + assert!(said("AT&T uses <b>").contains("\nAT\\&T uses \\<b\\>\n")); +} + +#[test] +fn an_empty_guide_is_just_its_title() { + let document = Document { + title: "Nothing yet".into(), + duration: 0.0, + intro: String::new(), + steps: Vec::new(), + }; + assert_eq!(markdown(&document, &Captions::default()), "# Nothing yet\n"); +} + +#[test] +fn json_lists_every_step_for_tools_to_read() { + let mut dragged = document_step(2, 9.5, Action::Drag, "Move the slider.", Some("Tune it")); + dragged.step.repeat = 1; + let document = Document { + title: "Invite a teammate".into(), + duration: 12.5, + intro: "A quick tour.".into(), + steps: vec![ + document_step(1, 4.0, Action::DoubleClick, "Open the file.", None), + dragged, + ], + }; + let value: serde_json::Value = serde_json::from_str(&json(&document)).expect("valid json"); + assert_eq!(value["title"], "Invite a teammate"); + assert_eq!(value["duration"], 12.5); + assert_eq!(value["intro"], "A quick tour."); + let steps = value["steps"].as_array().expect("steps"); + assert_eq!(steps.len(), 2); + assert_eq!(steps[0]["index"], 1); + assert_eq!(steps[0]["time"], 4.0); + assert_eq!(steps[0]["action"], "doubleClick"); + assert_eq!(steps[0]["position"]["x"], 0.5); + assert_eq!(steps[0]["position"]["y"], 0.5); + assert!(steps[0]["dragTo"].is_null()); + assert_eq!(steps[0]["repeat"], 1); + assert!(steps[0]["heading"].is_null()); + assert_eq!(steps[0]["narration"], "Open the file."); + assert_eq!(steps[0]["image"], "steps/step-01.png"); + assert_eq!(steps[1]["action"], "drag"); + assert_eq!(steps[1]["dragTo"]["x"], 0.6); + assert_eq!(steps[1]["heading"], "Tune it"); +} From 3f67e9e979df198799a235838768ece8c5d3b3a7 Mon Sep 17 00:00:00 2001 From: Aatman Jain Date: Sat, 28 Nov 2026 15:35:34 +0000 Subject: [PATCH 2/6] fix(desktop-gpui): keep steps export true to the recording and its masks Follow-up to the review of the Steps export. - Read each clip's clicks on that clip's own clock and from its uncut pointer path, then place the finished steps on the timeline. A clip's playback speed no longer turns a double-click into repeated clicks, or two clicks into a double-click. cap-steps now takes one clip's events at a time (clip_steps) and builds the guide from steps already placed. - Keep the clip and recorded time with every step and marker note, and take the screenshot from there. A click made in the outgoing clip of a crossfade was given the incoming clip's frame. - Refuse to export while a Sensitive mask is on the timeline. Screenshots are cut from the raw screen track and would show what the mask hides. The Export page says so and disables the button. - Replace an earlier guide as a unit. guide.md, guide.json and steps/ are swapped in together and put back if one of them fails, so a shorter guide leaves no screenshots from a longer one. Other files in the folder are left alone. - End narration sentences on full-width marks as well, so Japanese and Chinese narration is split between its steps. - Drop comments that restated the code. --- apps/desktop-gpui/locales/de.toml | 1 + apps/desktop-gpui/locales/en.toml | 1 + apps/desktop-gpui/locales/es.toml | 1 + apps/desktop-gpui/locales/fr.toml | 1 + apps/desktop-gpui/locales/hi.toml | 1 + apps/desktop-gpui/locales/ja.toml | 1 + apps/desktop-gpui/locales/zh-CN.toml | 1 + apps/desktop-gpui/src/editor_export.rs | 10 +- .../src/editor_export/steps_tests.rs | 5 +- .../src/i18n/editor_shell_surface_tests.rs | 4 + apps/desktop-gpui/src/steps_export.rs | 259 +++++++++-------- apps/desktop-gpui/src/steps_export/tests.rs | 268 ++++++++++++++---- apps/desktop-gpui/steps/src/detect.rs | 58 ++-- apps/desktop-gpui/steps/src/frame.rs | 1 - apps/desktop-gpui/steps/src/lib.rs | 34 ++- apps/desktop-gpui/steps/src/narration.rs | 9 +- .../double_click_in_slow_motion.json | 21 ++ .../narration_fullwidth_sentence_ends.json | 46 +++ .../scenarios/separate_clicks_sped_up.json | 22 ++ apps/desktop-gpui/steps/tests/spec.rs | 144 ++++++++-- 20 files changed, 641 insertions(+), 247 deletions(-) create mode 100644 apps/desktop-gpui/steps/tests/scenarios/double_click_in_slow_motion.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/narration_fullwidth_sentence_ends.json create mode 100644 apps/desktop-gpui/steps/tests/scenarios/separate_clicks_sped_up.json diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index b98a745f8e2..f9bcf43ddb6 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -2744,6 +2744,7 @@ finding = "Schritte werden gesucht…" folder = "{name} Schritte" format = "Schritte" guide = "Ein Screenshot für jeden Klick, jedes Ziehen und jeden Marker, mit dem, was Sie dazu gesagt haben. Gespeichert als Markdown mit Bildern, dazu eine JSON-Kopie für Tools und Agenten." +hidden_areas = "Diese Aufnahme enthält eine Maske vom Typ „Vertraulich“. Die Screenshots der Schritte stammen direkt aus der Bildschirmaufnahme und würden zeigen, was die Maske verbirgt. Solange sie in der Zeitleiste liegt, lassen sich keine Schritte exportieren." more = { one = "und {count} weiterer Schritt", other = "und {count} weitere Schritte" } none = "Diese Aufnahme enthält keine Klicks oder Marker. Klicken Sie sich durch das, was Sie zeigen, oder fügen Sie Marker hinzu: Jeder wird zu einem Schritt." diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 70a76ee4272..1366bb72930 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -2746,6 +2746,7 @@ finding = "Finding steps…" folder = { text = "{name} Steps", context = "Name of the folder an exported guide is saved in; {name} is the recording's name." } format = { text = "Steps", context = "Export format: a step-by-step guide with a screenshot for each click." } guide = "One screenshot for each click, drag and marker, with what you said around it. Saved as Markdown and images, with a JSON copy for tools and agents." +hidden_areas = { text = "This recording has a Sensitive mask. Step screenshots come straight from the screen recording and would show what the mask hides, so steps cannot be exported while it is on the timeline.", context = "Shown instead of exporting a step-by-step guide. A Sensitive mask is the editor's mask type that blurs a private area of the screen." } more = { one = "and {count} more step", other = "and {count} more steps", context = "Closes a list that shows only the first steps of a guide." } none = "No clicks or markers in this recording. Click through what you are showing, or add markers, and each one becomes a step." diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index 2fbd8719dbb..377e52efc84 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -2744,6 +2744,7 @@ finding = "Buscando pasos…" folder = "{name} Pasos" format = "Pasos" guide = "Una captura por cada clic, arrastre y marcador, con lo que dijiste en ese momento. Se guarda como Markdown con imágenes, y con una copia en JSON para herramientas y agentes." +hidden_areas = "Esta grabación tiene una máscara de tipo Sensible. Las capturas de los pasos salen directamente de la grabación de pantalla y mostrarían lo que la máscara oculta, así que no se pueden exportar pasos mientras esté en la línea de tiempo." more = { one = "y {count} paso más", other = "y {count} pasos más" } none = "No hay clics ni marcadores en esta grabación. Haz clic en lo que muestras, o añade marcadores, y cada uno se convertirá en un paso." diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index ec436815aa4..e0b1ba4f4f8 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -2744,6 +2744,7 @@ finding = "Recherche des étapes…" folder = "{name} Étapes" format = "Étapes" guide = "Une capture pour chaque clic, glissement et repère, avec ce que vous avez dit à ce moment-là. Enregistré en Markdown avec des images, et avec une copie JSON pour les outils et les agents." +hidden_areas = "Cet enregistrement contient un masque de type Sensible. Les captures des étapes proviennent directement de l'enregistrement de l'écran et montreraient ce que le masque cache : les étapes ne peuvent donc pas être exportées tant qu'il est sur la timeline." more = { one = "et {count} autre étape", other = "et {count} autres étapes" } none = "Aucun clic ni repère dans cet enregistrement. Cliquez sur ce que vous montrez, ou ajoutez des repères : chacun devient une étape." diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 352a8c726a8..cd11b3ea3c4 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -2744,6 +2744,7 @@ finding = "चरण खोजे जा रहे हैं…" folder = "{name} चरण" format = "चरण" guide = "हर क्लिक, ड्रैग और मार्कर के लिए एक स्क्रीनशॉट, साथ में वह जो आपने उस समय कहा। Markdown और इमेज के रूप में सेव होता है, टूल और एजेंट के लिए JSON कॉपी के साथ।" +hidden_areas = "इस रिकॉर्डिंग में एक संवेदनशील मास्क है। चरणों के स्क्रीनशॉट सीधे स्क्रीन रिकॉर्डिंग से लिए जाते हैं और वह दिखा देंगे जो मास्क छिपाता है, इसलिए जब तक यह टाइमलाइन पर है, चरण एक्सपोर्ट नहीं किए जा सकते।" more = { one = "और {count} चरण", other = "और {count} चरण" } none = "इस रिकॉर्डिंग में कोई क्लिक या मार्कर नहीं है। जो दिखा रहे हैं उस पर क्लिक करें, या मार्कर जोड़ें, और हर एक एक चरण बन जाएगा।" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 499fd862025..f9cc3577005 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -2744,6 +2744,7 @@ finding = "ステップを検出中…" folder = "{name} ステップ" format = "ステップ" guide = "クリック、ドラッグ、マーカーごとにスクリーンショットを1枚、その前後に話した内容と一緒に保存します。Markdownと画像で書き出し、ツールやエージェント向けのJSONも付きます。" +hidden_areas = "この録画には「機密」マスクがあります。ステップのスクリーンショットは画面収録からそのまま切り出すため、マスクで隠した部分が写ってしまいます。マスクがタイムラインにある間は、ステップを書き出せません。" more = { other = "ほか{count}ステップ" } none = "この録画にはクリックもマーカーもありません。見せたい操作をクリックするか、マーカーを追加すると、それぞれがステップになります。" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 4c77429f7d7..29234a2e793 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -2744,6 +2744,7 @@ finding = "正在查找步骤…" folder = "{name} 步骤" format = "步骤" guide = "每次点击、拖动和标记各生成一张截图,并附上你当时说的话。保存为 Markdown 和图片,另附一份供工具和智能体使用的 JSON。" +hidden_areas = "这段录制中有“敏感内容”遮罩。步骤截图直接取自屏幕录制,会显示遮罩隐藏的内容,因此只要遮罩还在时间线上,就无法导出步骤。" more = { other = "还有 {count} 个步骤" } none = "这段录制中没有点击或标记。点击你要演示的内容,或添加标记,每一个都会成为一个步骤。" diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs index 324f73850f8..3a7a6193ed1 100644 --- a/apps/desktop-gpui/src/editor_export.rs +++ b/apps/desktop-gpui/src/editor_export.rs @@ -237,6 +237,7 @@ fn step_rows(guide: &cap_steps::Guide, captions: &cap_steps::Captions) -> Vec String { match error { StepsError::NoSteps => tr::editor::export::steps::none().into(), + StepsError::HiddenAreas => tr::editor::export::steps::hidden_areas().into(), StepsError::Cancelled => String::new(), StepsError::Failed(error) => error.clone(), } @@ -492,8 +493,6 @@ pub struct ExportUi { /// exporting sound once does not change what the next video export /// opens with. saved_format: ExportFormatKind, - /// What the Steps format would write, for its stage. `None` until the - /// recording has been read. pub steps: Option>, steps_task: Option>, } @@ -3173,6 +3172,7 @@ impl EditorWindow { ); let found = ui.steps.as_deref(); let count = found.map_or(0, <[StepRow]>::len); + let hidden_areas = crate::steps_export::hides_areas(&self.project); let row = |step: &StepRow| { let text = if step.text.is_empty() { @@ -3312,6 +3312,9 @@ impl EditorWindow { card.child(note(tr::editor::export::steps::more( count - STEP_ROWS_SHOWN, ))) + }) + .when(count > 0 && hidden_areas, |card| { + card.child(note(tr::editor::export::steps::hidden_areas().into())) }), ) .child( @@ -3482,7 +3485,8 @@ impl EditorWindow { let busy = ui.phase.is_busy() || (ui.format == ExportFormatKind::Tracks && ui.tracks.is_empty()) || (ui.format == ExportFormatKind::Steps - && ui.steps.as_ref().is_none_or(|steps| steps.is_empty())); + && (ui.steps.as_ref().is_none_or(|steps| steps.is_empty()) + || crate::steps_export::hides_areas(&self.project))); let (bg, hover_bg, text) = if primary { ( Hsla::from(editor.accent), diff --git a/apps/desktop-gpui/src/editor_export/steps_tests.rs b/apps/desktop-gpui/src/editor_export/steps_tests.rs index 2442499b3fd..39f8f656c0c 100644 --- a/apps/desktop-gpui/src/editor_export/steps_tests.rs +++ b/apps/desktop-gpui/src/editor_export/steps_tests.rs @@ -1,4 +1,4 @@ -use cap_steps::{Action, Captions, Guide, Point, Step}; +use cap_steps::{Action, Captions, Guide, Point, Source, Step}; use super::{ ExportDestination, ExportFormatKind, ExportUi, normalize_export_options, step_rows, @@ -35,6 +35,7 @@ fn prefs(format: &str, export_to: &str) -> ExportPrefs { fn step(time: f64, action: Action, narration: &str, heading: Option<&str>, repeat: u32) -> Step { Step { time, + source: Source { clip: 0, time }, frame_time: time, action, position: (action != Action::Note).then(|| Point::new(0.5, 0.5)), @@ -128,4 +129,6 @@ fn a_recording_without_steps_says_how_to_get_some() { steps_failure(&StepsError::Failed("disk full".into())), "disk full" ); + let hidden = steps_failure(&StepsError::HiddenAreas); + assert!(hidden.contains("Sensitive mask"), "{hidden}"); } 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 8a7571e9cc2..c028c88aeca 100644 --- a/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs @@ -1580,6 +1580,10 @@ fn editor_shell_surfaces_match_the_literals_they_replaced() { tr::editor::export::steps::guide(), "One screenshot for each click, drag and marker, with what you said around it. Saved as Markdown and images, with a JSON copy for tools and agents.", ), + ( + tr::editor::export::steps::hidden_areas(), + "This recording has a Sensitive mask. Step screenshots come straight from the screen recording and would show what the mask hides, so steps cannot be exported while it is on the timeline.", + ), ( tr::editor::export::steps::none(), "No clicks or markers in this recording. Click through what you are showing, or add markers, and each one becomes a step.", diff --git a/apps/desktop-gpui/src/steps_export.rs b/apps/desktop-gpui/src/steps_export.rs index 52c99eb08f2..9717bd61684 100644 --- a/apps/desktop-gpui/src/steps_export.rs +++ b/apps/desktop-gpui/src/steps_export.rs @@ -2,27 +2,28 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use cap_project::{ - CursorEvents, ProjectConfiguration, RecordingMeta, StudioRecordingMeta, TimelineConfiguration, + CursorEvents, MaskKind, ProjectConfiguration, RecordingMeta, StudioRecordingMeta, + TimelineConfiguration, }; use cap_steps::{ - ButtonEvent, Captions, Document, DocumentStep, Marker, Point, PointerMove, Recording, Size, - Word, + ButtonEvent, Captions, ClipEvents, Document, DocumentStep, Marker, Point, PointerMove, Size, + Source, Word, }; pub(crate) const GUIDE_FILE: &str = "guide.md"; pub(crate) const GUIDE_DATA_FILE: &str = "guide.json"; pub(crate) const STEP_IMAGES_FOLDER: &str = "steps"; +const GUIDE_ENTRIES: [&str; 3] = [GUIDE_FILE, GUIDE_DATA_FILE, STEP_IMAGES_FOLDER]; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum StepsError { NoSteps, + HiddenAreas, Cancelled, Failed(String), } -const STOP_CLICK_WINDOW: f64 = 1.0; const OUTSIDE_FRAME: f64 = 0.001; -const MAX_FRAME_LEAD: f64 = 1.0; /// One recording segment. Cursor events are on the recording's clock, the /// timeline's source time starts at the segment's latest track start, and @@ -76,10 +77,10 @@ fn source_length(clip: &Clip) -> f64 { (media_duration(&clip.display) - clip.screen_offset).max(0.0) } -fn pointer_at(path: &[(f64, Point)], time: f64) -> Option { - let after = path.partition_point(|(moved, _)| *moved <= time); +fn pointer_at(path: &[PointerMove], time: f64) -> Option { + let after = path.partition_point(|moved| moved.time <= time); path.get(after.saturating_sub(1)) - .map(|(_, position)| *position) + .map(|moved| moved.position) } fn outside_frame(position: Point) -> bool { @@ -131,17 +132,6 @@ impl<'a> Playback<'a> { .map(|(start, _)| start + source_time), } } - - fn source(&self, output_time: f64) -> Option<(u32, f64)> { - match self { - Self::Edited(timeline) => timeline.source_for_output_time(output_time), - Self::BackToBack(spans) => spans - .iter() - .enumerate() - .rfind(|(_, (start, _))| *start <= output_time) - .map(|(index, (start, length))| (index as u32, (output_time - start).min(*length))), - } - } } fn caption_words(timeline: &TimelineConfiguration) -> Vec { @@ -166,13 +156,17 @@ fn caption_words(timeline: &TimelineConfiguration) -> Vec { words } -#[cfg(test)] -pub(crate) fn recording_events( - meta: &RecordingMeta, - project: &ProjectConfiguration, -) -> Result { - let clips = clips(meta); - Ok(events(project, &clips, &Playback::new(project, &clips)).0) +/// A Sensitive mask is drawn over the styled frame, after padding, zoom and +/// the 3D camera have moved the screen under it, so only the renderer knows +/// which part of the recorded screen it covers. Screenshots are cut from the +/// screen track below all of that and would show what the mask hides. +pub(crate) fn hides_areas(project: &ProjectConfiguration) -> bool { + project.timeline.as_ref().is_some_and(|timeline| { + timeline + .mask_segments + .iter() + .any(|mask| mask.enabled && matches!(mask.mask_type, MaskKind::Sensitive)) + }) } pub(crate) fn project_guide( @@ -180,99 +174,76 @@ pub(crate) fn project_guide( project: &ProjectConfiguration, ) -> cap_steps::Guide { let clips = clips(meta); - guide(project, &clips, &Playback::new(project, &clips)).1 -} - -/// The guide and the duration of the video it follows. The stop click is -/// already gone from the events (judged against the recording itself), so -/// the guide is built without a duration: an end the timeline trimmed would -/// otherwise cost a real click its step. -fn guide( - project: &ProjectConfiguration, - clips: &[Clip], - playback: &Playback, -) -> (f64, cap_steps::Guide) { - let (mut recording, anchors) = events(project, clips, playback); - let duration = std::mem::replace(&mut recording.duration, f64::INFINITY); - recording.moves.extend(anchors); - (duration, cap_steps::build_guide(&recording)) + guide(project, &clips, &Playback::new(project, &clips)) } -/// Returns the events and, for every button event, where the pointer was: -/// a click is placed from the uncut pointer path, because the pointer may -/// have reached it in footage the timeline cut. -fn events( - project: &ProjectConfiguration, - clips: &[Clip], - playback: &Playback, -) -> (Recording, Vec) { - let mut recording = Recording { - duration: playback.duration(), - ..Recording::default() - }; - let mut anchors = Vec::new(); +/// Actions are read on each clip's own clock and uncut pointer path, and +/// only then placed on the timeline: a clip's speed must not turn a +/// double-click into two clicks, and the pointer may have reached a click in +/// footage the timeline cut. +fn guide(project: &ProjectConfiguration, clips: &[Clip], playback: &Playback) -> cap_steps::Guide { + let mut steps = Vec::new(); for (index, clip) in clips.iter().enumerate() { let clip_index = index as u32; - let source_time = |time_ms: f64| time_ms / 1000.0 - clip.event_offset; - let mut path: Vec<(f64, Point)> = clip + let on_clip = |time_ms: f64| time_ms / 1000.0 - clip.event_offset; + let mut moves: Vec = clip .cursor .moves .iter() .filter(|event| event.time_ms.is_finite() && event.x.is_finite() && event.y.is_finite()) - .map(|event| (source_time(event.time_ms), Point::new(event.x, event.y))) + .map(|event| PointerMove { + time: on_clip(event.time_ms), + position: Point::new(event.x, event.y), + }) .collect(); - path.sort_by(|a, b| a.0.total_cmp(&b.0)); - let last_press = if index + 1 == clips.len() { - Some(source_length(clip)) - .filter(|length| *length > 0.0) - .map_or(f64::INFINITY, |length| length - STOP_CLICK_WINDOW) - } else { - f64::INFINITY - }; - - recording - .moves - .extend(path.iter().filter_map(|&(time, position)| { - Some(PointerMove { - time: playback.output_time(clip_index, time)?, - position, - }) - })); - for event in &clip.cursor.clicks { - let time = source_time(event.time_ms); - let position = pointer_at(&path, time); - if event.down && (time > last_press || position.is_some_and(outside_frame)) { - continue; - } - let Some(time) = playback.output_time(clip_index, time) else { - continue; - }; - recording.buttons.push(ButtonEvent { - time, + moves.sort_by(|a, b| a.time.total_cmp(&b.time)); + let buttons: Vec = clip + .cursor + .clicks + .iter() + .map(|event| ButtonEvent { + time: on_clip(event.time_ms), button: event.cursor_num, down: event.down, - }); - anchors.extend(position.map(|position| PointerMove { time, position })); - } + }) + .filter(|event| { + !(event.down && pointer_at(&moves, event.time).is_some_and(outside_frame)) + }) + .collect(); + let events = ClipEvents { + clip: clip_index, + stopped_at: (index + 1 == clips.len()) + .then(|| source_length(clip)) + .filter(|length| *length > 0.0), + moves: &moves, + buttons: &buttons, + }; + steps.extend(cap_steps::clip_steps(&events, |time| { + playback.output_time(clip_index, time) + })); } - recording.moves.sort_by(|a, b| a.time.total_cmp(&b.time)); - recording.buttons.sort_by(|a, b| a.time.total_cmp(&b.time)); - recording.markers = project + let mut markers: Vec = project .markers .iter() .filter_map(|marker| { Some(Marker { time: playback.output_time(marker.recording_clip, marker.time)?, + source: Source { + clip: marker.recording_clip, + time: marker.time, + }, label: marker.label.clone(), }) }) .collect(); - recording.markers.sort_by(|a, b| a.time.total_cmp(&b.time)); - if let Some(timeline) = &project.timeline { - recording.words = caption_words(timeline); - } - (recording, anchors) + markers.sort_by(|a, b| a.time.total_cmp(&b.time)); + let words = project + .timeline + .as_ref() + .map(caption_words) + .unwrap_or_default(); + cap_steps::build_guide(steps, &markers, &words) } fn settle( @@ -371,7 +342,7 @@ fn frame_at(path: &Path, seconds: f64) -> Result<(Size, Vec), String> { /// Blocking. The screenshots come from the screen track itself, not the /// styled video, so they are sharp and carry no cursor but the ring. The /// guide is written beside `folder` and moved in only once it is whole, so -/// a cancelled or failed export leaves an earlier guide there untouched. +/// a cancelled or failed export leaves an earlier guide there as it was. pub(crate) fn export_steps( meta: &RecordingMeta, project: &ProjectConfiguration, @@ -383,10 +354,13 @@ pub(crate) fn export_steps( ) -> Result, StepsError> { let clips = clips(meta); let playback = Playback::new(project, &clips); - let (duration, guide) = guide(project, &clips, &playback); + let guide = guide(project, &clips, &playback); if guide.steps.is_empty() { return Err(StepsError::NoSteps); } + if hides_areas(project) { + return Err(StepsError::HiddenAreas); + } let name = folder .file_name() .ok_or_else(|| StepsError::Failed("The guide needs a folder to be saved in".into()))? @@ -398,7 +372,7 @@ pub(crate) fn export_steps( cancel, progress, }; - let written = write_guide(&staging, &clips, &playback, guide, duration, &output) + let written = write_guide(&staging, &clips, &playback, guide, &output) .and_then(|names| publish(&staging, folder, &names).map_err(StepsError::Failed)); let _ = std::fs::remove_dir_all(&staging); written @@ -416,7 +390,6 @@ fn write_guide( clips: &[Clip], playback: &Playback, guide: cap_steps::Guide, - duration: f64, output: &Output, ) -> Result, StepsError> { let cancelled = || { @@ -438,18 +411,16 @@ fn write_guide( "{STEP_IMAGES_FOLDER}/{}", cap_steps::image_name(index + 1, total) ); - let pressed = playback.source(step.time); - playback - .source(step.frame_time) - .filter(|(clip, time)| { - pressed.is_none_or(|(pressed_clip, pressed_time)| { - *clip == pressed_clip && (0.0..=MAX_FRAME_LEAD).contains(&(pressed_time - time)) - }) - }) - .or(pressed) - .and_then(|(clip, time)| Some((clips.get(clip as usize)?, time))) - .ok_or_else(|| format!("Step {} is not on the timeline", index + 1)) - .and_then(|(clip, time)| frame_at(&clip.display, time + clip.screen_offset)) + let Source { clip, time } = step.source; + let shown = if playback.output_time(clip, step.frame_time).is_some() { + step.frame_time + } else { + time + }; + clips + .get(clip as usize) + .ok_or_else(|| format!("Step {} has no screen recording", index + 1)) + .and_then(|clip| frame_at(&clip.display, shown + clip.screen_offset)) .and_then(|(size, rgba)| { cap_steps::render_step_image(&rgba, size, &step) .ok_or_else(|| "The screen frame could not be read".to_string()) @@ -465,7 +436,7 @@ fn write_guide( let document = Document { title: output.title.to_string(), - duration, + duration: playback.duration(), intro: guide.intro, steps, }; @@ -480,15 +451,67 @@ fn write_guide( fn publish(staging: &Path, folder: &Path, names: &[String]) -> Result, String> { if folder.exists() { - std::fs::create_dir_all(folder.join(STEP_IMAGES_FOLDER)).map_err(|e| e.to_string())?; - for name in names { - std::fs::rename(staging.join(name), folder.join(name)).map_err(|e| e.to_string())?; - } + replace_guide(staging, folder)?; } else { std::fs::rename(staging, folder).map_err(|e| e.to_string())?; } Ok(names.iter().map(|name| folder.join(name)).collect()) } +/// Only the guide's own entries are swapped, because the folder is one the +/// user picked and may hold other files. The entries they replace wait in +/// `retired` until every new one is in. `retired` is deleted with its +/// contents only after that, so an entry that could not be put back after a +/// failed swap is still there. +fn replace_guide(staging: &Path, folder: &Path) -> Result<(), String> { + let mut retired = staging.as_os_str().to_owned(); + retired.push(".replaced"); + let retired = PathBuf::from(retired); + std::fs::create_dir(&retired).map_err(|e| e.to_string())?; + + let mut moved_out = Vec::new(); + let mut moved_in = Vec::new(); + let swapped = GUIDE_ENTRIES + .iter() + .try_for_each( + |entry| match std::fs::rename(folder.join(entry), retired.join(entry)) { + Ok(()) => { + moved_out.push(entry); + Ok(()) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error), + }, + ) + .and_then(|()| { + GUIDE_ENTRIES.iter().try_for_each(|entry| { + std::fs::rename(staging.join(entry), folder.join(entry))?; + moved_in.push(entry); + Ok(()) + }) + }); + let Err(error) = swapped else { + let _ = std::fs::remove_dir_all(&retired); + return Ok(()); + }; + + let restored = moved_in + .iter() + .try_for_each(|entry| std::fs::rename(folder.join(entry), staging.join(entry))) + .and_then(|()| { + moved_out + .iter() + .try_for_each(|entry| std::fs::rename(retired.join(entry), folder.join(entry))) + }); + let _ = std::fs::remove_dir(&retired); + Err(match restored { + Ok(()) => error.to_string(), + Err(_) => format!( + "{error}. The earlier guide was moved to {}", + retired.display() + ), + }) +} + #[cfg(test)] mod tests; diff --git a/apps/desktop-gpui/src/steps_export/tests.rs b/apps/desktop-gpui/src/steps_export/tests.rs index f9050c062e3..a97e42a4038 100644 --- a/apps/desktop-gpui/src/steps_export/tests.rs +++ b/apps/desktop-gpui/src/steps_export/tests.rs @@ -3,14 +3,16 @@ use std::sync::Mutex; use std::sync::atomic::AtomicBool; use cap_project::{ - CaptionTrackSegment, CaptionWord, ProjectConfiguration, RecordingMeta, TimelineMarker, + CaptionTrackSegment, CaptionWord, ClipTransition, ClipTransitionType, MaskSegment, + ProjectConfiguration, RecordingMeta, TimelineMarker, }; -use cap_steps::{Action, Captions, Point, Size, Step, crop_for}; +use cap_steps::{Action, Captions, Point, Size, Source, Step, crop_for}; use cap_verify::fixture::{FixtureSpec, SegmentSpec, Timing, VideoTrackSpec, write_fixture}; use serde_json::json; use super::{ - GUIDE_DATA_FILE, GUIDE_FILE, STEP_IMAGES_FOLDER, StepsError, export_steps, recording_events, + GUIDE_DATA_FILE, GUIDE_FILE, STEP_IMAGES_FOLDER, StepsError, caption_words, export_steps, + project_guide, publish, }; const FRAME: Size = Size { @@ -34,7 +36,6 @@ fn project(clicks: &[(f64, f64, f64)]) -> Project { project_with(clicks, |_| {}) } -/// The same project, with `patch` applied to its `recording-meta.json`. fn project_with(clicks: &[(f64, f64, f64)], patch: impl FnOnce(&mut serde_json::Value)) -> Project { let root = tempfile::tempdir().unwrap(); let bundle = root.path().join("steps.cap"); @@ -110,6 +111,7 @@ fn read_png(path: &Path) -> image::RgbaImage { fn click_step(x: f64, y: f64) -> Step { Step { time: 0.0, + source: Source { clip: 0, time: 0.0 }, frame_time: 0.0, action: Action::Click, position: Some(Point::new(x, y)), @@ -144,48 +146,52 @@ fn caption(start: f64, end: f64, text: &str, words: &[(f32, f32, &str)]) -> Capt } #[test] -fn events_come_out_in_seconds_at_their_positions() { +fn clicks_come_out_in_seconds_at_their_positions() { let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); - let recording = recording_events(&project.meta, &project.config).unwrap(); + let guide = project_guide(&project.meta, &project.config); - assert!((recording.duration - LENGTH).abs() < 0.2, "{recording:?}"); - assert_eq!(recording.buttons.len(), 4); - assert!((recording.buttons[0].time - 2.0).abs() < 1e-6); - assert_eq!(recording.buttons[0].button, cap_steps::LEFT_BUTTON); - assert!(recording.buttons[0].down); - assert!((recording.buttons[1].time - 2.08).abs() < 1e-6); - assert!(!recording.buttons[1].down); - assert_eq!(recording.moves.len(), 2); - assert!((recording.moves[0].time - 1.8).abs() < 1e-6); - assert_eq!(recording.moves[0].position, Point::new(0.25, 0.5)); + assert_eq!(guide.steps.len(), 2, "{guide:?}"); + for (step, (time, x, y)) in guide + .steps + .iter() + .zip([(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]) + { + assert_eq!(step.action, Action::Click); + assert!((step.time - time).abs() < 1e-6, "{guide:?}"); + assert_eq!(step.source.clip, 0); + assert!((step.source.time - time).abs() < 1e-6, "{guide:?}"); + assert_eq!(step.position, Some(Point::new(x, y))); + } } #[test] -fn events_in_cut_footage_are_dropped_and_the_rest_shift() { +fn clicks_in_cut_footage_are_dropped_and_the_rest_shift() { let mut project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); let timeline = project.config.timeline.as_mut().unwrap(); timeline.segments[0].start = 3.0; timeline.segments[0].end = 7.0; - let recording = recording_events(&project.meta, &project.config).unwrap(); + let guide = project_guide(&project.meta, &project.config); + + assert_eq!(guide.steps.len(), 1, "{guide:?}"); + assert!((guide.steps[0].time - 1.0).abs() < 1e-6, "{guide:?}"); + assert!((guide.steps[0].source.time - 4.0).abs() < 1e-6, "{guide:?}"); + assert_eq!(guide.steps[0].position, Some(Point::new(0.75, 0.25))); - assert!((recording.duration - 4.0).abs() < 1e-6, "{recording:?}"); - assert_eq!(recording.buttons.len(), 2, "{recording:?}"); - assert!((recording.buttons[0].time - 1.0).abs() < 1e-6); - assert_eq!(recording.moves.len(), 1); - assert!((recording.moves[0].time - 0.8).abs() < 1e-6); + export(&project).unwrap(); + let duration = guide_data(&project)["duration"].as_f64().unwrap(); + assert!((duration - 4.0).abs() < 1e-6, "{duration}"); } #[test] -fn a_faster_clip_brings_its_events_closer() { +fn a_faster_clip_brings_its_clicks_closer() { let mut project = project(&[(4.0, 0.75, 0.25)]); project.config.timeline.as_mut().unwrap().segments[0].timescale = 2.0; - let recording = recording_events(&project.meta, &project.config).unwrap(); + let guide = project_guide(&project.meta, &project.config); - assert!( - (recording.duration - LENGTH / 2.0).abs() < 0.2, - "{recording:?}" - ); - assert!((recording.buttons[0].time - 2.0).abs() < 1e-6); + assert_eq!(guide.steps.len(), 1, "{guide:?}"); + assert!((guide.steps[0].time - 2.0).abs() < 1e-6, "{guide:?}"); + assert!((guide.steps[0].source.time - 4.0).abs() < 1e-6, "{guide:?}"); + assert!((guide.steps[0].frame_time - 3.95).abs() < 1e-6, "{guide:?}"); } #[test] @@ -207,22 +213,26 @@ fn markers_and_captions_are_read_in_timeline_time() { ), caption(2.0, 3.0, "Then save", &[]), ]; - let recording = recording_events(&project.meta, &project.config).unwrap(); - - assert_eq!(recording.markers.len(), 1, "{recording:?}"); - assert_eq!(recording.markers[0].label, "Setup"); - assert!((recording.markers[0].time - 0.5).abs() < 1e-6); - let words: Vec<&str> = recording - .words - .iter() - .map(|word| word.text.as_str()) - .collect(); - assert_eq!(words, ["Open", "the", "menu.", "Then", "save"]); - assert!((recording.words[0].start - 0.2).abs() < 1e-4); - assert!((recording.words[2].end - 0.9).abs() < 1e-4); - assert!((recording.words[3].start - 2.0).abs() < 1e-4); - assert!((recording.words[3].end - 2.5).abs() < 1e-4); - assert!((recording.words[4].end - 3.0).abs() < 1e-4); + project.config.markers.push(TimelineMarker::new(0, 7.0)); + + let guide = project_guide(&project.meta, &project.config); + assert_eq!(guide.steps.len(), 2, "{guide:?}"); + assert_eq!(guide.steps[0].action, Action::Click); + assert_eq!(guide.steps[0].heading.as_deref(), Some("Setup")); + assert_eq!(guide.steps[0].narration, "Open the menu."); + assert_eq!(guide.steps[1].action, Action::Note); + assert_eq!(guide.steps[1].narration, "Then save"); + assert!((guide.steps[1].time - 4.0).abs() < 1e-6, "{guide:?}"); + assert_eq!(guide.steps[1].source, Source { clip: 0, time: 7.0 }); + + let words = caption_words(project.config.timeline.as_ref().unwrap()); + let spoken: Vec<&str> = words.iter().map(|word| word.text.as_str()).collect(); + assert_eq!(spoken, ["Open", "the", "menu.", "Then", "save"]); + assert!((words[0].start - 0.2).abs() < 1e-4); + assert!((words[2].end - 0.9).abs() < 1e-4); + assert!((words[3].start - 2.0).abs() < 1e-4); + assert!((words[3].end - 2.5).abs() < 1e-4); + assert!((words[4].end - 3.0).abs() < 1e-4); } #[test] @@ -401,6 +411,26 @@ fn guide_data(project: &Project) -> serde_json::Value { serde_json::from_slice(&std::fs::read(project.folder.join(GUIDE_DATA_FILE)).unwrap()).unwrap() } +fn listing(folder: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(folder) + .unwrap() + .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names +} + +fn mask(kind: &str) -> MaskSegment { + serde_json::from_value(json!({ + "start": 0.0, + "end": LENGTH, + "maskType": kind, + "center": { "x": 0.5, "y": 0.5 }, + "size": { "x": 0.3, "y": 0.3 }, + })) + .unwrap() +} + /// Cursor events are on the recording's clock; the timeline starts at the /// latest track start, and the screen file at the screen's own start. #[test] @@ -410,15 +440,9 @@ fn track_start_offsets_place_clicks_and_their_screenshots() { meta["segments"][0]["mic"] = json!({ "path": "content/segments/segment-0/mic.ogg", "start_time": 0.5 }); }); - let recording = recording_events(&offset.meta, &offset.config).unwrap(); - assert!( - (recording.buttons[0].time - 2.5).abs() < 1e-6, - "{recording:?}" - ); - assert!( - (recording.moves[0].time - 2.3).abs() < 1e-6, - "{recording:?}" - ); + let guide = project_guide(&offset.meta, &offset.config); + assert!((guide.steps[0].time - 2.5).abs() < 1e-6, "{guide:?}"); + assert!((guide.steps[0].frame_time - 2.45).abs() < 1e-6, "{guide:?}"); export(&offset).unwrap(); let plain = project(&[(2.8, 0.5, 0.5)]); @@ -487,14 +511,6 @@ fn a_cancelled_re_export_leaves_the_earlier_guide_as_it_was() { .iter() .map(|file| std::fs::read(file).unwrap()) .collect(); - let listing = |folder: &Path| { - let mut names: Vec<_> = std::fs::read_dir(folder) - .unwrap() - .map(|entry| entry.unwrap().file_name()) - .collect(); - names.sort(); - names - }; let beside = listing(project.folder.parent().unwrap()); let inside = listing(&project.folder.join(STEP_IMAGES_FOLDER)); @@ -540,3 +556,129 @@ fn cancelling_during_the_last_screenshot_still_cancels() { assert_eq!(result, Err(StepsError::Cancelled)); assert!(!project.folder.join(GUIDE_FILE).exists()); } + +#[test] +fn a_click_under_a_crossfade_shows_the_clip_it_was_made_in() { + let mut faded = project(&[(3.5, 0.5, 0.5)]); + let timeline = faded.config.timeline.as_mut().unwrap(); + let mut second = timeline.segments[0].clone(); + timeline.segments[0].end = 4.0; + second.start = 4.0; + timeline.segments.push(second); + timeline.transitions = vec![ClipTransition { + segment_index: 1, + kind: ClipTransitionType::CrossFade, + duration: 1.0, + }]; + export(&faded).unwrap(); + assert!((guide_data(&faded)["steps"][0]["time"].as_f64().unwrap() - 3.5).abs() < 1e-6); + + let plain = project(&[(3.5, 0.5, 0.5)]); + export(&plain).unwrap(); + assert_eq!(step_image(&faded, 1), step_image(&plain, 1)); +} + +#[test] +fn a_slowed_clip_keeps_its_double_click() { + let mut slowed = project(&[(2.0, 0.5, 0.5), (2.3, 0.5, 0.5)]); + slowed.config.timeline.as_mut().unwrap().segments[0].timescale = 0.5; + export(&slowed).unwrap(); + let data = guide_data(&slowed); + let steps = data["steps"].as_array().unwrap(); + assert_eq!(steps.len(), 1, "{data}"); + assert_eq!(steps[0]["action"], "doubleClick", "{data}"); + assert!( + (steps[0]["time"].as_f64().unwrap() - 4.0).abs() < 1e-6, + "{data}" + ); +} + +#[test] +fn a_sped_up_clip_keeps_its_clicks_apart() { + let mut fast = project(&[(2.0, 0.5, 0.5), (2.8, 0.5, 0.5)]); + fast.config.timeline.as_mut().unwrap().segments[0].timescale = 2.0; + export(&fast).unwrap(); + let data = guide_data(&fast); + let steps = data["steps"].as_array().unwrap(); + assert_eq!(steps.len(), 1, "{data}"); + assert_eq!(steps[0]["action"], "click", "{data}"); + assert_eq!(steps[0]["repeat"], 2, "{data}"); + assert!( + (steps[0]["time"].as_f64().unwrap() - 1.0).abs() < 1e-6, + "{data}" + ); +} + +#[test] +fn a_shorter_re_export_leaves_no_screenshots_from_the_longer_one() { + let longer = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25), (6.0, 0.5, 0.9)]); + export(&longer).unwrap(); + let kept = longer.folder.join("notes.txt"); + std::fs::write(&kept, "mine").unwrap(); + + let mut shorter = project(&[(2.0, 0.25, 0.5)]); + shorter.folder = longer.folder.clone(); + export(&shorter).unwrap(); + + assert_eq!( + listing(&longer.folder.join(STEP_IMAGES_FOLDER)), + ["step-01.png"] + ); + assert_eq!(guide_data(&shorter)["steps"].as_array().unwrap().len(), 1); + assert_eq!(std::fs::read_to_string(&kept).unwrap(), "mine"); + assert_eq!( + listing(longer.folder.parent().unwrap()), + ["guide", "steps.cap"] + ); +} + +#[test] +fn a_replacement_that_fails_part_way_puts_the_earlier_guide_back() { + let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); + let files = export(&project).unwrap(); + let before: Vec> = files + .iter() + .map(|file| std::fs::read(file).unwrap()) + .collect(); + + let staging = project.folder.with_file_name(".guide.staging"); + std::fs::create_dir(&staging).unwrap(); + std::fs::write(staging.join(GUIDE_FILE), "new").unwrap(); + std::fs::write(staging.join(GUIDE_DATA_FILE), "new").unwrap(); + let names = [ + GUIDE_FILE.to_string(), + GUIDE_DATA_FILE.to_string(), + format!("{STEP_IMAGES_FOLDER}/step-01.png"), + ]; + assert!(publish(&staging, &project.folder, &names).is_err()); + + for (file, bytes) in files.iter().zip(&before) { + assert_eq!(&std::fs::read(file).unwrap(), bytes, "{}", file.display()); + } + assert_eq!( + listing(&project.folder), + [GUIDE_DATA_FILE, GUIDE_FILE, STEP_IMAGES_FOLDER] + ); + assert_eq!( + listing(project.folder.parent().unwrap()), + [".guide.staging", "guide", "steps.cap"] + ); +} + +#[test] +fn a_recording_with_a_hidden_area_is_not_exported() { + let mut hidden = project(&[(2.0, 0.5, 0.5)]); + hidden.config.timeline.as_mut().unwrap().mask_segments = vec![mask("sensitive")]; + assert_eq!(export(&hidden), Err(StepsError::HiddenAreas)); + assert!(!hidden.folder.exists()); + assert_eq!(listing(hidden.folder.parent().unwrap()), ["steps.cap"]); +} + +#[test] +fn masks_that_hide_nothing_do_not_stop_an_export() { + let mut shown = project(&[(2.0, 0.5, 0.5)]); + let mut switched_off = mask("sensitive"); + switched_off.enabled = false; + shown.config.timeline.as_mut().unwrap().mask_segments = vec![switched_off, mask("highlight")]; + export(&shown).unwrap(); +} diff --git a/apps/desktop-gpui/steps/src/detect.rs b/apps/desktop-gpui/steps/src/detect.rs index 25f5038cec4..9c9ac56244a 100644 --- a/apps/desktop-gpui/steps/src/detect.rs +++ b/apps/desktop-gpui/steps/src/detect.rs @@ -1,8 +1,8 @@ use std::collections::HashMap; use crate::{ - Action, ButtonEvent, Guide, LEFT_BUTTON, Marker, Point, PointerMove, RIGHT_BUTTON, Recording, - Step, + Action, ButtonEvent, ClipEvents, Guide, LEFT_BUTTON, Marker, Point, PointerMove, RIGHT_BUTTON, + Source, Step, Word, }; const FRAME_LEAD: f64 = 0.05; @@ -19,14 +19,24 @@ struct Press { drag_to: Option, } -pub fn build_guide(recording: &Recording) -> Guide { - let moves = pointer_path(&recording.moves); - let mut presses = presses(&recording.buttons, &moves); - if recording.duration.is_finite() && recording.duration > 0.0 { - presses.retain(|press| press.time <= recording.duration - STOP_CLICK_WINDOW); +pub fn clip_steps(events: &ClipEvents, output_time: impl Fn(f64) -> Option) -> Vec { + let path = pointer_path(events.moves); + let mut buttons: Vec<&ButtonEvent> = events + .buttons + .iter() + .filter(|event| event.time.is_finite() && output_time(event.time).is_some()) + .collect(); + buttons.sort_by(|a, b| a.time.total_cmp(&b.time)); + let mut presses = presses(&buttons, &path); + if let Some(stopped_at) = events.stopped_at.filter(|time| time.is_finite()) { + presses.retain(|press| press.time <= stopped_at - STOP_CLICK_WINDOW); } - let steps = with_markers(pointer_steps(&presses), &recording.markers); - crate::narration::attach(recording, steps) + pointer_steps(events.clip, &presses, output_time) +} + +pub fn build_guide(mut steps: Vec, markers: &[Marker], words: &[Word]) -> Guide { + steps.sort_by(|a, b| a.time.total_cmp(&b.time)); + crate::narration::attach(words, with_markers(steps, markers)) } fn with_markers(mut steps: Vec, markers: &[Marker]) -> Vec { @@ -50,7 +60,8 @@ fn with_markers(mut steps: Vec, markers: &[Marker]) -> Vec { Some(step) => step.heading = heading, None => notes.push(Step { time: marker.time, - frame_time: marker.time.max(0.0), + source: marker.source, + frame_time: marker.source.time, action: Action::Note, position: None, drag_to: None, @@ -73,7 +84,11 @@ fn same_spot(a: Option, b: Option) -> bool { } } -fn pointer_steps(presses: &[Press]) -> Vec { +fn pointer_steps( + clip: u32, + presses: &[Press], + output_time: impl Fn(f64) -> Option, +) -> Vec { let mut steps = Vec::new(); let mut index = 0; while let Some(first) = presses.get(index) { @@ -93,8 +108,16 @@ fn pointer_steps(presses: &[Press]) -> Vec { } let double = count == 2 && first.button == LEFT_BUTTON && previous - first.time <= DOUBLE_CLICK_GAP; + index += count; + let Some(time) = output_time(first.time) else { + continue; + }; steps.push(Step { - time: first.time, + time, + source: Source { + clip, + time: first.time, + }, frame_time: (first.time - FRAME_LEAD).max(0.0), action: if first.drag_to.is_some() { Action::Drag @@ -111,7 +134,6 @@ fn pointer_steps(presses: &[Press]) -> Vec { heading: None, narration: String::new(), }); - index += count; } steps } @@ -140,16 +162,10 @@ fn position_at(path: &[PointerMove], time: f64) -> Option { .map(|event| event.position) } -fn presses(buttons: &[ButtonEvent], path: &[PointerMove]) -> Vec { - let mut events: Vec<&ButtonEvent> = buttons - .iter() - .filter(|event| event.time.is_finite()) - .collect(); - events.sort_by(|a, b| a.time.total_cmp(&b.time)); - +fn presses(buttons: &[&ButtonEvent], path: &[PointerMove]) -> Vec { let mut found: Vec = Vec::new(); let mut held: HashMap = HashMap::new(); - for event in events { + for event in buttons { if event.down { held.insert(event.button, found.len()); found.push(Press { diff --git a/apps/desktop-gpui/steps/src/frame.rs b/apps/desktop-gpui/steps/src/frame.rs index bb0a498a0e5..5543536ce78 100644 --- a/apps/desktop-gpui/steps/src/frame.rs +++ b/apps/desktop-gpui/steps/src/frame.rs @@ -84,7 +84,6 @@ pub fn crop_for(step: &Step, frame: Size) -> Rect { } } -/// `None` when the buffer is not a whole RGBA frame of that size. pub fn render_step_image(frame_rgba: &[u8], frame: Size, step: &Step) -> Option { let row_bytes = (frame.width as usize).checked_mul(4)?; let expected = row_bytes.checked_mul(frame.height as usize)?; diff --git a/apps/desktop-gpui/steps/src/lib.rs b/apps/desktop-gpui/steps/src/lib.rs index 10da0b77eb8..fdced3978a8 100644 --- a/apps/desktop-gpui/steps/src/lib.rs +++ b/apps/desktop-gpui/steps/src/lib.rs @@ -1,6 +1,8 @@ -//! Everything here is in output time, the seconds a viewer sees, and in -//! positions normalised to the recorded frame. Reading a project and decoding -//! its frames is the app's side. +//! Pointer events are read on their clip's own clock, the seconds since that +//! clip started recording: how fast someone clicked does not change with the +//! speed the clip is played at. A guide is in output time, the seconds a +//! viewer sees. Positions are normalised to the recorded frame. Reading a +//! project and decoding its frames is the app's side. mod detect; mod document; @@ -9,7 +11,7 @@ mod narration; use serde::{Deserialize, Serialize}; -pub use detect::build_guide; +pub use detect::{build_guide, clip_steps}; pub use document::{ Captions, Document, DocumentStep, image_name, instruction, json, markdown, timestamp, }; @@ -47,9 +49,23 @@ pub struct ButtonEvent { pub down: bool, } +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Source { + pub clip: u32, + pub time: f64, +} + +pub struct ClipEvents<'a> { + pub clip: u32, + pub stopped_at: Option, + pub moves: &'a [PointerMove], + pub buttons: &'a [ButtonEvent], +} + #[derive(Clone, Debug, PartialEq)] pub struct Marker { pub time: f64, + pub source: Source, pub label: String, } @@ -60,15 +76,6 @@ pub struct Word { pub text: String, } -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Recording { - pub duration: f64, - pub moves: Vec, - pub buttons: Vec, - pub markers: Vec, - pub words: Vec, -} - #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Action { @@ -82,6 +89,7 @@ pub enum Action { #[derive(Clone, Debug, PartialEq)] pub struct Step { pub time: f64, + pub source: Source, pub frame_time: f64, pub action: Action, pub position: Option, diff --git a/apps/desktop-gpui/steps/src/narration.rs b/apps/desktop-gpui/steps/src/narration.rs index 1ee75ee6127..d8280e49eb2 100644 --- a/apps/desktop-gpui/steps/src/narration.rs +++ b/apps/desktop-gpui/steps/src/narration.rs @@ -1,6 +1,7 @@ -use crate::{Guide, Recording, Step, Word}; +use crate::{Guide, Step, Word}; const SENTENCE_PAUSE: f64 = 1.0; +const SENTENCE_ENDS: [char; 6] = ['.', '!', '?', '。', '!', '?']; const EARLIER_STEP_WEIGHT: f64 = 1.5; const INTRO_LEAD: f64 = 4.0; @@ -12,10 +13,10 @@ struct Sentence { /// People mostly announce what they are about to do, so a step that has /// already happened counts as further away than one still to come. -pub(crate) fn attach(recording: &Recording, mut steps: Vec) -> Guide { +pub(crate) fn attach(words: &[Word], mut steps: Vec) -> Guide { let first_step = steps.first().map(|step| step.time); let mut intro: Vec = Vec::new(); - for sentence in sentences(&recording.words) { + for sentence in sentences(words) { let introduces = first_step.is_none_or(|first| sentence.end < first - INTRO_LEAD); match nearest(&steps, &sentence) { Some(index) if !introduces => { @@ -59,7 +60,7 @@ fn sentences(words: &[Word]) -> Vec { text: text.to_string(), }), } - open = !text.ends_with(['.', '!', '?']); + open = !text.ends_with(SENTENCE_ENDS); } found } diff --git a/apps/desktop-gpui/steps/tests/scenarios/double_click_in_slow_motion.json b/apps/desktop-gpui/steps/tests/scenarios/double_click_in_slow_motion.json new file mode 100644 index 00000000000..92ffbbeb236 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/double_click_in_slow_motion.json @@ -0,0 +1,21 @@ +{ + "about": "A double-click stays one when its clip is slowed to half speed: the gap that counts is the one it was made with, not the one it plays back with.", + "duration": 10, + "speed": 0.5, + "moves": [[1.0, 0.3, 0.3], [2.9, 0.4, 0.55]], + "buttons": [ + [3.0, 1, true], + [3.08, 1, false], + [3.3, 1, true], + [3.38, 1, false] + ], + "expect": { + "steps": [ + { + "action": "doubleClick", + "time": 6.0, + "at": [0.4, 0.55] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/narration_fullwidth_sentence_ends.json b/apps/desktop-gpui/steps/tests/scenarios/narration_fullwidth_sentence_ends.json new file mode 100644 index 00000000000..7c12f4eb355 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/narration_fullwidth_sentence_ends.json @@ -0,0 +1,46 @@ +{ + "about": "Japanese and Chinese sentences end in a full-width mark, so two said in one breath still go to their own steps.", + "duration": 12, + "moves": [[2.0, 0.3, 0.3], [5.6, 0.6, 0.6], [8.6, 0.5, 0.2]], + "buttons": [ + [2.3, 1, true], + [2.38, 1, false], + [5.8, 1, true], + [5.88, 1, false], + [8.8, 1, true], + [8.88, 1, false] + ], + "words": [ + [1.0, 1.6, "メニューを"], + [1.6, 2.2, "開きます。"], + [2.9, 4.2, "次に書き出しを"], + [4.2, 5.5, "選びますか?"], + [6.3, 7.4, "最后点击"], + [7.4, 8.6, "保存!"] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 2.3, + "at": [0.3, 0.3], + "says": ["メニューを 開きます。"], + "not_says": ["書き出し"] + }, + { + "action": "click", + "time": 5.8, + "at": [0.6, 0.6], + "says": ["次に書き出しを 選びますか?"], + "not_says": ["メニュー", "保存"] + }, + { + "action": "click", + "time": 8.8, + "at": [0.5, 0.2], + "says": ["最后点击 保存!"], + "not_says": ["書き出し"] + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/scenarios/separate_clicks_sped_up.json b/apps/desktop-gpui/steps/tests/scenarios/separate_clicks_sped_up.json new file mode 100644 index 00000000000..6f9ff7d6028 --- /dev/null +++ b/apps/desktop-gpui/steps/tests/scenarios/separate_clicks_sped_up.json @@ -0,0 +1,22 @@ +{ + "about": "Two unhurried clicks on one spot stay two clicks when their clip is sped up to double speed.", + "duration": 10, + "speed": 2, + "moves": [[1.0, 0.3, 0.3], [2.9, 0.4, 0.55]], + "buttons": [ + [3.0, 1, true], + [3.08, 1, false], + [3.8, 1, true], + [3.88, 1, false] + ], + "expect": { + "steps": [ + { + "action": "click", + "time": 1.5, + "at": [0.4, 0.55], + "repeat": 2 + } + ] + } +} diff --git a/apps/desktop-gpui/steps/tests/spec.rs b/apps/desktop-gpui/steps/tests/spec.rs index 4a2b1781af7..5d1e921742a 100644 --- a/apps/desktop-gpui/steps/tests/spec.rs +++ b/apps/desktop-gpui/steps/tests/spec.rs @@ -1,9 +1,9 @@ use std::path::Path; use cap_steps::{ - Action, ButtonEvent, Captions, Document, DocumentStep, Guide, LEFT_BUTTON, Marker, Point, - PointerMove, Recording, Rect, Size, Step, Word, build_guide, crop_for, encode_png, image_name, - json, markdown, render_step_image, timestamp, + Action, ButtonEvent, Captions, ClipEvents, Document, DocumentStep, Guide, LEFT_BUTTON, Marker, + Point, PointerMove, Rect, Size, Source, Step, Word, build_guide, clip_steps, crop_for, + encode_png, image_name, json, markdown, render_step_image, timestamp, }; use serde::Deserialize; @@ -16,6 +16,8 @@ struct Scenario { #[allow(dead_code)] about: String, duration: f64, + #[serde(default = "normal_speed")] + speed: f64, #[serde(default)] moves: Vec<(f64, f64, f64)>, #[serde(default)] @@ -58,10 +60,51 @@ fn once() -> u32 { 1 } +fn normal_speed() -> f64 { + 1.0 +} + +#[derive(Default)] +struct Recording { + duration: f64, + speed: f64, + moves: Vec, + buttons: Vec, + markers: Vec<(f64, String)>, + words: Vec, +} + +fn guide_of(recording: &Recording) -> Guide { + let events = ClipEvents { + clip: 0, + stopped_at: Some(recording.duration).filter(|duration| *duration > 0.0), + moves: &recording.moves, + buttons: &recording.buttons, + }; + let markers: Vec = recording + .markers + .iter() + .map(|(time, label)| Marker { + time: *time, + source: Source { + clip: 0, + time: time * recording.speed, + }, + label: label.clone(), + }) + .collect(); + build_guide( + clip_steps(&events, |time| Some(time / recording.speed)), + &markers, + &recording.words, + ) +} + impl Scenario { fn recording(&self) -> Recording { Recording { duration: self.duration, + speed: self.speed, moves: self .moves .iter() @@ -75,14 +118,7 @@ impl Scenario { .iter() .map(|&(time, button, down)| ButtonEvent { time, button, down }) .collect(), - markers: self - .markers - .iter() - .map(|(time, label)| Marker { - time: *time, - label: label.clone(), - }) - .collect(), + markers: self.markers.clone(), words: self .words .iter() @@ -130,7 +166,7 @@ fn says(narration: &str, fragment: &str) -> bool { fn judge(text: &str) -> Result<(), String> { let scenario: Scenario = serde_json::from_str(text).map_err(|error| error.to_string())?; - let guide = build_guide(&scenario.recording()); + let guide = guide_of(&scenario.recording()); let mut problems = Vec::new(); for fragment in &scenario.expect.intro { if !says(&guide.intro, fragment) { @@ -239,6 +275,9 @@ scenarios!( no_events, two_spots_fast, long_press_is_a_click, + double_click_in_slow_motion, + separate_clicks_sped_up, + narration_fullwidth_sentence_ends, ); /// Scores a folder of scenario files of your own: set @@ -275,6 +314,7 @@ fn extra_scenarios() { fn click_at(time: f64, x: f64, y: f64) -> Recording { Recording { duration: time + 10.0, + speed: 1.0, moves: vec![PointerMove { time: 0.0, position: Point::new(x, y), @@ -297,28 +337,84 @@ fn click_at(time: f64, x: f64, y: f64) -> Recording { #[test] fn the_frame_is_taken_just_before_the_press() { - let guide = build_guide(&click_at(4.0, 0.5, 0.5)); + let guide = guide_of(&click_at(4.0, 0.5, 0.5)); assert_eq!(guide.steps.len(), 1); assert!((guide.steps[0].frame_time - 3.95).abs() < 1e-9); - let guide = build_guide(&click_at(0.02, 0.5, 0.5)); + let guide = guide_of(&click_at(0.02, 0.5, 0.5)); assert_eq!(guide.steps.len(), 1); assert_eq!(guide.steps[0].frame_time, 0.0); } +#[test] +fn a_step_keeps_the_clip_and_moment_it_was_recorded_at() { + let mut recording = click_at(4.0, 0.5, 0.5); + recording.speed = 2.0; + let guide = guide_of(&recording); + assert_eq!(guide.steps.len(), 1); + assert_eq!(guide.steps[0].time, 2.0); + assert_eq!(guide.steps[0].source, Source { clip: 0, time: 4.0 }); + assert!((guide.steps[0].frame_time - 3.95).abs() < 1e-9); +} + +#[test] +fn clicks_cut_from_the_timeline_are_left_out_before_actions_are_read() { + let mut recording = click_at(4.0, 0.5, 0.5); + for (time, down) in [(4.3, true), (4.38, false)] { + recording.buttons.push(ButtonEvent { + time, + button: LEFT_BUTTON, + down, + }); + } + let events = ClipEvents { + clip: 3, + stopped_at: None, + moves: &recording.moves, + buttons: &recording.buttons, + }; + let steps = clip_steps(&events, |time| (time >= 4.2).then_some(time - 4.2)); + assert_eq!(steps.len(), 1); + assert_eq!(steps[0].action, Action::Click); + assert!((steps[0].time - 0.1).abs() < 1e-9); + assert_eq!(steps[0].source.clip, 3); + assert!((steps[0].source.time - 4.3).abs() < 1e-9); +} + +#[test] +fn steps_from_several_clips_are_put_in_output_order() { + let later = click_at(1.0, 0.2, 0.2); + let earlier = click_at(5.0, 0.8, 0.8); + let clip = |clip, recording: &Recording, starts: f64| { + clip_steps( + &ClipEvents { + clip, + stopped_at: None, + moves: &recording.moves, + buttons: &recording.buttons, + }, + |time| Some(starts + time), + ) + }; + let mut steps = clip(0, &later, 20.0); + steps.extend(clip(1, &earlier, 0.0)); + let guide = build_guide(steps, &[], &[]); + let order: Vec = guide.steps.iter().map(|step| step.source.clip).collect(); + assert_eq!(order, [1, 0]); +} + #[test] fn a_note_is_framed_at_its_marker() { - let guide = build_guide(&Recording { + let guide = guide_of(&Recording { duration: 20.0, - markers: vec![Marker { - time: 6.5, - label: "Overview".into(), - }], + speed: 2.0, + markers: vec![(6.5, "Overview".into())], ..Recording::default() }); assert_eq!(guide.steps.len(), 1); assert_eq!(guide.steps[0].action, Action::Note); - assert_eq!(guide.steps[0].frame_time, 6.5); + assert_eq!(guide.steps[0].time, 6.5); + assert_eq!(guide.steps[0].frame_time, 13.0); } #[test] @@ -343,7 +439,7 @@ fn events_out_of_order_still_give_steps_in_time_order() { button: LEFT_BUTTON, down: true, }); - let guide = build_guide(&recording); + let guide = guide_of(&recording); assert_eq!(guide.steps.len(), 2); assert!((guide.steps[0].time - 3.0).abs() < 1e-9); assert!((guide.steps[1].time - 8.0).abs() < 1e-9); @@ -372,7 +468,7 @@ fn broken_numbers_are_ignored_not_fatal() { end: 1.0, text: "lost".into(), }); - let guide = build_guide(&recording); + let guide = guide_of(&recording); assert_eq!(guide.steps.len(), 1); assert!(near(guide.steps[0].position, Some((0.5, 0.5)))); assert!(!says(&guide.steps[0].narration, "lost")); @@ -381,7 +477,7 @@ fn broken_numbers_are_ignored_not_fatal() { #[test] fn positions_outside_the_frame_are_pulled_onto_it() { - let guide = build_guide(&click_at(4.0, 1.2, -0.1)); + let guide = guide_of(&click_at(4.0, 1.2, -0.1)); assert_eq!(guide.steps.len(), 1); assert!(near(guide.steps[0].position, Some((1.0, 0.0)))); } @@ -389,6 +485,7 @@ fn positions_outside_the_frame_are_pulled_onto_it() { fn step(action: Action, position: Option<(f64, f64)>, drag_to: Option<(f64, f64)>) -> Step { Step { time: 4.0, + source: Source { clip: 0, time: 4.0 }, frame_time: 3.95, action, position: position.map(|(x, y)| Point::new(x, y)), @@ -749,6 +846,7 @@ fn document_step( DocumentStep { step: Step { time, + source: Source { clip: 0, time }, frame_time: time, action, position: (action != Action::Note).then(|| Point::new(0.5, 0.5)), From acc9ced1cf2f5326f5eb20baa9e50f8536ddbf8d Mon Sep 17 00:00:00 2001 From: Aatman Jain Date: Sat, 28 Nov 2026 16:15:36 +0000 Subject: [PATCH 3/6] fix(desktop-gpui): export steps from recordings left as fragments A Studio recording that was never remuxed keeps its screen track as a folder of init.mp4 and .m4s fragments, which the editor opens as it is. Steps export opened every screen track as a single file, so the first screenshot failed with "Is a directory", and a recording with no timeline read as zero seconds long and had no steps at all. Folders now go through open_fragmented_input, for the screenshots and for the duration. --- apps/desktop-gpui/Cargo.lock | 1 + apps/desktop-gpui/Cargo.toml | 4 + apps/desktop-gpui/src/steps_export.rs | 73 +++++++++++++--- apps/desktop-gpui/src/steps_export/tests.rs | 97 +++++++++++++++++++++ 4 files changed, 164 insertions(+), 11 deletions(-) diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock index 9ca8ae3ca99..71f3ebc4931 100644 --- a/apps/desktop-gpui/Cargo.lock +++ b/apps/desktop-gpui/Cargo.lock @@ -1599,6 +1599,7 @@ dependencies = [ "cap-timestamp", "cap-utils", "cap-verify", + "cap-video-decode", "cc", "chrono", "cidre", diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml index 437c7f15190..b27d8d07259 100644 --- a/apps/desktop-gpui/Cargo.toml +++ b/apps/desktop-gpui/Cargo.toml @@ -90,6 +90,10 @@ cap-rendering = { path = "../../crates/rendering" } # Already in this lockfile through cap-rendering, so naming it only makes the # edge direct. cap-camera-effects = { path = "../../crates/camera-effects" } +# Opens a screen track left as a folder of fragments (`src/steps_export.rs`). +# Already in this lockfile through cap-rendering, so naming it only makes the +# edge direct. +cap-video-decode = { path = "../../crates/video-decode" } # The blur worker's device/queue/texture types. Must stay on cap-rendering's # wgpu 25 line (the vendored wgpu-hal `[patch.crates-io]` below applies to # it); gpui's own wgpu 29 is a separate tree and never touches these types. diff --git a/apps/desktop-gpui/src/steps_export.rs b/apps/desktop-gpui/src/steps_export.rs index 9717bd61684..8bd26bfdd46 100644 --- a/apps/desktop-gpui/src/steps_export.rs +++ b/apps/desktop-gpui/src/steps_export.rs @@ -67,9 +67,56 @@ fn clips(meta: &RecordingMeta) -> Vec { } } +/// A recording that was never remuxed keeps its screen track as a folder of +/// `init.mp4` and `.m4s` fragments, which the editor plays as it is. +enum ScreenTrack { + File(ffmpeg::format::context::Input), + Fragments(cap_enc_ffmpeg::SegmentedInput), +} + +impl ScreenTrack { + fn open(path: &Path) -> Result { + if path.is_dir() { + cap_video_decode::ffmpeg::open_fragmented_input(path).map(Self::Fragments) + } else { + ffmpeg::format::input(path) + .map(Self::File) + .map_err(|error| error.to_string()) + } + } + + fn input(&self) -> &ffmpeg::format::context::Input { + match self { + Self::File(input) => input, + Self::Fragments(fragments) => fragments.input(), + } + } + + fn seek(&mut self, position: i64) -> Result<(), ffmpeg::Error> { + match self { + Self::File(input) => input.seek(position, ..position), + Self::Fragments(fragments) => fragments.seek(position), + } + } + + fn next_packet(&mut self) -> Result, ffmpeg::Error> { + match self { + Self::File(input) => Ok(input.packets().next().map(|(_, packet)| packet)), + Self::Fragments(fragments) => { + let mut packet = ffmpeg::Packet::empty(); + match fragments.read_packet(&mut packet) { + Ok(()) => Ok(Some(packet)), + Err(ffmpeg::Error::Eof) => Ok(None), + Err(error) => Err(error), + } + } + } + } +} + fn media_duration(path: &Path) -> f64 { - ffmpeg::format::input(path) - .map(|input| input.duration().max(0) as f64 / f64::from(ffmpeg::ffi::AV_TIME_BASE)) + ScreenTrack::open(path) + .map(|track| track.input().duration().max(0) as f64 / f64::from(ffmpeg::ffi::AV_TIME_BASE)) .unwrap_or(0.0) } @@ -264,8 +311,9 @@ fn settle( fn frame_at(path: &Path, seconds: f64) -> Result<(Size, Vec), String> { use ffmpeg::rescale::{Rescale, TIME_BASE}; - let mut input = ffmpeg::format::input(path).map_err(|error| error.to_string())?; - let stream = input + let mut track = ScreenTrack::open(path)?; + let stream = track + .input() .streams() .best(ffmpeg::media::Type::Video) .ok_or("No video stream found")?; @@ -285,8 +333,8 @@ fn frame_at(path: &Path, seconds: f64) -> Result<(Size, Vec), String> { .map_err(|error| error.to_string())?; if seconds > 0.0 { let position = target.rescale(time_base, TIME_BASE); - input - .seek(position, ..position) + track + .seek(position) .map_err(|error| format!("Failed to seek to {seconds:.3}s: {error}"))?; } @@ -294,16 +342,19 @@ fn frame_at(path: &Path, seconds: f64) -> Result<(Size, Vec), String> { let mut next = ffmpeg::frame::Video::empty(); let mut have_shown = false; let mut settled = false; - for (stream, packet) in input.packets() { - if stream.index() != stream_index || decoder.send_packet(&packet).is_err() { + while !settled { + let Some(packet) = track + .next_packet() + .map_err(|error| format!("Failed to read {}: {error}", path.display()))? + else { + break; + }; + if packet.stream() != stream_index || decoder.send_packet(&packet).is_err() { continue; } while !settled && decoder.receive_frame(&mut next).is_ok() { settled = settle(&mut shown, &mut next, &mut have_shown, target); } - if settled { - break; - } } if !settled && decoder.send_eof().is_ok() { while !settled && decoder.receive_frame(&mut next).is_ok() { diff --git a/apps/desktop-gpui/src/steps_export/tests.rs b/apps/desktop-gpui/src/steps_export/tests.rs index a97e42a4038..d42824267a7 100644 --- a/apps/desktop-gpui/src/steps_export/tests.rs +++ b/apps/desktop-gpui/src/steps_export/tests.rs @@ -1,6 +1,7 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::sync::atomic::AtomicBool; +use std::time::Duration; use cap_project::{ CaptionTrackSegment, CaptionWord, ClipTransition, ClipTransitionType, MaskSegment, @@ -665,6 +666,102 @@ fn a_replacement_that_fails_part_way_puts_the_earlier_guide_back() { ); } +const FRAGMENTS: &str = "content/segments/segment-0/display"; + +/// A screen track left as a folder of `init.mp4` and `.m4s` fragments, which +/// the editor opens as it is, and the same footage converted to one file. +/// Neighbouring frames differ, so a screenshot one frame off does not match. +fn fragmented_and_converted(clicks: &[(f64, f64, f64)]) -> (Project, Project) { + use cap_enc_ffmpeg::segmented_stream::{SegmentedVideoEncoder, SegmentedVideoEncoderConfig}; + + let fragmented = project_with(clicks, |meta| { + meta["segments"][0]["display"]["path"] = FRAGMENTS.into(); + }); + let folder = fragmented.meta.project_path.join(FRAGMENTS); + ffmpeg::init().unwrap(); + let mut encoder = SegmentedVideoEncoder::init( + folder.clone(), + cap_media_info::VideoInfo { + pixel_format: cap_media_info::Pixel::NV12, + width: FRAME.width, + height: FRAME.height, + time_base: ffmpeg::Rational(1, 1_000_000), + frame_rate: ffmpeg::Rational(30, 1), + }, + SegmentedVideoEncoderConfig { + segment_duration: Duration::from_secs(1), + ..Default::default() + }, + ) + .unwrap(); + for index in 0..(LENGTH * 30.0) as u64 { + let mut frame = + ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, FRAME.width, FRAME.height); + frame.data_mut(0).fill(16 + (index * 7 % 200) as u8); + frame.data_mut(1).fill(128); + encoder + .queue_frame(frame, Duration::from_micros(index * 1_000_000 / 30)) + .unwrap(); + } + encoder.finish().unwrap(); + + let mut fragments: Vec = std::fs::read_dir(&folder) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|extension| extension == "m4s")) + .collect(); + cap_enc_ffmpeg::fragment_order::sort_fragment_paths(&mut fragments); + assert!(fragments.len() >= 4, "{fragments:?}"); + let converted = project(clicks); + cap_enc_ffmpeg::remux::concatenate_m4s_segments_with_init( + &folder.join("init.mp4"), + &fragments, + &converted + .meta + .project_path + .join(FRAGMENTS) + .with_extension("mp4"), + ) + .unwrap(); + (fragmented, converted) +} + +#[test] +fn a_recording_left_as_fragments_exports_the_screenshots_of_its_one_file_form() { + let clicks = [(1.5, 0.5, 0.5), (4.2, 0.5, 0.5), (6.8, 0.5, 0.5)]; + let (fragmented, converted) = fragmented_and_converted(&clicks); + export(&fragmented).unwrap(); + export(&converted).unwrap(); + + for number in 1..=clicks.len() { + assert_eq!( + step_image(&fragmented, number), + step_image(&converted, number), + "step {number}" + ); + } + assert_ne!(step_image(&fragmented, 1), step_image(&fragmented, 2)); + assert_ne!(step_image(&fragmented, 2), step_image(&fragmented, 3)); +} + +#[test] +fn a_recording_left_as_fragments_that_was_never_edited_keeps_its_length() { + let clicks = [(1.5, 0.5, 0.5), (4.2, 0.5, 0.5), (7.9, 0.5, 0.5)]; + let (mut fragmented, mut converted) = fragmented_and_converted(&clicks); + fragmented.config.timeline = None; + converted.config.timeline = None; + export(&fragmented).unwrap(); + export(&converted).unwrap(); + + let data = guide_data(&fragmented); + assert_eq!(data["steps"], guide_data(&converted)["steps"]); + assert_eq!(data["steps"].as_array().unwrap().len(), 2, "{data}"); + assert!( + (data["duration"].as_f64().unwrap() - LENGTH).abs() < 0.05, + "{data}" + ); +} + #[test] fn a_recording_with_a_hidden_area_is_not_exported() { let mut hidden = project(&[(2.0, 0.5, 0.5)]); From 2983220f28aa28c8537d7856f9469017fac1c686 Mon Sep 17 00:00:00 2001 From: Aatman Jain Date: Sat, 28 Nov 2026 17:54:33 +0000 Subject: [PATCH 4/6] fix(desktop-gpui): replace only the guide's own files on re-export Re-exporting Steps into a folder that already held a guide moved the whole steps/ folder aside and deleted it, so anything else kept in it went with the old screenshots. The swap is now file by file. It replaces guide.md, guide.json and the screenshots this export writes, and removes the screenshots the earlier guide.json lists that the new guide no longer has. A listed path counts only as steps/step-.png, so an edited guide.json cannot point the export at other files. Everything else in the folder and in steps/ stays where it is, and a folder sitting where a guide file would go fails the export instead of being deleted. A failed swap still puts the earlier guide back. It now tries every file rather than stopping at the first that will not move, and removes steps/ again if this export created it. --- apps/desktop-gpui/src/steps_export.rs | 109 +++++++++++----- apps/desktop-gpui/src/steps_export/tests.rs | 136 ++++++++++++++++++++ apps/desktop-gpui/steps/src/document.rs | 36 +++++- apps/desktop-gpui/steps/src/lib.rs | 3 +- apps/desktop-gpui/steps/tests/spec.rs | 61 ++++++++- 5 files changed, 306 insertions(+), 39 deletions(-) diff --git a/apps/desktop-gpui/src/steps_export.rs b/apps/desktop-gpui/src/steps_export.rs index 8bd26bfdd46..01cf3ee2566 100644 --- a/apps/desktop-gpui/src/steps_export.rs +++ b/apps/desktop-gpui/src/steps_export.rs @@ -13,7 +13,6 @@ use cap_steps::{ pub(crate) const GUIDE_FILE: &str = "guide.md"; pub(crate) const GUIDE_DATA_FILE: &str = "guide.json"; pub(crate) const STEP_IMAGES_FOLDER: &str = "steps"; -const GUIDE_ENTRIES: [&str; 3] = [GUIDE_FILE, GUIDE_DATA_FILE, STEP_IMAGES_FOLDER]; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum StepsError { @@ -502,42 +501,78 @@ fn write_guide( fn publish(staging: &Path, folder: &Path, names: &[String]) -> Result, String> { if folder.exists() { - replace_guide(staging, folder)?; + replace_guide(staging, folder, names)?; } else { std::fs::rename(staging, folder).map_err(|e| e.to_string())?; } Ok(names.iter().map(|name| folder.join(name)).collect()) } -/// Only the guide's own entries are swapped, because the folder is one the -/// user picked and may hold other files. The entries they replace wait in -/// `retired` until every new one is in. `retired` is deleted with its -/// contents only after that, so an entry that could not be put back after a -/// failed swap is still there. -fn replace_guide(staging: &Path, folder: &Path) -> Result<(), String> { +/// `guide.json` is read back from a folder the user owns and may have been +/// edited, so what it lists counts only under a name an export gives its +/// screenshots, directly inside the screenshots folder. +fn earlier_screenshots(folder: &Path) -> Vec { + let screenshots = format!("{STEP_IMAGES_FOLDER}/"); + std::fs::read_to_string(folder.join(GUIDE_DATA_FILE)) + .map(|data| cap_steps::listed_images(&data)) + .unwrap_or_default() + .into_iter() + .filter(|image| { + image + .strip_prefix(&screenshots) + .is_some_and(cap_steps::is_image_name) + }) + .collect() +} + +fn retire(file: &Path, retired: &Path) -> std::io::Result { + match std::fs::symlink_metadata(file) { + Ok(found) if found.is_dir() => Err(std::io::Error::new( + std::io::ErrorKind::IsADirectory, + format!("{} is a folder", file.display()), + )), + Ok(_) => std::fs::rename(file, retired).map(|()| true), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + +/// The folder is one the user picked, and it and its screenshots folder may +/// hold other files. Only the guide's own files are swapped: the ones this +/// export writes, and the screenshots the earlier guide's `guide.json` +/// lists. The files they replace wait in `retired` until every new one is +/// in. `retired` is deleted with its contents only after that, so a file +/// that could not be put back after a failed swap is still there. +fn replace_guide(staging: &Path, folder: &Path, names: &[String]) -> Result<(), String> { let mut retired = staging.as_os_str().to_owned(); retired.push(".replaced"); let retired = PathBuf::from(retired); - std::fs::create_dir(&retired).map_err(|e| e.to_string())?; + + let mut outgoing = names.to_vec(); + for image in earlier_screenshots(folder) { + if !outgoing.contains(&image) { + outgoing.push(image); + } + } + let screenshots = folder.join(STEP_IMAGES_FOLDER); + let made_screenshots_folder = !screenshots.exists(); let mut moved_out = Vec::new(); let mut moved_in = Vec::new(); - let swapped = GUIDE_ENTRIES - .iter() - .try_for_each( - |entry| match std::fs::rename(folder.join(entry), retired.join(entry)) { - Ok(()) => { - moved_out.push(entry); - Ok(()) + let swapped = std::fs::create_dir_all(retired.join(STEP_IMAGES_FOLDER)) + .and_then(|()| { + outgoing.iter().try_for_each(|name| { + if retire(&folder.join(name), &retired.join(name))? { + moved_out.push(name); } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(error) => Err(error), - }, - ) + Ok(()) + }) + }) + .and_then(|()| std::fs::create_dir_all(&screenshots)) .and_then(|()| { - GUIDE_ENTRIES.iter().try_for_each(|entry| { - std::fs::rename(staging.join(entry), folder.join(entry))?; - moved_in.push(entry); + names.iter().try_for_each(|name| { + std::fs::rename(staging.join(name), folder.join(name))?; + moved_in.push(name); Ok(()) }) }); @@ -546,21 +581,25 @@ fn replace_guide(staging: &Path, folder: &Path) -> Result<(), String> { return Ok(()); }; - let restored = moved_in - .iter() - .try_for_each(|entry| std::fs::rename(folder.join(entry), staging.join(entry))) - .and_then(|()| { - moved_out - .iter() - .try_for_each(|entry| std::fs::rename(retired.join(entry), folder.join(entry))) - }); + for name in moved_in { + let _ = std::fs::rename(folder.join(name), staging.join(name)); + } + let mut stranded = false; + for name in moved_out { + stranded |= std::fs::rename(retired.join(name), folder.join(name)).is_err(); + } + if made_screenshots_folder { + let _ = std::fs::remove_dir(&screenshots); + } + let _ = std::fs::remove_dir(retired.join(STEP_IMAGES_FOLDER)); let _ = std::fs::remove_dir(&retired); - Err(match restored { - Ok(()) => error.to_string(), - Err(_) => format!( + Err(if stranded { + format!( "{error}. The earlier guide was moved to {}", retired.display() - ), + ) + } else { + error.to_string() }) } diff --git a/apps/desktop-gpui/src/steps_export/tests.rs b/apps/desktop-gpui/src/steps_export/tests.rs index d42824267a7..4b4d30ecfd2 100644 --- a/apps/desktop-gpui/src/steps_export/tests.rs +++ b/apps/desktop-gpui/src/steps_export/tests.rs @@ -633,6 +633,135 @@ fn a_shorter_re_export_leaves_no_screenshots_from_the_longer_one() { ); } +#[test] +fn a_re_export_leaves_other_files_in_the_screenshots_folder_alone() { + let longer = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25), (6.0, 0.5, 0.9)]); + export(&longer).unwrap(); + let images = longer.folder.join(STEP_IMAGES_FOLDER); + let mine = [ + images.join("diagram.png"), + images.join("step-09.png"), + images.join("raw").join("step-02.png"), + ]; + std::fs::create_dir(images.join("raw")).unwrap(); + for file in &mine { + std::fs::write(file, "mine").unwrap(); + } + let replaced = step_image(&longer, 1); + + let mut shorter = project(&[(5.0, 0.6, 0.6)]); + shorter.folder = longer.folder.clone(); + export(&shorter).unwrap(); + + assert_eq!( + listing(&images), + ["diagram.png", "raw", "step-01.png", "step-09.png"] + ); + for file in &mine { + assert_eq!( + std::fs::read_to_string(file).unwrap(), + "mine", + "{}", + file.display() + ); + } + assert_ne!(step_image(&shorter, 1), replaced); + assert_eq!( + listing(longer.folder.parent().unwrap()), + ["guide", "steps.cap"] + ); +} + +#[test] +fn an_earlier_guide_that_lists_files_elsewhere_has_none_of_them_removed() { + let project = project(&[(2.0, 0.25, 0.5)]); + export(&project).unwrap(); + let beside = project.folder.parent().unwrap(); + let images = project.folder.join(STEP_IMAGES_FOLDER); + let mine = [ + beside.join("step-08.png"), + project.folder.join("step-07.png"), + images.join("diagram.png"), + images.join("raw").join("step-02.png"), + ]; + std::fs::create_dir(images.join("raw")).unwrap(); + for file in &mine { + std::fs::write(file, "mine").unwrap(); + } + let mut data = guide_data(&project); + data["steps"] = json!([ + { "image": "../step-08.png" }, + { "image": "steps/../../step-08.png" }, + { "image": mine[0].to_string_lossy() }, + { "image": "step-07.png" }, + { "image": "steps/../step-07.png" }, + { "image": "steps/diagram.png" }, + { "image": "steps/raw/step-02.png" }, + ]); + std::fs::write( + project.folder.join(GUIDE_DATA_FILE), + serde_json::to_vec(&data).unwrap(), + ) + .unwrap(); + + export(&project).unwrap(); + + for file in &mine { + assert_eq!( + std::fs::read_to_string(file).unwrap(), + "mine", + "{}", + file.display() + ); + } + assert_eq!(guide_data(&project)["steps"].as_array().unwrap().len(), 1); +} + +#[test] +fn a_folder_where_a_guide_file_would_go_is_not_replaced() { + let project = project(&[(2.0, 0.25, 0.5)]); + let taken = project.folder.join(GUIDE_FILE); + std::fs::create_dir_all(&taken).unwrap(); + std::fs::write(taken.join("notes.txt"), "mine").unwrap(); + + assert!(matches!(export(&project), Err(StepsError::Failed(_)))); + + assert_eq!(listing(&project.folder), [GUIDE_FILE]); + assert_eq!( + std::fs::read_to_string(taken.join("notes.txt")).unwrap(), + "mine" + ); + assert_eq!( + listing(project.folder.parent().unwrap()), + ["guide", "steps.cap"] + ); +} + +#[test] +fn a_failed_first_export_into_a_folder_leaves_it_as_it_was() { + let root = tempfile::tempdir().unwrap(); + let folder = root.path().join("guide"); + std::fs::create_dir(&folder).unwrap(); + std::fs::write(folder.join("notes.txt"), "mine").unwrap(); + + let staging = root.path().join(".guide.staging"); + let written = format!("{STEP_IMAGES_FOLDER}/step-01.png"); + std::fs::create_dir_all(staging.join(STEP_IMAGES_FOLDER)).unwrap(); + for name in [GUIDE_FILE, GUIDE_DATA_FILE, written.as_str()] { + std::fs::write(staging.join(name), "new").unwrap(); + } + let names = [ + GUIDE_FILE.to_string(), + GUIDE_DATA_FILE.to_string(), + written, + format!("{STEP_IMAGES_FOLDER}/step-02.png"), + ]; + assert!(publish(&staging, &folder, &names).is_err()); + + assert_eq!(listing(&folder), ["notes.txt"]); + assert_eq!(listing(root.path()), [".guide.staging", "guide"]); +} + #[test] fn a_replacement_that_fails_part_way_puts_the_earlier_guide_back() { let project = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); @@ -641,6 +770,8 @@ fn a_replacement_that_fails_part_way_puts_the_earlier_guide_back() { .iter() .map(|file| std::fs::read(file).unwrap()) .collect(); + let mine = project.folder.join(STEP_IMAGES_FOLDER).join("diagram.png"); + std::fs::write(&mine, "mine").unwrap(); let staging = project.folder.with_file_name(".guide.staging"); std::fs::create_dir(&staging).unwrap(); @@ -656,10 +787,15 @@ fn a_replacement_that_fails_part_way_puts_the_earlier_guide_back() { for (file, bytes) in files.iter().zip(&before) { assert_eq!(&std::fs::read(file).unwrap(), bytes, "{}", file.display()); } + assert_eq!(std::fs::read_to_string(&mine).unwrap(), "mine"); assert_eq!( listing(&project.folder), [GUIDE_DATA_FILE, GUIDE_FILE, STEP_IMAGES_FOLDER] ); + assert_eq!( + listing(&project.folder.join(STEP_IMAGES_FOLDER)), + ["diagram.png", "step-01.png", "step-02.png"] + ); assert_eq!( listing(project.folder.parent().unwrap()), [".guide.staging", "guide", "steps.cap"] diff --git a/apps/desktop-gpui/steps/src/document.rs b/apps/desktop-gpui/steps/src/document.rs index c37337f6080..cbb5b82a55a 100644 --- a/apps/desktop-gpui/steps/src/document.rs +++ b/apps/desktop-gpui/steps/src/document.rs @@ -1,4 +1,4 @@ -use serde::Serialize; +use serde::{Deserialize, Serialize}; use crate::{Action, Point, Step}; @@ -39,9 +39,20 @@ impl Default for Captions { } } +const IMAGE_NAME_START: &str = "step-"; +const IMAGE_NAME_END: &str = ".png"; + pub fn image_name(index: usize, total: usize) -> String { let digits = total.max(index).to_string().len().max(2); - format!("step-{index:0digits$}.png") + format!("{IMAGE_NAME_START}{index:0digits$}{IMAGE_NAME_END}") +} + +pub fn is_image_name(name: &str) -> bool { + name.strip_prefix(IMAGE_NAME_START) + .and_then(|rest| rest.strip_suffix(IMAGE_NAME_END)) + .is_some_and(|number| { + !number.is_empty() && number.bytes().all(|byte| byte.is_ascii_digit()) + }) } pub fn timestamp(seconds: f64) -> String { @@ -163,6 +174,27 @@ struct StepData<'a> { image: &'a str, } +#[derive(Deserialize)] +struct ListedGuide { + #[serde(default)] + steps: Vec, +} + +#[derive(Deserialize)] +struct ListedStep { + #[serde(default)] + image: String, +} + +/// The `image` of every step in a guide's JSON, exactly as written there: +/// the text may come from a file someone else has edited, so these are not +/// yet paths to trust. +pub fn listed_images(json: &str) -> Vec { + serde_json::from_str::(json) + .map(|guide| guide.steps.into_iter().map(|step| step.image).collect()) + .unwrap_or_default() +} + pub fn json(document: &Document) -> String { let data = GuideData { title: &document.title, diff --git a/apps/desktop-gpui/steps/src/lib.rs b/apps/desktop-gpui/steps/src/lib.rs index fdced3978a8..c3973008dfd 100644 --- a/apps/desktop-gpui/steps/src/lib.rs +++ b/apps/desktop-gpui/steps/src/lib.rs @@ -13,7 +13,8 @@ use serde::{Deserialize, Serialize}; pub use detect::{build_guide, clip_steps}; pub use document::{ - Captions, Document, DocumentStep, image_name, instruction, json, markdown, timestamp, + Captions, Document, DocumentStep, image_name, instruction, is_image_name, json, listed_images, + markdown, timestamp, }; pub use frame::{Rect, Size, StepImage, crop_for, encode_png, render_step_image}; diff --git a/apps/desktop-gpui/steps/tests/spec.rs b/apps/desktop-gpui/steps/tests/spec.rs index 5d1e921742a..ec568d9f3a5 100644 --- a/apps/desktop-gpui/steps/tests/spec.rs +++ b/apps/desktop-gpui/steps/tests/spec.rs @@ -3,7 +3,8 @@ use std::path::Path; use cap_steps::{ Action, ButtonEvent, Captions, ClipEvents, Document, DocumentStep, Guide, LEFT_BUTTON, Marker, Point, PointerMove, Rect, Size, Source, Step, Word, build_guide, clip_steps, crop_for, - encode_png, image_name, json, markdown, render_step_image, timestamp, + encode_png, image_name, is_image_name, json, listed_images, markdown, render_step_image, + timestamp, }; use serde::Deserialize; @@ -827,6 +828,30 @@ fn image_names_are_zero_padded() { assert_eq!(image_name(7, 120), "step-007.png"); } +#[test] +fn only_names_a_guide_gives_its_screenshots_are_image_names() { + for (index, total) in [(1, 1), (9, 9), (12, 12), (7, 120), (1000, 1000)] { + let name = image_name(index, total); + assert!(is_image_name(&name), "{name}"); + } + for name in [ + "", + "step-.png", + "step-01.PNG", + "step-01.png.bak", + "step-one.png", + "step-01.jpg", + "my-step-01.png", + "step--1.png", + "step-01/x.png", + "../step-01.png", + "step-01.png/..", + "diagram.png", + ] { + assert!(!is_image_name(name), "{name}"); + } +} + #[test] fn timestamps_read_like_a_player() { assert_eq!(timestamp(4.2), "0:04"); @@ -1091,3 +1116,37 @@ fn json_lists_every_step_for_tools_to_read() { assert_eq!(steps[1]["dragTo"]["x"], 0.6); assert_eq!(steps[1]["heading"], "Tune it"); } + +#[test] +fn the_screenshots_a_guide_lists_can_be_read_back_from_its_json() { + let document = Document { + title: "Invite a teammate".into(), + duration: 12.5, + intro: String::new(), + steps: vec![ + document_step(1, 4.0, Action::Click, "", None), + document_step(2, 9.5, Action::Click, "", None), + ], + }; + let images: Vec = document + .steps + .iter() + .map(|entry| entry.image.clone()) + .collect(); + assert_eq!(listed_images(&json(&document)), images); +} + +#[test] +fn text_that_is_not_a_guide_lists_no_screenshots() { + for text in [ + "", + "not json", + "[]", + "{}", + r#"{"steps": "steps/step-01.png"}"#, + r#"{"steps": [{"image": 4}]}"#, + ] { + assert!(listed_images(text).is_empty(), "{text}"); + } + assert_eq!(listed_images(r#"{"steps": [{"index": 1}]}"#), [""]); +} From 06f67483bb12fb180616f28c0bbfea5441403972 Mon Sep 17 00:00:00 2001 From: Aatman Jain Date: Sat, 28 Nov 2026 17:54:34 +0000 Subject: [PATCH 5/6] fix(desktop-gpui): never merge clicks across a timeline split Steps grouped a clip's presses into double-clicks and repeated clicks in recording order, and only then placed the result on the timeline. Two clicks either side of a split were read as one action at the first click's place. When the pieces were reordered, or had other footage between them, the second click lost its own time and screenshot. Each recording clip now comes with the source times where its timeline segments start and end, and presses are never grouped across one. A press exactly on a boundary belongs to the segment that starts there, which is also where the timeline places it. A split that changes nothing else separates the two clicks as well. --- apps/desktop-gpui/src/steps_export.rs | 14 ++++ apps/desktop-gpui/src/steps_export/tests.rs | 68 +++++++++++++++++ apps/desktop-gpui/steps/src/detect.rs | 10 ++- apps/desktop-gpui/steps/src/lib.rs | 4 + apps/desktop-gpui/steps/tests/spec.rs | 85 +++++++++++++++++++++ 5 files changed, 179 insertions(+), 2 deletions(-) diff --git a/apps/desktop-gpui/src/steps_export.rs b/apps/desktop-gpui/src/steps_export.rs index 01cf3ee2566..80ab9782994 100644 --- a/apps/desktop-gpui/src/steps_export.rs +++ b/apps/desktop-gpui/src/steps_export.rs @@ -169,6 +169,18 @@ impl<'a> Playback<'a> { } } + fn breaks(&self, clip: u32) -> Vec { + match self { + Self::Edited(timeline) => timeline + .segments + .iter() + .filter(|segment| segment.recording_clip == clip && segment.end > segment.start) + .flat_map(|segment| [segment.start, segment.end]) + .collect(), + Self::BackToBack(_) => Vec::new(), + } + } + fn output_time(&self, clip: u32, source_time: f64) -> Option { match self { Self::Edited(timeline) => timeline.output_time_for_source(clip, source_time), @@ -256,11 +268,13 @@ fn guide(project: &ProjectConfiguration, clips: &[Clip], playback: &Playback) -> !(event.down && pointer_at(&moves, event.time).is_some_and(outside_frame)) }) .collect(); + let breaks = playback.breaks(clip_index); let events = ClipEvents { clip: clip_index, stopped_at: (index + 1 == clips.len()) .then(|| source_length(clip)) .filter(|length| *length > 0.0), + breaks: &breaks, moves: &moves, buttons: &buttons, }; diff --git a/apps/desktop-gpui/src/steps_export/tests.rs b/apps/desktop-gpui/src/steps_export/tests.rs index 4b4d30ecfd2..8b658e3e4e7 100644 --- a/apps/desktop-gpui/src/steps_export/tests.rs +++ b/apps/desktop-gpui/src/steps_export/tests.rs @@ -610,6 +610,74 @@ fn a_sped_up_clip_keeps_its_clicks_apart() { ); } +fn split(project: &mut Project, at: f64) { + let timeline = project.config.timeline.as_mut().unwrap(); + let mut after = timeline.segments[0].clone(); + timeline.segments[0].end = at; + after.start = at; + timeline.segments.push(after); +} + +fn placed_clicks(project: &Project) -> Vec<(Action, u32, f64, f64)> { + project_guide(&project.meta, &project.config) + .steps + .iter() + .map(|step| { + ( + step.action, + step.repeat, + (step.time * 1000.0).round() / 1000.0, + step.source.time, + ) + }) + .collect() +} + +#[test] +fn a_double_click_is_read_when_no_split_falls_inside_it() { + let mut whole = project(&[(3.9, 0.5, 0.5), (4.1, 0.5, 0.5)]); + assert_eq!(placed_clicks(&whole), [(Action::DoubleClick, 1, 3.9, 3.9)]); + split(&mut whole, 5.0); + assert_eq!(placed_clicks(&whole), [(Action::DoubleClick, 1, 3.9, 3.9)]); +} + +#[test] +fn clicks_either_side_of_a_split_are_separate_steps() { + let mut project = project(&[(3.9, 0.5, 0.5), (4.1, 0.5, 0.5)]); + split(&mut project, 4.0); + assert_eq!( + placed_clicks(&project), + [(Action::Click, 1, 3.9, 3.9), (Action::Click, 1, 4.1, 4.1)] + ); +} + +#[test] +fn clicks_in_reordered_pieces_each_keep_their_own_place_on_the_timeline() { + let mut project = project(&[(3.9, 0.5, 0.5), (4.1, 0.5, 0.5)]); + split(&mut project, 4.0); + let timeline = project.config.timeline.as_mut().unwrap(); + timeline.segments.swap(0, 1); + let moved_back = ((timeline.segments[0].duration() + 3.9) * 1000.0).round() / 1000.0; + + assert_eq!( + placed_clicks(&project), + [ + (Action::Click, 1, 0.1, 4.1), + (Action::Click, 1, moved_back, 3.9) + ] + ); + + export(&project).unwrap(); + let data = guide_data(&project); + let steps = data["steps"].as_array().unwrap(); + assert_eq!(steps.len(), 2, "{data}"); + for step in steps { + assert_eq!(step["action"], "click", "{data}"); + assert_eq!(step["repeat"], 1, "{data}"); + } + assert_ne!(step_image(&project, 1), step_image(&project, 2)); +} + #[test] fn a_shorter_re_export_leaves_no_screenshots_from_the_longer_one() { let longer = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25), (6.0, 0.5, 0.9)]); diff --git a/apps/desktop-gpui/steps/src/detect.rs b/apps/desktop-gpui/steps/src/detect.rs index 9c9ac56244a..6e9c71157d9 100644 --- a/apps/desktop-gpui/steps/src/detect.rs +++ b/apps/desktop-gpui/steps/src/detect.rs @@ -31,7 +31,7 @@ pub fn clip_steps(events: &ClipEvents, output_time: impl Fn(f64) -> Option) if let Some(stopped_at) = events.stopped_at.filter(|time| time.is_finite()) { presses.retain(|press| press.time <= stopped_at - STOP_CLICK_WINDOW); } - pointer_steps(events.clip, &presses, output_time) + pointer_steps(events.clip, &presses, events.breaks, output_time) } pub fn build_guide(mut steps: Vec, markers: &[Marker], words: &[Word]) -> Guide { @@ -84,9 +84,14 @@ fn same_spot(a: Option, b: Option) -> bool { } } +fn parted(breaks: &[f64], earlier: f64, later: f64) -> bool { + breaks.iter().any(|at| earlier < *at && *at <= later) +} + fn pointer_steps( clip: u32, presses: &[Press], + breaks: &[f64], output_time: impl Fn(f64) -> Option, ) -> Vec { let mut steps = Vec::new(); @@ -99,7 +104,8 @@ fn pointer_steps( && first.drag_to.is_none() && next.drag_to.is_none() && next.time - previous <= REPEAT_GAP - && same_spot(first.position, next.position); + && same_spot(first.position, next.position) + && !parted(breaks, previous, next.time); if !continues { break; } diff --git a/apps/desktop-gpui/steps/src/lib.rs b/apps/desktop-gpui/steps/src/lib.rs index c3973008dfd..b0b45bbac43 100644 --- a/apps/desktop-gpui/steps/src/lib.rs +++ b/apps/desktop-gpui/steps/src/lib.rs @@ -59,6 +59,10 @@ pub struct Source { pub struct ClipEvents<'a> { pub clip: u32, pub stopped_at: Option, + /// On the clip's clock, where each piece of this clip on the timeline + /// starts and ends. Presses on either side of one are separate actions: + /// the pieces may play in another order, or with other footage between. + pub breaks: &'a [f64], pub moves: &'a [PointerMove], pub buttons: &'a [ButtonEvent], } diff --git a/apps/desktop-gpui/steps/tests/spec.rs b/apps/desktop-gpui/steps/tests/spec.rs index ec568d9f3a5..67c34bcf575 100644 --- a/apps/desktop-gpui/steps/tests/spec.rs +++ b/apps/desktop-gpui/steps/tests/spec.rs @@ -79,6 +79,7 @@ fn guide_of(recording: &Recording) -> Guide { let events = ClipEvents { clip: 0, stopped_at: Some(recording.duration).filter(|duration| *duration > 0.0), + breaks: &[], moves: &recording.moves, buttons: &recording.buttons, }; @@ -371,6 +372,7 @@ fn clicks_cut_from_the_timeline_are_left_out_before_actions_are_read() { let events = ClipEvents { clip: 3, stopped_at: None, + breaks: &[], moves: &recording.moves, buttons: &recording.buttons, }; @@ -391,6 +393,7 @@ fn steps_from_several_clips_are_put_in_output_order() { &ClipEvents { clip, stopped_at: None, + breaks: &[], moves: &recording.moves, buttons: &recording.buttons, }, @@ -404,6 +407,88 @@ fn steps_from_several_clips_are_put_in_output_order() { assert_eq!(order, [1, 0]); } +fn clicks_at(times: &[f64]) -> Recording { + let mut recording = click_at(times[0], 0.5, 0.5); + for &time in ×[1..] { + for (time, down) in [(time, true), (time + 0.08, false)] { + recording.buttons.push(ButtonEvent { + time, + button: LEFT_BUTTON, + down, + }); + } + } + recording +} + +fn steps_with_breaks( + recording: &Recording, + breaks: &[f64], + output_time: impl Fn(f64) -> Option, +) -> Vec { + clip_steps( + &ClipEvents { + clip: 0, + stopped_at: None, + breaks, + moves: &recording.moves, + buttons: &recording.buttons, + }, + output_time, + ) +} + +#[test] +fn two_clicks_either_side_of_a_break_are_two_steps_each_at_its_own_time() { + let recording = clicks_at(&[4.9, 5.1]); + let second_piece_first = |time: f64| Some(if time < 5.0 { time + 5.0 } else { time - 5.0 }); + let steps = steps_with_breaks(&recording, &[0.0, 5.0, 5.0, 10.0], second_piece_first); + let guide = build_guide(steps, &[], &[]); + + assert_eq!(guide.steps.len(), 2, "{}", describe(&guide)); + for (step, (time, source)) in guide.steps.iter().zip([(0.1, 5.1), (9.9, 4.9)]) { + assert_eq!(step.action, Action::Click, "{}", describe(&guide)); + assert_eq!(step.repeat, 1, "{}", describe(&guide)); + assert!((step.time - time).abs() < 1e-9, "{}", describe(&guide)); + assert!((step.source.time - source).abs() < 1e-9); + } +} + +#[test] +fn repeated_clicks_are_counted_within_one_piece_of_the_clip() { + let recording = clicks_at(&[4.0, 4.7, 5.4, 6.1]); + let steps = steps_with_breaks(&recording, &[0.0, 5.0, 5.0, 10.0], Some); + + let found: Vec<(Action, u32, f64)> = steps + .iter() + .map(|step| (step.action, step.repeat, step.time)) + .collect(); + assert_eq!( + found, + [(Action::Click, 2, 4.0), (Action::Click, 2, 5.4)], + "{steps:?}" + ); +} + +#[test] +fn a_press_on_a_break_belongs_to_the_piece_that_starts_there() { + let recording = clicks_at(&[4.9, 5.1]); + let actions = |breaks: &[f64]| -> Vec { + steps_with_breaks(&recording, breaks, Some) + .iter() + .map(|step| step.action) + .collect() + }; + + assert_eq!(actions(&[0.0, 4.0, 4.0, 10.0]), [Action::DoubleClick]); + assert_eq!(actions(&[0.0, 4.9, 4.9, 10.0]), [Action::DoubleClick]); + assert_eq!(actions(&[0.0, 5.2, 5.2, 10.0]), [Action::DoubleClick]); + assert_eq!( + actions(&[0.0, 5.1, 5.1, 10.0]), + [Action::Click, Action::Click] + ); +} + #[test] fn a_note_is_framed_at_its_marker() { let guide = guide_of(&Recording { From f0b12ed9c3bb752add7ade2e1c0dfab0b41b4050 Mon Sep 17 00:00:00 2001 From: Aatman Jain Date: Sat, 28 Nov 2026 18:10:44 +0000 Subject: [PATCH 6/6] fix(desktop-gpui): never follow a link at the guide's screenshots folder Re-exporting Steps reaches every screenshot through steps/ in the chosen folder. When steps was a link to another folder, the file-by-file swap went through it: screenshots with matching names there were moved out and deleted, and the new ones were written in their place. The swap now looks at steps itself, without following it, before any file moves. Only a real folder, or none yet, lets the export go on. A link or a file there fails the export, and the chosen folder and whatever the link points at stay as they were. A link at guide.md, guide.json or a screenshot was already safe: it is moved and removed as a link and never followed. A test now holds that as well. --- apps/desktop-gpui/src/steps_export.rs | 26 ++++++- apps/desktop-gpui/src/steps_export/tests.rs | 79 +++++++++++++++++++++ 2 files changed, 103 insertions(+), 2 deletions(-) diff --git a/apps/desktop-gpui/src/steps_export.rs b/apps/desktop-gpui/src/steps_export.rs index 80ab9782994..a883e38b283 100644 --- a/apps/desktop-gpui/src/steps_export.rs +++ b/apps/desktop-gpui/src/steps_export.rs @@ -551,6 +551,26 @@ fn retire(file: &Path, retired: &Path) -> std::io::Result { } } +/// Every screenshot is reached through this one name, so a link here would +/// carry the swap into the folder it points at: screenshots there moved out +/// and deleted, new ones written in. `symlink_metadata` does not follow the +/// link, so only a real folder passes. `Ok(false)` is none there yet. +fn has_screenshots_folder(screenshots: &Path) -> std::io::Result { + match std::fs::symlink_metadata(screenshots) { + Ok(found) if found.is_dir() => Ok(true), + Ok(found) => Err(std::io::Error::new( + std::io::ErrorKind::NotADirectory, + format!( + "{} is a {}, not a folder", + screenshots.display(), + if found.is_symlink() { "link" } else { "file" } + ), + )), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), + Err(error) => Err(error), + } +} + /// The folder is one the user picked, and it and its screenshots folder may /// hold other files. Only the guide's own files are swapped: the ones this /// export writes, and the screenshots the earlier guide's `guide.json` @@ -558,6 +578,10 @@ fn retire(file: &Path, retired: &Path) -> std::io::Result { /// in. `retired` is deleted with its contents only after that, so a file /// that could not be put back after a failed swap is still there. fn replace_guide(staging: &Path, folder: &Path, names: &[String]) -> Result<(), String> { + let screenshots = folder.join(STEP_IMAGES_FOLDER); + let made_screenshots_folder = + !has_screenshots_folder(&screenshots).map_err(|error| error.to_string())?; + let mut retired = staging.as_os_str().to_owned(); retired.push(".replaced"); let retired = PathBuf::from(retired); @@ -568,8 +592,6 @@ fn replace_guide(staging: &Path, folder: &Path, names: &[String]) -> Result<(), outgoing.push(image); } } - let screenshots = folder.join(STEP_IMAGES_FOLDER); - let made_screenshots_folder = !screenshots.exists(); let mut moved_out = Vec::new(); let mut moved_in = Vec::new(); diff --git a/apps/desktop-gpui/src/steps_export/tests.rs b/apps/desktop-gpui/src/steps_export/tests.rs index 8b658e3e4e7..bf6bd2c9564 100644 --- a/apps/desktop-gpui/src/steps_export/tests.rs +++ b/apps/desktop-gpui/src/steps_export/tests.rs @@ -805,6 +805,85 @@ fn a_folder_where_a_guide_file_would_go_is_not_replaced() { ); } +#[cfg(unix)] +#[test] +fn a_link_where_the_screenshots_folder_would_go_is_not_followed() { + let earlier = project(&[(2.0, 0.25, 0.5), (4.0, 0.75, 0.25)]); + export(&earlier).unwrap(); + let images = earlier.folder.join(STEP_IMAGES_FOLDER); + let elsewhere = earlier.folder.with_file_name("elsewhere"); + let theirs = ["diagram.png", "step-01.png", "step-02.png"]; + std::fs::remove_dir_all(&images).unwrap(); + std::fs::create_dir(&elsewhere).unwrap(); + for name in theirs { + std::fs::write(elsewhere.join(name), "theirs").unwrap(); + } + std::os::unix::fs::symlink(&elsewhere, &images).unwrap(); + let guide = [GUIDE_FILE, GUIDE_DATA_FILE]; + let before = guide.map(|name| std::fs::read(earlier.folder.join(name)).unwrap()); + + let mut later = project(&[(5.0, 0.6, 0.6)]); + later.folder = earlier.folder.clone(); + assert!(matches!(export(&later), Err(StepsError::Failed(_)))); + + assert_eq!(listing(&elsewhere), theirs); + for name in theirs { + assert_eq!( + std::fs::read_to_string(elsewhere.join(name)).unwrap(), + "theirs", + "{name}" + ); + } + assert_eq!(std::fs::read_link(&images).unwrap(), elsewhere); + for (name, bytes) in guide.iter().zip(&before) { + assert_eq!( + &std::fs::read(earlier.folder.join(name)).unwrap(), + bytes, + "{name}" + ); + } + assert_eq!( + listing(&earlier.folder), + [GUIDE_DATA_FILE, GUIDE_FILE, STEP_IMAGES_FOLDER] + ); + assert_eq!( + listing(earlier.folder.parent().unwrap()), + ["elsewhere", "guide", "steps.cap"] + ); +} + +#[cfg(unix)] +#[test] +fn a_link_where_a_guide_file_would_go_is_replaced_and_what_it_points_at_is_kept() { + let project = project(&[(2.0, 0.25, 0.5)]); + export(&project).unwrap(); + let elsewhere = project.folder.with_file_name("elsewhere"); + std::fs::create_dir(&elsewhere).unwrap(); + let screenshot = format!("{STEP_IMAGES_FOLDER}/step-01.png"); + let linked = [GUIDE_FILE, screenshot.as_str()]; + for name in linked { + let theirs = elsewhere.join(Path::new(name).file_name().unwrap()); + std::fs::write(&theirs, "theirs").unwrap(); + std::fs::remove_file(project.folder.join(name)).unwrap(); + std::os::unix::fs::symlink(&theirs, project.folder.join(name)).unwrap(); + } + + export(&project).unwrap(); + + assert_eq!(listing(&elsewhere), [GUIDE_FILE, "step-01.png"]); + for name in listing(&elsewhere) { + assert_eq!( + std::fs::read_to_string(elsewhere.join(&name)).unwrap(), + "theirs", + "{name}" + ); + } + for name in linked { + let written = std::fs::symlink_metadata(project.folder.join(name)).unwrap(); + assert!(written.is_file(), "{name}"); + } +} + #[test] fn a_failed_first_export_into_a_folder_leaves_it_as_it_was() { let root = tempfile::tempdir().unwrap();