From 11353e6c4916e267180b6ccbe735ccd4c77c8453 Mon Sep 17 00:00:00 2001 From: Mehfuz Hossain Date: Mon, 16 Nov 2026 19:05:44 -0800 Subject: [PATCH 1/5] Recording HUD: a small bar like Loom's The tape-recorder HUD (bordered keys, LCD window, REC lamp, equalizer) becomes one compact bar: the red stop button with the time beside it and a small microphone level, then plain icon buttons for pause, marker, start over and delete. The countdown shows its seconds on the stop button. Same frosted glass and 10 px bar corners. --- apps/studio/src/recorder.rs | 178 +++++++++++++++++------------------- 1 file changed, 83 insertions(+), 95 deletions(-) diff --git a/apps/studio/src/recorder.rs b/apps/studio/src/recorder.rs index c1fccbb..82ef90d 100644 --- a/apps/studio/src/recorder.rs +++ b/apps/studio/src/recorder.rs @@ -294,9 +294,9 @@ impl RecordingScreen { /// Draw the countdown / HUD into the floating window. Returns what to do next. /// - /// Styled like a tape recorder (bordered keys, a display window holding the REC light, the - /// timer and, with a microphone, a level equalizer), drawn flat on the same frosted glass - /// as the main toolbar so it follows the theme. + /// A small bar like Loom's: the red stop button with the time beside it (and a microphone + /// level when one is recording), then plain icon buttons for pause, marker, restart and + /// delete. Drawn on the same frosted glass as the main toolbar so it follows the theme. pub fn ui(&mut self, ui: &mut Ui, ctx: &egui::Context) -> RecordingOutcome { let full = ui.max_rect(); if let Some(b) = self.camera.as_mut() { @@ -309,7 +309,7 @@ impl RecordingScreen { let pal = theme::p(); let t = ui.input(|i| i.time); - // microphone level history for the equalizer (newest last) + // microphone level history for the meter (newest last) let level = match &self.phase { Phase::Recording(rec) => rec.microphone_level(), _ => None, @@ -318,36 +318,35 @@ impl RecordingScreen { if t - self.level_sampled_at >= 0.06 { self.level_sampled_at = t; self.levels.push_back(l); - while self.levels.len() > EQ_BARS { + while self.levels.len() > METER_BARS { self.levels.pop_front(); } } } - let has_eq = self.req.microphone.is_some(); - ctx.request_repaint_after(std::time::Duration::from_millis(if has_eq { 50 } else { 100 })); - - // pill: [stop] [lcd] [keys…] - let key = vec2(36.0, 40.0); - let lcd_w = match self.phase { - Phase::Recording(_) => if has_eq { 196.0 } else { 150.0 }, - _ => 230.0, + let has_mic = self.req.microphone.is_some(); + ctx.request_repaint_after(std::time::Duration::from_millis(if has_mic { 50 } else { 100 })); + + // bar: [stop] time [meter] | [pause] [marker] [restart] [delete] + let (stop_w, time_w, meter_w) = (BTN, 58.0, if has_mic { 22.0 } else { 0.0 }); + let inner_w = match self.phase { + Phase::Recording(_) => stop_w + 10.0 + time_w + meter_w + GAP + 1.0 + GAP + 4.0 * BTN + 3.0 * 2.0, + Phase::Countdown { .. } => stop_w + 10.0 + 170.0 + GAP + 64.0, + Phase::Finishing => 140.0, }; - let keys_w = match self.phase { - Phase::Recording(_) => 4.0 * key.x + 3.0 * 4.0, - _ => 84.0, - }; - let pill_w = 12.0 + 40.0 + 8.0 + lcd_w + 8.0 + keys_w + 12.0; - let pill = egui::Rect::from_center_size(pos2(full.center().x, full.bottom() - 10.0 - 29.0), vec2(pill_w, 58.0)); + let bar = egui::Rect::from_center_size(pos2(full.center().x, full.bottom() - 10.0 - BAR_H / 2.0), vec2(inner_w + 2.0 * PAD, BAR_H)); let painter = ui.painter().clone(); - self.hud_rect = pill; - crate::vibrancy::set(Some([pill.left(), pill.top(), pill.width(), pill.height()]), full.height(), crate::picker::PILL_RADIUS); + self.hud_rect = bar; + crate::vibrancy::set(Some([bar.left(), bar.top(), bar.width(), bar.height()]), full.height(), crate::picker::PILL_RADIUS); let tint = if crate::vibrancy::is_active() { pal.glass } else { pal.glass_solid }; - painter.rect(pill, CornerRadius::same(crate::picker::PILL_RADIUS as u8), tint, Stroke::new(1.0, pal.glass_border), egui::StrokeKind::Inside); - let cy = pill.center().y; - let stop_rect = egui::Rect::from_min_size(pos2(pill.left() + 12.0, cy - 20.0), vec2(40.0, 40.0)); - let lcd = egui::Rect::from_min_size(pos2(stop_rect.right() + 8.0, cy - 20.0), vec2(lcd_w, 40.0)); - let keys_left = lcd.right() + 8.0; - lcd_window(&painter, lcd); + painter.rect(bar, CornerRadius::same(crate::picker::PILL_RADIUS as u8), tint, Stroke::new(1.0, pal.glass_border), egui::StrokeKind::Inside); + let cy = bar.center().y; + let mut x = bar.left() + PAD; + // the next `w` wide slot along the bar, then `gap` after it + let next = |x: &mut f32, w: f32, gap: f32| { + let r = egui::Rect::from_min_size(pos2(*x, cy - BTN / 2.0), vec2(w, BTN)); + *x += w + gap; + r + }; match &mut self.phase { Phase::Countdown { until, total_ms } => { @@ -360,18 +359,18 @@ impl RecordingScreen { } return RecordingOutcome::Continue; } - // stop key stands idle; the LCD counts down - tape_key(ui, stop_rect, "stop-idle", None, |p, r| paint_stop_glyph(p, r, pal.text_faint), ""); - rec_light(&painter, pos2(lcd.left() + 14.0, cy), (t * 2.0).sin() > 0.0); - painter.text(pos2(lcd.left() + 46.0, cy), Align2::CENTER_CENTER, secs.to_string(), FontId::monospace(24.0), pal.accent_hover); - let title = if left.is_zero() && camera_opening { "Starting camera…" } else { "Recording starts in" }; - painter.text(pos2(lcd.left() + 70.0, cy - 8.0), Align2::LEFT_CENTER, title, FontId::proportional(12.5), pal.on_glass); - painter.text(pos2(lcd.left() + 70.0, cy + 9.0), Align2::LEFT_CENTER, match self.req.mode { Mode::Window => "Selected window", Mode::Area => "Selected area", _ => "Entire display" }, FontId::proportional(11.0), pal.text_dim); - let cancel = egui::Rect::from_min_size(pos2(keys_left, cy - 20.0), vec2(keys_w, 40.0)); + // the seconds left where the stop button will be + let n = next(&mut x, stop_w, 10.0); + painter.rect_filled(n, CornerRadius::same(2), pal.danger); + painter.text(n.center(), Align2::CENTER_CENTER, secs.to_string(), FontId::proportional(15.0), Color32::WHITE); + let text = next(&mut x, 170.0, GAP); + let title = if left.is_zero() && camera_opening { "Starting camera…" } else { "Recording starts…" }; + painter.text(pos2(text.left(), cy), Align2::LEFT_CENTER, title, FontId::proportional(13.5), pal.on_glass); + let cancel = next(&mut x, 64.0, 0.0); let label = |p: &egui::Painter, r: egui::Rect| { p.text(r.center(), Align2::CENTER_CENTER, "Cancel", FontId::proportional(13.0), pal.on_glass); }; - if tape_key(ui, cancel, "cancel-countdown", None, label, "Cancel (Esc)").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + if hud_button(ui, cancel, "cancel-countdown", label, "Cancel (Esc)").clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { return RecordingOutcome::Cancelled(None); } RecordingOutcome::Continue @@ -385,35 +384,40 @@ impl RecordingScreen { let elapsed = rec.elapsed_ms(); let paused = matches!(state, RecorderState::Paused); - // stop: a red-faced key - let mut finish = tape_key(ui, stop_rect, "stop", Some(pal.danger), |p, r| paint_stop_glyph(p, r, Color32::WHITE), "Finish recording").clicked(); + // stop: red, with a white square + let stop = next(&mut x, stop_w, 10.0); + let resp = ui.interact(stop, ui.id().with("hud-stop"), egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand).on_hover_text("Finish recording (Esc)"); + painter.rect_filled(stop, CornerRadius::same(2), if resp.is_pointer_button_down_on() { pal.danger.gamma_multiply(0.8) } else if resp.hovered() { pal.danger.gamma_multiply(0.9) } else { pal.danger }); + painter.rect_filled(egui::Rect::from_center_size(stop.center(), vec2(10.0, 10.0)), CornerRadius::same(1), Color32::WHITE); + let mut finish = resp.clicked(); let mut restart = false; - // LCD: REC light · timer · equalizer - rec_light(&painter, pos2(lcd.left() + 14.0, cy - 7.0), !paused && (t * 2.0).sin() > -0.3); - painter.text(pos2(lcd.left() + 14.0, cy + 9.0), Align2::CENTER_CENTER, if paused { "PAUSE" } else { "REC" }, FontId::monospace(8.5), if paused { pal.text_dim } else { pal.danger }); - painter.text(pos2(lcd.left() + 34.0, cy), Align2::LEFT_CENTER, crate::editor::fmt_clock_short(elapsed), FontId::monospace(20.0), if paused { pal.text_dim } else { pal.accent_hover }); - if has_eq { - let eq = egui::Rect::from_min_max(pos2(lcd.right() - 10.0 - EQ_BARS as f32 * 6.0, lcd.top() + 9.0), pos2(lcd.right() - 10.0, lcd.bottom() - 9.0)); - paint_equalizer(&painter, eq, &self.levels, if paused { pal.text_faint } else { pal.meter }); + // time (dim and blinking while paused), then the microphone + let time = next(&mut x, time_w, 0.0); + let blink_off = paused && (t * 2.0).sin() < 0.0; + painter.text(pos2(time.left(), cy), Align2::LEFT_CENTER, crate::editor::fmt_clock_short(elapsed), FontId::monospace(15.0), if blink_off { pal.text_faint } else if paused { pal.text_dim } else { pal.on_glass }); + if has_mic { + let m = next(&mut x, meter_w, 0.0); + let levels: Vec = self.levels.iter().copied().collect(); + paint_meter(&painter, egui::Rect::from_center_size(m.center(), vec2(14.0, 14.0)), &levels, if paused { pal.text_faint } else { pal.meter }); } + let divider = next(&mut x, 2.0 * GAP + 1.0, 0.0); + painter.vline(divider.center().x, (cy - 10.0)..=(cy + 10.0), Stroke::new(1.0, pal.glass_border)); - // keys: pause · marker · restart · cancel - let at = |i: usize| egui::Rect::from_min_size(pos2(keys_left + i as f32 * (key.x + 4.0), cy - 20.0), key); let (icon, tip) = if paused { (crate::widgets::Icon::Play, "Resume") } else { (crate::widgets::Icon::Pause, "Pause") }; - if tape_key(ui, at(0), "pause", None, |p, r| icon_glyph(p, r, icon, 14.0), tip).clicked() { + if hud_button(ui, next(&mut x, BTN, 2.0), "pause", |p, r| icon_glyph(p, r, icon, 14.0), tip).clicked() { let r = if paused { rec.resume() } else { rec.pause() }; if let Err(e) = r { self.error = Some(e.to_string()); } } - if tape_key(ui, at(1), "marker", None, |p, r| icon_glyph(p, r, crate::widgets::Icon::Flag, 14.0), "Add marker (split point)").clicked() { + if hud_button(ui, next(&mut x, BTN, 2.0), "marker", |p, r| icon_glyph(p, r, crate::widgets::Icon::Flag, 14.0), "Add a marker (a split point)").clicked() { rec.add_marker(); } - if tape_key(ui, at(2), "restart", None, |p, r| icon_glyph(p, r, crate::widgets::Icon::Restart, 15.0), "Restart recording").clicked() { + if hud_button(ui, next(&mut x, BTN, 2.0), "restart", |p, r| icon_glyph(p, r, crate::widgets::Icon::Restart, 15.0), "Start over").clicked() { restart = true; } - if tape_key(ui, at(3), "cancel", None, |p, r| icon_glyph(p, r, crate::widgets::Icon::Close, 13.0), "Cancel recording").clicked() { + if hud_button(ui, next(&mut x, BTN, 0.0), "cancel", |p, r| icon_glyph(p, r, crate::widgets::Icon::Trash, 14.0), "Delete this recording").clicked() { if let Phase::Recording(rec) = std::mem::replace(&mut self.phase, Phase::Finishing) { rec.cancel(); } @@ -450,70 +454,54 @@ impl RecordingScreen { } } if let Some(e) = &self.error { - painter.text(pos2(pill.center().x, pill.top() - 16.0), Align2::CENTER_CENTER, e, FontId::proportional(12.0), pal.danger); + painter.text(pos2(bar.center().x, bar.top() - 16.0), Align2::CENTER_CENTER, e, FontId::proportional(12.0), pal.danger); } RecordingOutcome::Continue } Phase::Finishing => { - painter.text(lcd.center(), Align2::CENTER_CENTER, "Finishing…", FontId::proportional(15.0), pal.on_glass); + painter.text(bar.center(), Align2::CENTER_CENTER, "Finishing…", FontId::proportional(13.5), pal.on_glass); RecordingOutcome::Continue } } } } -/// Bars in the HUD's microphone equalizer. -const EQ_BARS: usize = 7; - -/// The display window: a faint glass tint inside a border. -fn lcd_window(p: &egui::Painter, r: egui::Rect) { - p.rect(r, CornerRadius::same(2), theme::glass_alpha(14), Stroke::new(1.0, theme::p().glass_border), egui::StrokeKind::Inside); -} - -/// The record indicator lamp. -fn rec_light(p: &egui::Painter, c: egui::Pos2, lit: bool) { - let pal = theme::p(); - if lit { - p.circle_filled(c, 7.0, pal.danger.gamma_multiply(0.25)); - p.circle_filled(c, 4.5, pal.danger); - } else { - p.circle_filled(c, 4.5, pal.danger.gamma_multiply(0.3)); - } -} - -/// Level history as bars rising from the bottom of `r` (newest on the right). -fn paint_equalizer(p: &egui::Painter, r: egui::Rect, levels: &std::collections::VecDeque, color: Color32) { - let bar_w = r.width() / EQ_BARS as f32; - for i in 0..EQ_BARS { - let l = levels.len().checked_sub(EQ_BARS - i).and_then(|k| levels.get(k)).copied().unwrap_or(0.0); +/// The HUD bar: its height, inner padding, the size of its buttons and the space around the +/// divider. +const BAR_H: f32 = 44.0; +const PAD: f32 = 8.0; +const BTN: f32 = 28.0; +const GAP: f32 = 8.0; +/// Bars in the microphone level next to the time. +const METER_BARS: usize = 4; + +/// The last [`METER_BARS`] microphone levels as bars rising from the bottom of `r`. +fn paint_meter(p: &egui::Painter, r: egui::Rect, levels: &[f32], color: Color32) { + let pitch = r.width() / METER_BARS as f32; + for i in 0..METER_BARS { + let l = levels.len().checked_sub(METER_BARS - i).and_then(|k| levels.get(k)).copied().unwrap_or(0.0); let h = (r.height() * l.clamp(0.0, 1.0)).max(2.0); - let x = r.left() + i as f32 * bar_w; - p.rect_filled(egui::Rect::from_min_max(pos2(x + 1.0, r.bottom() - h), pos2(x + bar_w - 1.0, r.bottom())), CornerRadius::same(1), color); + let x = r.left() + i as f32 * pitch; + p.rect_filled(egui::Rect::from_min_max(pos2(x + 0.5, r.bottom() - h), pos2(x + pitch - 1.0, r.bottom())), CornerRadius::same(1), color); } } -fn paint_stop_glyph(p: &egui::Painter, r: egui::Rect, color: Color32) { - p.rect_filled(egui::Rect::from_center_size(r.center(), vec2(12.0, 12.0)), CornerRadius::same(2), color); -} - fn icon_glyph(p: &egui::Painter, r: egui::Rect, icon: crate::widgets::Icon, size: f32) { crate::widgets::paint_icon(p, egui::Rect::from_center_size(r.center(), vec2(size, size)), icon, theme::p().on_glass); } -/// A flat, bordered tape-recorder key on the glass. `face` fills the key (e.g. red for -/// stop); `glyph` paints its label. Hover and press deepen the glass tint like the toolbar. -fn tape_key(ui: &mut Ui, rect: egui::Rect, id: &str, face: Option, glyph: impl FnOnce(&egui::Painter, egui::Rect), tooltip: &str) -> egui::Response { - let pal = theme::p(); - let resp = ui.interact(rect, ui.id().with(("tape-key", id)), egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); +/// A borderless button on the glass: hover and press tint it like the toolbar's buttons. +fn hud_button(ui: &mut Ui, rect: egui::Rect, id: &str, glyph: impl FnOnce(&egui::Painter, egui::Rect), tooltip: &str) -> egui::Response { + let resp = ui.interact(rect, ui.id().with(("hud-button", id)), egui::Sense::click()).on_hover_cursor(egui::CursorIcon::PointingHand); let p = ui.painter(); - let fill = match face { - Some(c) if resp.is_pointer_button_down_on() => c.gamma_multiply(0.8), - Some(c) => c, - None if resp.is_pointer_button_down_on() => theme::glass_alpha(44), - None if resp.hovered() => theme::glass_alpha(28), - None => Color32::TRANSPARENT, + let fill = if resp.is_pointer_button_down_on() { + theme::glass_alpha(44) + } else if resp.hovered() { + theme::glass_alpha(28) + } else { + Color32::TRANSPARENT }; - p.rect(rect, CornerRadius::same(2), fill, Stroke::new(1.0, pal.glass_border), egui::StrokeKind::Inside); + p.rect_filled(rect, CornerRadius::same(2), fill); glyph(p, rect); if tooltip.is_empty() { resp } else { resp.on_hover_text(tooltip) } } From e3f7e204a8934c1b8291978a646454ff729d09bd Mon Sep 17 00:00:00 2001 From: Mehfuz Hossain Date: Mon, 16 Nov 2026 19:05:44 -0800 Subject: [PATCH 2/5] Share links keep a description and tags share_links gets description and tags columns; create stores them when the app sends them (older apps send none and leave what a link had) and get returns them for the page. --- backend/supabase/functions/share/index.ts | 13 ++++-- .../20261116000000_share_links_details.sql | 4 ++ functions/s/[id].js | 43 +++++++++++++++++++ 3 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 backend/supabase/migrations/20261116000000_share_links_details.sql diff --git a/backend/supabase/functions/share/index.ts b/backend/supabase/functions/share/index.ts index a6a91e9..f7da7cd 100644 --- a/backend/supabase/functions/share/index.ts +++ b/backend/supabase/functions/share/index.ts @@ -5,7 +5,7 @@ // (see `verifyKey`), and the computer must still be the license's active one. A device id alone // is not enough, since device ids are not secret. // -// { action: "create", device, key, project?, title, bytes, poster?, width?, height?, duration_ms? } +// { action: "create", device, key, project?, title, description?, tags?, bytes, poster?, width?, height?, duration_ms? } // Pro only → { id, url, upload: { video, poster? } }: presigned PUT URLs (video/mp4, and // image/jpeg for the poster) the app uploads to, signed for exactly `bytes` / `poster` bytes. // A project has one link: sharing it again uploads over the same link (same URL), whose @@ -84,12 +84,12 @@ serve(async (req) => { switch (body.action) { case "get": { if (!isId(body.id)) return fail("not found", 404); - const { data } = await client.from("share_links").select("id, title, width, height, duration_ms, has_poster, views, created_at, rev").eq("id", body.id).eq("status", "ready").maybeSingle(); + const { data } = await client.from("share_links").select("id, title, description, tags, width, height, duration_ms, has_poster, views, created_at, rev").eq("id", body.id).eq("status", "ready").maybeSingle(); if (!data) return fail("not found", 404); // ?v=: a replaced video gets a new address, past the CDN's cached copy of the old one const v = data.rev ? `?v=${data.rev}` : ""; return json({ - id: data.id, title: data.title, url: urlFor(data.id), video: `${MEDIA_URL}/${videoKey(data.id)}${v}`, + id: data.id, title: data.title, description: data.description ?? null, tags: data.tags ?? [], url: urlFor(data.id), video: `${MEDIA_URL}/${videoKey(data.id)}${v}`, poster: data.has_poster ? `${MEDIA_URL}/${posterKey(data.id)}${v}` : null, width: data.width, height: data.height, duration_ms: data.duration_ms, views: data.views, created_at: data.created_at, }); @@ -132,7 +132,12 @@ serve(async (req) => { const total = (used ?? []).filter((r) => r.id !== existing?.id).reduce((n, r) => n + Number(r.bytes), 0); if (total + bytes > MAX_ACCOUNT_BYTES) return fail(`Your share links use ${(total / 1024 ** 3).toFixed(1)} GB of ${(MAX_ACCOUNT_BYTES / 1024 ** 3).toFixed(0)} GB. Contact ScreenForge support to remove old links, then try again.`, 413); const int = (v: unknown) => (Number.isInteger(v) && (v as number) > 0 && (v as number) < 2 ** 31 ? v as number : null); - const fields = { device_id: body.device, title: String(body.title ?? "").slice(0, 200), width: int(body.width), height: int(body.height), duration_ms: int(body.duration_ms), pending_bytes: bytes, updated_at: new Date().toISOString() }; + // the export's details: a description (chapters at its end) and tags; an app without + // them sends none, which leaves what a link had + const details: Record = {}; + if (typeof body.description === "string") details.description = body.description.trim().slice(0, 5000) || null; + if (Array.isArray(body.tags)) details.tags = body.tags.filter((t: unknown) => typeof t === "string" && t.trim()).map((t: string) => t.trim().slice(0, 60)).slice(0, 15); + const fields = { ...details, device_id: body.device, title: String(body.title ?? "").slice(0, 200), width: int(body.width), height: int(body.height), duration_ms: int(body.duration_ms), pending_bytes: bytes, updated_at: new Date().toISOString() }; let id: string; if (existing) { // the page keeps playing the old video (status stays) until `complete` diff --git a/backend/supabase/migrations/20261116000000_share_links_details.sql b/backend/supabase/migrations/20261116000000_share_links_details.sql new file mode 100644 index 0000000..908b24e --- /dev/null +++ b/backend/supabase/migrations/20261116000000_share_links_details.sql @@ -0,0 +1,4 @@ +-- What the page says about a shared video, from the export's details: a description (which may +-- end with the chapter list, `00:00 Intro` lines) and tags. +alter table public.share_links add column if not exists description text; +alter table public.share_links add column if not exists tags text[]; diff --git a/functions/s/[id].js b/functions/s/[id].js index e9fa10a..f47596f 100644 --- a/functions/s/[id].js +++ b/functions/s/[id].js @@ -17,6 +17,31 @@ function duration(ms) { return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; } +// A chapter line of a description: `00:00 Intro`, `1:02:03 Wrap-up`. +const CHAPTER = /^((?:\d{1,2}:)?\d{1,2}:\d{2})\s+(.+)$/; +const seconds = (t) => t.split(":").reduce((n, p) => n * 60 + Number(p), 0); + +// The description as HTML: paragraphs, and chapter lines as times that jump the player there. +function describe(text) { + const blocks = String(text ?? "").trim().split(/\n\s*\n/).filter((b) => b.trim()); + return blocks.map((block) => { + const lines = block.split("\n").map((l) => l.trim()).filter(Boolean); + const chapters = lines.filter((l) => CHAPTER.test(l)); + if (chapters.length >= 2 && chapters.length >= lines.length - 1) { + const head = lines.length > chapters.length ? `

${esc(lines.find((l) => !CHAPTER.test(l)))}

` : ""; + const items = chapters.map((l) => { const [, t, name] = l.match(CHAPTER); return `
  • ${esc(t)}${esc(name)}
  • `; }).join(""); + return `${head}
      ${items}
    `; + } + return `

    ${lines.map(esc).join("
    ")}

    `; + }).join(""); +} + +// The description's opening, for link previews (no chapter list). +function summary(text) { + const prose = String(text ?? "").split("\n").map((l) => l.trim()).filter((l) => l && !CHAPTER.test(l) && l !== "Chapters").join(" "); + return prose.length > 200 ? prose.slice(0, 197).replace(/\s+\S*$/, "") + "…" : prose; +} + const STYLE = ` :root{--ground:#15161e;--ink:#1e1f29;--line:rgba(248,248,242,.10);--fg:#c9cbdc;--white:#f8f8f2;--dim:#8e90a6;--accent:#ff8a5c;--on-accent:#1e1f29;color-scheme:dark} @media (prefers-color-scheme:light){:root{--ground:#ececf1;--ink:#f6f6fa;--line:rgba(30,31,41,.12);--fg:#2e2f3b;--white:#1a1b24;--dim:#5f6175;--accent:#d4442a;--on-accent:#fff;color-scheme:light}} @@ -34,6 +59,15 @@ h1{color:var(--white);font-size:22px;font-weight:600;letter-spacing:-.01em;margi .meta{color:var(--dim);font-size:13.5px;display:flex;gap:14px;flex-wrap:wrap;align-items:center} .row{display:flex;justify-content:space-between;align-items:flex-start;gap:16px;flex-wrap:wrap} .actions{display:flex;gap:8px;margin-top:18px} +.about{max-width:760px;margin-top:18px;color:var(--fg);font-size:15px} +.about p{margin-bottom:12px;overflow-wrap:anywhere} +.about h2{color:var(--white);font-size:14px;font-weight:600;margin:6px 0 6px} +.chapters{list-style:none;margin-bottom:12px} +.chapters li{display:flex;gap:12px;padding:3px 0} +.chapters a{color:var(--accent);text-decoration:none;font-variant-numeric:tabular-nums;min-width:52px} +.chapters a:hover{text-decoration:underline} +.tags{display:flex;flex-wrap:wrap;gap:6px;margin-top:4px} +.tags span{color:var(--dim);font-size:12.5px;border:1px solid var(--line);border-radius:2px;padding:2px 8px} footer{margin-top:auto;padding-top:40px;padding-bottom:28px;color:var(--dim);font-size:13px;text-align:center} footer a{color:var(--fg)} .gone{text-align:center;padding:18vh 0} @@ -94,12 +128,16 @@ async function render(id) { return new Response("This video could not be loaded. Try again in a moment.", { status: 502 }); } const title = s.title || "Screen recording"; + const about = summary(s.description); + const tags = Array.isArray(s.tags) ? s.tags.filter((t) => typeof t === "string" && t) : []; const date = s.created_at ? new Date(s.created_at).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" }) : ""; const og = [ ``, ``, ``, ``, + about ? `` : "", + tags.length ? `` : "", ``, ``, ``, @@ -115,6 +153,7 @@ async function render(id) {

    ${esc(title)}

    ${[date, duration(s.duration_ms), views].filter(Boolean).map(esc).join("·")}

    Download
    +${s.description || tags.length ? `
    ${describe(s.description)}${tags.length ? `
    ${tags.map((t) => `${esc(t)}`).join("")}
    ` : ""}
    ` : ""} @@ -133,6 +172,10 @@ async function render(id) { document.getElementById("qr").onclick=open; view.onclick=close;document.addEventListener("keydown",function(e){if(e.key==="Escape")close()}); })(); +// chapter times jump the player (and #t=… in the address starts there) +(function(){var v=document.querySelector("video");if(!v)return;function go(t){v.currentTime=t;v.play().catch(function(){});v.scrollIntoView({behavior:"smooth",block:"center"})} +document.querySelectorAll(".chapters a").forEach(function(a){a.onclick=function(e){e.preventDefault();go(Number(a.dataset.t));history.replaceState(null,"","#t="+a.dataset.t)}}); +var m=location.hash.match(/^#t=(\d+)$/);if(m)v.addEventListener("loadedmetadata",function(){v.currentTime=Number(m[1])},{once:true})})(); document.getElementById("copy").onclick=function(){var b=this;navigator.clipboard.writeText(${JSON.stringify(s.url)}).then(function(){b.textContent="Copied";setTimeout(function(){b.textContent="Copy link"},1500)})}; try{fetch(${JSON.stringify(`${SUPABASE_URL}/functions/v1/share`)},{method:"POST",keepalive:true,headers:{apikey:${JSON.stringify(SUPABASE_ANON_KEY)},Authorization:"Bearer "+${JSON.stringify(SUPABASE_ANON_KEY)},"Content-Type":"application/json"},body:JSON.stringify({action:"view",id:${JSON.stringify(id)}})})}catch(e){} `; From ac60da87a75559a690da3f380a3151f2142d0d38 Mon Sep 17 00:00:00 2001 From: Mehfuz Hossain Date: Mon, 16 Nov 2026 19:05:44 -0800 Subject: [PATCH 3/5] Site and README: async video, Loom import, export details The share links card becomes async video (every way to paste a link) and mentions importing from Loom; the README describes the export details, share links and Loom import. --- README.md | 14 ++++++++++++++ site/es/index.html | 8 ++++---- site/index.html | 10 +++++----- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 5069969..c3fe583 100644 --- a/README.md +++ b/README.md @@ -45,6 +45,20 @@ hand. Projects are saved as `.screenforge` packages. SRT and WebVTT export. - **Camera smarts**: on-device face tracking keeps you centred; DaVinci Resolve style colour grading and `.cube` LUTs. +- **Details for publishing**: every export writes a title, a description (ending with the + chapters) and tags beside the video (`Demo.details.txt`) and shows them to copy. With the agent + on, Claude writes them from the transcript while the video renders; otherwise they come from + the project name, the opening words and the chapter titles. + +## Async video and Loom + +- **Share links** (Pro) make ScreenForge an async video tool: Export uploads the video and lists + the page link, the MP4, Markdown with the poster (GitHub, Notion) and an HTML embed, each with + a copy button. Exporting again keeps the same link. +- **Import from Loom**: paste a `loom.com/share/…` link in the New project window (or run + `sf import `). The video is downloaded and becomes a project named after its Loom title. + Public videos only ("anyone with the link"), and not ones whose owner turned downloads off. + Loom's camera bubble is part of its picture, so it comes in with the screen. Captions, on-device narration and face tracking run locally; the agent runs on Claude and the ElevenLabs voices on ElevenLabs, both through the ScreenForge backend (see `site/privacy.html` for what is sent). diff --git a/site/es/index.html b/site/es/index.html index 9a00317..6a7f7b9 100644 --- a/site/es/index.html +++ b/site/es/index.html @@ -586,9 +586,9 @@

    Edita pidiéndolo

    -
    Enlaces para compartir Pro
    -

    Comparte con un enlace

    -

    Marca «Make a share link too» al exportar: ScreenForge sube el vídeo y copia un enlace al portapapeles. Se ve en cualquier navegador, sin iniciar sesión, y aparece con vista previa en los chats. Exporta de nuevo y el mismo enlace muestra la nueva versión.

    +
    Vídeo asíncrono Pro
    +

    Graba, comparte un enlace y ahórrate la reunión

    +

    Marca «Make a share link too» al exportar: ScreenForge sube el vídeo y te da todas las formas de pegarlo: el enlace, el MP4, Markdown para GitHub y Notion, y el código para insertarlo en tu web. Se ve en cualquier navegador, sin iniciar sesión, y aparece con vista previa en los chats. Exporta de nuevo y el mismo enlace muestra la nueva versión. ¿Vienes de Loom? Pega un enlace de Loom y el vídeo llega como proyecto.

    @@ -703,7 +703,7 @@

    Precios que se ajustan
    a tu forma de trabajar.

  • El agente de edición con IA: pide cambios o deja que edite todo el vídeo automáticamente
  • 1.000 créditos de agente al mes; los paquetes extra no caducan
  • Exportación ilimitada a MP4, ProRes, GIF y WebM
  • -
  • Enlaces para compartir: cada exportación puede ser un enlace que se ve en cualquier navegador
  • +
  • Vídeo asíncrono: cada exportación puede ser un enlace que se ve en cualquier navegador
  • Todas las actualizaciones futuras incluidas
  • Conseguir Pro diff --git a/site/index.html b/site/index.html index 0f9174e..495d0f1 100644 --- a/site/index.html +++ b/site/index.html @@ -38,7 +38,7 @@ "applicationSubCategory": "Screen recorder and video editor", "description": "AI screen recorder and video editor for tutorials, product demos, talking-head videos and screencasts. Records your screen, your webcam and, on a Mac, an iPhone or iPad. An AI agent edits from plain-language requests: cuts, zooms, speed, music and backgrounds. AI voice-over narration and captions run on your computer. Edits your own MP4 and MOV videos as well as its recordings. An open-source alternative to Screen Studio and CapCut.", "keywords": "AI video editor, AI screen recorder, screencast software, Screen Studio alternative, CapCut alternative, AI voice-over, automatic captions", - "featureList": ["AI editing agent", "AI voice-over narration, on-device or studio-quality ElevenLabs voices", "Your own voice cloned for narration (ElevenLabs)", "Voice-over clean-up and re-voicing (ElevenLabs)", "Automatic captions with on-device Whisper", "Automatic zooms", "Camera recording with face tracking", "Color grading", "iPhone and iPad recording (macOS)", "Phone and tablet device frames", "Voice-over recording", "Smooth cursor", "Backgrounds", "Separate voice track", "Blur and highlight masks", "Crop", "Keyboard shortcut overlay", "Edit any MP4, MOV or M4V video", "Share links that play in any browser"], + "featureList": ["AI editing agent", "AI voice-over narration, on-device or studio-quality ElevenLabs voices", "Your own voice cloned for narration (ElevenLabs)", "Voice-over clean-up and re-voicing (ElevenLabs)", "Automatic captions with on-device Whisper", "Automatic zooms", "Camera recording with face tracking", "Color grading", "iPhone and iPad recording (macOS)", "Phone and tablet device frames", "Voice-over recording", "Smooth cursor", "Backgrounds", "Separate voice track", "Blur and highlight masks", "Crop", "Keyboard shortcut overlay", "Edit any MP4, MOV or M4V video", "Import Loom videos from a share link", "Async video messages with share links that play in any browser", "Titles, descriptions and tags for YouTube, written by AI"], "applicationCategory": "MultimediaApplication", "operatingSystem": "macOS 14 or later, Windows 10 or later, Linux", "license": "https://www.apache.org/licenses/LICENSE-2.0", @@ -588,9 +588,9 @@

    Edit by asking

    -
    Share links Pro
    -

    Share with a link

    -

    Tick “Make a share link too” and Export uploads the video and puts a link on your clipboard. It plays in any browser, no sign-in, and unfurls with a preview in chat. Export again and the same link plays the new version.

    +
    Async video Pro
    +

    Record, share a link, skip the meeting

    +

    Tick “Make a share link too” and Export uploads the video, then lists every way to paste it: the link, the MP4, Markdown for GitHub and Notion, and an embed for your site. It plays in any browser, no sign-in, and unfurls with a preview in chat. Export again and the same link plays the new version. Coming from Loom? Paste a Loom link to bring the video in as a project.

    @@ -705,7 +705,7 @@

    Pricing that fits
    how you work.

  • The AI editing agent: ask for edits, or Auto edit the whole video
  • 1,000 agent credits a month; top-up packs never expire
  • Unlimited export to MP4, ProRes, GIF and WebM
  • -
  • Share links: an export becomes a link anyone can watch in a browser
  • +
  • Async video: an export becomes a link anyone can watch in a browser
  • Every future update included
  • Get Pro From a36734544b66bc9188d0eea5b4e2bda30f459b84 Mon Sep 17 00:00:00 2001 From: Mehfuz Hossain Date: Mon, 16 Nov 2026 19:05:45 -0800 Subject: [PATCH 4/5] Import from Loom, details on export, links to copy after sharing Loom: paste a loom.com/share link in the New project window (or run sf import ). The public video is fetched the way Loom's player does (an MP4, else its HLS playlist with the CloudFront signature as cookies; segments are downloaded here because the bundled ffmpeg has no certificate store) and imported like a video file, named after its Loom title. Videos whose owner turned downloads off are refused. Export writes a title, a description ending with the chapter list and tags beside the video (Name.details.txt) and shows them to copy. With the agent on, Claude writes them from the transcript while the video renders; otherwise they come from the project name, the opening words and the chapter titles. sf export writes the template. The export dialog shows one progress bar for the export and its upload instead of numbered steps, then the links to copy: the page, the MP4, Markdown with the poster and an HTML embed. A share sends the export's title, description and tags for the page. The New project window is one aligned column, with the Loom field under an "or import from Loom" divider. --- Cargo.lock | 1 + apps/sf-cli/src/main.rs | 34 +- apps/studio/src/agent_panel.rs | 13 + apps/studio/src/app.rs | 155 ++++++++-- apps/studio/src/export.rs | 261 +++++++++------- apps/studio/src/share.rs | 106 ++++++- apps/studio/src/widgets.rs | 41 +++ crates/sf-agent/src/details.rs | 108 +++++++ crates/sf-agent/src/lib.rs | 1 + crates/sf-engine/src/details.rs | 242 +++++++++++++++ crates/sf-engine/src/lib.rs | 1 + crates/sf-export/src/lib.rs | 24 ++ crates/sf-recording/Cargo.toml | 1 + crates/sf-recording/src/lib.rs | 1 + crates/sf-recording/src/loom.rs | 531 ++++++++++++++++++++++++++++++++ 15 files changed, 1378 insertions(+), 142 deletions(-) create mode 100644 crates/sf-agent/src/details.rs create mode 100644 crates/sf-engine/src/details.rs create mode 100644 crates/sf-recording/src/loom.rs diff --git a/Cargo.lock b/Cargo.lock index 44ef9c9..50dcc0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4750,6 +4750,7 @@ dependencies = [ "tempfile", "thiserror 2.0.21", "tracing", + "ureq 2.12.1", "which", "windows", "x11rb", diff --git a/apps/sf-cli/src/main.rs b/apps/sf-cli/src/main.rs index 27069a0..2e3084f 100644 --- a/apps/sf-cli/src/main.rs +++ b/apps/sf-cli/src/main.rs @@ -103,7 +103,8 @@ enum Cmd { Chapters { path: PathBuf }, /// Re-save a package (useful to migrate v3 → v4 on disk). Writes project.json.bak first. Resave { path: PathBuf }, - /// Copy a .screenstudio package into a folder as a .screenforge package (the original is untouched) + /// Copy a .screenstudio package into a folder as a .screenforge package (the original is + /// untouched), or download a public Loom video (a loom.com/share/… link) as a new project Import { path: PathBuf, /// Destination folder (default: ~/ScreenForge Projects) @@ -185,6 +186,11 @@ fn main() -> Result<()> { if modified(&txt).zip(modified(&result)).is_some_and(|(t, v)| t >= v) { eprintln!("wrote {} (chapters for a YouTube description)", txt.display()); } + // title, description and tags from the template (the app asks Claude when AI is on) + let details = sf_engine::details::template(&sf_export::details_input(&session, opts.range_ms)); + let dtxt = sf_export::details_txt_path(&result); + std::fs::write(&dtxt, details.to_text())?; + eprintln!("wrote {} (title, description and tags)", dtxt.display()); Ok(()) } Cmd::Presets { folder } => { @@ -277,6 +283,12 @@ fn main() -> Result<()> { println!("saved {} (migrated: {})", path.display(), pkg.migrated); Ok(()) } + Cmd::Import { path, to } if sf_recording::loom::is_link(&path.to_string_lossy()) => { + let folder = to.unwrap_or_else(sf_session::create::default_projects_folder); + let dest = import_loom(&path.to_string_lossy(), &folder)?; + println!("imported {} as {}", path.display(), dest.display()); + Ok(()) + } Cmd::Import { path, to } => { let folder = to.unwrap_or_else(sf_session::create::default_projects_folder); let dest = sf_project::package::import_screen_studio(&path, &folder)?; @@ -291,6 +303,26 @@ fn main() -> Result<()> { } } +/// Download a Loom share link and make a project of it in `folder` (named after the video). +fn import_loom(link: &str, folder: &std::path::Path) -> Result { + let cancel = std::sync::atomic::AtomicBool::new(false); + let work = std::env::temp_dir().join(format!("sf-loom-{}-{}", std::process::id(), chrono::Local::now().format("%Y%m%d%H%M%S"))); + let result = (|| -> Result { + let file = sf_recording::loom::download(link, &work.join("download"), |f| { + eprint!("\rdownloading {:5.1}%", f * 100.0); + let _ = std::io::stderr().flush(); + }, &cancel)?; + eprintln!(); + let name = file.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "Loom video".into()); + let rec = work.join("recording"); + sf_recording::import::import_video(&file, &rec, |_| {}, &cancel)?; + let opts = sf_session::create::CreateOptions { name, projects_folder: folder.to_path_buf(), default_config: None, create_automatic_zooms: false, markers_ms: vec![], device_mockup: false }; + Ok(sf_session::create::create_project_from_recording(&rec, opts)?.path) + })(); + let _ = std::fs::remove_dir_all(&work); + result +} + fn inspect(path: &std::path::Path, json: bool) -> Result<()> { let pkg = sf_project::ProjectPackage::open(path)?; if json { diff --git a/apps/studio/src/agent_panel.rs b/apps/studio/src/agent_panel.rs index 5bf5423..bb09afc 100644 --- a/apps/studio/src/agent_panel.rs +++ b/apps/studio/src/agent_panel.rs @@ -32,6 +32,13 @@ fn route() -> Result { Ok(Route { url: format!("{}/functions/v1/agent", sf_license::SUPABASE_URL), anon_key: sf_license::SUPABASE_ANON_KEY.into(), device }) } +/// How Export asks Claude for a video's title, description and tags: the agent's route and the +/// model chosen in the agent panel. `None` when this computer cannot be identified. +pub fn details_route() -> Option<(Route, &'static str)> { + let model = settings_path().map(|p| Settings::load(&p)).unwrap_or_default().pick(); + route().ok().map(|r| (r, model)) +} + /// The editor's side of the agent: catalogs gathered on the UI thread when a turn starts, and /// what needs files or the network (presets, Unsplash, imports), run on the agent's thread. struct StudioHost { @@ -437,6 +444,12 @@ fn credits_label(n: f64) -> String { impl AgentPanel { /// Ask the backend for this computer's balance. + /// Whether the agent (AI) is on for this computer, as the backend last said: `None` until + /// it has answered. + pub fn ai_allowed(&self) -> Option { + self.credits.as_ref().and_then(|c| c["allowed"].as_bool()) + } + fn fetch_credits(&mut self) { if self.credits_rx.is_some() { return; diff --git a/apps/studio/src/app.rs b/apps/studio/src/app.rs index fd0c43f..7437501 100644 --- a/apps/studio/src/app.rs +++ b/apps/studio/src/app.rs @@ -412,13 +412,18 @@ impl App { /// Render and upload `project` for a share link in the background (one job per project: /// a newer request replaces a running one). - fn start_share(&mut self, project: PathBuf, source: crate::share::Source, ctx: &egui::Context) { + fn start_share(&mut self, project: PathBuf, source: crate::share::Source, details: Option, ctx: &egui::Context) { for job in self.shares.iter().filter(|j| j.project == project) { job.cancel(); } self.shares.retain(|j| j.project != project); - let title = ed_name(&project); - self.shares.push(crate::share::ShareJob::start(project, title, source, ctx.clone())); + // the page shows the export's details: its title, description (with the chapters) and + // tags; without them, the project's name + let meta = match details { + Some(d) => crate::share::Meta { title: d.title.clone(), description: d.description.clone(), tags: d.tags.clone() }, + None => crate::share::Meta { title: ed_name(&project), ..Default::default() }, + }; + self.shares.push(crate::share::ShareJob::start(project, meta, source, ctx.clone())); } /// Follow the share jobs: a finished one copies its link and says so in a notification @@ -433,8 +438,9 @@ impl App { } if let Some(s) = ed.export.share_request.take() { let path = ed.path.clone(); + let details = ed.export.share_details.take(); ed.save(); - self.start_share(path, s, ctx); + self.start_share(path, s, details, ctx); } } let mut finished = Vec::new(); @@ -449,16 +455,17 @@ impl App { }; let editor_path = editor.as_ref().map(|ed| ed.path.clone()); let mut status: Option = None; - let mut last_link: Option> = None; + let mut last_link: Option> = None; for job in &self.shares { let mine = editor_path.as_ref() == Some(&job.project); match &job.result { - Some(Ok(url)) if finished.contains(&job.project) => { + Some(Ok(shared)) if finished.contains(&job.project) => { + let url = &shared.url; ctx.copy_text(url.clone()); crate::os::notify("Your share link is ready", &format!("“{}” is uploaded. The link is on your clipboard: {url}", job.title)); if mine { status = Some(format!("Share link copied: {url}")); - last_link = Some(Ok(url.clone())); + last_link = Some(Ok(shared.clone())); } } Some(Err(e)) if finished.contains(&job.project) && !crate::share::is_cancel(e) => { @@ -662,14 +669,56 @@ fn drop_unused_appended(project: &std::path::Path) { /// video file (`.mov`, `.mp4`, `.m4v`) made into a new project (progress in ms of video). fn open_or_import(path: &std::path::Path, progress: &sf_project::ImportProgress) -> anyhow::Result { use std::sync::atomic::Ordering; + if let Some(link) = loom_link(path) { + return import_loom(&link, progress); + } if !sf_recording::import::is_video(path) { return sf_session::create::package_to_open(path, progress); } let probe = sf_recording::import::probe(path)?; progress.total.store(probe.duration_ms.max(1.0) as u64, Ordering::Relaxed); + import_video_file(path, &probe, progress, |ms| ms as u64) +} + +/// The Loom share link an "open" path stands for (`begin_open` takes a pasted link as a path). +pub(crate) fn loom_link(path: &std::path::Path) -> Option { + let s = path.to_string_lossy(); + sf_recording::loom::is_link(&s).then(|| s.trim().to_string()) +} + +/// Parts of a Loom import's progress (`ImportProgress` counts to [`LOOM_STEPS`]): the download +/// is the first half, turning the video into a project the second. +const LOOM_STEPS: u64 = 1000; + +/// A Loom share link downloaded, then imported like a video file; the project takes the +/// video's title in Loom. +fn import_loom(link: &str, progress: &sf_project::ImportProgress) -> anyhow::Result { + use std::sync::atomic::Ordering; + progress.total.store(LOOM_STEPS, Ordering::Relaxed); + let half = LOOM_STEPS / 2; + let tmp = crate::recorder::recordings_folder().join(format!("Loom download {}", chrono::Local::now().format("%Y-%m-%d %H.%M.%S"))); + let cancelled = || progress.cancel.load(Ordering::Relaxed); + let result = (|| { + let file = sf_recording::loom::download(link, &tmp, |f| progress.done.store((f * half as f64) as u64, Ordering::Relaxed), &progress.cancel)?; + progress.done.store(half, Ordering::Relaxed); + let probe = sf_recording::import::probe(&file)?; + let total = probe.duration_ms.max(1.0); + import_video_file(&file, &probe, progress, |ms| half + (ms / total * half as f64) as u64) + })(); + let _ = std::fs::remove_dir_all(&tmp); + match result { + Err(_) if cancelled() => Err(sf_project::Error::Cancelled.into()), + r => r, + } +} + +/// `path` (a video ffprobe read as `probe`) as a new project named after the file. `step` +/// turns ms of video converted into the progress count. +fn import_video_file(path: &std::path::Path, probe: &sf_recording::import::Probe, progress: &sf_project::ImportProgress, step: impl Fn(f64) -> u64) -> anyhow::Result { + use std::sync::atomic::Ordering; let name = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "Video".into()); let dir = crate::recorder::recordings_folder().join(format!("Import {} {}", name, chrono::Local::now().format("%Y-%m-%d %H.%M.%S"))); - sf_recording::import::import_video(path, &dir, |ms| progress.done.store(ms as u64, Ordering::Relaxed), &progress.cancel)?; + sf_recording::import::import_video(path, &dir, |ms| progress.done.store(step(ms), Ordering::Relaxed), &progress.cancel)?; // a tall, phone-shaped video starts in a phone frame, like a Device recording let tall = probe.height as f64 >= probe.width as f64 * 1.6; let opts = sf_session::create::CreateOptions { name, projects_folder: sf_session::create::default_projects_folder(), default_config: None, create_automatic_zooms: false, markers_ms: vec![], device_mockup: tall }; @@ -707,7 +756,8 @@ fn import_dialog(ui: &mut egui::Ui, path: &std::path::Path, progress: &sf_projec let started = ctx.data_mut(|d| *d.get_temp_mut_or_insert_with(started_id, std::time::Instant::now)); let gb = |b: u64| b as f64 / 1e9; // a video (or a project being added) reports ms of video converted, an import bytes copied - let video = appending || sf_recording::import::is_video(path); + let loom = loom_link(path).is_some(); + let video = appending || loom || sf_recording::import::is_video(path); let adding_video = appending && sf_recording::import::is_video(path); let clock = |ms: u64| short_duration(ms as f64 / 1000.0); @@ -723,9 +773,9 @@ fn import_dialog(ui: &mut egui::Ui, path: &std::path::Path, progress: &sf_projec widgets::paint_icon(ui.painter(), egui::Rect::from_center_size(tile.center(), vec2(18.0, 18.0)), Icon::Folder, pal.accent); ui.vertical(|ui| { ui.add_space(2.0); - ui.label(RichText::new(if adding_video { "Adding video to project" } else if appending { "Adding project to the end" } else if video { "Importing video" } else { "Importing project" }).size(15.0).strong().color(pal.text)); + ui.label(RichText::new(if loom { "Importing from Loom" } else if adding_video { "Adding video to project" } else if appending { "Adding project to the end" } else if video { "Importing video" } else { "Importing project" }).size(15.0).strong().color(pal.text)); ui.add_space(3.0); - let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let name = if loom { path.to_string_lossy().into_owned() } else { path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default() }; ui.add(egui::Label::new(RichText::new(name).size(12.5).color(pal.text_dim)).truncate()); }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -742,7 +792,7 @@ fn import_dialog(ui: &mut egui::Ui, path: &std::path::Path, progress: &sf_projec ui.add_space(10.0); ui.horizontal(|ui| { - let amount = if video { format!("{} of {}", clock(done), clock(total)) } else { format!("{:.2} of {:.2} GB", gb(done), gb(total)) }; + let amount = if loom { (if done < LOOM_STEPS / 2 { "Downloading the video…" } else { "Making the project…" }).to_string() } else if video { format!("{} of {}", clock(done), clock(total)) } else { format!("{:.2} of {:.2} GB", gb(done), gb(total)) }; ui.label(RichText::new(amount).size(12.5).color(pal.text_dim)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let el = started.elapsed().as_secs_f64(); @@ -758,7 +808,7 @@ fn import_dialog(ui: &mut egui::Ui, path: &std::path::Path, progress: &sf_projec ui.horizontal(|ui| { ui.vertical(|ui| { ui.set_max_width(ui.available_width() - 100.0); - widgets::hint(ui, if adding_video { "The video goes after the last clip on the timeline. Your video file stays as it is." } else if appending { "Its clips go after the last one on the timeline, in this project's background and style. The project you dropped stays as it is." } else if video { "Your video stays as it is. The new project is saved to ScreenForge Projects." } else { "Your original project stays as it is. The copy is saved to ScreenForge Projects." }); + widgets::hint(ui, if loom { "Your Loom video stays as it is. The new project is saved to ScreenForge Projects." } else if adding_video { "The video goes after the last clip on the timeline. Your video file stays as it is." } else if appending { "Its clips go after the last one on the timeline, in this project's background and style. The project you dropped stays as it is." } else if video { "Your video stays as it is. The new project is saved to ScreenForge Projects." } else { "Your original project stays as it is. The copy is saved to ScreenForge Projects." }); }); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let cancel = ui.add_enabled_ui(!cancelling, |ui| widgets::secondary_button(ui, "Cancel").on_hover_text("Esc")).inner; @@ -777,36 +827,98 @@ fn import_dialog(ui: &mut egui::Ui, path: &std::path::Path, progress: &sf_projec enum BlankAction { Choose, Home, + /// A Loom share link to import. + Loom(String), } /// The new, empty project: a drop zone for a screencast or video, or a file to choose. fn blank_ui(ui: &mut egui::Ui) -> Option { use crate::widgets; + use egui::{pos2, vec2, Align, Align2, FontId, Layout, Rect, UiBuilder}; let pal = crate::theme::p(); let rect = ui.max_rect(); ui.painter().rect_filled(rect, 0.0, pal.bg); - let zone = egui::Rect::from_center_size(rect.center(), egui::vec2((rect.width() - 120.0).min(640.0), (rect.height() - 160.0).min(360.0))); + let zone = Rect::from_center_size(rect.center(), vec2((rect.width() - 120.0).min(640.0), (rect.height() - 120.0).min(440.0))); // a dashed outline, like a drop target let dash = |a: egui::Pos2, b: egui::Pos2| ui.painter().extend(egui::Shape::dashed_line(&[a, b], egui::Stroke::new(1.5, pal.border), 8.0, 6.0)); dash(zone.left_top(), zone.right_top()); dash(zone.right_top(), zone.right_bottom()); dash(zone.right_bottom(), zone.left_bottom()); dash(zone.left_bottom(), zone.left_top()); - let c = zone.center(); - widgets::paint_icon(ui.painter(), egui::Rect::from_center_size(egui::pos2(c.x, c.y - 70.0), egui::vec2(34.0, 34.0)), widgets::Icon::Plus, pal.text_dim); - ui.painter().text(egui::pos2(c.x, c.y - 22.0), egui::Align2::CENTER_CENTER, "Drop a screencast or video here", egui::FontId::proportional(18.0), pal.text); - ui.painter().text(egui::pos2(c.x, c.y + 6.0), egui::Align2::CENTER_CENTER, "A .mov, .mp4 or .m4v becomes a new project you can edit", egui::FontId::proportional(13.0), pal.text_dim); + + // one column, everything lined up on its edges: the drop target, its two buttons, then + // "or import from Loom" with the link field and Import under it + let w = 400.0_f32.min(zone.width() - 48.0); + let h = widgets::BUTTON_H.max(36.0); + let total = 34.0 + 18.0 + 22.0 + 10.0 + 16.0 + 24.0 + h + 30.0 + 14.0 + 16.0 + h + 10.0 + 16.0; + let (cx, mut y) = (zone.center().x, zone.center().y - total / 2.0); + let left = cx - w / 2.0; + let painter = ui.painter().clone(); + widgets::paint_icon(&painter, Rect::from_center_size(pos2(cx, y + 17.0), vec2(34.0, 34.0)), widgets::Icon::Plus, pal.text_dim); + y += 34.0 + 18.0; + painter.text(pos2(cx, y + 11.0), Align2::CENTER_CENTER, "Drop a screencast or video here", FontId::proportional(18.0), pal.text); + y += 22.0 + 10.0; + painter.text(pos2(cx, y + 8.0), Align2::CENTER_CENTER, "A .mov, .mp4 or .m4v becomes a new project you can edit", FontId::proportional(13.0), pal.text_dim); + y += 16.0 + 24.0; + let mut action = None; - let buttons = egui::Rect::from_center_size(egui::pos2(c.x, c.y + 56.0), egui::vec2(360.0, 36.0)); - ui.scope_builder(egui::UiBuilder::new().max_rect(buttons).layout(egui::Layout::left_to_right(egui::Align::Center).with_main_justify(false)), |ui| { - ui.add_space(((buttons.width() - 300.0) / 2.0).max(0.0)); + // a box of `width` at `x` on this row, its button stretched to fill it + let cell = |ui: &mut egui::Ui, x: f32, y: f32, width: f32, add: &mut dyn FnMut(&mut egui::Ui)| { + ui.scope_builder(UiBuilder::new().max_rect(Rect::from_min_size(pos2(x, y), vec2(width, h))).layout(Layout::top_down_justified(Align::Center)), |ui| { + ui.spacing_mut().interact_size.y = h; + add(ui) + }); + }; + let half = (w - 8.0) / 2.0; + cell(ui, left, y, half, &mut |ui| { if widgets::accent_button(ui, "Choose a video…").clicked() { action = Some(BlankAction::Choose); } + }); + cell(ui, left + half + 8.0, y, half, &mut |ui| { if widgets::secondary_button(ui, "Back to projects").clicked() { action = Some(BlankAction::Home); } }); + y += h + 30.0; + + // ── or import from Loom ── + let label = painter.layout_no_wrap("or import from Loom".into(), FontId::proportional(12.5), pal.text_dim); + let mid = y + 7.0; + let gap = label.size().x / 2.0 + 10.0; + painter.hline(left..=cx - gap, mid, egui::Stroke::new(1.0, pal.border)); + painter.hline(cx + gap..=left + w, mid, egui::Stroke::new(1.0, pal.border)); + painter.galley(pos2(cx - label.size().x / 2.0, mid - label.size().y / 2.0), label, pal.text_dim); + y += 14.0 + 16.0; + + // the link (kept in the UI's memory while the window is open) and Import, one row + let id = egui::Id::new("blank_loom_link"); + let mut link: String = ui.data(|d| d.get_temp(id)).unwrap_or_default(); + let ok = sf_recording::loom::is_link(&link); + let import_w = 96.0; + let mut submit = false; + let field_w = w - import_w - 8.0; + ui.scope_builder(UiBuilder::new().max_rect(Rect::from_min_size(pos2(left, y), vec2(field_w, h))).layout(Layout::left_to_right(Align::Center)), |ui| { + ui.set_width(field_w); + let field = widgets::text_field(ui, &mut link, "loom.com/share/…"); + submit |= widgets::submitted(ui, &field); + }); + cell(ui, left + field_w + 8.0, y, import_w, &mut |ui| { + if ui.add_enabled_ui(ok, |ui| widgets::secondary_button(ui, "Import")).inner.on_hover_text("Download the Loom video and make a project of it").clicked() { + submit = true; + } + }); + y += h + 10.0; + let typed = !link.trim().is_empty(); + let ok = sf_recording::loom::is_link(&link); + let (note, color) = if typed && !ok { ("That is not a Loom video link. Copy it from Share in Loom.", pal.danger) } else { ("Public Loom videos only. Their camera bubble stays in the picture.", pal.text_faint) }; + let galley = painter.layout(note.to_string(), FontId::proportional(12.0), color, w); + painter.galley(pos2(cx - galley.size().x / 2.0, y), galley, color); + if submit && ok { + action = Some(BlankAction::Loom(link.trim().to_string())); + link.clear(); + } + ui.data_mut(|d| d.insert_temp(id, link)); action } @@ -1096,6 +1208,7 @@ impl eframe::App for App { Screen::Blank => match blank_ui(ui) { Some(BlankAction::Choose) => self.ask(ctx, pick_video, &mut open_request), Some(BlankAction::Home) => go_home = true, + Some(BlankAction::Loom(link)) => open_request = Some(PathBuf::from(link)), None => {} }, Screen::Opening(path, rx, progress) => { diff --git a/apps/studio/src/export.rs b/apps/studio/src/export.rs index b211201..2398dc3 100644 --- a/apps/studio/src/export.rs +++ b/apps/studio/src/export.rs @@ -19,8 +19,15 @@ pub const DIALOG_W: f32 = 440.0; pub enum Msg { Progress(sf_export::Progress), Done(Result), + /// The title, description and tags written beside the video. + Details(sf_engine::details::Details), } +/// Part of the progress bar that is the export when it is shared too (the rest is the upload). +const EXPORT_SHARE: f32 = 0.7; +/// How long a finished export waits for Claude's details before using the template. +const DETAILS_WAIT: std::time::Duration = std::time::Duration::from_secs(60); + #[derive(Clone, Copy, PartialEq, Eq)] pub enum Format { Mp4, @@ -76,13 +83,18 @@ pub struct ExportDialog { /// A share to make (an export with "Make a share link too" finished): the app takes this /// and starts the share job. pub share_request: Option, + /// The export's title, description and tags, for the page behind the link (taken with + /// `share_request`). + pub share_details: Option, /// This project's share job, while one runs: 0..1 and what it is doing (set by the app /// every frame). pub share_running: Option<(f32, String)>, /// Set by Cancel while a share job runs; the app stops the job. pub share_cancel: bool, /// This project's last share link, or why it failed (set by the app). - pub last_link: Option>, + pub last_link: Option>, + /// The last export's title, description and tags (also in `.details.txt`). + details: Option, /// "Make a share link too": Export uploads what it wrote (Pro; `share::with_export_enabled`). share_with_export: bool, /// The running or finished export makes a link too: step 2 of the progress dialog. @@ -99,7 +111,7 @@ pub struct ExportDialog { /// that loads the license and talks to the backend. impl Default for ExportDialog { fn default() -> Self { - ExportDialog { open: false, license: sf_license::Status::Invalid("no key".into()), email: String::new(), activation: None, check_in: None, activation_msg: None, code_sent_to: None, code: String::new(), signing_in: false, promo: String::new(), promo_open: false, checkout: None, claim_until: None, next_claim: None, claim: None, free_left: None, free_rx: None, was_open: false, license_seen: 0, free_job: false, format: Format::Mp4, fps: 60.0, height: 1080, quality: QualityPreset::SocialMedia, codec: VideoCodec::H264, audio: true, job: None, progress: None, result: None, started: None, share_request: None, share_running: None, share_cancel: false, last_link: None, share_with_export: false, export_shared: false, project_id: String::new(), qr_open: false } + ExportDialog { open: false, license: sf_license::Status::Invalid("no key".into()), email: String::new(), activation: None, check_in: None, activation_msg: None, code_sent_to: None, code: String::new(), signing_in: false, promo: String::new(), promo_open: false, checkout: None, claim_until: None, next_claim: None, claim: None, free_left: None, free_rx: None, was_open: false, license_seen: 0, free_job: false, format: Format::Mp4, fps: 60.0, height: 1080, quality: QualityPreset::SocialMedia, codec: VideoCodec::H264, audio: true, job: None, progress: None, result: None, started: None, share_request: None, share_details: None, share_running: None, share_cancel: false, last_link: None, share_with_export: false, export_shared: false, project_id: String::new(), qr_open: false, details: None } } } @@ -339,6 +351,7 @@ impl ExportDialog { while let Ok(m) = rx.try_recv() { match m { Msg::Progress(p) => self.progress = Some(p), + Msg::Details(d) => self.details = Some(d), Msg::Done(r) => { // a finished free export is counted (kept on disk until online) // the server's answer replaces the count (a cancelled or failed one @@ -358,6 +371,8 @@ impl ExportDialog { if self.export_shared { let as_is = self.format == Format::Mp4 && self.codec == VideoCodec::H264; self.share_request = Some(if as_is { crate::share::Source::File(out.clone()) } else { crate::share::Source::Render(self.share_settings()) }); + // written before the video finished (Msg::Details comes first) + self.share_details = self.details.clone(); self.share_running = Some((0.0, "Starting…".into())); } } @@ -381,7 +396,8 @@ impl ExportDialog { } /// Progress / result shown in the export dialog while `is_busy()`: a preview of the video, - /// then the export and (with "Make a share link too") its share link, as two numbered steps. + /// one progress bar for the export and (with "Make a share link too") its upload, then the + /// file, the links to copy and the video's details. /// `preview`: the editor's frame (texture, width / height). pub fn compact_ui(&mut self, ui: &mut egui::Ui, preview: Option<(egui::TextureId, f32)>) { let pal = theme::p(); @@ -400,19 +416,23 @@ impl ExportDialog { } let exporting = self.job.is_some(); let sharing = self.export_shared; + let uploading = sharing && !exporting && self.share_running.is_some(); let title = if exporting { - "Exporting…" - } else if sharing && self.share_running.is_some() { - "Making the share link…" + if sharing { "Exporting and sharing…" } else { "Exporting…" } + } else if uploading { + "Uploading…" + } else if sharing && matches!(self.last_link, Some(Ok(_))) { + "Exported and shared" } else { "Export complete" }; ui.label(RichText::new(title).size(15.0).strong().color(pal.text)); ui.add_space(8.0); if let Some((tex, aspect)) = preview { - // what is being exported, as wide as the box (at most 220 px tall) + // what is being exported, as wide as the box (at most 220 px tall, less once done + // to leave room for the links) let w = ui.available_width(); - let h = (w / aspect.max(0.1)).min(220.0); + let h = (w / aspect.max(0.1)).min(if exporting || uploading { 220.0 } else { 150.0 }); let size = egui::vec2(h * aspect, h).min(egui::vec2(w, h)); ui.vertical_centered(|ui| { ui.add(egui::Image::new((tex, size)).corner_radius(4)); @@ -420,75 +440,126 @@ impl ExportDialog { ui.add_space(12.0); } - // 1. the video file - let p = self.progress; - let frac = p.map(|p| p.frame as f32 / p.total_frames.max(1) as f32).unwrap_or(0.0); - step_header(ui, 1, "Video", if exporting { StepState::Active } else { StepState::Done }, exporting.then(|| format!("{:.0}%", frac * 100.0))); - step_body(ui, |ui| { - if exporting { - progress_bar(ui, frac); - ui.add_space(2.0); - match (p, self.started) { - (Some(_), Some(t)) if frac > 0.02 => { - let el = t.elapsed().as_secs_f64(); - widgets::hint(ui, &format!("About {:.0}s left", el / frac as f64 - el)); - } - _ => widgets::hint(ui, "Preparing…"), - } - } else if let Some(Ok(out)) = self.result.clone() { - ui.horizontal(|ui| { + if exporting || uploading { + self.progress_ui(ui, exporting, sharing); + return; + } + + // the file + if let Some(Ok(out)) = self.result.clone() { + widgets::labeled_row(ui, "File", |ui| { + ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 30.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { let name = out.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); ui.label(RichText::new(name).size(13.0).color(pal.text)).on_hover_text(out.display().to_string()); if widgets::icon_button(ui, widgets::Icon::Folder, 13.0, &format!("Show in {}", crate::os::FILE_MANAGER)).clicked() { crate::os::reveal(&out); } }); - // written after the video by this export (an older list of a project that - // has no chapters now is not mentioned) - let txt = sf_export::chapters_txt_path(&out); - let modified = |f: &std::path::Path| std::fs::metadata(f).and_then(|m| m.modified()).ok(); - if modified(&txt).zip(modified(&out)).is_some_and(|(t, v)| t >= v) { - let txt_name = txt.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); - widgets::hint(ui, &format!("Chapters are in the video, and listed for a YouTube description in {txt_name}.")); - } - } - }); + }); + } - // 2. the project's share link, always at hand (with its QR code); this export puts its - // video behind it with "Make a share link too" + // the links: everything this export was shared as, or the project's page if sharing || crate::share::allowed() { - ui.add_space(10.0); - let state = match (&self.share_running, &self.last_link) { - _ if !sharing => StepState::Done, - _ if exporting => StepState::Waiting, - (Some(_), _) => StepState::Active, - (None, Some(Err(_))) => StepState::Failed, - _ => StepState::Done, + ui.add_space(6.0); + section_label(ui, "Links"); + let shared = match &self.last_link { + Some(Ok(s)) if sharing => Some(s.clone()), + _ => self.shown_link().map(crate::share::Shared::page), }; - let pct = self.share_running.as_ref().map(|(f, _)| format!("{:.0}%", f * 100.0)); - step_header(ui, 2, "Share link", state, pct); - step_body(ui, |ui| { - self.link_status_ui(ui); + if let Some(Err(e)) = self.last_link.clone().filter(|_| sharing) { + ui.add(egui::Label::new(RichText::new(format!("The upload failed: {e}")).size(13.0).color(pal.danger)).wrap()); + ui.add_space(4.0); + } + if let Some(shared) = shared { + let rows = if sharing && matches!(self.last_link, Some(Ok(_))) { crate::share::link_rows(&shared, &self.title_for_links()) } else { crate::share::link_rows(&shared, "").into_iter().take(1).collect() }; + for row in rows { + if row.label == "Page" { + widgets::labeled_row(ui, row.label, |ui| widgets::link_field_qr(ui, &row.text, &mut self.qr_open)); + } else { + widgets::labeled_row(ui, row.label, |ui| widgets::copy_field(ui, &row.text, row.tip)); + } + } + } + if !sharing { widgets::hint(ui, LINK_HINT); - }); + } + } + + // the title, description and tags + if let Some(d) = self.details.clone() { + ui.add_space(6.0); + section_label(ui, if d.by_ai { "Details · written by AI" } else { "Details" }); + widgets::labeled_row(ui, "Title", |ui| widgets::copy_field(ui, &d.title, "Copy the title")); + if !d.description.is_empty() { + widgets::labeled_row(ui, "Description", |ui| widgets::copy_field(ui, &d.description, "Copy the description (with the chapters)")); + } + if !d.tags.is_empty() { + widgets::labeled_row(ui, "Tags", |ui| widgets::copy_field(ui, &d.tags_line(), "Copy the tags")); + } + if let Some(Ok(out)) = &self.result { + let txt = sf_export::details_txt_path(out); + let name = txt.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + widgets::hint(ui, &format!("Also saved beside the video in {name}.")); + } } ui.add_space(10.0); buttons_row(ui, |ui| { - if exporting { - if widgets::secondary_button(ui, "Cancel").on_hover_text("Esc").clicked() { - if let Some((_, _, cancel)) = &self.job { - cancel.store(true, Ordering::Relaxed); - } - } - } else if widgets::accent_button(ui, "Done").clicked() { - // a link still uploading carries on; a notification says when it is ready + if widgets::accent_button(ui, "Done").clicked() { self.result = None; self.export_shared = false; } }); } + /// One bar for the whole job: the export, then (when shared) the upload. + fn progress_ui(&mut self, ui: &mut egui::Ui, exporting: bool, sharing: bool) { + let pal = theme::p(); + let p = self.progress; + let export_frac = if exporting { p.map(|p| p.frame as f32 / p.total_frames.max(1) as f32).unwrap_or(0.0) } else { 1.0 }; + let share_frac = self.share_running.as_ref().map_or(0.0, |(f, _)| *f); + let overall = if !sharing { export_frac } else if exporting { EXPORT_SHARE * export_frac } else { EXPORT_SHARE + (1.0 - EXPORT_SHARE) * share_frac }; + let label = if exporting { + match (p, self.started) { + (Some(_), Some(t)) if export_frac > 0.02 => { + let el = t.elapsed().as_secs_f64(); + format!("Rendering the video · about {:.0}s left", el / export_frac as f64 - el) + } + _ => "Preparing…".to_string(), + } + } else { + self.share_running.as_ref().map(|(_, l)| l.clone()).unwrap_or_else(|| "Uploading…".into()) + }; + progress_bar(ui, overall); + ui.add_space(4.0); + ui.horizontal(|ui| { + widgets::hint(ui, &label); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.label(RichText::new(format!("{:.0}%", overall * 100.0)).size(13.0).color(pal.text_dim)); + }); + }); + if sharing { + widgets::hint(ui, "The links to copy show here once it is uploaded."); + } + ui.add_space(10.0); + buttons_row(ui, |ui| { + if widgets::secondary_button(ui, "Cancel").on_hover_text("Esc").clicked() { + if let Some((_, _, cancel)) = &self.job { + cancel.store(true, Ordering::Relaxed); + } else { + // stop uploading; the link keeps what it had + self.share_cancel = true; + } + } + }); + } + + /// The title the Markdown and embed links carry: the video's details, else nothing (the + /// links then say "Watch the video"). + fn title_for_links(&self) -> String { + self.details.as_ref().map(|d| d.title.clone()).unwrap_or_default() + } + /// Export settings, drawn in the export dialog over the editor. Escape, Cancel or a click /// outside dismisses it. /// Without a license: the free exports line. Returns true when Pro, Creator and sign-in @@ -575,7 +646,7 @@ impl ExportDialog { if !self.project_id.is_empty() { return Some(crate::share::link_url(&self.project_id)); } - self.last_link.clone().and_then(Result::ok) + self.last_link.clone().and_then(Result::ok).map(|s| s.url) } /// Cloud share links (Pro): made by Export with "Make a share link too"; others see what @@ -787,6 +858,19 @@ impl ExportDialog { QualityPreset::WebLow => 0.2, }; let opts = sf_export::ExportOptions { output: out, fps: self.fps, max_height: self.height, codec, quality, include_audio: self.audio, range_ms: None }; + // the title, description and tags are written while the video renders: by Claude when + // the agent (AI) is on for this computer, else from the template + let input = sf_export::details_input(&ed.session, None); + let fallback = input.clone(); + let ai = ed.agent.ai_allowed() != Some(false); + let (details_tx, details_rx) = channel(); + std::thread::Builder::new() + .name("export-details".into()) + .spawn(move || { + let drafted = if ai { crate::agent_panel::details_route().and_then(|(route, model)| sf_agent::details::draft(&route, model, &input).ok()) } else { None }; + let _ = details_tx.send(drafted.unwrap_or_else(|| sf_engine::details::template(&input))); + }) + .expect("spawn export details"); let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); let cancel2 = cancel.clone(); @@ -800,7 +884,13 @@ impl ExportDialog { let _ = tx2.send(Msg::Progress(p)); }) }; - let _ = tx.send(Msg::Done(run().map_err(|e| format!("{e:#}")))); + let done = run(); + if let Ok(video) = &done { + let details = details_rx.recv_timeout(DETAILS_WAIT).unwrap_or_else(|_| sf_engine::details::template(&fallback)); + let _ = std::fs::write(sf_export::details_txt_path(video), details.to_text()); + let _ = tx.send(Msg::Details(details)); + } + let _ = tx.send(Msg::Done(done.map_err(|e| format!("{e:#}")))); }); self.free_job = !self.license.is_valid(); if self.free_job { @@ -812,6 +902,7 @@ impl ExportDialog { self.started = Some(std::time::Instant::now()); self.progress = None; self.result = None; + self.details = None; // step 2 of the progress dialog: the link, once the file is written self.export_shared = self.share_with_export && crate::share::allowed(); if self.export_shared { @@ -822,61 +913,15 @@ impl ExportDialog { } } -#[derive(Clone, Copy, PartialEq)] -enum StepState { - Waiting, - Active, - Done, - Failed, -} - /// The one note under a project's share link, the same whatever is uploaded. const LINK_HINT: &str = "This project's link. Export with \u{201c}Make a share link too\u{201d} to put the latest video behind it."; -/// A numbered step of the export dialog: its marker (number, or a check once done), its name, -/// and on the right its percentage while it runs. -fn step_header(ui: &mut egui::Ui, n: u32, name: &str, state: StepState, right: Option) { - let pal = theme::p(); - ui.horizontal(|ui| { - let (rect, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); - let c = rect.center(); - let painter = ui.painter(); - match state { - StepState::Done => { - painter.circle_filled(c, 9.0, pal.accent); - widgets::paint_icon(painter, rect.shrink(4.5), widgets::Icon::Check, pal.bg); - } - StepState::Failed => { - painter.circle_filled(c, 9.0, pal.danger); - widgets::paint_icon(painter, rect.shrink(5.0), widgets::Icon::Close, pal.bg); - } - StepState::Active | StepState::Waiting => { - let color = if state == StepState::Active { pal.accent } else { pal.text_faint }; - painter.circle_stroke(c, 8.25, egui::Stroke::new(1.5, color)); - painter.text(c, egui::Align2::CENTER_CENTER, n.to_string(), egui::FontId::proportional(11.0), color); - } - } - let text = if state == StepState::Waiting { pal.text_dim } else { pal.text }; - ui.label(RichText::new(name).size(14.0).color(text)); - if let Some(r) = right { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(RichText::new(r).size(13.0).color(pal.text_dim)); - }); - } - }); +/// A small heading over a list of copy rows ("Links", "Details"). +fn section_label(ui: &mut egui::Ui, text: &str) { + ui.label(RichText::new(text).size(13.0).strong().color(theme::p().text)); ui.add_space(4.0); } -/// What a step shows under its header, lined up with the step's name (past the 18 px marker) -/// and as wide as the box from there. -fn step_body(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) { - let left = 18.0 + ui.spacing().item_spacing.x; - egui::Frame::NONE.inner_margin(egui::Margin { left: left as i8, right: 0, top: 0, bottom: 0 }).show(ui, |ui| { - ui.set_width(ui.available_width()); - add(ui); - }); -} - /// A full-width bar painted by hand (egui's ProgressBar shrinks to its label in these dialogs). fn progress_bar(ui: &mut egui::Ui, frac: f32) { let pal = theme::p(); diff --git a/apps/studio/src/share.rs b/apps/studio/src/share.rs index 0a3a4ba..71a24f0 100644 --- a/apps/studio/src/share.rs +++ b/apps/studio/src/share.rs @@ -35,9 +35,65 @@ pub enum Stage { Uploading(f32), } +/// A finished share: the page anyone can watch, and (when the server says) the video file and +/// poster behind it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Shared { + pub url: String, + pub video: Option, + pub poster: Option, +} + +impl Shared { + /// Just the page (its id is known before anything is uploaded; `link_url`). + pub fn page(url: String) -> Shared { + Shared { url, ..Default::default() } + } +} + +/// One link to copy from the export dialog: what it is, and the text that goes on the clipboard. +#[derive(Clone, Debug, PartialEq)] +pub struct LinkRow { + pub label: &'static str, + pub text: String, + pub tip: &'static str, +} + +/// Everything a share can be pasted as: the page, the video file, Markdown with the poster +/// (GitHub, Notion, docs) and HTML to embed the player. +pub fn link_rows(s: &Shared, title: &str) -> Vec { + let title = title.trim(); + let alt = if title.is_empty() { "Watch the video" } else { title }; + let alt_md = alt.replace(['[', ']'], ""); + let esc = |t: &str| t.replace('&', "&").replace('"', """).replace('<', "<"); + let mut rows = vec![LinkRow { label: "Page", text: s.url.clone(), tip: "The page anyone can watch: paste it in a message, email or ticket" }]; + if let Some(v) = &s.video { + rows.push(LinkRow { label: "Video file", text: v.clone(), tip: "The MP4 itself, for players and tools that take a video address" }); + } + let md = match &s.poster { + Some(p) => format!("[![{alt_md}]({p})]({})", s.url), + None => format!("[{alt_md}]({})", s.url), + }; + rows.push(LinkRow { label: "Markdown", text: md, tip: "For GitHub, Notion and docs: the poster image, linked to the page" }); + if let Some(v) = &s.video { + let poster = s.poster.as_ref().map(|p| format!(" poster=\"{}\"", esc(p))).unwrap_or_default(); + rows.push(LinkRow { label: "Embed", text: format!("", esc(v), esc(alt)), tip: "HTML for a web page: the video plays right there" }); + } + rows +} + +/// What the page behind a link says about the video: its title, a description (which may end +/// with the chapter list) and tags. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Meta { + pub title: String, + pub description: String, + pub tags: Vec, +} + enum Msg { Stage(Stage), - Done(Result), + Done(Result), } /// A share in progress (or just finished) for one project. @@ -45,8 +101,8 @@ pub struct ShareJob { pub project: PathBuf, pub title: String, pub stage: Stage, - /// The link, or why there is none. Set once the job is over. - pub result: Option>, + /// The links, or why there are none. Set once the job is over. + pub result: Option>, rx: Receiver, cancel: Arc, } @@ -54,10 +110,11 @@ pub struct ShareJob { impl ShareJob { /// Render `project` (or take the exported file) and upload it on a background thread. /// `repaint` wakes the UI as the job moves on. - pub fn start(project: PathBuf, title: String, source: Source, repaint: egui::Context) -> ShareJob { + pub fn start(project: PathBuf, meta: Meta, source: Source, repaint: egui::Context) -> ShareJob { let (tx, rx) = channel(); let cancel = Arc::new(AtomicBool::new(false)); - let (path, name, stop) = (project.clone(), title.clone(), cancel.clone()); + let title = meta.title.clone(); + let (path, name, stop) = (project.clone(), meta, cancel.clone()); let first = if matches!(source, Source::File(_)) { Stage::Uploading(0.0) } else { Stage::Rendering(0.0) }; std::thread::Builder::new() .name("share-link".into()) @@ -181,7 +238,7 @@ fn ask_allowed(generation: u64) { }); } -fn run(project: &Path, title: &str, source: Source, cancel: &AtomicBool, stage: &dyn Fn(Stage)) -> Result { +fn run(project: &Path, meta: &Meta, source: Source, cancel: &AtomicBool, stage: &dyn Fn(Stage)) -> Result { let auth = sf_license::owner_auth().ok_or("Sign in to ScreenForge Pro on this computer to share links (Export → Sign in).")?; let s = match source { Source::File(video) => { @@ -189,7 +246,7 @@ fn run(project: &Path, title: &str, source: Source, cancel: &AtomicBool, stage: let info = sf_media::probe::probe(&video).map_err(|e| format!("Could not read the exported video: {e:#}"))?; let v = info.video(); let dims = (v.and_then(|v| v.width).unwrap_or(0), v.and_then(|v| v.height).unwrap_or(0), info.duration_ms().unwrap_or(0.0).max(0.0) as u64); - return upload(project, &video, title, dims, auth, cancel, &|f| stage(Stage::Uploading(f))); + return upload(project, &video, meta, dims, auth, cancel, &|f| stage(Stage::Uploading(f))); } Source::Render(s) => s, }; @@ -203,7 +260,7 @@ fn run(project: &Path, title: &str, source: Source, cancel: &AtomicBool, stage: return Err(CANCELLED.to_string()); } stage(Stage::Uploading(0.0)); - upload(project, &video, title, (width, height, duration_ms), auth, cancel, &|f| stage(Stage::Uploading(f))) + upload(project, &video, meta, (width, height, duration_ms), auth, cancel, &|f| stage(Stage::Uploading(f))) })(); let _ = std::fs::remove_file(&video); result @@ -244,7 +301,7 @@ fn poster_jpeg(project: &Path) -> Option> { Some(out) } -fn upload(project: &Path, video: &Path, title: &str, (width, height, duration_ms): (u32, u32, u64), auth: serde_json::Value, cancel: &AtomicBool, progress: &dyn Fn(f32)) -> Result { +fn upload(project: &Path, video: &Path, meta: &Meta, (width, height, duration_ms): (u32, u32, u64), auth: serde_json::Value, cancel: &AtomicBool, progress: &dyn Fn(f32)) -> Result { let bytes = std::fs::metadata(video).map_err(|e| format!("The rendered video is missing: {e}"))?.len(); let poster = poster_jpeg(project); let mut req = auth.clone(); @@ -254,7 +311,14 @@ fn upload(project: &Path, video: &Path, title: &str, (width, height, duration_ms if let Some(id) = &project_id { req["project"] = id.clone().into(); } - req["title"] = title.into(); + req["title"] = meta.title.as_str().into(); + // older share servers ignore these + if !meta.description.trim().is_empty() { + req["description"] = meta.description.trim().into(); + } + if !meta.tags.is_empty() { + req["tags"] = meta.tags.clone().into(); + } req["bytes"] = bytes.into(); req["width"] = width.into(); req["height"] = height.into(); @@ -280,10 +344,14 @@ fn upload(project: &Path, video: &Path, title: &str, (width, height, duration_ms } let mut req = auth; req["action"] = "complete".into(); - req["id"] = id.into(); + req["id"] = id.clone().into(); let done = call(req)?; let url = done["url"].as_str().map(String::from).ok_or("The share server sent no link.")?; - Ok(url) + // the file and poster addresses (with the version that gets past the CDN's cached copy) + // come from the public `get`; without them the dialog lists the page alone + let media = call(serde_json::json!({ "action": "get", "id": id })).ok(); + let field = |k: &str| media.as_ref().and_then(|m| m[k].as_str()).filter(|s| s.starts_with("https://")).map(String::from); + Ok(Shared { url, video: field("video"), poster: field("poster") }) } /// The video file as the upload body, reporting progress and stopping when cancelled. @@ -398,6 +466,20 @@ mod tests { assert!((job.fraction() - 1.0).abs() < 1e-6); } + #[test] + fn link_rows_cover_page_file_markdown_and_embed() { + let s = Shared { url: "https://screenforge.studio/s/abc".into(), video: Some("https://media.screenforge.studio/v/abc/video.mp4?v=2".into()), poster: Some("https://media.screenforge.studio/v/abc/poster.jpg?v=2".into()) }; + let rows = link_rows(&s, "My [demo] & more"); + let labels: Vec<_> = rows.iter().map(|r| r.label).collect(); + assert_eq!(labels, vec!["Page", "Video file", "Markdown", "Embed"]); + assert_eq!(rows[2].text, "[![My demo & more](https://media.screenforge.studio/v/abc/poster.jpg?v=2)](https://screenforge.studio/s/abc)"); + assert!(rows[3].text.starts_with("