Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add optional text layer backgrounds

Richie McIlroy04c7c69c853e
diff --git a/apps/desktop-gpui/src/editor_edits.rs b/apps/desktop-gpui/src/editor_edits.rs
index c4e23b8e6..b465d9af0 100644
--- a/apps/desktop-gpui/src/editor_edits.rs
+++ b/apps/desktop-gpui/src/editor_edits.rs
@@ -1034,6 +1034,7 @@ pub fn default_text_segment(start: f64, end: f64, track: u32) -> TextSegment {
font_weight: 700.0,
italic: false,
color: "#ffffff".to_string(),
+ background_color: None,
fade_duration: 0.15,
align: Default::default(),
letter_spacing: 0.0,
diff --git a/apps/desktop-gpui/src/editor_panels.rs b/apps/desktop-gpui/src/editor_panels.rs
index 72f180486..b50c9765e 100644
--- a/apps/desktop-gpui/src/editor_panels.rs
+++ b/apps/desktop-gpui/src/editor_panels.rs
@@ -3880,6 +3880,8 @@ impl EditorWindow {
let italic = segment.italic;
let enabled = segment.enabled;
let color = segment.color.clone();
+ let background_color = segment.background_color.clone();
+ let background_enabled = background_color.is_some();
let family = segment.font_family.clone();
let weight_label = TEXT_SEGMENT_WEIGHTS
.iter()
@@ -4179,6 +4181,42 @@ impl EditorWindow {
&color,
cx,
))
+ .child(
+ self.labelled_small(
+ "Background",
+ ui::Toggle::plain(
+ &theme,
+ SharedString::from(format!(
+ "text-background-enabled-{index}"
+ )),
+ background_enabled,
+ )
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.edit_text_segment(
+ "text-background",
+ index,
+ window,
+ cx,
+ move |segment| {
+ segment.background_color = if background_enabled {
+ None
+ } else {
+ Some("#000000".to_string())
+ };
+ true
+ },
+ );
+ }))
+ .into_any_element(),
+ ),
+ )
+ .when_some(background_color, |this, background_color| {
+ this.child(self.render_color_input(
+ ColorTarget::TextBackground(index),
+ &background_color,
+ cx,
+ ))
+ })
.child(
self.labelled_small(
"Opacity",
@@ -6091,6 +6129,9 @@ impl EditorWindow {
for index in indices(timeline.text_segments.len()) {
fields.push(FieldKey::TextContent(index));
colors.push(ColorTarget::TextColor(index));
+ if timeline.text_segments[index].background_color.is_some() {
+ colors.push(ColorTarget::TextBackground(index));
+ }
}
}
TrackKind::Caption => {
diff --git a/apps/desktop-gpui/src/editor_sidebar.rs b/apps/desktop-gpui/src/editor_sidebar.rs
index a17b89f2c..9bb5c454d 100644
--- a/apps/desktop-gpui/src/editor_sidebar.rs
+++ b/apps/desktop-gpui/src/editor_sidebar.rs
@@ -736,6 +736,7 @@ pub enum ColorTarget {
KeyboardBackground,
/// A text segment's colour, per segment index.
TextColor(usize),
+ TextBackground(usize),
}
impl ColorTarget {
@@ -1669,6 +1670,12 @@ impl EditorWindow {
.as_ref()
.and_then(|timeline| timeline.text_segments.get(index))
.map(|segment| segment.color.clone()),
+ ColorTarget::TextBackground(index) => self
+ .project
+ .timeline
+ .as_ref()
+ .and_then(|timeline| timeline.text_segments.get(index))
+ .and_then(|segment| segment.background_color.clone()),
_ => None,
}
}
@@ -1789,6 +1796,15 @@ impl EditorWindow {
true
})
}
+ ColorTarget::TextBackground(index) => {
+ self.edit_text_segment("text-background-color", index, window, cx, move |segment| {
+ if segment.background_color.as_deref() == Some(hex.as_str()) {
+ return false;
+ }
+ segment.background_color = Some(hex);
+ true
+ })
+ }
_ => {}
}
}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 2db5ee967..96c4094d5 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -5649,6 +5649,19 @@ fn random_animated_gradient() -> cap_project::AnimatedGradientConfig {
cap_project::AnimatedGradientConfig::random()
}
+#[cfg(any(debug_assertions, test))]
+fn typescript_exporter() -> specta_typescript::Typescript {
+ specta_typescript::Typescript::default().formatter(|path| {
+ let source = std::fs::read_to_string(path)?;
+ let formatted = source
+ .lines()
+ .map(str::trim_end)
+ .collect::<Vec<_>>()
+ .join("\n");
+ std::fs::write(path, format!("{formatted}\n"))
+ })
+}
+
fn specta_builder() -> tauri_specta::Builder {
tauri_specta::Builder::new()
.commands(tauri_specta::collect_commands![
@@ -5929,9 +5942,7 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
{
let bindings_path = std::path::Path::new("../src/utils/tauri.ts");
if bindings_path.parent().is_some_and(|parent| parent.exists()) {
- if let Err(err) =
- specta_builder.export(specta_typescript::Typescript::default(), bindings_path)
- {
+ if let Err(err) = specta_builder.export(typescript_exporter(), bindings_path) {
warn!(error = %err, "Failed to export TypeScript bindings");
}
} else {
@@ -8527,7 +8538,7 @@ mod typescript_bindings_tests {
let bindings_path = std::path::Path::new("../src/utils/tauri.ts");
if bindings_path.parent().is_some_and(|parent| parent.exists()) {
super::specta_builder()
- .export(specta_typescript::Typescript::default(), bindings_path)
+ .export(super::typescript_exporter(), bindings_path)
.expect("failed to export TypeScript bindings");
}
}
diff --git a/apps/desktop/src/routes/editor/ConfigSidebar.tsx b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
index 16cabfc58..a58f3f13d 100644
--- a/apps/desktop/src/routes/editor/ConfigSidebar.tsx
+++ b/apps/desktop/src/routes/editor/ConfigSidebar.tsx
@@ -4013,6 +4013,28 @@ function TextSegmentConfig(props: {
})
}
/>
+ <div class="flex items-center justify-between gap-3">
+ <span class="text-xs text-gray-11">Background</span>
+ <Toggle
+ checked={props.segment.backgroundColor != null}
+ onChange={(enabled) =>
+ updateSegment((segment) => {
+ segment.backgroundColor = enabled ? "#000000" : undefined;
+ })
+ }
+ />
+ </div>
+ <Show when={props.segment.backgroundColor != null}>
+ <HexColorInput
+ value={props.segment.backgroundColor ?? "#000000"}
+ brandColorSwatches={props.brandColorSwatches}
+ onChange={(value) =>
+ updateSegment((segment) => {
+ segment.backgroundColor = value;
+ })
+ }
+ />
+ </Show>
<div class="flex flex-col gap-1">
<span class="text-xs text-gray-11">Opacity</span>
<Slider
diff --git a/apps/desktop/src/routes/editor/TextOverlay.tsx b/apps/desktop/src/routes/editor/TextOverlay.tsx
index 3d527d99b..253104368 100644
--- a/apps/desktop/src/routes/editor/TextOverlay.tsx
+++ b/apps/desktop/src/routes/editor/TextOverlay.tsx
@@ -265,6 +265,7 @@ type SegmentWithDefaults = {
fontWeight: number;
italic: boolean;
color: string;
+ backgroundColor: string | null;
align: TextAlign;
letterSpacing: number;
lineHeight: number;
@@ -274,7 +275,12 @@ function normalizeSegment(segment: TauriTextSegment): SegmentWithDefaults {
// The generated bindings lag behind the Rust schema until the next debug
// run regenerates them; the style fields are always present at runtime.
const styled = segment as TauriTextSegment &
- Partial<Pick<TextSegment, "align" | "letterSpacing" | "lineHeight">>;
+ Partial<
+ Pick<
+ TextSegment,
+ "align" | "backgroundColor" | "letterSpacing" | "lineHeight"
+ >
+ >;
return {
start: segment.start,
end: segment.end,
@@ -287,6 +293,7 @@ function normalizeSegment(segment: TauriTextSegment): SegmentWithDefaults {
fontWeight: segment.fontWeight ?? 700,
italic: segment.italic ?? false,
color: segment.color ?? "#ffffff",
+ backgroundColor: styled.backgroundColor ?? null,
align: styled.align ?? "center",
letterSpacing: styled.letterSpacing ?? 0,
lineHeight: styled.lineHeight ?? 1.2,
@@ -722,6 +729,8 @@ function TextSegmentOverlay(props: {
// fontSize; scale it to preview px the same way.
const letterSpacingPx = () =>
(segment().letterSpacing * props.size.height) / TEXT_REFERENCE_HEIGHT;
+ const backgroundPaddingPx = () => fontPx() * 0.2;
+ const backgroundRadiusPx = () => fontPx() * 0.15;
const textStyle = () => ({
"font-family": segment().fontFamily,
@@ -775,6 +784,35 @@ function TextSegmentOverlay(props: {
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
+ <Show when={editing() && segment().backgroundColor}>
+ <div
+ class="absolute pointer-events-none"
+ style={{
+ top: `${-backgroundPaddingPx()}px`,
+ left: `${-backgroundPaddingPx()}px`,
+ width: `calc(100% + ${backgroundPaddingPx() * 2}px)`,
+ "min-height": `calc(100% + ${backgroundPaddingPx() * 2}px)`,
+ padding: `${backgroundPaddingPx()}px`,
+ "box-sizing": "border-box",
+ "border-radius": `${backgroundRadiusPx()}px`,
+ "background-color": segment().backgroundColor ?? "transparent",
+ }}
+ >
+ <div
+ aria-hidden="true"
+ style={{
+ ...textStyle(),
+ visibility: "hidden",
+ "white-space": "pre-wrap",
+ "word-break": "break-word",
+ "text-align": segment().align,
+ }}
+ >
+ {segment().content}
+ {segment().content.endsWith("\n") ? <br /> : null}
+ </div>
+ </div>
+ </Show>
<div
class="absolute inset-0 border-2 transition-colors rounded-md pointer-events-none"
classList={{
diff --git a/apps/desktop/src/routes/editor/text.ts b/apps/desktop/src/routes/editor/text.ts
index bf791e95b..2141eb0c3 100644
--- a/apps/desktop/src/routes/editor/text.ts
+++ b/apps/desktop/src/routes/editor/text.ts
@@ -32,6 +32,7 @@ export type TextSegment = {
fontWeight: number;
italic: boolean;
color: string;
+ backgroundColor?: string | null;
fadeDuration: number;
align: TextAlign;
letterSpacing: number;
@@ -120,6 +121,7 @@ export const defaultTextSegment = (
fontWeight: 700,
italic: false,
color: "#ffffff",
+ backgroundColor: undefined,
fadeDuration: 0.15,
align: "center",
letterSpacing: 0,
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 1f0fe1b8e..a4b575601 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -632,19 +632,19 @@ export type AudioConfiguration = { mute: boolean; improve: boolean; micVolumeDb:
* editor can compensate for stale-startup audio drift from typed data instead of scraping
* the recording log. See `cap-editor`'s `audio_timing_repair_offset`.
*/
-export type AudioGapSummary = {
+export type AudioGapSummary = {
/**
* Total audio trimmed from overlapping frames over the whole recording, in milliseconds.
*/
-total_overlap_trimmed_ms: number;
+total_overlap_trimmed_ms: number;
/**
* Startup-window trim used for stale-startup repair, excluding mid-recording trims.
*/
-startup_overlap_trimmed_ms?: number;
+startup_overlap_trimmed_ms?: number;
/**
* Number of whole audio frames dropped because they fully overlapped the committed timeline.
*/
-overlap_dropped_frames: number;
+overlap_dropped_frames: number;
/**
* Subset of `overlap_dropped_frames` that dropped within the first few frames — the
* signature of a stale buffered burst at capture start.
@@ -655,17 +655,17 @@ export type AudioLibraryTrack = { id: string; name: string; category: string }
export type AudioMeta = { path: string; start_time?: number | null; device_id?: string | null; gap_summary?: AudioGapSummary | null }
/**
* A timeline-positioned audio clip (background music or imported audio).
- *
+ *
* Unlike the recording's mic/system audio (which is keyed to recording clips),
* these segments live in output/timeline time exactly like zoom/text/mask
* segments. `path` is resolved relative to the project directory so projects
* stay portable when moved.
*/
-export type AudioTrackSegment = { start: number; end: number; track?: number; path: string; name?: string | null; enabled?: boolean;
+export type AudioTrackSegment = { start: number; end: number; track?: number; path: string; name?: string | null; enabled?: boolean;
/**
* Offset into the source audio file (seconds) at which playback begins.
*/
-trimStart?: number; volumeDb?: number; fadeIn?: number; fadeOut?: number;
+trimStart?: number; volumeDb?: number; fadeIn?: number; fadeOut?: number;
/**
* Source duration in seconds, persisted so the UI can clamp resizing
* without re-decoding the file.
@@ -681,18 +681,18 @@ export type AutomationTestReport = { ruleId: string; ruleName: string; actionChe
export type AutomationsStore = { version?: number; rules?: AutomationRule[] }
export type BackgroundBlurConfig = { mode: BackgroundBlurMode }
export type BackgroundBlurMode = "off" | "light" | "heavy"
-export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; roundingType: CornerStyle; inset: number; crop: Crop | null;
+export type BackgroundConfiguration = { source: BackgroundSource; blur: number; padding: number; rounding: number; roundingType: CornerStyle; inset: number; crop: Crop | null;
/**
* Normalized (0-1) center of the display rect in output-frame space.
* `None` keeps the display centered. When a frame is active this is the
* center of the framed card (chrome included), not the bare video.
*/
-displayPosition: XY<number> | null; shadow: number; advancedShadow: ShadowConfiguration | null; border: BorderConfiguration | null;
+displayPosition: XY<number> | null; shadow: number; advancedShadow: ShadowConfiguration | null; border: BorderConfiguration | null;
/**
* Decorative frame around the recording. `None` (or `FrameStyle::None`)
* renders the bare video exactly as before the feature existed.
*/
-frame: FrameConfiguration | null;
+frame: FrameConfiguration | null;
/**
* Redraws the recording device's physical notch over the capture. Distinct
* from `frame`: the decorative MacBook style is a mockup, this restores
@@ -701,7 +701,7 @@ frame: FrameConfiguration | null;
notch: NotchConfiguration | null }
export type BackgroundSource = { type: "wallpaper"; path: string | null } | { type: "image"; path: string | null } | { type: "color"; value: [number, number, number]; alpha?: number } | { type: "gradient"; from: [number, number, number]; to: [number, number, number]; angle?: number; noise_intensity?: number | null; noise_scale?: number | null; animated?: boolean | null; animation_speed?: number | null } | { type: "animatedGradient"; config: AnimatedGradientConfig }
export type BorderConfiguration = { enabled: boolean; width: number; color: [number, number, number]; opacity: number }
-export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition;
+export type Camera = { hide: boolean; mirror: boolean; position: CameraPosition;
/**
* Normalized (0-1) center of the camera rect in output-frame space.
* Overrides `position` when set.
@@ -713,27 +713,27 @@ manualPosition: XY<number> | null; size: number; zoomSize: number | null; roundi
* blur radius in pixels at 1080p output height; the renderer scales it with
* output size so preview and export match.
*/
-export type Camera3DBlur = { mode?: Camera3DBlurMode; strength?: number;
+export type Camera3DBlur = { mode?: Camera3DBlurMode; strength?: number;
/**
* Widens and flattens the sharp-to-blurred transition (0..1).
*/
-falloff?: number;
+falloff?: number;
/**
* Focus center in screen UV (radial mode).
*/
-focusX?: number; focusY?: number;
+focusX?: number; focusY?: number;
/**
* Sharp region size: radius (radial) or band width (tilt-shift).
*/
-focusSize?: number;
+focusSize?: number;
/**
* Degrees; blur direction (directional) or band angle (tilt-shift).
*/
-angle?: number;
+angle?: number;
/**
* Where the directional blur begins along its axis (0..1).
*/
-dirPosition?: number;
+dirPosition?: number;
/**
* Swaps the gaussian kernel for a ring-disc bokeh kernel with highlight
* gain. Strength is capped at 20 while enabled.
@@ -747,22 +747,22 @@ export type Camera3DBlurMode = "none" | "radial" | "directional" | "tiltShift"
* `in_easing` (a split-handle model). Absent handles default to cubic
* ease-in-out: P1 [0.65, 0], P2 [0.35, 1].
*/
-export type Camera3DKeyframe = {
+export type Camera3DKeyframe = {
/**
* Seconds relative to the segment start.
*/
-time: number; value: number;
+time: number; value: number;
/**
* Bezier P1 for the track segment leaving this keyframe.
*/
-outEasing?: [number, number] | null;
+outEasing?: [number, number] | null;
/**
* Bezier P2 for the track segment entering this keyframe.
*/
inEasing?: [number, number] | null }
/**
* A 3D camera pose for the composed content plane. Angles are degrees.
- *
+ *
* Geometry: the content plane's longest side spans 2 world units, centered at
* the origin facing +Z. `tilt_x`/`tilt_y`/`roll` orbit the CAMERA (Euler YXZ,
* roll innermost); `rotate_x`/`rotate_y` rotate the CONTENT plane itself.
@@ -771,40 +771,40 @@ inEasing?: [number, number] | null }
* apparent size ∝ 1 / (zoom · tan(fov/2)). `pan_x`/`pan_y` truck the camera in
* its own plane (world units; +x moves the subject right, +y up).
*/
-export type Camera3DProperties = {
+export type Camera3DProperties = {
/**
* Camera orbit pitch.
*/
-tiltX?: number;
+tiltX?: number;
/**
* Camera orbit yaw.
*/
-tiltY?: number;
+tiltY?: number;
/**
* Camera roll (innermost camera rotation).
*/
-roll?: number;
+roll?: number;
/**
* Content plane pitch.
*/
-rotateX?: number;
+rotateX?: number;
/**
* Content plane yaw.
*/
-rotateY?: number; fov?: number;
+rotateY?: number; fov?: number;
/**
* Camera distance in world units.
*/
zoom?: number; panX?: number; panY?: number }
-export type Camera3DSegment = { start: number; end: number; enabled?: boolean;
+export type Camera3DSegment = { start: number; end: number; enabled?: boolean;
/**
* Base pose; per-property tracks override individual values.
*/
-properties?: Camera3DProperties; blur?: Camera3DBlur; tracks?: Camera3DTracks;
+properties?: Camera3DProperties; blur?: Camera3DBlur; tracks?: Camera3DTracks;
/**
* Seconds to ease from the flat frame into the pose at the segment start.
*/
-transitionIn?: number;
+transitionIn?: number;
/**
* Seconds to ease back to the flat frame before the segment end.
*/
@@ -832,7 +832,7 @@ export type CaptionSegment = { id: string; start: number; end: number; text: str
export type CaptionSettings = { enabled: boolean; font: string; size: number; color: string; backgroundColor: string; backgroundOpacity: number; position: string; italic: boolean; fontWeight: number; outline: boolean; outlineColor: string; exportWithSubtitles: boolean; highlightColor: string; fadeDuration: number; lingerDuration: number; wordTransitionDuration: number; activeWordHighlight: boolean; manualPosition: XY<number> | null; preset: string; animation: string; highlightStyle: string; uppercase: boolean }
export type CaptionTrackSegment = { id: string; start: number; end: number; text: string; words?: CaptionWord[]; fadeDurationOverride?: number | null; lingerDurationOverride?: number | null; positionOverride?: string | null; colorOverride?: string | null; backgroundColorOverride?: string | null; fontSizeOverride?: number | null }
export type CaptionWord = { text: string; start: number; end: number }
-export type CaptionsData = { segments: CaptionSegment[]; settings: CaptionSettings;
+export type CaptionsData = { segments: CaptionSegment[]; settings: CaptionSettings;
/**
* When true, `segments` are stored in source/recording time and the
* rendered `timeline.caption_segments` are derived by projecting them
@@ -847,14 +847,14 @@ export type CaptureDisplayWithThumbnail = { id: DisplayId; name: string; refresh
export type CaptureTargetKind = "display" | "window" | "area"
export type CaptureWindow = { id: WindowId; owner_name: string; name: string; bounds: LogicalBounds; refresh_rate: number; bundle_identifier: string | null }
export type CaptureWindowWithThumbnail = { id: WindowId; owner_name: string; name: string; bounds: LogicalBounds; refresh_rate: number; thumbnail: string | null; app_icon: string | null; bundle_identifier: string | null }
-export type CliInstallStatus = { installDir: string; shimPath: string; targetPath: string; installed: boolean; onPath: boolean; conflict: string | null; pathEntry: string; shellCommand: string;
+export type CliInstallStatus = { installDir: string; shimPath: string; targetPath: string; installed: boolean; onPath: boolean; conflict: string | null; pathEntry: string; shellCommand: string;
/**
* Whether the install dir is persisted to the user's shell PATH config (profile/registry),
* so `cap` will be available in a new terminal even though it is not on the current PATH.
*/
pathConfigured: boolean }
export type ClickSpringConfig = { tension: number; mass: number; friction: number }
-export type ClipConfiguration = { index: number; offsets: ClipOffsets;
+export type ClipConfiguration = { index: number; offsets: ClipOffsets;
/**
* Whether `offsets` were computed automatically (recording start-time
* alignment + device sync calibration) rather than entered by the user.
@@ -872,54 +872,54 @@ export type ClipboardSource = "raw" | "rendered"
* exactly like no grade at all. Adjustment fields are normalized: -1..1 for
* bipolar controls, 0..1 for unipolar ones.
*/
-export type ColorCorrection = {
+export type ColorCorrection = {
/**
* UI preset id ("none", "cinematic", ..., or "custom"). The renderer
* ignores this; the numeric fields below are the source of truth.
*/
-preset: string;
+preset: string;
/**
* 0..1 master strength applied to every adjustment except `grain`,
* which has its own dedicated control.
*/
-intensity: number;
+intensity: number;
/**
* -1..1, full scale is ±1.5 stops.
*/
-exposure: number;
+exposure: number;
/**
* -1..1 around a mid-gray pivot.
*/
-contrast: number;
+contrast: number;
/**
* -1..1; -1 is grayscale.
*/
-saturation: number;
+saturation: number;
/**
* -1..1; positive warms, negative cools.
*/
-temperature: number;
+temperature: number;
/**
* -1..1; positive shifts magenta, negative green.
*/
-tint: number;
+tint: number;
/**
* 0..1 lifted-blacks film fade.
*/
-fade: number;
+fade: number;
/**
* -1..1 teal-shadows/orange-highlights split toning (negative reverses).
*/
-splitTone: number;
+splitTone: number;
/**
* 0..1 edge darkening within the layer's own rect.
*/
-vignette: number;
+vignette: number;
/**
* 0..1 animated film grain.
*/
grain: number }
-export type ColorCorrectionConfiguration = { screen: ColorCorrection; camera: ColorCorrection;
+export type ColorCorrectionConfiguration = { screen: ColorCorrection; camera: ColorCorrection;
/**
* Whether the screen grade also covers the rendered cursor. On by
* default so the pointer reads as part of the graded footage; off keeps
@@ -941,7 +941,7 @@ export type CursorType = "auto" | "pointer" | "circle" | "macos" | "tahoe" | "wi
export type Cursors = { [key in string]: string } | { [key in string]: CursorMeta }
export type DeviceOrModelID = { DeviceID: string } | { ModelID: ModelIDType }
export type DevicesUpdated = { cameras: CameraInfo[]; microphones: string[]; permissions: OSPermissionsCheck }
-export type DiagnosticOptions = { includeSyncTest: boolean;
+export type DiagnosticOptions = { includeSyncTest: boolean;
/**
* `studio`, `instant` or `both`.
*/
@@ -956,13 +956,13 @@ export type DisplayId = string
export type DisplayInformation = { name: string | null; physical_size: PhysicalSize | null; logical_size: LogicalSize | null; logical_bounds: LogicalBounds | null; refresh_rate: string }
/**
* Where the recording device's physical notch sits within the captured video.
- *
+ *
* macOS captures the pixels behind the notch, so without this the recording
* shows an unbroken menu bar where the recorder saw a cutout. Fractions of the
* captured frame rather than of the display, so area recordings, which are
* cropped at capture time, need no extra context to interpret.
*/
-export type DisplayNotch = {
+export type DisplayNotch = {
/**
* Distance from the left edge of the video to the notch.
*/
@@ -981,11 +981,11 @@ export type ExportProfile = { format: ExportFormat; fps?: number; resolutionBase
export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ format: "Gif" } & GifExportSettings) | ({ format: "Mov" } & MovExportSettings)
export type FileType = "recording" | "screenshot"
export type Flags = { captions: boolean }
-export type FrameConfiguration = { style: FrameStyle; theme: FrameTheme;
+export type FrameConfiguration = { style: FrameStyle; theme: FrameTheme;
/**
* Text shown in the browser style's URL pill.
*/
-url: string;
+url: string;
/**
* Text shown in the macOS window style's title bar.
*/
@@ -1001,48 +1001,48 @@ export type FrameLayoutEvent = { display: [number, number, number, number]; came
* chrome; the framed card as a whole follows padding / position / zoom
* exactly like the bare video does today.
*/
-export type FrameStyle =
+export type FrameStyle =
/**
* No frame: the video renders bare, exactly as before this feature.
*/
-"none" |
+"none" |
/**
* A macOS window title bar with traffic-light buttons.
*/
-"macOS" |
+"macOS" |
/**
* A Windows 11 window title bar with minimize/maximize/close controls.
*/
-"windows" |
+"windows" |
/**
* A browser toolbar: traffic lights plus a centered URL pill.
*/
-"browser" |
+"browser" |
/**
* A MacBook mockup: black bezel, aluminum body and deck.
*/
"macbook"
export type FrameTheme = "dark" | "light"
export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }
-export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; defaultZoomAmount?: number | null;
+export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; custom_cursor_capture2?: boolean; serverUrl?: string; recordingCountdown?: number | null; enableNativeCameraPreview: boolean; autoZoomOnClicks?: boolean; defaultZoomAmount?: number | null;
/**
* `None` until [`init`] seeds it from whether this machine has a notched
* display. From then on it is the user's preference and nothing re-reads
* the hardware, so moving between machines can't silently flip it.
*/
-macbookNotchOverlay?: boolean | null; captureKeyboardEvents?: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number; defaultProjectNameTemplate?: string | null; crashRecoveryRecording?: boolean; maxFps?: number; transcriptionHints?: string[]; editorPreviewQuality?: EditorPreviewQuality; studioRecordingQuality?: StudioRecordingQuality; mainWindowPosition?: WindowPosition | null; cameraWindowPosition?: WindowPosition | null; cameraWindowPositionsByMonitorName?: { [key in string]: WindowPosition }; hasCompletedOnboarding?: boolean; enableTelemetry?: boolean; outOfProcessMuxer?: boolean; recordingsPath?: string | null;
+macbookNotchOverlay?: boolean | null; captureKeyboardEvents?: boolean; postDeletionBehaviour?: PostDeletionBehaviour; excludedWindows?: WindowExclusion[]; deleteInstantRecordingsAfterUpload?: boolean; instantModeMaxResolution?: number; defaultProjectNameTemplate?: string | null; crashRecoveryRecording?: boolean; maxFps?: number; transcriptionHints?: string[]; editorPreviewQuality?: EditorPreviewQuality; studioRecordingQuality?: StudioRecordingQuality; mainWindowPosition?: WindowPosition | null; cameraWindowPosition?: WindowPosition | null; cameraWindowPositionsByMonitorName?: { [key in string]: WindowPosition }; hasCompletedOnboarding?: boolean; enableTelemetry?: boolean; outOfProcessMuxer?: boolean; recordingsPath?: string | null;
/**
* Custom recordings folders that were used before; recordings left in
* them stay visible in the library. Most recent last.
*/
-previousRecordingsPaths?: string[];
+previousRecordingsPaths?: string[];
/**
* App version at which camera background blur was disabled after a crash
* was attributed to the blur pipeline; `None` means blur is allowed.
* Cleared automatically when the app version changes (one retry per
* update, since a new ort/wgpu/driver stack may have fixed the crash).
*/
-cameraBlurDisabledByCrash?: string | null; updateChannel?: UpdateChannel;
+cameraBlurDisabledByCrash?: string | null; updateChannel?: UpdateChannel;
/**
* Run the experimental gpui-native app (`cap-gpui`) *instead of* this one:
* while enabled, startup hands off to it and exits, and the native app's
@@ -1050,11 +1050,11 @@ cameraBlurDisabledByCrash?: string | null; updateChannel?: UpdateChannel;
*/
enableGpuiApp?: boolean }
export type GifExportSettings = { fps: number; resolution_base: XY<number>; quality: GifQuality | null }
-export type GifQuality = {
+export type GifQuality = {
/**
* Encoding quality from 1-100 (default: 90)
*/
-quality: number | null;
+quality: number | null;
/**
* Whether to prioritize speed over quality (default: false)
*/
@@ -1067,7 +1067,7 @@ export type HotkeyAction = "startStudioRecording" | "startInstantRecording" | "s
export type HotkeysConfiguration = { show: boolean }
export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }
export type ImportStage = "Probing" | "Converting" | "Finalizing" | "Complete" | "Failed"
-export type ImportedAudioTrack = {
+export type ImportedAudioTrack = {
/**
* Path relative to the project directory, e.g. `assets/audio/<file>`.
*/
@@ -1108,7 +1108,7 @@ export type NewStudioRecordingAdded = { path: string }
* Draws a MacBook notch over the recording. Nothing here is inferred from the
* video: a finished recording carries no evidence of the panel it came from.
*/
-export type NotchConfiguration = { enabled: boolean;
+export type NotchConfiguration = { enabled: boolean;
/**
* Manual placement, as fractions of the video. Each `None` falls back to
* the geometry measured at capture time, else [`DEFAULT_MACBOOK_NOTCH`].
@@ -1128,13 +1128,13 @@ export type PostDeletionBehaviour = "doNothing" | "reopenRecordingWindow"
export type PostStudioRecordingBehaviour = "openEditor" | "showOverlay"
export type Preset = { name: string; config: ProjectConfiguration }
export type PresetsStore = { presets: Preset[]; default: number | null }
-export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline: TimelineConfiguration | null; captions: CaptionsData | null; keyboard: KeyboardData | null; clips: ClipConfiguration[]; annotations: Annotation[]; screenMotionBlur?: number; screenMovementSpring?: ScreenMovementSpring;
+export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: Camera; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline: TimelineConfiguration | null; captions: CaptionsData | null; keyboard: KeyboardData | null; clips: ClipConfiguration[]; annotations: Annotation[]; screenMotionBlur?: number; screenMovementSpring?: ScreenMovementSpring;
/**
* Per-layer cinematic color grades. Field-level default keeps old
* project files (and old saved presets) deserializing to the identity
* grade.
*/
-colorCorrection?: ColorCorrectionConfiguration;
+colorCorrection?: ColorCorrectionConfiguration;
/**
* How text segment font sizes are interpreted. 0 (legacy): the renderer
* multiplied `font_size` by `size.y / 0.2`, coupling glyph size to the
@@ -1143,7 +1143,7 @@ colorCorrection?: ColorCorrectionConfiguration;
* `font_size`. The field-level default keeps old files at 0 while
* `Default::default()` produces the current version.
*/
-textSizeVersion?: number;
+textSizeVersion?: number;
/**
* 0 (legacy): text segments animate with the single symmetric
* `fade_duration`. 1: the enter/exit animation fields drive timing;
@@ -1176,7 +1176,7 @@ export type RequestScrollToSettingsSection = { section: string }
export type RequestSetTargetMode = { target_mode: RecordingTargetMode | null; display_id: string | null }
export type RequestStartRecording = { mode: RecordingMode }
export type S3UploadMeta = { id: string }
-export type SceneMode = "default" | "cameraOnly" | "hideCamera" | "splitScreen" |
+export type SceneMode = "default" | "cameraOnly" | "hideCamera" | "splitScreen" |
/**
* Like [`SceneMode::SplitScreen`], but the screen and camera render as
* padded, rounded, shadowed cards floating over the background instead
@@ -1194,7 +1194,7 @@ export type ScreenshotProjectExport = { imageBytes: number[]; config: ProjectCon
export type ScreenshotProjectShareState = { config: ProjectConfiguration; sharing: ScreenshotSharingState | null }
export type ScreenshotSharingState = { link: string; contentHash: string | null }
export type SegmentRecordings = { display: Video; camera: Video | null; mic: Audio | null; system_audio: Audio | null }
-export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string;
+export type SerializedEditorInstance = { framesSocketUrl: string; recordingDuration: number; savedProjectConfig: ProjectConfiguration; recordings: ProjectRecordingsMeta; path: string;
/**
* Notch geometry the overlay uses when the project sets no manual
* placement: this recording's own measurements where the recorder took
@@ -1222,34 +1222,34 @@ export type TextAnimation = "none" | "fade" | "slideUp" | "slideDown" | "pop" |
* How a text segment shares the frame with the display recording. The
* variants name where the TEXT sits; the display card makes room for it.
*/
-export type TextLayout =
+export type TextLayout =
/**
* Text draws over the untouched display (the original behavior).
*/
-"overlay" |
+"overlay" |
/**
* The display card shrinks and fades away; text owns the frame.
*/
-"fullscreen" |
+"fullscreen" |
/**
* Text in the left half, display card contained in the right half.
*/
-"splitLeft" |
+"splitLeft" |
/**
* Text in the right half, display card contained in the left half.
*/
"splitRight"
-export type TextSegment = { start: number; end: number; track?: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string;
+export type TextSegment = { start: number; end: number; track?: number; enabled?: boolean; content?: string; center?: XY<number>; size?: XY<number>; fontFamily?: string; fontSize?: number; fontWeight?: number; italic?: boolean; color?: string; backgroundColor?: string | null;
/**
* Legacy symmetric fade. Superseded by the animation fields below; kept
* so configs written by new builds still fade in old builds. The
* `text_anim_version` migration seeds the animation durations from it.
*/
-fadeDuration?: number; align?: TextAlign;
+fadeDuration?: number; align?: TextAlign;
/**
* Px at the 1080p reference height, like `font_size`.
*/
-letterSpacing?: number; lineHeight?: number; opacity?: number; shadow?: number; animationIn?: TextAnimation; animationOut?: TextAnimation; animationInDuration?: number; animationOutDuration?: number; layout?: TextLayout;
+letterSpacing?: number; lineHeight?: number; opacity?: number; shadow?: number; animationIn?: TextAnimation; animationOut?: TextAnimation; animationInDuration?: number; animationOutDuration?: number; layout?: TextLayout;
/**
* Seconds the display card takes to morph aside (and back) at the
* segment edges when `layout` is not `Overlay`.
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 8114d1552..43403a526 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -1134,6 +1134,8 @@ pub struct TextSegment {
pub italic: bool,
#[serde(default = "TextSegment::default_color")]
pub color: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub background_color: Option<String>,
/// Legacy symmetric fade. Superseded by the animation fields below; kept
/// so configs written by new builds still fade in old builds. The
/// `text_anim_version` migration seeds the animation durations from it.
@@ -2663,6 +2665,7 @@ mod tests {
font_weight: 700.0,
italic: false,
color: "#ffffff".to_string(),
+ background_color: None,
fade_duration: 0.15,
align: TextAlign::Center,
letter_spacing: 0.0,
@@ -3142,6 +3145,7 @@ mod tests {
font_weight: 700.0,
italic: false,
color: "#ffffff".to_string(),
+ background_color: None,
fade_duration: 0.15,
align: TextAlign::Center,
letter_spacing: 0.0,
@@ -3242,6 +3246,7 @@ mod tests {
font_weight: 700.0,
italic: false,
color: "#ffffff".to_string(),
+ background_color: None,
fade_duration,
align: TextAlign::Center,
letter_spacing: 0.0,
@@ -3325,6 +3330,30 @@ mod tests {
assert_eq!(segment.animation_out_duration, 0.0);
}
+ #[test]
+ fn text_background_color_is_optional_and_omitted_when_unset() {
+ let segment: TextSegment = serde_json::from_value(serde_json::json!({
+ "start": 0.0,
+ "end": 1.0,
+ }))
+ .unwrap();
+ assert_eq!(segment.background_color, None);
+ assert!(
+ serde_json::to_value(segment)
+ .unwrap()
+ .get("backgroundColor")
+ .is_none()
+ );
+
+ let segment: TextSegment = serde_json::from_value(serde_json::json!({
+ "start": 0.0,
+ "end": 1.0,
+ "backgroundColor": "#102030",
+ }))
+ .unwrap();
+ assert_eq!(segment.background_color.as_deref(), Some("#102030"));
+ }
+
#[test]
fn legacy_config_without_motion_rework_fields_resolves_defaults() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/rendering/src/layers/text.rs b/crates/rendering/src/layers/text.rs
index e4a94b62f..070b3dbe7 100644
--- a/crates/rendering/src/layers/text.rs
+++ b/crates/rendering/src/layers/text.rs
@@ -1,3 +1,4 @@
+use bytemuck::{Pod, Zeroable};
use cap_project::TextAlign;
use glyphon::cosmic_text::Align;
use glyphon::{
@@ -5,7 +6,7 @@ use glyphon::{
SwashCache, TextArea, TextAtlas, TextBounds, TextRenderer, Viewport, Weight,
};
use log::warn;
-use wgpu::{Device, Queue};
+use wgpu::{Device, Queue, include_wgsl, util::DeviceExt};
use crate::text::PreparedText;
@@ -16,6 +17,132 @@ pub struct TextLayer {
text_renderer: TextRenderer,
viewport: Viewport,
buffers: Vec<Buffer>,
+ segment_renderers: Vec<TextRenderer>,
+ background: Option<TextBackgroundResources>,
+ segmented_render: bool,
+ segment_backgrounds: Vec<bool>,
+}
+
+#[repr(C)]
+#[derive(Copy, Clone, Pod, Zeroable)]
+struct TextBackgroundUniforms {
+ rect: [f32; 4],
+ color: [f32; 4],
+ radius: f32,
+ _padding0: f32,
+ _padding1: f32,
+ _padding2: f32,
+ output_size: [f32; 2],
+ _padding3: [f32; 2],
+}
+
+struct TextBackgroundResources {
+ pipeline: wgpu::RenderPipeline,
+ bind_group_layout: wgpu::BindGroupLayout,
+ uniform_buffers: Vec<wgpu::Buffer>,
+ bind_groups: Vec<wgpu::BindGroup>,
+}
+
+impl TextBackgroundResources {
+ fn new(device: &Device) -> Self {
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Text Background Bind Group Layout"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+ let shader = device.create_shader_module(include_wgsl!("../shaders/text_bg.wgsl"));
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("Text Background Pipeline Layout"),
+ bind_group_layouts: &[&bind_group_layout],
+ push_constant_ranges: &[],
+ });
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("Text Background Pipeline"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: Some(wgpu::BlendState::ALPHA_BLENDING),
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: wgpu::PipelineCompilationOptions::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview: None,
+ cache: None,
+ });
+
+ Self {
+ pipeline,
+ bind_group_layout,
+ uniform_buffers: Vec::new(),
+ bind_groups: Vec::new(),
+ }
+ }
+
+ fn ensure_capacity(&mut self, device: &Device, count: usize) {
+ while self.uniform_buffers.len() < count {
+ let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: Some("Text Background Uniform Buffer"),
+ contents: bytemuck::bytes_of(&TextBackgroundUniforms {
+ rect: [0.0; 4],
+ color: [0.0; 4],
+ radius: 0.0,
+ _padding0: 0.0,
+ _padding1: 0.0,
+ _padding2: 0.0,
+ output_size: [1.0; 2],
+ _padding3: [0.0; 2],
+ }),
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ });
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Text Background Bind Group"),
+ layout: &self.bind_group_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: buffer.as_entire_binding(),
+ }],
+ });
+ self.uniform_buffers.push(buffer);
+ self.bind_groups.push(bind_group);
+ }
+ }
+
+ fn write(&self, queue: &Queue, index: usize, uniforms: &TextBackgroundUniforms) {
+ queue.write_buffer(
+ &self.uniform_buffers[index],
+ 0,
+ bytemuck::bytes_of(uniforms),
+ );
+ }
+
+ fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>, index: usize) {
+ pass.set_pipeline(&self.pipeline);
+ pass.set_bind_group(0, &self.bind_groups[index], &[]);
+ pass.draw(0..6, 0..1);
+ }
}
struct AreaSpec {
@@ -25,6 +152,29 @@ struct AreaSpec {
scale: f32,
color: Color,
shadow: Option<(f32, f32, Color)>,
+ background: Option<TextBackgroundUniforms>,
+}
+
+fn text_areas<'a>(buffer: &'a Buffer, spec: &AreaSpec) -> impl Iterator<Item = TextArea<'a>> {
+ let shadow_area = spec.shadow.map(|(dx, dy, shadow_color)| TextArea {
+ buffer,
+ left: spec.left + dx,
+ top: spec.top + dy,
+ scale: spec.scale,
+ bounds: shift_bounds(spec.bounds, dx, dy),
+ default_color: shadow_color,
+ custom_glyphs: &[],
+ });
+ let main_area = TextArea {
+ buffer,
+ left: spec.left,
+ top: spec.top,
+ scale: spec.scale,
+ bounds: spec.bounds,
+ default_color: spec.color,
+ custom_glyphs: &[],
+ };
+ shadow_area.into_iter().chain(std::iter::once(main_area))
}
fn shift_bounds(bounds: TextBounds, dx: f32, dy: f32) -> TextBounds {
@@ -57,6 +207,10 @@ impl TextLayer {
text_renderer,
viewport,
buffers: Vec::new(),
+ segment_renderers: Vec::new(),
+ background: None,
+ segmented_render: false,
+ segment_backgrounds: Vec::new(),
}
}
@@ -191,6 +345,31 @@ impl TextLayer {
(dx, dy, Color::rgba(0, 0, 0, (shadow_alpha * 255.0) as u8))
});
+ let background = text.background_color.map(|background_color| {
+ let (rect, radius) = crate::text::text_background_rect(
+ text.bounds,
+ laid_out_height,
+ text.font_size,
+ scale,
+ text.offset,
+ );
+ TextBackgroundUniforms {
+ rect,
+ color: [
+ background_color[0],
+ background_color[1],
+ background_color[2],
+ background_color[3] * text.opacity.clamp(0.0, 1.0),
+ ],
+ radius,
+ _padding0: 0.0,
+ _padding1: 0.0,
+ _padding2: 0.0,
+ output_size: [output_size.0.max(1) as f32, output_size.1.max(1) as f32],
+ _padding3: [0.0; 2],
+ }
+ });
+
self.buffers.push(buffer);
specs.push(AreaSpec {
bounds,
@@ -199,36 +378,10 @@ impl TextLayer {
scale,
color,
shadow,
+ background,
});
}
- let text_areas = self
- .buffers
- .iter()
- .zip(&specs)
- .flat_map(|(buffer, spec)| {
- let shadow_area = spec.shadow.map(|(dx, dy, shadow_color)| TextArea {
- buffer,
- left: spec.left + dx,
- top: spec.top + dy,
- scale: spec.scale,
- bounds: shift_bounds(spec.bounds, dx, dy),
- default_color: shadow_color,
- custom_glyphs: &[],
- });
- let main_area = TextArea {
- buffer,
- left: spec.left,
- top: spec.top,
- scale: spec.scale,
- bounds: spec.bounds,
- default_color: spec.color,
- custom_glyphs: &[],
- };
- shadow_area.into_iter().chain(std::iter::once(main_area))
- })
- .collect::<Vec<_>>();
-
self.viewport.update(
queue,
Resolution {
@@ -237,13 +390,50 @@ impl TextLayer {
},
);
- if let Err(error) = self.text_renderer.prepare(
+ self.segmented_render = specs.iter().any(|spec| spec.background.is_some());
+ if self.segmented_render {
+ self.segment_backgrounds = specs.iter().map(|spec| spec.background.is_some()).collect();
+ let background = self
+ .background
+ .get_or_insert_with(|| TextBackgroundResources::new(device));
+ background.ensure_capacity(device, specs.len());
+ for (index, spec) in specs.iter().enumerate() {
+ if let Some(uniforms) = spec.background {
+ background.write(queue, index, &uniforms);
+ }
+ }
+
+ while self.segment_renderers.len() < specs.len() {
+ self.segment_renderers.push(TextRenderer::new(
+ &mut self.text_atlas,
+ device,
+ wgpu::MultisampleState::default(),
+ None,
+ ));
+ }
+ for (index, spec) in specs.iter().enumerate() {
+ if let Err(error) = self.segment_renderers[index].prepare(
+ device,
+ queue,
+ &mut self.font_system,
+ &mut self.text_atlas,
+ &self.viewport,
+ text_areas(&self.buffers[index], spec),
+ &mut self.swash_cache,
+ ) {
+ warn!("Failed to prepare text: {error:?}");
+ }
+ }
+ } else if let Err(error) = self.text_renderer.prepare(
device,
queue,
&mut self.font_system,
&mut self.text_atlas,
&self.viewport,
- text_areas,
+ self.buffers
+ .iter()
+ .zip(&specs)
+ .flat_map(|(buffer, spec)| text_areas(buffer, spec)),
&mut self.swash_cache,
) {
warn!("Failed to prepare text: {error:?}");
@@ -251,7 +441,23 @@ impl TextLayer {
}
pub fn render<'a>(&'a self, pass: &mut wgpu::RenderPass<'a>) {
- if let Err(error) = self
+ if self.segmented_render {
+ if let Some(background) = &self.background {
+ for (index, (renderer, has_background)) in self
+ .segment_renderers
+ .iter()
+ .zip(&self.segment_backgrounds)
+ .enumerate()
+ {
+ if *has_background {
+ background.render(pass, index);
+ }
+ if let Err(error) = renderer.render(&self.text_atlas, &self.viewport, pass) {
+ warn!("Failed to render text: {error:?}");
+ }
+ }
+ }
+ } else if let Err(error) = self
.text_renderer
.render(&self.text_atlas, &self.viewport, pass)
{
@@ -259,3 +465,160 @@ impl TextLayer {
}
}
}
+
+#[cfg(test)]
+mod gpu_tests {
+ use super::*;
+ use crate::create_wgpu_instance_sync;
+ use crate::text::PreparedText;
+
+ const OUTPUT: u32 = 64;
+
+ fn device() -> Option<(Device, Queue)> {
+ let instance = create_wgpu_instance_sync();
+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::LowPower,
+ force_fallback_adapter: false,
+ compatible_surface: None,
+ }))
+ .ok()?;
+ pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).ok()
+ }
+
+ fn text(bounds: [f32; 4], color: [f32; 4]) -> PreparedText {
+ PreparedText {
+ content: " ".to_string(),
+ bounds,
+ color: [1.0; 4],
+ background_color: Some(color),
+ font_family: "sans-serif".to_string(),
+ font_size: 48.0,
+ font_weight: 400.0,
+ italic: false,
+ opacity: 1.0,
+ align: TextAlign::Left,
+ letter_spacing: 0.0,
+ line_height: 1.2,
+ shadow: 0.0,
+ offset: [0.0, 0.0],
+ scale: 1.0,
+ }
+ }
+
+ fn render_pixels(device: &Device, queue: &Queue, layer: &TextLayer) -> Vec<u8> {
+ let target = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Text Background Test Target"),
+ size: wgpu::Extent3d {
+ width: OUTPUT,
+ height: OUTPUT,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
+ view_formats: &[],
+ });
+ let view = target.create_view(&Default::default());
+ let readback = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("Text Background Test Readback"),
+ size: (OUTPUT * OUTPUT * 4) as u64,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("Text Background Test Pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::WHITE),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ layer.render(&mut pass);
+ }
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo {
+ texture: &target,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::All,
+ },
+ wgpu::TexelCopyBufferInfo {
+ buffer: &readback,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(OUTPUT * 4),
+ rows_per_image: Some(OUTPUT),
+ },
+ },
+ wgpu::Extent3d {
+ width: OUTPUT,
+ height: OUTPUT,
+ depth_or_array_layers: 1,
+ },
+ );
+ queue.submit([encoder.finish()]);
+ readback.slice(..).map_async(wgpu::MapMode::Read, |_| {});
+ device.poll(wgpu::PollType::Wait).unwrap();
+ let pixels = readback.slice(..).get_mapped_range().to_vec();
+ readback.unmap();
+ pixels
+ }
+
+ fn pixel(pixels: &[u8], x: u32, y: u32) -> [u8; 4] {
+ let index = ((y * OUTPUT + x) * 4) as usize;
+ pixels[index..index + 4].try_into().unwrap()
+ }
+
+ #[test]
+ #[ignore = "requires a working wgpu adapter"]
+ fn text_background_timeline_preserves_order_and_shrinks_without_stale_layers() {
+ let (device, queue) = device().expect("A working wgpu adapter is required for this test");
+ let mut layer = TextLayer::new(&device, &queue);
+ let first = text([16.0, 16.0, 32.0, 32.0], [1.0, 0.0, 0.0, 1.0]);
+ let second = text([32.0, 32.0, 48.0, 48.0], [0.0, 0.0, 1.0, 1.0]);
+
+ layer.prepare(&device, &queue, (OUTPUT, OUTPUT), &[first.clone(), second]);
+ let pixels = render_pixels(&device, &queue, &layer);
+ assert_eq!(pixel(&pixels, 12, 28), [255, 0, 0, 255]);
+ assert_eq!(pixel(&pixels, 28, 28), [0, 0, 255, 255]);
+ assert_eq!(pixel(&pixels, 48, 40), [0, 0, 255, 255]);
+
+ layer.prepare(&device, &queue, (OUTPUT, OUTPUT), &[first.clone()]);
+ let pixels = render_pixels(&device, &queue, &layer);
+ assert_eq!(pixel(&pixels, 28, 28), [255, 0, 0, 255]);
+ assert_eq!(pixel(&pixels, 48, 40), [255, 255, 255, 255]);
+
+ layer.prepare(&device, &queue, (OUTPUT, OUTPUT), &[]);
+ let pixels = render_pixels(&device, &queue, &layer);
+ assert_eq!(pixel(&pixels, 28, 28), [255, 255, 255, 255]);
+
+ let mut no_background = first;
+ no_background.background_color = None;
+ layer.prepare(&device, &queue, (OUTPUT, OUTPUT), &[no_background]);
+ let pixels = render_pixels(&device, &queue, &layer);
+ assert_eq!(pixel(&pixels, 12, 28), [255, 255, 255, 255]);
+
+ let mut multiline = text([12.0, 8.0, 48.0, 20.0], [0.0, 0.0, 1.0, 1.0]);
+ multiline.content = "Top\ngyp\nq".to_string();
+ multiline.font_size = 10.0;
+ layer.prepare(&device, &queue, (OUTPUT, OUTPUT), &[multiline]);
+ assert_eq!(layer.buffers[0].layout_runs().count(), 3);
+ let pixels = render_pixels(&device, &queue, &layer);
+ assert_eq!(pixel(&pixels, 11, 38), [0, 0, 255, 255]);
+ assert_eq!(pixel(&pixels, 11, 42), [0, 0, 255, 255]);
+ assert!((32..44).any(|y| (12..32).any(|x| {
+ let [red, green, _, _] = pixel(&pixels, x, y);
+ red > 200 && green > 200
+ })));
+ }
+}
diff --git a/crates/rendering/src/shaders/text_bg.wgsl b/crates/rendering/src/shaders/text_bg.wgsl
new file mode 100644
index 000000000..172d6d94b
--- /dev/null
+++ b/crates/rendering/src/shaders/text_bg.wgsl
@@ -0,0 +1,58 @@
+struct BackgroundUniforms {
+ rect: vec4<f32>,
+ color: vec4<f32>,
+ radius: f32,
+ _padding0: f32,
+ _padding1: f32,
+ _padding2: f32,
+ output_size: vec2<f32>,
+ _padding3: vec2<f32>,
+};
+
+@group(0) @binding(0) var<uniform> uniforms: BackgroundUniforms;
+
+struct VertexOutput {
+ @builtin(position) position: vec4<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
+ var positions = array<vec2<f32>, 6>(
+ vec2<f32>(0.0, 0.0),
+ vec2<f32>(1.0, 0.0),
+ vec2<f32>(0.0, 1.0),
+ vec2<f32>(0.0, 1.0),
+ vec2<f32>(1.0, 0.0),
+ vec2<f32>(1.0, 1.0),
+ );
+
+ let fringe = 2.0;
+ let expanded_min = uniforms.rect.xy - vec2<f32>(fringe);
+ let expanded_size = uniforms.rect.zw + vec2<f32>(fringe * 2.0);
+ let pixel = expanded_min + positions[vertex_index] * expanded_size;
+ var output: VertexOutput;
+ output.position = vec4<f32>(
+ pixel.x / uniforms.output_size.x * 2.0 - 1.0,
+ 1.0 - pixel.y / uniforms.output_size.y * 2.0,
+ 0.0,
+ 1.0,
+ );
+ return output;
+}
+
+fn rounded_rect_sdf(p: vec2<f32>, half_size: vec2<f32>, radius: f32) -> f32 {
+ let q = abs(p) - half_size + vec2<f32>(radius);
+ return length(max(q, vec2<f32>(0.0))) + min(max(q.x, q.y), 0.0) - radius;
+}
+
+@fragment
+fn fs_main(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
+ let rect_min = uniforms.rect.xy;
+ let rect_size = uniforms.rect.zw;
+ let rect_center = rect_min + rect_size * 0.5;
+ let half_size = rect_size * 0.5;
+ let distance = rounded_rect_sdf(position.xy - rect_center, half_size, uniforms.radius);
+ let alpha = 1.0 - smoothstep(-1.5, 1.5, distance);
+
+ return vec4<f32>(uniforms.color.rgb, uniforms.color.a * alpha);
+}
diff --git a/crates/rendering/src/takeover.rs b/crates/rendering/src/takeover.rs
index f91bf3d4a..5ba40d57c 100644
--- a/crates/rendering/src/takeover.rs
+++ b/crates/rendering/src/takeover.rs
@@ -167,6 +167,7 @@ mod tests {
font_weight: 700.0,
italic: false,
color: "#ffffff".to_string(),
+ background_color: None,
fade_duration: 0.15,
align: TextAlign::Center,
letter_spacing: 0.0,
diff --git a/crates/rendering/src/text.rs b/crates/rendering/src/text.rs
index 29bd89046..921d9d1c7 100644
--- a/crates/rendering/src/text.rs
+++ b/crates/rendering/src/text.rs
@@ -14,6 +14,7 @@ pub struct PreparedText {
pub content: String,
pub bounds: [f32; 4],
pub color: [f32; 4],
+ pub background_color: Option<[f32; 4]>,
pub font_family: String,
pub font_size: f32,
pub font_weight: f32,
@@ -33,18 +34,55 @@ pub struct PreparedText {
}
fn parse_color(hex: &str) -> [f32; 4] {
+ parse_rgb_color(hex).unwrap_or([1.0, 1.0, 1.0, 1.0])
+}
+
+fn parse_rgb_color(hex: &str) -> Option<[f32; 4]> {
let color = hex.trim_start_matches('#');
if color.len() == 6
+ && color.is_ascii()
&& let (Ok(r), Ok(g), Ok(b)) = (
u8::from_str_radix(&color[0..2], 16),
u8::from_str_radix(&color[2..4], 16),
u8::from_str_radix(&color[4..6], 16),
)
{
- return [r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0];
+ return Some([r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, 1.0]);
}
- [1.0, 1.0, 1.0, 1.0]
+ None
+}
+
+pub(crate) fn text_background_rect(
+ bounds: [f32; 4],
+ laid_out_height: f32,
+ font_size: f32,
+ scale: f32,
+ offset: [f32; 2],
+) -> ([f32; 4], f32) {
+ let padding = font_size * 0.2;
+ let left = bounds[0] - padding;
+ let top = bounds[1] - padding;
+ let right = bounds[2] + padding;
+ let bottom = bounds[1] + (bounds[3] - bounds[1]).max(laid_out_height) + padding;
+ let cx = (bounds[0] + bounds[2]) * 0.5;
+ let cy = (bounds[1] + bounds[3]) * 0.5;
+ let transform = |x: f32, y: f32| {
+ [
+ cx + (x - cx) * scale + offset[0],
+ cy + (y - cy) * scale + offset[1],
+ ]
+ };
+ let [transformed_left, transformed_top] = transform(left, top);
+ let [transformed_right, transformed_bottom] = transform(right, bottom);
+ let width = (transformed_right - transformed_left).max(0.0);
+ let height = (transformed_bottom - transformed_top).max(0.0);
+ (
+ [transformed_left, transformed_top, width, height],
+ (font_size * 0.15 * scale)
+ .min(width * 0.5)
+ .min(height * 0.5),
+ )
}
fn ease_out_cubic(t: f32) -> f32 {
@@ -213,6 +251,10 @@ pub fn prepare_texts(
content,
bounds: [left, top, right, bottom],
color: parse_color(&segment.color),
+ background_color: segment
+ .background_color
+ .as_deref()
+ .and_then(parse_rgb_color),
font_family: segment.font_family.clone(),
font_size,
font_weight: segment.font_weight,
@@ -252,6 +294,7 @@ mod tests {
font_weight: 700.0,
italic: false,
color: "#ffffff".to_string(),
+ background_color: None,
fade_duration: 0.15,
align: TextAlign::Center,
letter_spacing: 0.0,
@@ -280,6 +323,50 @@ mod tests {
assert_eq!(text.offset, [0.0, 0.0]);
assert_eq!(text.scale, 1.0);
assert_eq!(text.content, "Hello");
+ assert_eq!(text.background_color, None);
+ }
+
+ #[test]
+ fn background_color_is_prepared_and_invalid_colors_are_ignored() {
+ let mut with_background = segment(TextAnimation::None, TextAnimation::None);
+ with_background.background_color = Some("#102030".to_string());
+ let prepared = prepare_one(with_background, 5.0).unwrap();
+ assert_eq!(
+ prepared.background_color,
+ Some([16.0 / 255.0, 32.0 / 255.0, 48.0 / 255.0, 1.0])
+ );
+
+ let mut malformed = segment(TextAnimation::None, TextAnimation::None);
+ malformed.color = "#ééé".to_string();
+ malformed.background_color = Some("#ééé".to_string());
+ let prepared = prepare_one(malformed, 5.0).unwrap();
+ assert_eq!(prepared.color, [1.0, 1.0, 1.0, 1.0]);
+ assert_eq!(prepared.background_color, None);
+ }
+
+ #[test]
+ fn background_rect_expands_authored_bounds_then_transforms_about_center() {
+ let (rect, radius) = text_background_rect(
+ [100.0, 200.0, 300.0, 400.0],
+ 100.0,
+ 50.0,
+ 0.5,
+ [10.0, -20.0],
+ );
+ assert_eq!(rect, [155.0, 225.0, 110.0, 110.0]);
+ assert!((radius - 3.75).abs() < 0.000_001);
+ }
+
+ #[test]
+ fn multiline_background_keeps_the_authored_transform_origin() {
+ let (rect, _) = text_background_rect(
+ [100.0, 200.0, 300.0, 400.0],
+ 300.0,
+ 50.0,
+ 0.5,
+ [10.0, -20.0],
+ );
+ assert_eq!(rect, [155.0, 225.0, 110.0, 160.0]);
}
#[test]