Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

Graphics: point text and paragraph text, as Premiere has them

justjohn123458407f233c1e2
diff --git a/crates/engine/src/graphics.rs b/crates/engine/src/graphics.rs
index b7e57625a..d3f7c7c5b 100644
--- a/crates/engine/src/graphics.rs
+++ b/crates/engine/src/graphics.rs
@@ -9,8 +9,8 @@
use filmcraft_geom::Vec2;
use filmcraft_project::graphic::{self, LayerContent, SHAPE_OPTS, eval_layer, layer_display_name, layer_indices, new_shape_layer, new_text_layer};
-use filmcraft_project::{ClipId, ItemId, ItemKind, Label, ParamValue, Sequence, TrackKind};
-use filmcraft_render::graphic_clip::{item_layer_specs, layer_local_bounds, layer_quad};
+use filmcraft_project::{ClipId, EffectInstance, ItemId, ItemKind, Label, Param, ParamValue, Sequence, TrackKind};
+use filmcraft_render::graphic_clip::{item_layer_specs, layer_local_bounds, layer_quad, text_layout};
use filmcraft_time::{Tick, TimeRange};
use serde_json::{Value, json};
@@ -191,6 +191,7 @@ fn param_id(k: &str) -> &str {
"fauxBold" => "faux_bold",
"fauxItalic" => "faux_italic",
"boxWidth" => "box_width",
+ "boxHeight" => "box_height",
"anchorPoint" => "anchor",
"cornerRadius" => "corner_radius",
other => other,
@@ -214,6 +215,38 @@ pub(crate) fn to_param(template: &ParamValue, id: &str, v: &Value) -> Option<Par
crate::commands::json_to_param(template, v)
}
+/// Parameter `id` of a layer, created from the layer definition when the layer was saved before
+/// the parameter existed.
+fn param_entry<'a>(e: &'a mut EffectInstance, id: &str) -> Option<&'a mut Param> {
+ if !e.params.contains_key(id) {
+ let d = filmcraft_project::find_effect(&e.effect)?.param(id)?.default.clone();
+ e.params.insert(id.to_string(), Param::new(d));
+ }
+ e.params.get_mut(id)
+}
+
+/// Set properties `props` on layer `e` (keyframe-aware at media time `mt`). Changing the text
+/// keeps per-character styles on their characters.
+fn apply_props(e: &mut EffectInstance, props: &serde_json::Map<String, Value>, mt: Tick) -> Result<()> {
+ for (k, v) in props {
+ if k == "enabled" {
+ e.enabled = v.as_bool().unwrap_or(true);
+ continue;
+ }
+ let id = param_id(k);
+ let prm = param_entry(e, id).ok_or_else(|| bad("graphics.set", format!("no property `{k}`")))?;
+ let pv = to_param(&prm.value, id, v).ok_or_else(|| bad("graphics.set", format!("`{k}`: value has the wrong type")))?;
+ let old = prm.value_at(mt);
+ prm.set_at(mt, pv.clone());
+ if let (ParamValue::Text(a), ParamValue::Text(b), "text") = (&old, &pv, id)
+ && let Some(x) = e.layer.as_mut()
+ {
+ x.runs = filmcraft_project::graphic_design::adjust_runs(a, b, &x.runs);
+ }
+ }
+ Ok(())
+}
+
/// Set properties `props` on a layer (keyframe-aware at time `tl`). Changing the text keeps
/// per-character styles on their characters.
pub(crate) fn set_props(s: &mut Session, clip: ClipId, eidx: usize, props: &serde_json::Map<String, Value>, tl: Tick, label: &str) -> Result<()> {
@@ -222,24 +255,89 @@ pub(crate) fn set_props(s: &mut Session, clip: ClipId, eidx: usize, props: &serd
let (_, it) = q.find_item_mut(clip).ok_or(filmcraft_edit::EditError::NoItem(clip))?;
let mt = it.source_time_at(tl.clamp(it.start, it.end() - Tick(1)));
let e = it.effects.get_mut(eidx).ok_or_else(|| bad("graphics.set", "no such layer"))?;
- for (k, v) in &props {
- if k == "enabled" {
- e.enabled = v.as_bool().unwrap_or(true);
- continue;
- }
- let id = param_id(k);
- let prm = e.params.get_mut(id).ok_or_else(|| bad("graphics.set", format!("no property `{k}`")))?;
- let pv = to_param(&prm.value, id, v).ok_or_else(|| bad("graphics.set", format!("`{k}`: value has the wrong type")))?;
- let old = prm.value_at(mt);
- prm.set_at(mt, pv.clone());
- if let (ParamValue::Text(a), ParamValue::Text(b), "text") = (&old, &pv, id)
- && let Some(x) = e.layer.as_mut()
- {
- x.runs = filmcraft_project::graphic_design::adjust_runs(a, b, &x.runs);
+ apply_props(e, &props, mt)?;
+ Ok(())
+ })
+}
+
+/// Turn a text layer into point text (no box; the lines the box wrapped become real lines) or
+/// paragraph text (a box fitted to the text). The text stays where it is: the layer's origin
+/// moves between the first baseline and the box's top-left corner, and the anchor point is
+/// renumbered to stay on the same spot.
+fn set_text_type(s: &mut Session, p: &Value) -> Result<Value> {
+ const ID: &str = "graphics.setTextType";
+ let clip = target_clip(s, p).ok_or_else(|| bad(ID, "no graphic clip"))?;
+ let (layer, ei) = layer_effect_index(s, clip, p)?;
+ let to_paragraph = match str_p(p, "type").map(str::to_ascii_lowercase).as_deref() {
+ Some("paragraph" | "paragraph text") => true,
+ Some("point" | "point text") => false,
+ _ => return Err(bad(ID, "need `type`: point or paragraph")),
+ };
+ let seq = s.active_sequence().ok_or(EngineError::NoSequence)?;
+ let (_, it) = seq.find_item(clip).ok_or_else(|| bad(ID, "no such clip"))?;
+ let size = match s.project.item(it.item).map(|p| &p.kind) {
+ Some(ItemKind::Graphic { width, height, .. }) => (*width, *height),
+ _ => (seq.settings.width, seq.settings.height),
+ };
+ let ph = s.playhead();
+ let mt = it.source_time_at(ph.clamp(it.start, it.end() - Tick(1)));
+ let spec = it.effects.get(ei).and_then(|e| eval_layer(e, mt, size)).ok_or_else(|| bad(ID, "no such layer"))?;
+ let LayerContent::Text(tp) = &spec.content else { return Err(bad(ID, "not a text layer")) };
+ if tp.vertical {
+ return Err(bad(ID, "vertical text is always point text"));
+ }
+ let name = |paragraph: bool| if paragraph { "paragraph" } else { "point" };
+ if (tp.box_width > 0.0) == to_paragraph {
+ return Ok(json!({"clip": clip.0, "layer": layer, "type": name(to_paragraph), "changed": false}));
+ }
+ // where point text's origin (its alignment point on the first baseline) sits in a box `w` wide
+ let origin_x = |w: f32| match tp.align {
+ 1 => w / 2.0,
+ 2 => w,
+ _ => 0.0,
+ };
+ let mut props = serde_json::Map::new();
+ // what to add to the anchor so that it stays on the same spot of the picture
+ let shift = if to_paragraph {
+ let widest = text_layout(tp).lines.iter().map(|l| l.width).fold(0.0, f32::max);
+ // a little slack, so that no line wraps
+ let w = (widest.ceil() + 1.0).clamp(1.0, 100_000.0);
+ let boxed = text_layout(&graphic::TextProps { box_width: w, box_height: 0.0, ..tp.clone() });
+ let h = (boxed.bounds[3].ceil() + 1.0).clamp(1.0, 100_000.0);
+ props.insert("box_width".into(), json!(w));
+ props.insert("box_height".into(), json!(h));
+ (origin_x(w), boxed.lines.first().map_or(0.0, |l| l.baseline))
+ } else {
+ // every line, also those the box hides
+ let all = text_layout(&graphic::TextProps { box_height: 0.0, ..tp.clone() });
+ let mut text = String::with_capacity(tp.text.len());
+ for (i, l) in all.lines.iter().enumerate() {
+ let line = tp.text.get(l.range.clone()).unwrap_or_default();
+ // a wrapped line ends where the next begins: its trailing space becomes the line break
+ let wrapped = all.lines.get(i + 1).is_some_and(|n| n.range.start == l.range.end);
+ text.push_str(if wrapped { line.trim_end() } else { line });
+ if i + 1 < all.lines.len() {
+ text.push('\n');
}
}
+ props.insert("text".into(), json!(text));
+ props.insert("box_width".into(), json!(0.0));
+ props.insert("box_height".into(), json!(0.0));
+ (-origin_x(tp.box_width), -all.lines.first().map_or(0.0, |l| l.baseline))
+ };
+ s.edit_sequence("Text Layer Type", |q, _, _| {
+ let (_, it) = q.find_item_mut(clip).ok_or(filmcraft_edit::EditError::NoItem(clip))?;
+ let e = it.effects.get_mut(ei).ok_or_else(|| bad(ID, "no such layer"))?;
+ apply_props(e, &props, mt)?;
+ if let Some(a) = param_entry(e, "anchor") {
+ a.map_values(|v| match v.as_vec2() {
+ Some(a) => ParamValue::Vec2(Vec2::new(a.x + shift.0 as f64, a.y + shift.1 as f64)),
+ None => v,
+ });
+ }
Ok(())
- })
+ })?;
+ Ok(json!({"clip": clip.0, "layer": layer, "type": name(to_paragraph), "changed": true}))
}
/// Layers of a graphic clip with their evaluated bounds (sequence/canvas pixels).
@@ -265,6 +363,14 @@ fn list_layers(s: &Session, clip: ClipId) -> Result<Value> {
LayerContent::Text(t) => ("text", Some(t.text.clone())),
LayerContent::Shape(sh) => (SHAPE_OPTS.get(sh.shape as usize).copied().unwrap_or("Shape"), None),
};
+ // point text has no box; paragraph text wraps in one and hides what does not fit
+ let (text_type, text_box, overflow) = match &sp.content {
+ LayerContent::Text(t) if t.box_width > 0.0 && !t.vertical => {
+ (Some("paragraph"), Some([t.box_width, t.box_height]), Some(text_layout(t).overflow))
+ }
+ LayerContent::Text(_) => (Some("point"), None, None),
+ LayerContent::Shape(_) => (None, None, None),
+ };
Some(json!({
"layer": i,
"effectIndex": ei,
@@ -272,7 +378,13 @@ fn list_layers(s: &Session, clip: ClipId) -> Result<Value> {
"kind": kind,
"text": text,
"enabled": e.enabled,
+ "textType": text_type,
+ "box": text_box,
+ "overflow": overflow,
"position": [sp.transform.position.x, sp.transform.position.y],
+ "anchor": [sp.transform.anchor.x, sp.transform.anchor.y],
+ "scale": sp.transform.scale.y * 100.0,
+ "scaleWidth": sp.transform.scale.x * 100.0,
"uid": extra.map_or(0, |x| x.uid),
"pin": extra.and_then(|x| x.pin.as_ref()).map(|p| serde_json::to_value(p).unwrap_or_default()),
"styles": extra.map(|x| serde_json::to_value(&x.runs).unwrap_or_default()).unwrap_or(json!([])),
@@ -751,7 +863,7 @@ pub fn commands() -> Vec<CommandSpec> {
"Text",
&["Graphics and Titles", "New Layer"],
Some("Cmd+T"),
- r#"{"text":str="New Text","position":[x,y]?,"clip":id?,"newClip":bool?,"vertical":bool=false,"size":px=100,"font":str?,"fontStyle":str?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
+ r#"{"text":str="New Text","position":[x,y]? (point text: its alignment point on the first baseline; with `box`: the box's top-left corner),"box":[w,h]? (paragraph text wrapped in a box this size),"clip":id?,"newClip":bool?,"vertical":bool=false,"size":px=100,"font":str?,"fontStyle":str?,"seconds":f64=5,"track":index?,"time":ticks?}"#,
has_seq,
|s, p| {
let text = str_p(p, "text").unwrap_or("New Text").to_string();
@@ -761,18 +873,20 @@ pub fn commands() -> Vec<CommandSpec> {
let (w, h) = s.active_sequence().map(|q| (q.settings.width, q.settings.height)).unwrap_or((1920, 1080));
let pos = vec2_p(p, "position").unwrap_or(Vec2::new(w as f64 / 2.0, h as f64 / 2.0));
let size = f64_p(p, "size").unwrap_or(100.0);
- let mut layer = if p.get("vertical").and_then(Value::as_bool) == Some(true) {
- graphic::new_vertical_text_layer(&text, pos, size)
- } else {
- new_text_layer(&text, pos, size)
- };
- layer.params.insert("ligatures".into(), filmcraft_project::Param::new(ParamValue::Bool(gp.ligatures)));
+ let vertical = p.get("vertical").and_then(Value::as_bool) == Some(true);
+ let mut layer = if vertical { graphic::new_vertical_text_layer(&text, pos, size) } else { new_text_layer(&text, pos, size) };
+ if let Some(b) = vec2_p(p, "box").filter(|_| !vertical) {
+ for (id, v) in [("box_width", b.x), ("box_height", b.y)] {
+ layer.params.insert(id.into(), Param::new(ParamValue::Float(v.clamp(1.0, 100_000.0))));
+ }
+ }
+ layer.params.insert("ligatures".into(), Param::new(ParamValue::Bool(gp.ligatures)));
if !gp.default_font.trim().is_empty() {
- layer.params.insert("font".into(), filmcraft_project::Param::new(ParamValue::Text(gp.default_font.trim().into())));
+ layer.params.insert("font".into(), Param::new(ParamValue::Text(gp.default_font.trim().into())));
}
for (k, id) in [("font", "font"), ("fontStyle", "font_style")] {
if let Some(v) = str_p(p, k) {
- layer.params.insert(id.into(), filmcraft_project::Param::new(ParamValue::Text(v.into())));
+ layer.params.insert(id.into(), Param::new(ParamValue::Text(v.into())));
}
}
let into = if p.get("newClip").and_then(Value::as_bool) == Some(true) { None } else { u64_p(p, "clip").map(ClipId) };
@@ -859,6 +973,15 @@ pub fn commands() -> Vec<CommandSpec> {
Ok(Value::Null)
},
),
+ spec(
+ "graphics.setTextType",
+ "Text Layer Type",
+ &[],
+ None,
+ r#"{"clip":id?,"layer":n|name?,"type":"point|paragraph" (point: no box, handles scale the text; paragraph: the text wraps in a box that handles resize)}"#,
+ has_graphic,
+ set_text_type,
+ ),
spec("graphics.selectLayer", "Select Graphic Layer", &[], None, r#"{"clip":id?,"layers":[n]}"#, has_graphic, |s, p| {
let clip = target_clip(s, p).ok_or_else(|| bad("graphics.selectLayer", "no graphic clip"))?;
let layers: Vec<usize> =
diff --git a/crates/engine/src/graphics_tests.rs b/crates/engine/src/graphics_tests.rs
index 10ae78527..79159b80b 100644
--- a/crates/engine/src/graphics_tests.rs
+++ b/crates/engine/src/graphics_tests.rs
@@ -373,3 +373,164 @@ fn new_layer_from_file_places_the_image_above() {
assert!(s.execute("graphics.newFromFile", json!({})).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
+
+/// Where each line of text layer `layer` starts on the canvas (the left end of its baseline),
+/// with the line's text.
+fn line_starts(s: &Session, clip: ClipId, layer: usize) -> Vec<(String, f64, f64)> {
+ let spec = layers(s, clip).remove(layer);
+ let LayerContent::Text(t) = &spec.content else { panic!("not text") };
+ let l = filmcraft_render::graphic_clip::text_layout(t);
+ let m = filmcraft_render::graphic_clip::layer_matrix(&spec);
+ l.lines
+ .iter()
+ .map(|line| {
+ let p = m.apply(filmcraft_geom::Vec2::new(line.x as f64, line.baseline as f64));
+ (t.text[line.range.clone()].trim_end().to_string(), p.x, p.y)
+ })
+ .collect()
+}
+
+fn same_places(a: &[(String, f64, f64)], b: &[(String, f64, f64)]) {
+ assert_eq!(a.len(), b.len(), "{a:?} vs {b:?}");
+ for (x, y) in a.iter().zip(b) {
+ assert_eq!(x.0, y.0);
+ assert!((x.1 - y.1).abs() < 0.05 && (x.2 - y.2).abs() < 0.05, "line `{}` moved: {x:?} -> {y:?}", x.0);
+ }
+}
+
+const FOX: &str = "The quick brown fox jumps over the lazy dog";
+
+#[test]
+fn paragraph_text_wraps_in_its_box_and_hides_what_does_not_fit() {
+ let mut s = demo();
+ let r = s.execute("graphics.newText", json!({"text": FOX, "position": [270, 583], "box": [500, 150], "size": 60})).unwrap();
+ let clip = ClipId(r["clip"].as_u64().unwrap());
+ let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
+ let l = &list["layers"][0];
+ assert_eq!(l["textType"], "paragraph");
+ assert_eq!(l["box"], json!([500.0, 150.0]));
+ assert_eq!(l["overflow"], true, "three lines of 60 px text do not fit 150 px");
+ assert_eq!(l["localBounds"], json!([0.0, 0.0, 500.0, 150.0]), "the box is the layer's bounds");
+ assert_eq!(l["quad"][0], json!([270.0, 583.0]), "the position is the box's top-left corner");
+ assert_eq!(l["quad"][2], json!([770.0, 733.0]));
+ let shown = line_starts(&s, clip, 0);
+ assert_eq!(shown.len(), 2, "{shown:?}");
+ assert!(shown.iter().all(|(_, x, _)| (*x - 270.0).abs() < 8.0), "lines start at the box's left edge: {shown:?}");
+
+ // a taller box shows everything; the font size and scale are untouched
+ s.execute("graphics.set", json!({"clip": clip.0, "props": {"boxHeight": 400}})).unwrap();
+ let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
+ assert_eq!(list["layers"][0]["overflow"], false);
+ assert_eq!(list["layers"][0]["scale"], 100.0);
+ assert!(line_starts(&s, clip, 0).len() >= 3);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.execute("graphics.list", json!({"clip": clip.0})).unwrap()["layers"][0]["overflow"], true);
+
+ // point text has no box, and a vertical layer never gets one
+ let r = s.execute("graphics.newText", json!({"text": "Title", "newClip": true, "track": 3})).unwrap();
+ let point = s.execute("graphics.list", json!({"clip": r["clip"]})).unwrap();
+ assert_eq!(point["layers"][0]["textType"], "point");
+ assert_eq!(point["layers"][0]["box"], json!(null));
+ let r = s.execute("graphics.newText", json!({"text": "Tate", "vertical": true, "box": [300, 300], "newClip": true, "track": 4})).unwrap();
+ assert_eq!(s.execute("graphics.list", json!({"clip": r["clip"]})).unwrap()["layers"][0]["textType"], "point");
+}
+
+#[test]
+fn text_type_converts_both_ways_and_keeps_the_text_in_place() {
+ for align in ["left", "center", "right"] {
+ let mut s = demo();
+ let r = s.execute("graphics.newText", json!({"text": FOX, "position": [270, 400], "box": [500, 150], "size": 60})).unwrap();
+ let clip = ClipId(r["clip"].as_u64().unwrap());
+ // scaled and turned, so that the anchor arithmetic matters
+ s.execute("graphics.set", json!({"clip": clip.0, "props": {"align": align, "scale": 150, "scale_width": 150, "rotation": 20}})).unwrap();
+ let hidden = line_starts(&s, clip, 0);
+ assert_eq!(hidden.len(), 2, "the box hides the third line");
+ s.execute("graphics.set", json!({"clip": clip.0, "props": {"boxHeight": 0}})).unwrap();
+ let before = line_starts(&s, clip, 0);
+ assert!(before.len() >= 3);
+ s.execute("edit.undo", json!({})).unwrap();
+ let position = layers(&s, clip)[0].transform.position;
+
+ // paragraph → point: every line stays where it was, also the hidden one
+ let r = s.execute("graphics.setTextType", json!({"clip": clip.0, "type": "point"})).unwrap();
+ assert_eq!(r, json!({"clip": clip.0, "layer": 0, "type": "point", "changed": true}));
+ let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
+ assert_eq!(list["layers"][0]["textType"], "point", "{align}");
+ let spec = layers(&s, clip).remove(0);
+ assert_eq!(text_of(&spec).lines().count(), before.len(), "the wrapped lines became real lines: {:?}", text_of(&spec));
+ assert_eq!(text_of(&spec).replace('\n', " "), FOX, "nothing but the line breaks changed");
+ assert_eq!(spec.transform.position, position, "the layer's position is untouched ({align})");
+ assert!(spec.transform.anchor.y < -1.0, "the anchor, still on the box's old corner, is above the first baseline: {:?}", spec.transform.anchor);
+ same_places(&before, &line_starts(&s, clip, 0));
+ // again: nothing to do
+ assert_eq!(s.execute("graphics.setTextType", json!({"clip": clip.0, "type": "Point Text"})).unwrap()["changed"], false);
+
+ // point → paragraph: a box fitted to the text, which still does not move
+ s.execute("graphics.setTextType", json!({"clip": clip.0, "type": "paragraph"})).unwrap();
+ let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
+ let l = &list["layers"][0];
+ assert_eq!(l["textType"], "paragraph");
+ assert_eq!(l["overflow"], false, "the fitted box shows every line");
+ let widest = 500.0;
+ assert!(l["box"][0].as_f64().unwrap() <= widest + 2.0 && l["box"][0].as_f64().unwrap() > 200.0, "{}", l["box"]);
+ let spec = layers(&s, clip).remove(0);
+ assert_eq!(spec.transform.position, position);
+ // the anchor is level with the box's top again; the fitted box is narrower than the old
+ // one, so centred and right-aligned text leave the anchor to its left
+ let a = spec.transform.anchor;
+ assert!(a.y.abs() < 1e-3 && a.x < 1e-3 && (align != "left" || a.x.abs() < 1e-3), "{align}: {a:?}");
+ same_places(&before, &line_starts(&s, clip, 0));
+
+ // each conversion is one undo step
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.execute("graphics.list", json!({"clip": clip.0})).unwrap()["layers"][0]["textType"], "point");
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.execute("graphics.list", json!({"clip": clip.0})).unwrap()["layers"][0]["textType"], "paragraph");
+ same_places(&hidden, &line_starts(&s, clip, 0));
+ s.execute("edit.redo", json!({})).unwrap();
+ same_places(&before, &line_starts(&s, clip, 0));
+ }
+}
+
+#[test]
+fn text_type_refuses_what_it_cannot_convert() {
+ let mut s = Session::default();
+ assert!(s.execute("graphics.setTextType", json!({"type": "point"})).is_err(), "no sequence");
+ let mut s = demo();
+ let r = s.execute("graphics.newText", json!({"text": "Title"})).unwrap();
+ let clip = r["clip"].as_u64().unwrap();
+ assert!(s.execute("graphics.setTextType", json!({"clip": clip})).is_err(), "no type");
+ assert!(s.execute("graphics.setTextType", json!({"clip": clip, "type": "wavy"})).is_err());
+ s.execute("graphics.newShape", json!({"shape": "ellipse", "clip": clip})).unwrap();
+ let e = s.execute("graphics.setTextType", json!({"clip": clip, "layer": 1, "type": "paragraph"})).unwrap_err();
+ assert!(e.to_string().contains("not a text layer"), "{e}");
+ s.execute("graphics.newText", json!({"text": "Tate", "vertical": true, "clip": clip})).unwrap();
+ let e = s.execute("graphics.setTextType", json!({"clip": clip, "layer": 2, "type": "paragraph"})).unwrap_err();
+ assert!(e.to_string().contains("vertical"), "{e}");
+ // a point-text layer keeps its own line breaks when it gets a box
+ s.execute("graphics.setText", json!({"clip": clip, "layer": 0, "text": "one\ntwo words\n\nfour"})).unwrap();
+ let before = line_starts(&s, ClipId(clip), 0);
+ s.execute("graphics.setTextType", json!({"clip": clip, "layer": 0, "type": "paragraph"})).unwrap();
+ same_places(&before, &line_starts(&s, ClipId(clip), 0));
+ s.execute("graphics.setTextType", json!({"clip": clip, "layer": 0, "type": "point"})).unwrap();
+ assert_eq!(text_of(&layers(&s, ClipId(clip))[0]), "one\ntwo words\n\nfour");
+}
+
+#[test]
+fn a_layer_saved_before_the_box_height_existed_can_still_get_one() {
+ let mut s = demo();
+ let r = s.execute("graphics.newText", json!({"text": FOX, "box": [500, 150], "size": 60})).unwrap();
+ let clip = ClipId(r["clip"].as_u64().unwrap());
+ s.edit_sequence("old file", |q, _, _| {
+ let (_, it) = q.find_item_mut(clip).unwrap();
+ let ei = layer_indices(&it.effects)[0];
+ it.effects[ei].params.remove("box_height");
+ Ok(())
+ })
+ .unwrap();
+ let list = s.execute("graphics.list", json!({"clip": clip.0})).unwrap();
+ assert_eq!(list["layers"][0]["box"], json!([500.0, 0.0]), "as tall as its text");
+ assert_eq!(list["layers"][0]["overflow"], false);
+ s.execute("graphics.set", json!({"clip": clip.0, "props": {"box_height": 100}})).unwrap();
+ assert_eq!(s.execute("graphics.list", json!({"clip": clip.0})).unwrap()["layers"][0]["box"], json!([500.0, 100.0]));
+}
diff --git a/crates/project/src/graphic.rs b/crates/project/src/graphic.rs
index 1ecf6292d..5908d423e 100644
--- a/crates/project/src/graphic.rs
+++ b/crates/project/src/graphic.rs
@@ -125,6 +125,7 @@ pub(crate) fn layer_defs() -> Vec<EffectDef> {
chc("caps", "Capitalisation", CAPS_OPTS, 0, X),
bo("underline", "Underline", false, X),
fl("box_width", "Text Box Width", 0.0, (0.0, 100_000.0), (0.0, 3840.0), "", X),
+ fl("box_height", "Text Box Height", 0.0, (0.0, 100_000.0), (0.0, 2160.0), "", X),
bo("vertical", "Vertical Text", false, X),
],
),
@@ -192,8 +193,10 @@ pub struct TextProps {
/// 0 normal, 1 all caps, 2 small caps.
pub caps: u32,
pub underline: bool,
- /// Area-text width (0 = point text).
+ /// Paragraph-text box width (0 = point text).
pub box_width: f32,
+ /// Paragraph-text box height: lines that do not fit are not shown (0 = as tall as the text).
+ pub box_height: f32,
/// Vertical text (characters stacked top to bottom; columns right to left).
pub vertical: bool,
/// Per-character style overrides as *byte* ranges of `text` (sorted, non-overlapping).
@@ -286,6 +289,7 @@ pub fn eval_layer(e: &EffectInstance, t: Tick, frame: (u32, u32)) -> Option<Laye
caps: ch(e, "caps", t),
underline: bb(e, "underline", t),
box_width: ff(e, "box_width", t).max(0.0),
+ box_height: ff(e, "box_height", t).max(0.0),
vertical: bb(e, "vertical", t),
}
}),
@@ -393,7 +397,7 @@ pub fn new_vertical_text_layer(text: &str, position: Vec2, size: f64) -> EffectI
/// Reset a layer's parameters to their defaults, keeping its content (name, text, shape kind,
/// geometry and path) — Graphics ▸ Reset All Parameters.
pub fn reset_layer_params(e: &mut EffectInstance) {
- const KEEP: &[&str] = &["name", "text", "shape", "size", "sides", "points", "vertical"];
+ const KEEP: &[&str] = &["name", "text", "shape", "size", "sides", "points", "vertical", "box_width", "box_height"];
let Some(def) = crate::effect::find_effect(&e.effect) else { return };
let mut fresh = def.instance();
for k in KEEP {
diff --git a/crates/render/src/graphic_clip.rs b/crates/render/src/graphic_clip.rs
index 88c84765c..70df605b7 100644
--- a/crates/render/src/graphic_clip.rs
+++ b/crates/render/src/graphic_clip.rs
@@ -59,6 +59,7 @@ pub fn text_styles(t: &TextProps) -> (TextStyle, ParagraphStyle) {
},
leading: t.leading,
width: (t.box_width > 0.0 && !t.vertical).then_some(t.box_width),
+ height: (t.box_width > 0.0 && t.box_height > 0.0 && !t.vertical).then_some(t.box_height),
rtl: None,
vertical: t.vertical,
},
diff --git a/crates/text/src/layout.rs b/crates/text/src/layout.rs
index e1cd11310..31281afb9 100644
--- a/crates/text/src/layout.rs
+++ b/crates/text/src/layout.rs
@@ -87,6 +87,9 @@ pub struct ParagraphStyle {
pub leading: f32,
/// Wrap width (area text); None = point text.
pub width: Option<f32>,
+ /// Box height (area text only): lines that end below it are left out, except the first.
+ /// None = as tall as the text.
+ pub height: Option<f32>,
/// Base direction: None = from the first strong character.
pub rtl: Option<bool>,
/// Vertical text: characters stack top to bottom, paragraphs are columns laid out right to
@@ -114,6 +117,7 @@ impl Hash for ParagraphStyle {
self.align.hash(h);
hf(h, self.leading);
self.width.map(f32::to_bits).hash(h);
+ self.height.map(f32::to_bits).hash(h);
self.rtl.hash(h);
self.vertical.hash(h);
}
@@ -211,6 +215,8 @@ pub struct Layout {
pub bounds: [f32; 4],
/// The face requested was missing (substituted).
pub missing_font: bool,
+ /// Lines were left out because they do not fit the box height.
+ pub overflow: bool,
pub text_len: usize,
/// Laid out vertically (one line per character; columns right to left).
pub vertical: bool,
@@ -632,10 +638,15 @@ pub fn layout_rich_uncached(text: &str, style: &TextStyle, runs: &[StyleRun], pa
};
let mut baseline = first_baseline;
let mut prev_desc = 0.0f32;
+ let box_h = para.width.and(para.height);
for (i, pl) in plines.into_iter().enumerate() {
if i > 0 {
// rich text: a line holding a larger run pushes its baseline down
baseline += if rich { line_h.max(prev_desc + pl.ascent + para.leading) } else { line_h };
+ if box_h.is_some_and(|h| baseline + pl.descent > h + 0.01) {
+ lay.overflow = true;
+ break;
+ }
}
prev_desc = pl.descent;
let shift = match (para.width, para.align) {
@@ -688,6 +699,11 @@ pub fn layout_rich_uncached(text: &str, style: &TextStyle, runs: &[StyleRun], pa
if let (Some(first), Some(last)) = (lay.lines.first(), lay.lines.last()) {
lay.bounds = [x0, first.baseline - first.ascent, x1.max(x0), last.baseline + last.descent];
}
+ if let Some(h) = box_h {
+ // a sized box is its own bounds, however much text it holds
+ lay.bounds[1] = 0.0;
+ lay.bounds[3] = h.max(0.0);
+ }
lay
}
@@ -839,6 +855,33 @@ mod tests {
assert!(left.lines.iter().all(|l| l.width <= 300.0 + 0.01));
}
+ #[test]
+ fn a_box_height_leaves_out_the_lines_that_do_not_fit() {
+ let text = "the quick brown fox jumps over the lazy dog again and again";
+ let free = layout(text, &st(40.0), &ParagraphStyle { width: Some(300.0), ..Default::default() });
+ assert!(free.lines.len() >= 3 && !free.overflow);
+ // room for two lines only
+ let h = free.lines[1].baseline + free.lines[1].descent + 1.0;
+ let boxed = layout(text, &st(40.0), &ParagraphStyle { width: Some(300.0), height: Some(h), ..Default::default() });
+ assert_eq!(boxed.lines.len(), 2);
+ assert!(boxed.overflow);
+ assert_eq!(boxed.lines[..], free.lines[..2]);
+ assert_eq!(boxed.glyphs.len(), free.lines[1].glyphs.end);
+ assert_eq!(boxed.bounds, [0.0, 0.0, 300.0, h], "the box is the bounds");
+ assert_eq!(boxed.text_len, text.len());
+ // a box tall enough for everything hides nothing; a box too short for one line keeps the first
+ let tall = layout(text, &st(40.0), &ParagraphStyle { width: Some(300.0), height: Some(5000.0), ..Default::default() });
+ assert_eq!(tall.lines.len(), free.lines.len());
+ assert!(!tall.overflow);
+ let tiny = layout(text, &st(40.0), &ParagraphStyle { width: Some(300.0), height: Some(2.0), ..Default::default() });
+ assert_eq!(tiny.lines.len(), 1);
+ assert!(tiny.overflow);
+ // point text has no box: the height is ignored
+ let point = layout("a\nb\nc", &st(40.0), &ParagraphStyle { height: Some(2.0), ..Default::default() });
+ assert_eq!(point.lines.len(), 3);
+ assert!(!point.overflow);
+ }
+
#[test]
fn newlines_make_paragraphs_and_leading_adds() {
let l = layout("one\ntwo\n\nfour", &st(30.0), &ParagraphStyle::default());
diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs
index f33907015..525e8c9ac 100644
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@ -14,6 +14,7 @@ pub fn show(app: &mut FilmcraftApp, ctx: &egui::Context) {
crate::panels::multicam::show_dialog(app, ctx);
crate::panels::multicam::show_edit_cameras(app, ctx);
crate::panels::monitor_view::dialogs(app, ctx);
+ crate::panels::graphics::dialogs(app, ctx);
crate::panels::workspaces::dialogs(app, ctx);
crate::panels::voiceover::show(app, ctx);
crate::panels::remix::show(app, ctx);
diff --git a/crates/ui-egui/src/panels/graphics.rs b/crates/ui-egui/src/panels/graphics.rs
index 7aefe56ff..f405bba75 100644
--- a/crates/ui-egui/src/panels/graphics.rs
+++ b/crates/ui-egui/src/panels/graphics.rs
@@ -2,19 +2,22 @@
//! the Properties / Essential Graphics panels.
//!
//! Monitor overlay:
-//! - **Type tool (T):** click on empty picture → a new text layer (in the selected graphic clip
-//! under the playhead, else a new graphic clip) with a caret; click on a text layer → caret at
+//! - **Type tool (T):** click on empty picture → a new point-text layer (in the selected graphic
+//! clip under the playhead, else a new graphic clip) with a caret; drag on empty picture → a new
+//! paragraph-text layer whose box is the dragged rectangle; click on a text layer → caret at
//! the click. Typing edits the text (one undo step per typing session); arrows, Home/End,
//! Shift-selection, ⌘A, ⌘C/⌘X/⌘V, Return (new line) and Esc (stop editing) work as in a text
//! field. Double-clicking a text layer with the Selection tool also edits it.
-//! - **Selection tool:** click selects a layer (bounding box with handles); drag moves it; drag a
-//! handle scales it towards the pointer with the opposite side held in place (a corner scales
-//! both axes alike, an edge handle only its own).
+//! - **Selection tool:** click selects a layer (bounding box with handles and anchor point); drag
+//! moves it; drag the anchor point to move that alone. What a handle does depends on the layer
+//! (see [`HandleDrag`]): point text scales about its anchor point, a paragraph-text box is
+//! resized and its text re-wraps, a shape stretches away from its opposite side.
//! - **Rectangle / Ellipse tools:** drag out a shape. **Pen tool:** click points; click the first
//! point again (or press Return) to close the path; Esc cancels.
//!
//! All edits go through `graphics.*` commands. Automation ids: `program.layer.<clip>.<layer>`,
-//! `program.layer.<clip>.<layer>.handle.<n>`, `program.textEdit`, `graphics.*` in the panels.
+//! `program.layer.<clip>.<layer>.handle.<n>`, `program.layer.<clip>.<layer>.anchor`,
+//! `program.textEdit`, `graphics.*` in the panels.
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
use filmcraft_geom::{Affine, Vec2};
@@ -26,7 +29,7 @@ use serde_json::{Value, json};
use crate::FilmcraftApp;
use crate::icons::{self, Icon};
-use crate::state::{GfxEdit, Tool};
+use crate::state::{GfxEdit, TextPropsDialog, Tool};
use crate::theme::Tokens;
/// A graphic layer visible at the playhead, with its layer→screen transform.
@@ -151,9 +154,13 @@ fn next_boundary(s: &str, i: usize) -> usize {
#[derive(Clone, Copy, Debug)]
enum DragKind {
Move,
- /// Handle `n` of the layer's box (see [`handle_points`]): scales it with the opposite side held in place.
- Scale(usize),
+ /// Handle `n` of the layer's box (see [`handle_points`] and [`HandleDrag`]).
+ Handle(usize),
+ /// The layer's anchor point: it moves, the layer stays where it is.
+ Anchor,
NewShape,
+ /// The Type tool dragging out the box of a new paragraph-text layer.
+ NewTextBox,
TextSelect,
}
@@ -213,6 +220,161 @@ impl HandleScale {
}
}
+/// A handle closer than this (in points) to the anchor point scales point text as if it were this
+/// much further away, so that a handle on the anchor does not scale without bound. Measured in
+/// Premiere Pro 26 with the Program monitor at Fit.
+const NEAR_ANCHOR: f32 = 60.0;
+
+/// What dragging handle `n` of a layer from `start` to `cur` does, as Premiere Pro does it: point
+/// text scales about its anchor point, a paragraph-text box is resized (its text re-wraps at the
+/// same size), and a shape stretches away from its opposite side.
+enum HandleDrag {
+ Stretch(HandleScale),
+ /// Scale both axes by `f` about the anchor point, which is at `anchor` on screen.
+ Scale {
+ anchor: Pos2,
+ f: f32,
+ },
+ /// The text box becomes `rect` (`[x0, y0, x1, y1]` in the layer's pixels; it was `from`).
+ /// `tall`: the drag sets the box's height too.
+ Resize {
+ rect: [f32; 4],
+ from: [f32; 4],
+ tall: bool,
+ },
+}
+
+impl HandleDrag {
+ fn new(v: &LayerView, n: usize, start: Pos2, cur: Pos2) -> Self {
+ let n = n.min(7);
+ let quad = v.quad();
+ let Some(t) = text_of(&v.spec) else { return Self::Stretch(HandleScale::new(&quad, n, start, cur)) };
+ if is_paragraph(t) {
+ // a box without a height is as tall as its text
+ let from = if t.box_height > 0.0 { [0.0, 0.0, t.box_width, t.box_height] } else { [0.0, v.local[1], t.box_width, v.local[3]] };
+ let (dx, dy) = match (v.to_local(start), v.to_local(cur)) {
+ (Some(a), Some(b)) => (b.0 - a.0, b.1 - a.1),
+ _ => (0.0, 0.0),
+ };
+ // the handle follows the pointer and the opposite side stays; the box does not flip
+ let min = (t.size * 0.5).max(1.0);
+ let [mut x0, mut y0, mut x1, mut y1] = from;
+ if matches!(n, 0 | 3 | 7) {
+ x0 = (x0 + dx).min(x1 - min);
+ }
+ if matches!(n, 1 | 2 | 5) {
+ x1 = (x1 + dx).max(x0 + min);
+ }
+ if matches!(n, 0 | 1 | 4) {
+ y0 = (y0 + dy).min(y1 - min);
+ }
+ if matches!(n, 2 | 3 | 6) {
+ y1 = (y1 + dy).max(y0 + min);
+ }
+ return Self::Resize { rect: [x0, y0, x1, y1], from, tall: t.box_height > 0.0 || !matches!(n, 5 | 7) };
+ }
+ // Every handle scales both axes alike. Only the pointer's travel along one side of the box
+ // counts: along its width for the two side handles, along its height for all the others.
+ let anchor = anchor_screen(v);
+ let axis = if matches!(n, 5 | 7) { (quad[1] - quad[0]).normalized() } else { (quad[3] - quad[0]).normalized() };
+ let handle = handle_points(&quad)[n];
+ let from = (handle - anchor).dot(axis);
+ // Away from the anchor grows. A handle sitting on the anchor counts as just inside the box
+ // (where a letter's side bearing puts it in Premiere), so dragging it into the box grows.
+ let centre = quad[0] + (quad[2] - quad[0]) * 0.5;
+ let away = if from.abs() > 0.5 {
+ from.signum()
+ } else if (centre - handle).dot(axis) < 0.0 {
+ -1.0
+ } else {
+ 1.0
+ };
+ let reach = from.abs() + if from.abs() < NEAR_ANCHOR { NEAR_ANCHOR } else { 0.0 };
+ let f = 1.0 + (cur - start).dot(axis) * away / reach;
+ Self::Scale { anchor, f: if f.is_finite() { f.max(0.01) } else { 1.0 } }
+ }
+
+ /// The layer's box on screen as the drag leaves it.
+ fn quad(&self, v: &LayerView) -> [Pos2; 4] {
+ match self {
+ Self::Stretch(h) => v.quad().map(|q| h.apply(q)),
+ Self::Scale { anchor, f } => v.quad().map(|q| *anchor + (q - *anchor) * *f),
+ Self::Resize { rect: b, .. } => [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])].map(|(x, y)| sp(&v.to_screen, x, y)),
+ }
+ }
+
+ /// The `graphics.set` properties that carry out the drag.
+ fn props(&self, v: &LayerView, n: usize) -> Value {
+ let tr = &v.spec.transform;
+ match self {
+ Self::Stretch(h) => {
+ // the layer scales about its anchor, so it also moves to keep the pinned side still
+ let a = anchor_screen(v);
+ let delta = unscale(&v.canvas_to_screen, h.apply(a) - a);
+ let mut props = json!({
+ "scale": tr.scale.y * 100.0 * h.fy as f64,
+ "scale_width": tr.scale.x * 100.0 * h.fx as f64,
+ "position": [tr.position.x + delta.x, tr.position.y + delta.y],
+ });
+ if n >= 4 {
+ // an edge stretches one axis only
+ props["uniform_scale"] = json!(false);
+ }
+ props
+ }
+ Self::Scale { f, .. } => json!({"scale": tr.scale.y * 100.0 * *f as f64, "scale_width": tr.scale.x * 100.0 * *f as f64}),
+ Self::Resize { rect, from, tall } => {
+ // the box's top-left corner is the layer's origin: when it moves, the anchor point
+ // is renumbered so that it (and the position) stay on the same spot
+ let mut props = json!({
+ "box_width": rect[2] - rect[0],
+ "anchor": [tr.anchor.x - (rect[0] - from[0]) as f64, tr.anchor.y - (rect[1] - from[1]) as f64],
+ });
+ if *tall {
+ props["box_height"] = json!(rect[3] - rect[1]);
+ }
+ props
+ }
+ }
+ }
+}
+
+/// Paragraph text: wrapped in a box (vertical text never is).
+fn is_paragraph(t: &filmcraft_project::graphic::TextProps) -> bool {
+ t.box_width > 0.0 && !t.vertical
+}
+
+/// The layer's anchor point on screen.
+fn anchor_screen(v: &LayerView) -> Pos2 {
+ sp(&v.to_screen, v.spec.transform.anchor.x as f32, v.spec.transform.anchor.y as f32)
+}
+
+/// A screen offset in the units `m` maps to the screen (its translation left out).
+fn unscale(m: &Affine, off: egui::Vec2) -> Vec2 {
+ Affine { e: 0.0, f: 0.0, ..*m }.inverse().map(|i| i.apply(Vec2::new(off.x as f64, off.y as f64))).unwrap_or_default()
+}
+
+/// `graphics.newText` for the Type tool: point text at `at`, or paragraph text in the box from
+/// `at` to `corner`.
+fn new_text_action(app: &FilmcraftApp, pic: Rect, frame: (u32, u32), at: Pos2, corner: Option<Pos2>) -> (String, Value) {
+ let (into, m) = canvas_target(app, pic, frame);
+ let a = to_canvas(&m, at);
+ let size = 100.0 * frame.1 as f64 / 1080.0;
+ let mut prm = json!({"text": "", "position": [a.x, a.y], "size": size.round()});
+ if let Some(b) = corner.map(|c| to_canvas(&m, c)) {
+ let (w, h) = ((b.x - a.x).abs(), (b.y - a.y).abs());
+ // a box too small to hold a letter was meant as a click
+ if w >= 4.0 && h >= 4.0 {
+ prm["position"] = json!([a.x.min(b.x), a.y.min(b.y)]);
+ prm["box"] = json!([w, h]);
+ }
+ }
+ if let Some(cl) = into {
+ prm["clip"] = json!(cl.0);
+ }
+ ("graphics.newText#edit".into(), prm)
+}
+
const TEXT_EDIT_ID: &str = "gfx-text-edit";
fn end_edit(app: &mut FilmcraftApp, ui: &egui::Ui) {
@@ -243,25 +405,43 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
let q = v.quad();
let selected = sel_layers.contains(&v.layer);
let is_edit = editing.as_ref().is_some_and(|e| e.clip == v.clip.0 && e.layer == v.layer);
- let col = if selected || is_edit { accent } else { Color32::from_white_alpha(70) };
+ // the box of the text being typed into is red, as in Premiere
+ let col = if is_edit {
+ t.danger
+ } else if selected {
+ accent
+ } else {
+ Color32::from_white_alpha(70)
+ };
painter.add(egui::Shape::closed_line(q.to_vec(), Stroke::new(1.0, col)));
if selected && !is_edit {
+ let paragraph = text_of(&v.spec).filter(|tp| is_paragraph(tp));
+ let label = if paragraph.is_some() { "resize handle" } else { "scale handle" };
+ // text the box hides: its bottom-right handle turns into a red plus
+ let overflow = paragraph.is_some_and(|tp| text_layout(tp).overflow);
for (n, c) in q.iter().enumerate() {
let hr = Rect::from_center_size(*c, vec2(7.0, 7.0));
- painter.rect_filled(hr, 0.0, Color32::WHITE);
- painter.rect_stroke(hr, 0.0, Stroke::new(1.0, accent), StrokeKind::Middle);
- app.auto.add(&format!("program.layer.{}.{}.handle.{n}", v.clip.0, v.layer), hr.expand(3.0), "scale handle");
+ if overflow && n == 2 {
+ painter.rect_filled(hr.expand(1.0), 0.0, t.danger);
+ painter.line_segment([*c - vec2(3.0, 0.0), *c + vec2(3.0, 0.0)], Stroke::new(1.0, Color32::WHITE));
+ painter.line_segment([*c - vec2(0.0, 3.0), *c + vec2(0.0, 3.0)], Stroke::new(1.0, Color32::WHITE));
+ } else {
+ painter.rect_filled(hr, 0.0, Color32::WHITE);
+ painter.rect_stroke(hr, 0.0, Stroke::new(1.0, accent), StrokeKind::Middle);
+ }
+ app.auto.add(&format!("program.layer.{}.{}.handle.{n}", v.clip.0, v.layer), hr.expand(3.0), label);
}
for (n, m) in handle_points(&q).iter().enumerate().skip(4) {
let hr = Rect::from_center_size(*m, vec2(5.0, 5.0));
painter.rect_filled(hr, 0.0, Color32::WHITE);
- app.auto.add(&format!("program.layer.{}.{}.handle.{n}", v.clip.0, v.layer), hr.expand(4.0), "scale handle");
+ app.auto.add(&format!("program.layer.{}.{}.handle.{n}", v.clip.0, v.layer), hr.expand(4.0), label);
}
// anchor point
- let a = sp(&v.to_screen, v.spec.transform.anchor.x as f32, v.spec.transform.anchor.y as f32);
+ let a = anchor_screen(v);
painter.circle_stroke(a, 4.0, Stroke::new(1.0, accent));
painter.line_segment([a - vec2(6.0, 0.0), a + vec2(6.0, 0.0)], Stroke::new(1.0, accent));
painter.line_segment([a - vec2(0.0, 6.0), a + vec2(0.0, 6.0)], Stroke::new(1.0, accent));
+ app.auto.add(&format!("program.layer.{}.{}.anchor", v.clip.0, v.layer), Rect::from_center_size(a, vec2(12.0, 12.0)), "anchor point");
}
}
}
@@ -322,13 +502,16 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
} else {
match tool {
Tool::Selection | Tool::Type => {
- // handles of the selected layers first
- let handle = views
- .iter()
- .filter(|v| Some(v.clip) == sel_clip && sel_layers.contains(&v.layer))
- .find_map(|v| handle_points(&v.quad()).iter().position(|c| (*c - p).length() <= 7.0).map(|n| (v.clip, v.layer, n)));
- if let Some((c, l, n)) = handle {
- drag = Some(DragState { kind: DragKind::Scale(n), clip: c, layer: l, start: p });
+ // of the selected layers: the anchor point first (it can sit on a handle), then the handles
+ let selected = || views.iter().filter(|v| Some(v.clip) == sel_clip && sel_layers.contains(&v.layer));
+ let anchor = selected().find(|v| tool == Tool::Selection && (anchor_screen(v) - p).length() <= 7.0);
+ let handle = selected().find_map(|v| handle_points(&v.quad()).iter().position(|c| (*c - p).length() <= 7.0).map(|n| (v.clip, v.layer, n)));
+ if let Some(v) = anchor {
+ drag = Some(DragState { kind: DragKind::Anchor, clip: v.clip, layer: v.layer, start: p });
+ } else if let Some((c, l, n)) = handle {
+ drag = Some(DragState { kind: DragKind::Handle(n), clip: c, layer: l, start: p });
+ } else if tool == Tool::Type && !views.iter().any(|v| v.is_text() && v.hit(p)) {
+ drag = Some(DragState { kind: DragKind::NewTextBox, clip: ClipId(0), layer: 0, start: p });
} else if tool == Tool::Selection
&& let Some(v) = views.iter().find(|v| v.hit(p))
{
@@ -374,12 +557,23 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
crate::panels::monitor_view::draw_snap_lines(&painter, pic, &snap_off.1);
}
}
- DragKind::Scale(n) => {
+ DragKind::Handle(n) => {
if let Some(v) = v {
- let h = HandleScale::new(&v.quad(), n, d.start, cur);
- painter.add(egui::Shape::closed_line(v.quad().iter().map(|q| h.apply(*q)).collect(), Stroke::new(1.0, Color32::WHITE)));
+ let h = HandleDrag::new(v, n, d.start, cur);
+ painter.add(egui::Shape::closed_line(h.quad(v).to_vec(), Stroke::new(1.0, Color32::WHITE)));
}
}
+ DragKind::Anchor => {
+ if let Some(v) = v {
+ let a = anchor_screen(v) + (cur - d.start);
+ painter.circle_stroke(a, 4.0, Stroke::new(1.0, Color32::WHITE));
+ painter.line_segment([a - vec2(6.0, 0.0), a + vec2(6.0, 0.0)], Stroke::new(1.0, Color32::WHITE));
+ painter.line_segment([a - vec2(0.0, 6.0), a + vec2(0.0, 6.0)], Stroke::new(1.0, Color32::WHITE));
+ }
+ }
+ DragKind::NewTextBox => {
+ painter.rect_stroke(Rect::from_two_pos(d.start, cur), 0.0, Stroke::new(1.0, t.danger), StrokeKind::Middle);
+ }
DragKind::NewShape => {
let r = Rect::from_two_pos(d.start, cur);
if tool == Tool::Ellipse {
@@ -416,27 +610,27 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
));
}
}
- DragKind::Scale(n) if moved => {
+ DragKind::Handle(n) if moved => {
if let Some(v) = v {
- // the layer scales about its anchor, so it also moves to keep the pinned side still
- let a = sp(&v.to_screen, v.spec.transform.anchor.x as f32, v.spec.transform.anchor.y as f32);
- let h = HandleScale::new(&v.quad(), n, d.start, cur);
- let off = h.apply(a) - a;
- let lin = Affine { e: 0.0, f: 0.0, ..v.canvas_to_screen };
- let delta = lin.inverse().map(|i| i.apply(Vec2::new(off.x as f64, off.y as f64))).unwrap_or_default();
- let (s, p0) = (v.spec.transform.scale, v.spec.transform.position);
- let mut props = json!({
- "scale": s.y * 100.0 * h.fy as f64,
- "scale_width": s.x * 100.0 * h.fx as f64,
- "position": [p0.x + delta.x, p0.y + delta.y],
- });
- if n >= 4 {
- // an edge stretches one axis only
- props["uniform_scale"] = json!(false);
- }
+ let props = HandleDrag::new(v, n, d.start, cur).props(v, n);
actions.push(("graphics.set".into(), json!({"clip": v.clip.0, "layer": v.layer, "props": props})));
}
}
+ DragKind::Anchor if moved => {
+ if let Some(v) = v {
+ // the anchor moves over the layer; the position follows it, so the layer stays
+ let (canvas, local) = (unscale(&v.canvas_to_screen, cur - d.start), unscale(&v.to_screen, cur - d.start));
+ let (p0, a0) = (v.spec.transform.position, v.spec.transform.anchor);
+ actions.push((
+ "graphics.set".into(),
+ json!({"clip": v.clip.0, "layer": v.layer, "props": {"position": [p0.x + canvas.x, p0.y + canvas.y], "anchor": [a0.x + local.x, a0.y + local.y]}}),
+ ));
+ }
+ }
+ DragKind::NewTextBox if moved => {
+ end_edit(app, ui);
+ actions.push(new_text_action(app, pic, frame, d.start, Some(cur)));
+ }
DragKind::NewShape if moved => {
let (into, m) = canvas_target(app, pic, frame);
let (a, b) = (to_canvas(&m, d.start), to_canvas(&m, cur));
@@ -466,14 +660,7 @@ pub fn monitor_overlay(app: &mut FilmcraftApp, ui: &mut egui::Ui, pic: Rect, fra
start_edit_at(app, ui, v, p, &mut actions);
} else {
end_edit(app, ui);
- let (into, m) = canvas_target(app, pic, frame);
- let c = to_canvas(&m, p);
- let size = 100.0 * frame.1 as f64 / 1080.0;
- let mut prm = json!({"text": "", "position": [c.x, c.y], "size": size.round()});
- if let Some(cl) = into {
- prm["clip"] = json!(cl.0);
- }
- actions.push(("graphics.newText#edit".into(), prm));
+ actions.push(new_text_action(app, pic, frame, p, None));
}
}
Tool::Selection => {
@@ -933,6 +1120,11 @@ impl Ctx<'_> {
}
fn section(ui: &mut egui::Ui, app: &mut FilmcraftApp, name: &str, t: &Tokens) -> bool {
+ section_header(ui, app, name, t).0
+}
+
+/// A collapsible section's header row: whether the section is open, and the row.
+fn section_header(ui: &mut egui::Ui, app: &mut FilmcraftApp, name: &str, t: &Tokens) -> (bool, Rect) {
ui.add_space(4.0);
let key = format!("gfx:{name}");
let open = !app.ui.collapsed_fx.contains(&key);
@@ -953,7 +1145,7 @@ fn section(ui: &mut egui::Ui, app: &mut FilmcraftApp, name: &str, t: &Tokens) ->
app.ui.collapsed_fx.retain(|k| *k != key);
}
}
- open
+ (open, r)
}
/// A small code-drawn alignment glyph (original artwork: bars against an edge line).
@@ -1197,7 +1389,28 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
cx.number(ui, "Opacity", "opacity", 0.5, (0.0, 100.0), 0, " %");
}
// ---- text
- if e.effect == graphic::TEXT_LAYER && section(ui, app, "Text", &t) {
+ let text_open = e.effect == graphic::TEXT_LAYER && {
+ let (open, head) = section_header(ui, app, "Text", &t);
+ // Text Properties: the layer type (point / paragraph) and text styling
+ let wr = Rect::from_center_size(pos2(head.max.x - 16.0, head.center().y), vec2(22.0, 22.0));
+ let wresp = ui.interact(wr, egui::Id::new(("gfx-text-props", clip.0, l)), Sense::click());
+ icons::paint(ui.painter(), wr.shrink(4.0), Icon::Wrench, if wresp.hovered() { t.text } else { t.text_dim });
+ cx.autos.push(("graphics.textProperties".into(), wr, "Text Properties".into()));
+ if wresp.on_hover_text("Text Properties").clicked() {
+ let flag = |id: &str| pv(e, id, mt).as_bool().unwrap_or(false);
+ let ligatures = flag("ligatures");
+ app.ui.text_props_dialog = Some(TextPropsDialog {
+ clip: clip.0,
+ layer: l,
+ paragraph: pv(e, "box_width", mt).as_f64().unwrap_or(0.0) > 0.0 && !flag("vertical"),
+ vertical: flag("vertical"),
+ ligatures,
+ ligatures_was: ligatures,
+ });
+ }
+ open
+ };
+ if text_open {
// source text (multi-line), committed as it is typed
let mut s = match pv(e, "text", mt) {
ParamValue::Text(s) => s,
@@ -1270,6 +1483,7 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
cx.number(ui, "Leading", "leading", 0.5, (-5000.0, 5000.0), 0, "");
cx.number(ui, "Baseline Shift", "baseline_shift", 0.5, (-5000.0, 5000.0), 0, "");
cx.number(ui, "Text Box Width", "box_width", 2.0, (0.0, 100_000.0), 0, "");
+ cx.number(ui, "Text Box Height", "box_height", 2.0, (0.0, 100_000.0), 0, "");
let (_, mut vui) = cx.row(ui, "Style");
let flag = |id: &str| pv(e, id, mt).as_bool().unwrap_or(false);
let caps = match pv(e, "caps", mt) {
@@ -1356,3 +1570,62 @@ pub fn properties(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
}
}
}
+
+/// Text Properties (the wrench in the Text section): Text Layer Type and Text Styling.
+pub fn dialogs(app: &mut FilmcraftApp, ctx: &egui::Context) {
+ let Some(mut d) = app.ui.text_props_dialog.clone() else { return };
+ let mut elems: Vec<(String, Rect, &str)> = Vec::new();
+ let mut close = ctx.input(|i| i.key_pressed(egui::Key::Escape));
+ let mut ok = false;
+ let name = |paragraph: bool| if paragraph { "Paragraph Text" } else { "Point Text" };
+ egui::Window::new("Text Properties").collapsible(false).resizable(false).anchor(Align2::CENTER_CENTER, [0.0, 0.0]).show(ctx, |ui| {
+ ui.label("Text Layer Type");
+ let r = egui::ComboBox::from_id_salt("gfx-text-type").selected_text(name(d.paragraph)).width(190.0).show_ui(ui, |ui| {
+ for paragraph in [false, true] {
+ // vertical text has no box to wrap in
+ let r = ui.add_enabled_ui(!(paragraph && d.vertical), |ui| ui.selectable_label(d.paragraph == paragraph, name(paragraph))).inner;
+ elems.push((format!("graphics.textProperties.type.{}", if paragraph { "paragraph" } else { "point" }), r.rect, name(paragraph)));
+ if r.clicked() {
+ d.paragraph = paragraph;
+ }
+ }
+ });
+ elems.push(("graphics.textProperties.type".into(), r.response.rect, "Text Layer Type"));
+ ui.add_space(6.0);
+ ui.label("Text Styling");
+ let r = ui.checkbox(&mut d.ligatures, "Ligatures");
+ elems.push(("graphics.textProperties.ligatures".into(), r.rect, "Ligatures"));
+ ui.add_space(6.0);
+ ui.horizontal(|ui| {
+ let r = ui.button("Cancel");
+ elems.push(("graphics.textProperties.cancel".into(), r.rect, "Cancel"));
+ close |= r.clicked();
+ let r = ui.button("OK");
+ elems.push(("graphics.textProperties.ok".into(), r.rect, "OK"));
+ ok |= r.clicked();
+ });
+ });
+ for (id, r, l) in elems {
+ app.auto.add(&id, r, l);
+ }
+ if ok {
+ let target = json!({"clip": d.clip, "layer": d.layer});
+ let mut run = |cmd: &str, extra: Value| {
+ let mut p = target.clone();
+ if let (Some(p), Some(x)) = (p.as_object_mut(), extra.as_object()) {
+ p.extend(x.clone());
+ }
+ if let Err(e) = app.session.execute(cmd, p) {
+ app.ui.status = e.to_string();
+ }
+ };
+ // a layer already of that type is left alone (no undo step)
+ run("graphics.setTextType", json!({"type": if d.paragraph { "paragraph" } else { "point" }}));
+ if d.ligatures != d.ligatures_was {
+ run("graphics.set", json!({"props": {"ligatures": d.ligatures}}));
+ }
+ // the text being typed into may have been rewritten
+ app.ui.gfx_edit = None;
+ }
+ app.ui.text_props_dialog = if ok || close { None } else { Some(d) };
+}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 12f810e25..7eacd9d4d 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -470,6 +470,9 @@ pub struct UiState {
/// Open guide dialog (Add Guide / Save Guides as Template / Manage Guides).
#[serde(default)]
pub guide_dialog: Option<GuideDialog>,
+ /// Open Text Properties dialog (the wrench in the Properties panel's Text section).
+ #[serde(default)]
+ pub text_props_dialog: Option<TextPropsDialog>,
/// Open Window ▸ Workspaces dialog.
#[serde(default)]
pub workspace_dialog: Option<WorkspaceDialog>,
@@ -745,6 +748,20 @@ impl Default for DeleteTracksDraft {
}
}
+/// Draft of the Text Properties dialog of a text layer: its type (point text, or paragraph text
+/// wrapped in a box) and text styling.
+#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
+pub struct TextPropsDialog {
+ pub clip: u64,
+ pub layer: usize,
+ pub paragraph: bool,
+ /// Vertical text is always point text.
+ pub vertical: bool,
+ pub ligatures: bool,
+ /// Ligatures when the dialog opened.
+ pub ligatures_was: bool,
+}
+
/// The text layer being edited on the Program monitor: caret and selection anchor are byte
/// offsets into the layer's text.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -813,6 +830,7 @@ impl Default for UiState {
multicam_record: true,
edit_cameras: None,
guide_dialog: None,
+ text_props_dialog: None,
workspace_dialog: None,
clip_dialog: None,
extras: Default::default(),
diff --git a/crates/ui-egui/tests/graphics_handles_ui.rs b/crates/ui-egui/tests/graphics_handles_ui.rs
index 0fa850ee5..957bda097 100644
--- a/crates/ui-egui/tests/graphics_handles_ui.rs
+++ b/crates/ui-egui/tests/graphics_handles_ui.rs
@@ -1,4 +1,8 @@
-//! Headless UI tests of handle scaling of graphic layers in the Program monitor.
+//! Headless UI tests of the handles of graphic layers in the Program monitor: point text scales
+//! about its anchor point, a paragraph-text box is resized, a shape stretches away from its
+//! opposite side (docs/graphics.md).
+//!
+//! With `FILMCRAFT_UI_SHOTS=<dir>` the tests also render the UI with wgpu and save PNGs there.
use std::sync::mpsc::{Sender, channel};
@@ -11,6 +15,7 @@ use serde_json::{Value, json};
struct Driver {
harness: Harness<'static, FilmcraftApp>,
tx: Sender<ControlRequest>,
+ shots: Option<std::path::PathBuf>,
}
impl Driver {
@@ -19,8 +24,13 @@ impl Driver {
s.execute("file.openDemoProject", json!({})).unwrap();
let (tx, rx) = channel();
let app = FilmcraftApp::new(s).with_control(rx);
- let harness = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_step_dt(1.0 / 60.0).with_max_steps(10_000).build_eframe(move |_cc| app);
- let mut d = Driver { harness, tx };
+ let shots = std::env::var_os("FILMCRAFT_UI_SHOTS").map(std::path::PathBuf::from);
+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 980.0)).with_step_dt(1.0 / 60.0).with_max_steps(10_000);
+ if shots.is_some() {
+ b = b.wgpu().with_pixels_per_point(1.0);
+ }
+ let harness = b.build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, shots };
d.frames(4);
d
}
@@ -57,6 +67,14 @@ impl Driver {
fn exec(&mut self, command: &str, params: Value) -> Value {
self.ok("engine.execute", json!({"command": command, "params": params}))
}
+
+ fn shot(&mut self, name: &str) {
+ let Some(dir) = self.shots.clone() else { return };
+ self.frames(8);
+ let img = self.harness.render().expect("wgpu render");
+ std::fs::create_dir_all(&dir).unwrap();
+ img.save(dir.join(format!("{name}.png"))).unwrap();
+ }
}
impl Driver {
@@ -69,38 +87,277 @@ impl Driver {
}
impl Driver {
- /// A selected text layer; returns the id prefix of its handles (0–3 corners TL, TR, BR, BL;
- /// 4–7 the top, right, bottom and left edges).
- fn text_layer(&mut self) -> String {
- let r = self.exec("graphics.newText", json!({"text": "Title", "position": [600, 500], "size": 120}));
- let clip = r["clip"].as_u64().unwrap();
+ fn select(&mut self, clip: u64) -> String {
self.exec("graphics.selectLayer", json!({"clip": clip, "layers": [0]}));
self.ok("ui.set", json!({"tool": "Selection"}));
self.frames(4);
- format!("program.layer.{clip}.0.handle.")
+ format!("program.layer.{clip}.0.")
}
- /// Centre of handle `n`.
- fn handle(&mut self, pre: &str, n: usize) -> (f64, f64) {
- let r = self.rect(&format!("{pre}{n}"));
+ /// A selected layer of each kind; returns the clip and the id prefix of the layer's handles
+ /// (`handle.0`–`3` corners TL, TR, BR, BL; `handle.4`–`7` the top, right, bottom and left
+ /// edges) and anchor point (`anchor`).
+ fn point_text(&mut self) -> (u64, String) {
+ let r = self.exec("graphics.newText", json!({"text": "Title", "position": [600, 500], "size": 120}));
+ let clip = r["clip"].as_u64().unwrap();
+ (clip, self.select(clip))
+ }
+
+ fn paragraph_text(&mut self) -> (u64, String) {
+ let r = self.exec("graphics.newText", json!({"text": FOX, "position": [500, 300], "box": [700, 500], "size": 80}));
+ let clip = r["clip"].as_u64().unwrap();
+ (clip, self.select(clip))
+ }
+
+ fn shape(&mut self) -> String {
+ let r = self.exec("graphics.newShape", json!({"shape": "rectangle", "position": [800, 500], "size": [500, 300]}));
+ let clip = r["clip"].as_u64().unwrap();
+ self.select(clip)
+ }
+
+ /// Centre of element `pre` + `what` ("handle.2", "anchor").
+ fn at(&mut self, pre: &str, what: &str) -> (f64, f64) {
+ let r = self.rect(&format!("{pre}{what}"));
(r[0] + r[2] / 2.0, r[1] + r[3] / 2.0)
}
- fn drag_handle(&mut self, pre: &str, n: usize, dx: f64, dy: f64) {
- let (x, y) = self.handle(pre, n);
- self.ok("ui.drag", json!({"from": {"x": x, "y": y}, "to": {"x": x + dx, "y": y + dy}}));
+ fn handle(&mut self, pre: &str, n: usize) -> (f64, f64) {
+ self.at(pre, &format!("handle.{n}"))
+ }
+
+ fn drag(&mut self, from: (f64, f64), by: (f64, f64)) {
+ self.ok("ui.drag", json!({"from": {"x": from.0, "y": from.1}, "to": {"x": from.0 + by.0, "y": from.1 + by.1}, "steps": 6}));
self.frames(4);
}
+
+ fn drag_handle(&mut self, pre: &str, n: usize, dx: f64, dy: f64) {
+ let h = self.handle(pre, n);
+ self.drag(h, (dx, dy));
+ }
+
+ fn layer(&mut self, clip: u64) -> Value {
+ self.exec("graphics.list", json!({"clip": clip}))["layers"][0].clone()
+ }
}
+const FOX: &str = "The quick brown fox jumps over the lazy dog";
+
fn near(a: (f64, f64), b: (f64, f64)) -> bool {
(a.0 - b.0).abs() < 1.5 && (a.1 - b.1).abs() < 1.5
}
+fn num(v: &Value) -> f64 {
+ v.as_f64().unwrap_or_else(|| panic!("not a number: {v}"))
+}
+
+#[test]
+fn point_text_handles_scale_it_about_its_anchor() {
+ let mut d = Driver::new();
+ let (clip, pre) = d.point_text();
+ let before = d.layer(clip);
+ assert_eq!(before["textType"], "point");
+ let (anchor, tl, br) = (d.at(&pre, "anchor"), d.handle(&pre, 0), d.handle(&pre, 2));
+ assert!(
+ (anchor.0 - tl.0).abs() < 1.5 && anchor.1 > tl.1 && anchor.1 < br.1,
+ "the anchor is on the first baseline's left end: {anchor:?} in {tl:?}..{br:?}"
+ );
+
+ // a corner dragged down: the text grows, both axes alike, and the anchor does not move
+ d.drag_handle(&pre, 2, 0.0, 40.0);
+ let after = d.layer(clip);
+ let f = num(&after["scale"]) / 100.0;
+ assert!(f > 1.2, "bigger: {f}");
+ assert_eq!(after["scale"], after["scaleWidth"], "uniform");
+ assert_eq!(after["position"], before["position"]);
+ assert_eq!(after["anchor"], before["anchor"]);
+ assert!(near(d.at(&pre, "anchor"), anchor), "the anchor stays put");
+ d.shot("point-text-scaled");
+ let (tl2, br2) = (d.handle(&pre, 0), d.handle(&pre, 2));
+ for (was, now) in [(tl, tl2), (br, br2)] {
+ let want = (anchor.0 + (was.0 - anchor.0) * f, anchor.1 + (was.1 - anchor.1) * f);
+ assert!(near(now, want), "every corner moves away from the anchor by the scale: {was:?} -> {now:?}, expected {want:?}");
+ }
+ // the handle is nearer than 60 points to the anchor, so it scales as if 60 points further away
+ let reach = (br.1 - anchor.1) + 60.0;
+ assert!((f - (1.0 + 40.0 / reach)).abs() < 0.02, "scale {f} for 40 points with the handle {} from the anchor", br.1 - anchor.1);
+
+ // sideways travel of a corner does nothing
+ d.drag_handle(&pre, 2, 80.0, 0.0);
+ assert!((num(&d.layer(clip)["scale"]) / 100.0 - f).abs() < 0.01);
+
+ // an edge handle scales the whole text too: the right edge follows the pointer, since it is
+ // further than 60 points from the anchor
+ let (right, top) = (d.handle(&pre, 5), d.handle(&pre, 4));
+ d.drag_handle(&pre, 5, 50.0, 0.0);
+ let l = d.layer(clip);
+ assert_eq!(l["scale"], l["scaleWidth"], "still uniform");
+ let (right2, top2) = (d.handle(&pre, 5), d.handle(&pre, 4));
+ assert!((right2.0 - right.0 - 50.0).abs() < 2.0, "right edge follows the pointer: {right:?} -> {right2:?}");
+ assert!(top2.1 < top.1 - 2.0, "and the text got taller with it: {top:?} -> {top2:?}");
+ assert!(near(d.at(&pre, "anchor"), anchor));
+
+ // towards the anchor shrinks; one undo step per drag
+ let s = num(&l["scale"]);
+ d.drag_handle(&pre, 4, 0.0, 30.0);
+ assert!(num(&d.layer(clip)["scale"]) < s - 5.0);
+ d.exec("edit.undo", json!({}));
+ assert_eq!(num(&d.layer(clip)["scale"]), s);
+}
+
+#[test]
+fn the_anchor_point_can_be_dragged_without_moving_the_layer() {
+ let mut d = Driver::new();
+ let (clip, pre) = d.point_text();
+ d.exec("graphics.set", json!({"clip": clip, "props": {"scale": 200, "scale_width": 200}}));
+ d.frames(4);
+ let (anchor, tl, br) = (d.at(&pre, "anchor"), d.handle(&pre, 0), d.handle(&pre, 2));
+ let before = d.layer(clip);
+ d.drag(anchor, (90.0, -40.0));
+ let after = d.layer(clip);
+ assert!(near(d.at(&pre, "anchor"), (anchor.0 + 90.0, anchor.1 - 40.0)), "the anchor follows the pointer");
+ assert!(near(d.handle(&pre, 0), tl) && near(d.handle(&pre, 2), br), "the layer stays where it is");
+ // the position moves with the anchor; the anchor moves half as far in the layer's own pixels (scale 200)
+ let (dp, da) = (num(&after["position"][0]) - num(&before["position"][0]), num(&after["anchor"][0]) - num(&before["anchor"][0]));
+ assert!(dp > 10.0 && (da - dp / 2.0).abs() < 0.01, "position {dp}, anchor {da}");
+ assert_eq!(after["scale"], before["scale"]);
+
+ // now a handle scales about the moved anchor
+ d.drag_handle(&pre, 2, 0.0, 30.0);
+ assert!(near(d.at(&pre, "anchor"), (anchor.0 + 90.0, anchor.1 - 40.0)));
+ assert!(num(&d.layer(clip)["scale"]) > 201.0);
+}
+
+#[test]
+fn paragraph_text_handles_resize_the_box_and_the_text_reflows() {
+ let mut d = Driver::new();
+ let (clip, pre) = d.paragraph_text();
+ let before = d.layer(clip);
+ assert_eq!(before["textType"], "paragraph");
+ assert_eq!(before["overflow"], false, "{before}");
+ let (anchor, tl, br) = (d.at(&pre, "anchor"), d.handle(&pre, 0), d.handle(&pre, 2));
+ assert!(near(anchor, tl), "the anchor is on the box's top-left corner: {anchor:?} vs {tl:?}");
+ let k = (br.0 - tl.0) / 700.0; // screen points per canvas pixel
+
+ // bottom-right corner: it follows the pointer on both axes, the top-left stays, nothing scales
+ let (dx, dy) = (-70.0 * k, 50.0 * k);
+ d.drag_handle(&pre, 2, dx, dy);
+ let after = d.layer(clip);
+ assert!(near(d.handle(&pre, 0), tl));
+ assert!(near(d.handle(&pre, 2), (br.0 + dx, br.1 + dy)), "the corner follows the pointer");
+ assert!((num(&after["box"][0]) - 630.0).abs() < 1.0 && (num(&after["box"][1]) - 550.0).abs() < 1.0, "{}", after["box"]);
+ assert_eq!(after["overflow"], false);
+ assert_eq!(after["scale"], 100.0);
+ assert_eq!(after["position"], before["position"]);
+ assert_eq!(after["anchor"], before["anchor"]);
+
+ // a box too low for its text hides the rest (and says so); the font size is untouched
+ d.drag_handle(&pre, 6, 0.0, -400.0 * k);
+ let low = d.layer(clip);
+ assert_eq!(low["overflow"], true, "{low}");
+ d.shot("paragraph-text-overflow");
+ assert_eq!(low["scale"], 100.0);
+ d.exec("edit.undo", json!({}));
+ assert_eq!(d.layer(clip)["overflow"], false);
+
+ // the left edge: it follows the pointer, the right edge stays; the anchor stays on its spot
+ // of the picture (now outside the box) and the position is untouched
+ let (right, left) = (d.handle(&pre, 5), d.handle(&pre, 7));
+ d.drag_handle(&pre, 7, 60.0 * k, 0.0);
+ let moved = d.layer(clip);
+ assert!(near(d.handle(&pre, 5), right));
+ assert!(near(d.handle(&pre, 7), (left.0 + 60.0 * k, left.1)));
+ assert!(near(d.at(&pre, "anchor"), anchor), "the anchor stays put");
+ assert_eq!(moved["position"], before["position"]);
+ assert!((num(&moved["anchor"][0]) + 60.0).abs() < 1.0 && num(&moved["anchor"][1]).abs() < 1e-6, "{}", moved["anchor"]);
+ assert!((num(&moved["box"][0]) - 570.0).abs() < 1.0, "{}", moved["box"]);
+ d.shot("paragraph-text-left-edge-moved");
+
+ // a side dragged past its opposite stops at a small box instead of flipping
+ d.drag_handle(&pre, 5, -900.0, 0.0);
+ let w = num(&d.layer(clip)["box"][0]);
+ assert!((w - 40.0).abs() < 0.5, "half the font size: {w}");
+}
+
+#[test]
+fn type_tool_drag_makes_paragraph_text_and_a_click_point_text() {
+ let mut d = Driver::new();
+ d.ok("ui.set", json!({"tool": "Type"}));
+ d.frames(3);
+ let pic = d.rect("program.picture");
+ let at = |fx: f64, fy: f64| (pic[0] + pic[2] * fx, pic[1] + pic[3] * fy);
+ let (a, b) = (at(0.2, 0.5), at(0.6, 0.8));
+ d.drag(a, (b.0 - a.0, b.1 - a.1));
+ d.ok("ui.type", json!({"text": FOX}));
+ let list = d.exec("graphics.list", json!({}));
+ let clip = list["clip"].as_u64().unwrap();
+ let l = &list["layers"][0];
+ assert_eq!(l["text"], FOX);
+ assert_eq!(l["textType"], "paragraph");
+ let canvas = (num(&list["canvas"][0]), num(&list["canvas"][1]));
+ assert!(
+ (num(&l["box"][0]) - canvas.0 * 0.4).abs() < 2.0 && (num(&l["box"][1]) - canvas.1 * 0.3).abs() < 2.0,
+ "the box is the dragged rectangle: {}",
+ l["box"]
+ );
+ assert!((num(&l["quad"][0][0]) - canvas.0 * 0.2).abs() < 2.0 && (num(&l["quad"][0][1]) - canvas.1 * 0.5).abs() < 2.0, "{}", l["quad"]);
+ assert_eq!(l["scale"], 100.0);
+ // the text being typed is the box
+ d.shot("paragraph-text-typing");
+ let edit = d.rect("program.textEdit");
+ assert!((edit[2] - (b.0 - a.0)).abs() < 3.0, "{edit:?}");
+
+ // a click makes point text, in the same graphic
+ d.ok("ui.key", json!({"key": "Escape"}));
+ let c = at(0.3, 0.2);
+ d.ok("ui.click", json!({"x": c.0, "y": c.1}));
+ d.ok("ui.type", json!({"text": "Title"}));
+ let list = d.exec("graphics.list", json!({"clip": clip}));
+ assert_eq!(list["layers"][1]["textType"], "point");
+ assert_eq!(list["layers"][1]["box"], json!(null));
+}
+
+#[test]
+fn text_properties_switches_between_point_and_paragraph_text() {
+ let mut d = Driver::new();
+ d.ok("ui.set", json!({"workspace": "Captions and Graphics"}));
+ let (clip, pre) = d.paragraph_text();
+ let tl = d.handle(&pre, 0);
+ d.ok("ui.click", json!({"id": "graphics.textProperties"}));
+ d.frames(3);
+ d.ok("ui.click", json!({"id": "graphics.textProperties.type"}));
+ d.frames(3);
+ d.shot("text-properties-type-list");
+ d.ok("ui.click", json!({"id": "graphics.textProperties.type.point"}));
+ d.frames(3);
+ assert_eq!(d.layer(clip)["textType"], "paragraph", "nothing happens before OK");
+ d.shot("text-properties-dialog");
+ d.ok("ui.click", json!({"id": "graphics.textProperties.ok"}));
+ d.frames(4);
+ let l = d.layer(clip);
+ assert_eq!(l["textType"], "point");
+ assert!(l["text"].as_str().unwrap().contains('\n'), "the wrapped lines are real lines now: {}", l["text"]);
+ assert!(near(d.at(&pre, "anchor"), tl), "the anchor stays where the box's corner was");
+ assert!(d.ok("ui.elements", json!({"prefix": "graphics.textProperties.ok"})).as_array().unwrap().is_empty(), "the dialog closed");
+ // its handles scale it now
+ d.drag_handle(&pre, 2, 0.0, 40.0);
+ assert!(num(&d.layer(clip)["scale"]) > 101.0);
+
+ // Cancel changes nothing
+ d.ok("ui.click", json!({"id": "graphics.textProperties"}));
+ d.frames(3);
+ d.ok("ui.click", json!({"id": "graphics.textProperties.type"}));
+ d.frames(3);
+ d.ok("ui.click", json!({"id": "graphics.textProperties.type.paragraph"}));
+ d.frames(3);
+ d.ok("ui.click", json!({"id": "graphics.textProperties.cancel"}));
+ d.frames(3);
+ assert_eq!(d.layer(clip)["textType"], "point");
+}
+
#[test]
-fn corner_handles_scale_away_from_the_opposite_corner() {
+fn shape_corner_handles_scale_away_from_the_opposite_corner() {
let mut d = Driver::new();
- let pre = d.text_layer();
+ let pre = d.shape();
// bottom-right: grows down and to the right, the top-left stays
let (tl, br) = (d.handle(&pre, 0), d.handle(&pre, 2));
d.drag_handle(&pre, 2, 60.0, 30.0);
@@ -116,9 +373,9 @@ fn corner_handles_scale_away_from_the_opposite_corner() {
}
#[test]
-fn edge_handles_stretch_one_axis() {
+fn shape_edge_handles_stretch_one_axis() {
let mut d = Driver::new();
- let pre = d.text_layer();
+ let pre = d.shape();
// bottom edge: taller downwards, the top edge and the width stay
let (tl, tr, bottom) = (d.handle(&pre, 0), d.handle(&pre, 1), d.handle(&pre, 6));
d.drag_handle(&pre, 6, 0.0, 40.0);
diff --git a/crates/ui-egui/tests/view_ui.rs b/crates/ui-egui/tests/view_ui.rs
index 2b73bd05a..1339ad6c2 100644
--- a/crates/ui-egui/tests/view_ui.rs
+++ b/crates/ui-egui/tests/view_ui.rs
@@ -281,7 +281,8 @@ fn snap_in_program_monitor_and_graphics_menu() {
let pic = d.rect("program.picture");
let k = pic[2] / 1920.0;
let lr = d.rect(&format!("program.layer.{clip}.0"));
- let (x, y) = (lr[0] + lr[2] / 2.0, lr[1] + lr[3] / 2.0);
+ // off the centre: there the anchor point is picked, and dragging it moves it alone
+ let (x, y) = (lr[0] + lr[2] / 4.0, lr[1] + lr[3] / 2.0);
d.ok("ui.drag", json!({"from": {"x": x, "y": y}, "to": {"x": x + frame_dx * k + extra, "y": y}, "steps": 8}));
d.frames(2);
};
diff --git a/docs/graphics.md b/docs/graphics.md
index 5b988bcc4..e5ebefe84 100644
--- a/docs/graphics.md
+++ b/docs/graphics.md
@@ -23,13 +23,50 @@ kerning and ligatures, bidi, line breaking, all drawn as vectors in linear light
| Group | Properties (parameter ids) |
|---|---|
-| Text | `text` (Source Text), `font`, `font_style`, `size` (px), `align` (Left/Center/Right/Justify), `tracking` (1/1000 em), `kerning`, `ligatures`, `leading` (px added to the natural line height), `baseline_shift`, `faux_bold`, `faux_italic`, `caps` (Normal/All Caps/Small Caps), `underline`, `box_width` (0 = point text, else area text wrapped at that width) |
+| Text | `text` (Source Text), `font`, `font_style`, `size` (px), `align` (Left/Center/Right/Justify), `tracking` (1/1000 em), `kerning`, `ligatures`, `leading` (px added to the natural line height), `baseline_shift`, `faux_bold`, `faux_italic`, `caps` (Normal/All Caps/Small Caps), `underline`, `box_width` (0 = point text, else paragraph text wrapped at that width), `box_height` (paragraph text: lines that do not fit are not shown; 0 = as tall as the text) |
| Shape | `shape` (Rectangle/Ellipse/Polygon/Path), `size` [w, h], `sides`, `corner_radius`, `points` (path vertices relative to the layer origin) |
| Appearance | `fill`, `fill_color`; `stroke`, `stroke_color`, `stroke_width`, `stroke_type` (Outer/Center/Inner) and the same for `stroke2`; `background`, `background_color`, `background_opacity`, `background_size` (padding), `background_radius`; `shadow`, `shadow_color`, `shadow_opacity`, `shadow_angle` (135° = down-right), `shadow_distance`, `shadow_size`, `shadow_blur` |
| Transform | `position` (graphic canvas px), `anchor` (layer px), `scale`, `scale_width`, `uniform_scale`, `rotation`, `opacity` |
Point text's origin is its alignment point on the first baseline (the click point of the Type
-tool); a shape's origin is its centre. Colours are `#rrggbb` (sRGB).
+tool); paragraph text's origin is the top-left corner of its box; a shape's origin is its centre.
+Colours are `#rrggbb` (sRGB).
+
+### Point text and paragraph text
+
+A text layer is one of two types, as in Premiere Pro (behaviour observed in Premiere Pro 26):
+
+| | Point text | Paragraph text |
+|---|---|---|
+| Made with the Type tool by | a click | a drag: the dragged rectangle is the box |
+| Lines | only where Return was typed | wrap at the box's width; lines below the box's bottom are not shown, and the bottom-right handle turns into a red plus |
+| Selection box | fits the text | the box, whatever it holds |
+| New layer's anchor point | the origin (left end of the first baseline) | the box's top-left corner |
+| Dragging a handle | scales the layer about its anchor point: every handle scales both axes alike (Uniform Scale stays on), the font size is untouched | moves that side or corner of the box to the pointer, the opposite side stays; the text re-wraps at the same size and Scale is untouched |
+
+- **Point-text scale.** Only the pointer's travel along one side of the box counts: along its
+ width for the two side handles, along its height for the corners and the top and bottom handles.
+ Travel `d` away from the anchor scales by `1 + d / r`, where `r` is the handle's distance from
+ the anchor along that side, plus 60 points when the handle is nearer than 60 points (so a handle
+ on the anchor does not scale without bound). A handle exactly on the anchor grows the text when
+ dragged into the box.
+- **Paragraph box.** A side dragged past its opposite stops at half the font size. When the top or
+ left side moves, the layer's origin moves with the corner, so the anchor point is renumbered to
+ stay on the same spot of the picture and Position does not change.
+- **Anchor point.** Drag it with the Selection tool: the anchor moves, the layer stays (Position
+ and Anchor Point change together). It is picked before anything under it: a shape dragged by
+ its exact centre moves its anchor, not the shape, and the top-left handle of a new paragraph
+ box is reached only after moving the anchor.
+- **Switching type.** Properties ▸ Text ▸ wrench ▸ **Text Properties** ▸ Text Layer Type
+ (`graphics.setTextType`). To point text: the wrapped lines become real lines (also those the
+ box hid). To paragraph text: the box is fitted to the text. Either way the text stays where it
+ is and Position is untouched; only Anchor Point is renumbered. Vertical text is always point
+ text.
+
+Known differences from Premiere: the first line of paragraph text sits one font ascent below the
+box's top (Premiere places it higher, about one cap height below); Premiere's smallest box and
+the box it fits when switching to paragraph text were not measured exactly; the 60 points were
+measured with the Program monitor at Fit only; Text Properties has no Hindi Digits option.
## Rendering
@@ -45,11 +82,12 @@ Timecode and Clip Name effects also draw with the text engine.
| Command | Menu / shortcut | Params |
|---|---|---|
-| `graphics.newText` | Graphics and Titles ▸ New Layer ▸ Text (⌘T) | `text`, `position`, `clip` (add to this graphic), `vertical`, `size`, `font`, `fontStyle`, `seconds` (5), `track`, `time` |
+| `graphics.newText` | Graphics and Titles ▸ New Layer ▸ Text (⌘T) | `text`, `position`, `box` (`[w, h]`: paragraph text in a box, `position` is its top-left corner), `clip` (add to this graphic), `vertical`, `size`, `font`, `fontStyle`, `seconds` (5), `track`, `time` |
| `graphics.newVerticalText` | New Layer ▸ Vertical Text | as `graphics.newText`; characters stack top to bottom, paragraphs are columns right to left |
| `graphics.newRectangle`, `graphics.newEllipse`, `graphics.newPolygon` | New Layer ▸ Rectangle (⌥⌘R), Ellipse (⌥⌘E), Polygon | `position`, `size`, `clip`; polygon `sides` (6) |
| `graphics.newFromFile` | New Layer ▸ From file… | `path` — imports the image or video and places it above the clips at the playhead (a separate clip; graphics have no media layers yet) |
| `graphics.newShape` | (agents) | `shape` (rectangle/ellipse/polygon/path), `position`, `size`, `points`, `clip` |
+| `graphics.setTextType` | Text Properties ▸ Text Layer Type | `clip`, `layer`, `type` (`point` / `paragraph`); the text stays where it is |
| `graphics.setText` | typing on the monitor | `clip`, `layer`, `text`, `merge` (coalesce one typing session into one undo step) |
| `graphics.set` | Properties panel | `clip`, `layer`, `props` {parameter id or camelCase alias: value; choices by index or name}, `time` |
| `graphics.selectLayer` | layer list / monitor click | `clip`, `layers` |
@@ -65,7 +103,7 @@ Timecode and Clip Name effects also draw with the text engine.
| `graphics.selectNextLayer`, `graphics.selectPreviousLayer` | Select ▸ Select Next / Previous Layer (⌥⌘], ⌥⌘[) | cycles the selected layer |
| `graphics.resetAllParameters` | Reset All Parameters | `layers` (default: the selected layers, else all) — appearance, text formatting and transform back to defaults; text, shape and geometry kept |
| `graphics.resetDuration` | Reset Duration | `seconds` (5), limited by the next clip on the track |
-| `graphics.list` | (query) | `clip` — layers with names, kinds, text, position and on-canvas quads |
+| `graphics.list` | (query) | `clip` — layers with names, kinds, text, `textType` (point / paragraph), `box`, `overflow` (the box hides text), position, anchor, scale and on-canvas quads |
| `fonts.list` | (query) | `system` (scan system font folders, default true) — families and styles |
Without `clip`, commands use the selected graphic clip, else the topmost graphic clip under the
@@ -77,8 +115,8 @@ duration (a track is added if needed).
| Tool | On the Program monitor |
|---|---|
-| Type (T) | Click empty picture: new text layer with a caret. Click a text layer: caret there. Type; ←/→ (⌥ word, ⌘ line), ↑/↓, Home/End, Shift to select, ⌘A, ⌘C/⌘X/⌘V, Return = new line, Backspace/Delete, Esc = stop editing. Drag inside the edited text to select. |
-| Selection (V) | Click a layer to select it (box with handles and anchor point); drag to move; drag a corner handle to scale; double-click a text layer to edit it. |
+| Type (T) | Click empty picture: new point-text layer with a caret. Drag on empty picture: new paragraph-text layer with that box. Click a text layer: caret there. The box of the text being typed into is red. Type; ←/→ (⌥ word, ⌘ line), ↑/↓, Home/End, Shift to select, ⌘A, ⌘C/⌘X/⌘V, Return = new line, Backspace/Delete, Esc = stop editing. Drag inside the edited text to select. |
+| Selection (V) | Click a layer to select it (box with handles and anchor point); drag to move; drag the anchor point to move it alone; drag a handle to scale point text about its anchor, resize a paragraph-text box, or stretch a shape away from its opposite side (see *Point text and paragraph text*); double-click a text layer to edit it. |
| Rectangle / Ellipse | Drag to draw a shape layer. |
| Pen (P) | Click to place points; click the first point (or Return) to close the path; Esc cancels. |
@@ -86,7 +124,9 @@ Moving a layer snaps its edges or centre to the frame edges, the frame centre an
(View ▸ Snap in Program Monitor, on by default; hold ⌘/Ctrl to move freely). See
[monitors.md](monitors.md) for rulers and guides.
-Automation ids: `program.layer.<clip>.<layer>`, `program.layer.<clip>.<layer>.handle.<n>`,
+Automation ids: `program.layer.<clip>.<layer>`, `program.layer.<clip>.<layer>.handle.<n>`
+(0–3 the corners from the top-left clockwise, 4–7 the top, right, bottom and left sides),
+`program.layer.<clip>.<layer>.anchor`,
`program.textEdit` (while editing).
## Properties / Essential Graphics panels
@@ -95,11 +135,14 @@ With a graphic clip selected, the Properties panel (and Essential Graphics) show
(front first; new text / rectangle / ellipse, bring forward / send backward, delete, visibility),
**Align and Transform** (six align buttons, two distribute buttons, position, anchor, scale,
rotation, opacity), **Text** (Source Text field, font family and style, size, paragraph alignment,
-tracking, leading, baseline shift, box width, faux bold / faux italic / all caps / small caps /
-underline, kerning and ligatures), **Shape**, and **Appearance** (fill, two strokes, background,
+tracking, leading, baseline shift, box width and height, faux bold / faux italic / all caps /
+small caps / underline, kerning and ligatures; the wrench in the section's header opens **Text
+Properties**: Text Layer Type and Ligatures), **Shape**, and **Appearance** (fill, two strokes, background,
shadow). Automation ids: `graphics.layers.<n>`, `graphics.prop.<parameter id>`,
`graphics.align.<how>`, `graphics.distribute.<axis>`, `graphics.sourceText`, `graphics.NewTextLayer`,
-`graphics.NewRectangle`, `graphics.NewEllipse`, `graphics.deleteLayer`, `graphics.section.<name>`.
+`graphics.NewRectangle`, `graphics.NewEllipse`, `graphics.deleteLayer`, `graphics.section.<name>`,
+`graphics.textProperties` (the wrench) and in its dialog `graphics.textProperties.type`,
+`.type.point`, `.type.paragraph`, `.ligatures`, `.ok`, `.cancel`.
## Per-character styles