Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

feat(text): a title's side grips set where its words wrap

Jareerd69b797b5060
diff --git a/engine/crates/concat-host/src/titles.rs b/engine/crates/concat-host/src/titles.rs
index a0dbfaed..fe977c8b 100644
--- a/engine/crates/concat-host/src/titles.rs
+++ b/engine/crates/concat-host/src/titles.rs
@@ -310,6 +310,7 @@ fn title_style(style: &TextStyle) -> TitleStyle {
shadow: style.shadow,
background: style.background.clone(),
line_height: style.line_height,
+ max_width: style.max_width,
tracking: style.tracking,
}
}
diff --git a/engine/crates/concat-project/src/commands.rs b/engine/crates/concat-project/src/commands.rs
index b5dc3245..4d022f3e 100644
--- a/engine/crates/concat-project/src/commands.rs
+++ b/engine/crates/concat-project/src/commands.rs
@@ -205,6 +205,11 @@ pub struct NewMedia {
/// so a caller need not read `apply` to know what a command will do.
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "camelCase", rename_all_fields = "camelCase")]
+// A clip patch carries a whole text style, which is the largest variant by
+// a couple of hundred bytes. Commands are made one at a time and kept only
+// in the undo history, where a few hundred bytes each is nothing; boxing
+// the patch would cost every caller for a saving nobody would measure.
+#[allow(clippy::large_enum_variant)]
pub enum Command {
/// Imports a file into the bin, minting an "m" id. A path already
/// present is a tolerated no-op that mints nothing.
diff --git a/engine/crates/concat-project/src/doc.rs b/engine/crates/concat-project/src/doc.rs
index 324873cb..21a67d75 100644
--- a/engine/crates/concat-project/src/doc.rs
+++ b/engine/crates/concat-project/src/doc.rs
@@ -195,6 +195,7 @@ fn read_text_style(raw: Option<&Value>) -> TextStyle {
background: text(style.get("background"), &base.background),
line_height: number(style.get("lineHeight"), base.line_height).max(0.5),
tracking: number(style.get("tracking"), base.tracking),
+ max_width: number(style.get("maxWidth"), base.max_width).max(0.0),
}
}
diff --git a/engine/crates/concat-project/src/model.rs b/engine/crates/concat-project/src/model.rs
index 70b66731..6d3778d6 100644
--- a/engine/crates/concat-project/src/model.rs
+++ b/engine/crates/concat-project/src/model.rs
@@ -805,6 +805,10 @@ pub struct TextStyle {
/// Extra letter spacing, in the same frame-height fractions as
/// `font_size`. Zero is the font's natural fit.
pub tracking: f64,
+ /// The widest a line may run, as a fraction of frame width, before its
+ /// words wrap onto the next; the stage's side grips set it. Zero - the
+ /// default - is no limit: a line is as long as its words.
+ pub max_width: f64,
}
impl Default for TextStyle {
@@ -824,6 +828,7 @@ impl Default for TextStyle {
background: String::new(),
line_height: 1.2,
tracking: 0.0,
+ max_width: 0.0,
}
}
}
diff --git a/engine/crates/concat-text/src/lib.rs b/engine/crates/concat-text/src/lib.rs
index 83222e17..56fe4dce 100644
--- a/engine/crates/concat-text/src/lib.rs
+++ b/engine/crates/concat-text/src/lib.rs
@@ -81,6 +81,9 @@ pub struct TitleStyle {
pub line_height: f64,
/// Extra advance after every glyph, as a fraction of frame height.
pub tracking: f64,
+ /// The widest a line may run, as a fraction of frame width, before its
+ /// words wrap; zero for no limit.
+ pub max_width: f64,
}
/// The finished title.
@@ -267,6 +270,44 @@ impl ttf_parser::OutlineBuilder for Outliner<'_> {
}
/// Shapes one line and outlines it, pen starting at (0, 0) on the baseline.
+/// A paragraph as the lines it wraps to within `max_w` pixels: words are
+/// added while they fit, and a word that fits nowhere gets a line of its
+/// own rather than being cut. No limit, one line.
+fn wrap_line(
+ face: &rustybuzz::Face<'_>,
+ text: &str,
+ em: f32,
+ tracking: f32,
+ max_w: f32,
+) -> Vec<Line> {
+ if max_w <= 0.0 || text.trim().is_empty() {
+ return vec![shape_line(face, text, em, tracking)];
+ }
+ let mut lines = Vec::new();
+ let mut current = String::new();
+ let mut shaped = shape_line(face, "", em, tracking);
+ for word in text.split_whitespace() {
+ let candidate = if current.is_empty() {
+ word.to_owned()
+ } else {
+ format!("{current} {word}")
+ };
+ let trial = shape_line(face, &candidate, em, tracking);
+ if trial.width <= max_w || current.is_empty() {
+ current = candidate;
+ shaped = trial;
+ } else {
+ lines.push(shaped);
+ current = word.to_owned();
+ shaped = shape_line(face, word, em, tracking);
+ }
+ }
+ if !current.is_empty() {
+ lines.push(shaped);
+ }
+ lines
+}
+
fn shape_line(face: &rustybuzz::Face<'_>, text: &str, em: f32, tracking: f32) -> Line {
if text.is_empty() {
return Line {
@@ -384,11 +425,13 @@ pub fn render(
let descent = -(face.descender() as f32) / upem * em;
// Shape every line with the pen at the origin; placement comes after,
- // once the block's width is known.
+ // once the block's width is known. A paragraph wider than the style's
+ // limit is wrapped at its spaces first.
+ let max_w = (style.max_width as f32) * width as f32;
let lines: Vec<Line> = style
.content
.lines()
- .map(|line| shape_line(&face, line, em, tracking))
+ .flat_map(|line| wrap_line(&face, line, em, tracking, max_w))
.collect();
let rows = lines.len().max(1);
let block_w = lines.iter().map(|line| line.width).fold(0.0, f32::max);
@@ -592,9 +635,38 @@ mod tests {
background: String::new(),
line_height: 1.2,
tracking: 0.0,
+ max_width: 0.0,
}
}
+ /// A limit narrower than the words wraps them: the block comes out no
+ /// wider than the limit and taller than the one-line block.
+ #[test]
+ fn a_width_limit_wraps_words_onto_more_lines() {
+ let fonts = Fonts::new();
+ let one = render(&fonts, &style("one two three four five six"), 640, 360).expect("renders");
+ let mut narrow = style("one two three four five six");
+ narrow.max_width = 0.3;
+ let wrapped = render(&fonts, &narrow, 640, 360).expect("renders");
+ assert!(
+ one.block_width > wrapped.block_width,
+ "{} vs {}",
+ one.block_width,
+ wrapped.block_width
+ );
+ assert!(
+ wrapped.block_width <= (0.3 * 640.0) as u32 + 1,
+ "{}",
+ wrapped.block_width
+ );
+ assert!(wrapped.block_height > one.block_height);
+ // and a word no line can hold still gets a line, uncut
+ let mut tiny = style("unbreakable");
+ tiny.max_width = 0.01;
+ let rendered = render(&fonts, &tiny, 640, 360).expect("renders");
+ assert!(rendered.block_width > 7);
+ }
+
fn opaque_pixels(png: &[u8]) -> usize {
let pixmap = Pixmap::decode_png(png).expect("our own PNG decodes");
pixmap.pixels().iter().filter(|p| p.alpha() > 0).count()
diff --git a/engine/crates/concat/locales/de.json b/engine/crates/concat/locales/de.json
index 2452a0ad..87b0df60 100644
--- a/engine/crates/concat/locales/de.json
+++ b/engine/crates/concat/locales/de.json
@@ -125,6 +125,7 @@
"Default title": "Standardtitel",
"Delay": "Verzögerung",
"Delete": "Löschen",
+ "Max width": "Maximale Breite",
"Generate Captions": "Untertitel erzeugen",
"Text to Speech": "Text zu Sprache",
"Downloads": "Downloads",
diff --git a/engine/crates/concat/locales/en.json b/engine/crates/concat/locales/en.json
index da9d9176..8a1131eb 100644
--- a/engine/crates/concat/locales/en.json
+++ b/engine/crates/concat/locales/en.json
@@ -359,6 +359,7 @@
"Master": "Master",
"Matcha": "Matcha",
"Matte": "Matte",
+ "Max width": "Max width",
"Media": "Media",
"Medium": "Medium",
"Midnight": "Midnight",
diff --git a/engine/crates/concat/locales/es.json b/engine/crates/concat/locales/es.json
index 49df9641..8535496a 100644
--- a/engine/crates/concat/locales/es.json
+++ b/engine/crates/concat/locales/es.json
@@ -125,6 +125,7 @@
"Default title": "Título predeterminado",
"Delay": "Retardo",
"Delete": "Eliminar",
+ "Max width": "Ancho máximo",
"Generate Captions": "Generar subtítulos",
"Text to Speech": "Texto a voz",
"Downloads": "Descargas",
diff --git a/engine/crates/concat/locales/fr.json b/engine/crates/concat/locales/fr.json
index a8669d5b..2b872788 100644
--- a/engine/crates/concat/locales/fr.json
+++ b/engine/crates/concat/locales/fr.json
@@ -125,6 +125,7 @@
"Default title": "Titre par défaut",
"Delay": "Délai",
"Delete": "Supprimer",
+ "Max width": "Largeur maximale",
"Generate Captions": "Générer les sous-titres",
"Text to Speech": "Synthèse vocale",
"Downloads": "Téléchargements",
diff --git a/engine/crates/concat/locales/hr.json b/engine/crates/concat/locales/hr.json
index 81e9e224..461df42c 100644
--- a/engine/crates/concat/locales/hr.json
+++ b/engine/crates/concat/locales/hr.json
@@ -158,6 +158,7 @@
"Default title": "Zadani naslov",
"Delay": "Kašnjenje",
"Delete": "Obriši",
+ "Max width": "Najveća širina",
"Generate Captions": "Generiraj titlove",
"Text to Speech": "Tekst u govor",
"Downloads": "Preuzimanja",
diff --git a/engine/crates/concat/locales/it.json b/engine/crates/concat/locales/it.json
index 237bb467..24b9af89 100644
--- a/engine/crates/concat/locales/it.json
+++ b/engine/crates/concat/locales/it.json
@@ -125,6 +125,7 @@
"Default title": "Titolo predefinito",
"Delay": "Ritardo",
"Delete": "Elimina",
+ "Max width": "Larghezza massima",
"Generate Captions": "Genera sottotitoli",
"Text to Speech": "Sintesi vocale",
"Downloads": "Download",
diff --git a/engine/crates/concat/locales/ja.json b/engine/crates/concat/locales/ja.json
index a5289338..9d6490bb 100644
--- a/engine/crates/concat/locales/ja.json
+++ b/engine/crates/concat/locales/ja.json
@@ -125,6 +125,7 @@
"Default title": "デフォルトのタイトル",
"Delay": "ディレイ",
"Delete": "削除",
+ "Max width": "最大幅",
"Generate Captions": "字幕を生成",
"Text to Speech": "テキスト読み上げ",
"Downloads": "ダウンロード",
diff --git a/engine/crates/concat/locales/ko.json b/engine/crates/concat/locales/ko.json
index 98852be6..2cdd1579 100644
--- a/engine/crates/concat/locales/ko.json
+++ b/engine/crates/concat/locales/ko.json
@@ -125,6 +125,7 @@
"Default title": "기본 자막",
"Delay": "지연",
"Delete": "삭제",
+ "Max width": "최대 너비",
"Generate Captions": "자막 생성",
"Text to Speech": "텍스트 음성 변환",
"Downloads": "다운로드",
diff --git a/engine/crates/concat/locales/pt-BR.json b/engine/crates/concat/locales/pt-BR.json
index 2528314a..2adec9c2 100644
--- a/engine/crates/concat/locales/pt-BR.json
+++ b/engine/crates/concat/locales/pt-BR.json
@@ -125,6 +125,7 @@
"Default title": "Título padrão",
"Delay": "Atraso",
"Delete": "Excluir",
+ "Max width": "Largura máxima",
"Generate Captions": "Gerar legendas",
"Text to Speech": "Texto para fala",
"Downloads": "Downloads",
diff --git a/engine/crates/concat/locales/ru.json b/engine/crates/concat/locales/ru.json
index f6a43e63..b0a42632 100644
--- a/engine/crates/concat/locales/ru.json
+++ b/engine/crates/concat/locales/ru.json
@@ -125,6 +125,7 @@
"Default title": "Титр по умолчанию",
"Delay": "Задержка",
"Delete": "Удалить",
+ "Max width": "Максимальная ширина",
"Generate Captions": "Создать субтитры",
"Text to Speech": "Озвучить текст",
"Downloads": "Загрузки",
diff --git a/engine/crates/concat/locales/tr.json b/engine/crates/concat/locales/tr.json
index b94996f4..378f3f39 100644
--- a/engine/crates/concat/locales/tr.json
+++ b/engine/crates/concat/locales/tr.json
@@ -125,6 +125,7 @@
"Default title": "Varsayılan yazı",
"Delay": "Gecikme",
"Delete": "Sil",
+ "Max width": "En fazla genişlik",
"Generate Captions": "Altyazı oluştur",
"Text to Speech": "Metinden konuşmaya",
"Downloads": "İndirmeler",
diff --git a/engine/crates/concat/locales/zh-Hans.json b/engine/crates/concat/locales/zh-Hans.json
index 832e1f9e..30ca0087 100644
--- a/engine/crates/concat/locales/zh-Hans.json
+++ b/engine/crates/concat/locales/zh-Hans.json
@@ -125,6 +125,7 @@
"Default title": "默认字幕",
"Delay": "延迟",
"Delete": "删除",
+ "Max width": "最大宽度",
"Generate Captions": "生成字幕",
"Text to Speech": "文本转语音",
"Downloads": "下载",
diff --git a/engine/crates/concat/locales/zh-TW.json b/engine/crates/concat/locales/zh-TW.json
index 3f2ae585..bd456714 100644
--- a/engine/crates/concat/locales/zh-TW.json
+++ b/engine/crates/concat/locales/zh-TW.json
@@ -158,6 +158,7 @@
"Default title": "預設標題",
"Delay": "延遲時間",
"Delete": "刪除",
+ "Max width": "最大寬度",
"Generate Captions": "產生字幕",
"Text to Speech": "文字轉語音",
"Downloads": "下載",
diff --git a/engine/crates/concat/src/presets.rs b/engine/crates/concat/src/presets.rs
index 1d92e081..ef607b75 100644
--- a/engine/crates/concat/src/presets.rs
+++ b/engine/crates/concat/src/presets.rs
@@ -83,6 +83,7 @@ struct PresetStyle {
background: Option<String>,
line_height: Option<f64>,
tracking: Option<f64>,
+ max_width: Option<f64>,
}
impl PresetStyle {
@@ -112,6 +113,7 @@ impl PresetStyle {
background: self.background.unwrap_or_default(),
line_height: self.line_height.unwrap_or(base.line_height).max(0.5),
tracking: self.tracking.unwrap_or(0.0),
+ max_width: self.max_width.unwrap_or(0.0).max(0.0),
}
}
}
diff --git a/engine/crates/concat/src/studio.rs b/engine/crates/concat/src/studio.rs
index c6da228a..3211d4ce 100644
--- a/engine/crates/concat/src/studio.rs
+++ b/engine/crates/concat/src/studio.rs
@@ -473,6 +473,16 @@ pub enum Gesture {
/// The picture's turn, to project the pointer onto its axes.
rotation: f64,
},
+ /// A side grip on a title pulls the width its words wrap at, not the
+ /// glyphs: the box edge follows the pointer and the words reflow into
+ /// it. The width is twice the pointer's distance from the centre along
+ /// the box's own axis, as the box is drawn about the centre.
+ TextWidth {
+ clip: String,
+ centre: (f64, f64),
+ /// The title's turn, to project the pointer onto its axis.
+ rotation: f64,
+ },
/// The rotation grip dragged: the picture turns by the angle the pointer
/// has swept about the centre since the press.
StageRotate {
@@ -3232,6 +3242,7 @@ impl Studio {
| Gesture::StageScale { .. }
| Gesture::StageRotate { .. }
| Gesture::StageStretch { .. }
+ | Gesture::TextWidth { .. }
| Gesture::Paint { .. } => {}
}
self.gesture = gesture;
@@ -3294,6 +3305,7 @@ impl Studio {
| Gesture::StageScale { .. }
| Gesture::StageRotate { .. }
| Gesture::StageStretch { .. }
+ | Gesture::TextWidth { .. }
| Gesture::Paint { .. }) => {
self.gesture = other;
}
@@ -3442,6 +3454,7 @@ impl Studio {
ClipField::Shadow => text.shadow = value != 0.0,
ClipField::LineHeight => text.line_height = value.clamp(0.7, 2.5),
ClipField::Tracking => text.tracking = value.clamp(-0.05, 0.3),
+ ClipField::TextWidth => text.max_width = value.clamp(0.0, 2.0),
}
// A media clip has no text; the placeholder must not linger.
if clip.kind != model::ClipKind::Text {
@@ -3970,6 +3983,14 @@ impl Studio {
centre,
from: dy.atan2(dx),
}
+ } else if (grip == 6 || grip == 8) && clip.kind == model::ClipKind::Text {
+ // A title's side grips set where its words wrap, not how wide
+ // its glyphs are; see `Gesture::TextWidth`.
+ Gesture::TextWidth {
+ clip: id.to_owned(),
+ centre,
+ rotation: clip.rotation,
+ }
} else if grip >= 5 {
// 5 top, 6 right, 7 bottom, 8 left: the pointer's offset from
// the centre, turned back into the box's own frame.
@@ -4192,6 +4213,25 @@ impl Studio {
}
}
}
+ Gesture::TextWidth {
+ clip,
+ centre,
+ rotation,
+ } => {
+ let dx = x * f64::from(width) - centre.0;
+ let dy = y * f64::from(height) - centre.1;
+ let (sin, cos) = rotation.to_radians().sin_cos();
+ let along = (dx * cos + dy * sin).abs();
+ // Twice the reach, as a fraction of the frame; no narrower
+ // than a few percent, or every word stands alone.
+ let mut next = (2.0 * along / f64::from(width)).clamp(0.03, 2.0);
+ if snap {
+ next = (next * 20.0).round() / 20.0;
+ }
+ if let Some(clip) = self.echo_clip_mut(clip) {
+ clip.text.get_or_insert_with(TextStyle::default).max_width = next;
+ }
+ }
Gesture::StageRotate {
clip,
rotation,
@@ -4235,7 +4275,8 @@ impl Studio {
}
Gesture::StageScale { clip, .. }
| Gesture::StageRotate { clip, .. }
- | Gesture::StageStretch { clip, .. } => vec![clip],
+ | Gesture::StageStretch { clip, .. }
+ | Gesture::TextWidth { clip, .. } => vec![clip],
Gesture::Paint {
clip,
tool,
@@ -4288,7 +4329,7 @@ impl Studio {
|| after.stretch_y != before.stretch_y
{
commands.push(Command::SetClipTransform {
- clip_id: id,
+ clip_id: id.clone(),
scale: Some(after.scale),
offset_x: Some(after.offset_x),
offset_y: Some(after.offset_y),
@@ -4297,6 +4338,16 @@ impl Studio {
stretch_y: Some(after.stretch_y),
});
}
+ // A title's wrap width, from its side grips.
+ if after.text != before.text {
+ commands.push(Command::UpdateClip {
+ clip_id: id,
+ patch: ClipPatch {
+ text: Some(after.text.clone()),
+ ..Default::default()
+ },
+ });
+ }
}
match commands.len() {
0 => {
@@ -6462,6 +6513,7 @@ impl Studio {
plated: plate.alpha() > 0,
line_height: text.line_height as f32,
tracking: text.tracking as f32,
+ text_width: text.max_width as f32,
cutout: match &clip.cutout {
None => 0,
Some(cutout) if cutout.mode == model::CutoutMode::Auto => 1,
diff --git a/engine/crates/concat/ui/inspector/text-panel.slint b/engine/crates/concat/ui/inspector/text-panel.slint
index a3719139..a1d92cfd 100644
--- a/engine/crates/concat/ui/inspector/text-panel.slint
+++ b/engine/crates/concat/ui/inspector/text-panel.slint
@@ -40,6 +40,7 @@ export component TextPanel inherits VerticalLayout {
property <float> stroke-width;
property <float> line-height;
property <float> tracking;
+ property <float> text-width;
property <float> offset-x;
property <float> offset-y;
property <int> weight-index;
@@ -53,6 +54,7 @@ export component TextPanel inherits VerticalLayout {
root.stroke-width = root.selected.stroke-width;
root.line-height = root.selected.line-height;
root.tracking = root.selected.tracking;
+ root.text-width = root.selected.text-width;
root.offset-x = root.selected.offset-x;
root.offset-y = root.selected.offset-y;
root.weight-index = root.selected.font-weight >= 700 ? 3
@@ -315,6 +317,21 @@ export component TextPanel inherits VerticalLayout {
unit-scale: 100;
changed(v) => { root.set(ClipField.tracking, v); root.commit(); }
}
+
+ // Where the words wrap. Zero is no limit; the side grips on the
+ // stage set it by pulling the box's edge.
+ Param {
+ label: I18n.t("Max width");
+ value <=> root.text-width;
+ minimum: 0;
+ maximum: 1;
+ step: 0.01;
+ default-value: 0;
+ fmt: ParamFormat.fraction;
+ unit: "%";
+ unit-scale: 100;
+ changed(v) => { root.set(ClipField.text-width, v); root.commit(); }
+ }
}
}
diff --git a/engine/crates/concat/ui/timeline/model.slint b/engine/crates/concat/ui/timeline/model.slint
index 55ea8c63..e02fb956 100644
--- a/engine/crates/concat/ui/timeline/model.slint
+++ b/engine/crates/concat/ui/timeline/model.slint
@@ -154,7 +154,7 @@ export enum ClipField {
anim-in, anim-out, anim-combo, anim-in-duration, anim-out-duration,
flip-h, flip-v, blend, crop-left, crop-top, crop-right, crop-bottom,
font-size, font-weight, italic, text-opacity, align,
- stroke-width, shadow, line-height, tracking,
+ stroke-width, shadow, line-height, tracking, text-width,
cutout-feather,
/// which of the media's audio tracks the clip plays, as a row of
/// Editor.audio-tracks
@@ -329,6 +329,9 @@ export struct SelectedClipData {
plated: bool,
line-height: float,
tracking: float,
+ /// the widest a line runs before wrapping, as a fraction of the frame;
+ /// zero for no limit
+ text-width: float,
}
/// One picture under the playhead, as the monitor places it.