Skip to content

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

feat(text): some of a title's words in a look of their own - colour, bold, italic, underline, strikethrough, size (#529)

Jareer64b25e902641
diff --git a/docs/MCP.md b/docs/MCP.md
index 6c0ffd5a..04c14292 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -59,7 +59,7 @@ Tools are named for what they do, and their argument schemas are generated from
| Media | `media_probe`, `media_import` |
| Editing | `clip_add`, `clips_add_sequence`, `clip_trim`, `clips_split`, `clips_move`, `clips_remove`, `clip_update`, `clip_transform`, `clip_speed`, `clip_frame`, `track_add` |
| Picture | `clip_mask`, `clip_stabilize`, `timeline_background` |
-| Titles and captions | `title_add`, `captions_add` |
+| Titles and captions | `title_add`, `title_style_words` (some words in another colour, weight, size...), `title_clear_word_styles`, `captions_add` |
| Keyframes and effects | `keyframe_set`, `keyframe_clear`, `effects_list`, `effect_layer_add`, `effect_key_set` |
| Anything else | `edit_apply` (any edit command, or a batch of them as one undo step), `edit_undo`, `edit_redo` |
| Templates | `template_list`, `template_instantiate` |
diff --git a/src/crates/concat-host/src/cards.rs b/src/crates/concat-host/src/cards.rs
index 452fe541..f816578e 100644
--- a/src/crates/concat-host/src/cards.rs
+++ b/src/crates/concat-host/src/cards.rs
@@ -354,6 +354,7 @@ impl Painter {
tracking: 0.0,
max_width: 0.0,
max_height: 0.0,
+ runs: Vec::new(),
};
let fonts = concat_text::Fonts::new();
let rendered = concat_text::render_frame(&fonts, &style, width, height)
diff --git a/src/crates/concat-host/src/titles.rs b/src/crates/concat-host/src/titles.rs
index 9d9fa554..56d6efb0 100644
--- a/src/crates/concat-host/src/titles.rs
+++ b/src/crates/concat-host/src/titles.rs
@@ -29,7 +29,7 @@ use concat_export::{ClipKind, ExportClip};
use concat_project::model::{
ClipKind as ModelClipKind, KeyProperty, Project, ShapeKind, ShapeStyle, TextAlign, TextStyle,
};
-use concat_text::{Align, Figure, Fonts, TitleStyle, WordRect};
+use concat_text::{Align, Figure, Fonts, TitleRun, TitleStyle, WordRect};
use crate::dirs::AppDirs;
@@ -493,8 +493,9 @@ fn key_of(project: &Project, painting: Painting<'_>, width: u32, height: u32) ->
// Bumped when the painter's output changes for the same input, so stale
// files are not mistaken for current ones. 3: left- and right-aligned
// blocks moved to their anchors. 4: the sidecar gained each word's box,
- // for a per-word reveal effect to read back.
- bytes.extend_from_slice(&4u32.to_le_bytes());
+ // for a per-word reveal effect to read back. 5: a title's lines are as
+ // tall as their biggest word, and each look is painted on its own.
+ bytes.extend_from_slice(&5u32.to_le_bytes());
crate::media::fnv1a(&bytes)
}
@@ -569,8 +570,11 @@ fn reveal_of(words: &[WordRect], width: u32, height: u32) -> Arc<RevealMap> {
/// The document's style, field for field, in the painter's terms.
fn title_style(style: &TextStyle) -> TitleStyle {
+ // The words in their case, and the runs moved onto the characters
+ // their own became in it.
+ let (content, runs) = style.display();
TitleStyle {
- content: style.display_content(),
+ content,
font_family: style.font_family.clone(),
font_size: style.font_size,
font_weight: style.font_weight,
@@ -594,6 +598,20 @@ fn title_style(style: &TextStyle) -> TitleStyle {
max_width: style.max_width,
max_height: style.max_height,
tracking: style.tracking,
+ runs: runs
+ .into_iter()
+ .map(|run| TitleRun {
+ start: run.start,
+ end: run.end,
+ color: run.style.color,
+ font_weight: run.style.font_weight,
+ italic: run.style.italic,
+ underline: run.style.underline,
+ strikethrough: run.style.strikethrough,
+ font_scale: run.style.font_scale,
+ stroke_color: run.style.stroke_color,
+ })
+ .collect(),
}
}
@@ -728,6 +746,66 @@ mod tests {
let _ = std::fs::remove_dir_all(dirs.data.parent().expect("a scratch root"));
}
+ /// Some words styled are a different picture, painted again, with the
+ /// runs on the characters the painter is given - in capitals, "ß" is
+ /// two of them, and the run after it moves along by one.
+ #[test]
+ fn styled_words_are_a_new_picture_and_follow_the_case() {
+ let dirs = scratch("styled_words");
+ let mut editor = Editor::new();
+ let id = editor
+ .apply(Command::AddTextClip {
+ above: false,
+ track_id: None,
+ start: 0.0,
+ style: Some(TextStyle {
+ content: "straße rot".into(),
+ ..TextStyle::default()
+ }),
+ duration: Some(3.0),
+ offset_y: None,
+ })
+ .expect("a title is added")
+ .created_id
+ .expect("with an id");
+ let titles = Titles::new(&dirs);
+ let plain = titles.clips(editor.project(), 640, 360)[0]
+ .clip
+ .path
+ .clone();
+ editor
+ .apply(Command::StyleTextRange {
+ clip_id: id.clone(),
+ start: 7,
+ end: 10,
+ patch: concat_project::model::RunStyle {
+ color: Some("#ff0000".into()),
+ ..Default::default()
+ },
+ })
+ .expect("styles");
+ let styled = titles.clips(editor.project(), 640, 360)[0]
+ .clip
+ .path
+ .clone();
+ assert_ne!(styled, plain, "a different picture");
+
+ let mut text = editor
+ .project()
+ .active()
+ .clip(&id)
+ .unwrap()
+ .text
+ .clone()
+ .unwrap();
+ text.text_case = concat_project::model::TextCase::Upper;
+ let painted = title_style(&text);
+ assert_eq!(painted.content, "STRASSE ROT");
+ assert_eq!((painted.runs[0].start, painted.runs[0].end), (8, 11));
+ assert_eq!(painted.runs[0].color.as_deref(), Some("#ff0000"));
+ let _ = std::fs::remove_dir_all(dirs.data.parent().expect("a scratch root"));
+ }
+
#[test]
fn a_title_rejoins_as_a_still() {
let dirs = scratch("a_title_rejo");
diff --git a/src/crates/concat-mcp/src/summary.rs b/src/crates/concat-mcp/src/summary.rs
index 66fc56d1..f83b7b20 100644
--- a/src/crates/concat-mcp/src/summary.rs
+++ b/src/crates/concat-mcp/src/summary.rs
@@ -116,6 +116,14 @@ fn clip_of(clip: &Value) -> Value {
if let Some(text) = clip.pointer("/text/content") {
out.insert("text".into(), text.clone());
}
+ // Words in a look of their own, as the document has them: characters
+ // into the text, and only the fields each overrides.
+ if let Some(runs) = clip
+ .pointer("/text/runs")
+ .filter(|runs| runs.as_array().is_some_and(|runs| !runs.is_empty()))
+ {
+ out.insert("textRuns".into(), runs.clone());
+ }
if let Some(shape) = clip.pointer("/shape/kind") {
out.insert("shape".into(), shape.clone());
}
diff --git a/src/crates/concat-mcp/src/tools.rs b/src/crates/concat-mcp/src/tools.rs
index 972fdad2..2f462139 100644
--- a/src/crates/concat-mcp/src/tools.rs
+++ b/src/crates/concat-mcp/src/tools.rs
@@ -360,9 +360,21 @@ pub fn catalogue() -> Vec<Tool> {
command(
"title_add",
"Add a title",
- "Places a title (text over the picture) at `start` seconds for `duration` seconds (4 s when absent). `style` sets the words and look - `content`, `fontFamily`, `fontSize` (fraction of frame height, 0.09 by default), `fontWeight` (100-900), `color` (\"#rrggbb\"), `align`, `background`, `strokeWidth`... - and needs only the fields that differ from the default. `offsetY` places it vertically as a fraction of frame height from the centre (positive is down). With no `trackId` and `above: true` it lands on a lane above the picture. The new clip's id is `createdId`.",
+ "Places a title (text over the picture) at `start` seconds for `duration` seconds (4 s when absent). `style` sets the words and look - `content`, `fontFamily`, `fontSize` (fraction of frame height, 0.09 by default), `fontWeight` (100-900), `color` (\"#rrggbb\"), `align`, `background`, `strokeWidth`... - and needs only the fields that differ from the default. `offsetY` places it vertically as a fraction of frame height from the centre (positive is down). With no `trackId` and `above: true` it lands on a lane above the picture. The new clip's id is `createdId`. To give some of its words a look of their own afterwards, use `title_style_words`.",
"addTextClip",
),
+ command(
+ "title_style_words",
+ "Style some of a title's words",
+ "Gives some of a title's words a look of their own, as dragging over them in the window's Text tab does: the characters `start` to `end` (counted in characters of the title's text, not bytes; `end` is one past the last) wear each field of `patch` - `color` (\"#rrggbb\"), `fontWeight` (100-900), `italic`, `underline`, `strikethrough`, `fontScale` (a multiple of the title's size, 0.1-10) and `strokeColor` - over the title's own look. Fields left out stay as they were on those characters; the rest of the title is untouched and keeps following its style. Typed words carry these looks along. `timeline_read` lists them as the clip's `textRuns`.",
+ "styleTextRange",
+ ),
+ command(
+ "title_clear_word_styles",
+ "Clear words' own looks",
+ "Gives a title's words back to its own look: every look of their own between the characters `start` and `end`, or on all of its words when they are left out.",
+ "clearTextStyles",
+ ),
Tool {
name: "captions_add",
title: "Add captions",
@@ -779,7 +791,12 @@ fn captions(mut arguments: Value) -> Result<Request, ApiError> {
"fontSize": 0.04,
"fontWeight": 600,
}),
- Some(Value::Object(style)) => Value::Object(style),
+ // Some words' looks are about one title's words, not every
+ // caption's, so a style's runs do not carry over.
+ Some(Value::Object(mut style)) => {
+ style.remove("runs");
+ Value::Object(style)
+ }
Some(_) => return Err(invalid("`style` is an object")),
};
if let Some(unknown) = fields.keys().next() {
@@ -1011,6 +1028,14 @@ mod tests {
"title_add",
json!({ "path": "/tmp/Cut", "start": 1.0, "duration": 3.0, "above": true, "style": { "content": "Hello", "fontSize": 0.08, "align": "left" }, "offsetY": -0.3 }),
),
+ (
+ "title_style_words",
+ json!({ "path": "/tmp/Cut", "clipId": "c1", "start": 0, "end": 4, "patch": { "color": "#ffd400", "fontWeight": 800 } }),
+ ),
+ (
+ "title_clear_word_styles",
+ json!({ "path": "/tmp/Cut", "clipId": "c1" }),
+ ),
(
"captions_add",
json!({ "path": "/tmp/Cut", "captions": [{ "start": 0.0, "end": 1.5, "text": "Hi" }], "style": { "color": "#ffff00" }, "offsetY": 0.3 }),
diff --git a/src/crates/concat-mcp/tests/e2e.rs b/src/crates/concat-mcp/tests/e2e.rs
index 411319ef..95a707a3 100644
--- a/src/crates/concat-mcp/tests/e2e.rs
+++ b/src/crates/concat-mcp/tests/e2e.rs
@@ -191,6 +191,31 @@ fn an_agent_edits_previews_and_exports_a_project_headless() {
let title = titled["structuredContent"]["createdId"].clone();
assert!(title.is_string(), "{titled}");
+ // "agent" in yellow, and the summary says which words wear what.
+ let styled = agent.tool(
+ "title_style_words",
+ json!({
+ "path": path,
+ "clipId": title,
+ "start": 7,
+ "end": 12,
+ "patch": { "color": "#ffd400" },
+ }),
+ );
+ let clips = styled["structuredContent"]["timeline"]["clips"]
+ .as_array()
+ .expect("clips");
+ let runs = clips
+ .iter()
+ .find(|clip| clip["id"] == title)
+ .map(|clip| clip["textRuns"].clone())
+ .expect("the title");
+ assert_eq!(
+ runs,
+ json!([{ "start": 7, "end": 12, "color": "#ffd400" }]),
+ "{styled}"
+ );
+
let captioned = agent.tool(
"captions_add",
json!({
diff --git a/src/crates/concat-project/src/commands/mod.rs b/src/crates/concat-project/src/commands/mod.rs
index 0acd9787..1eae24ca 100644
--- a/src/crates/concat-project/src/commands/mod.rs
+++ b/src/crates/concat-project/src/commands/mod.rs
@@ -15,8 +15,8 @@ use serde::{Deserialize, Serialize};
use crate::model::{
AppliedFilter, AudioTrack, Background, Clip, ClipKind, ClipMask, ColorRange, ColorSpace, Crop,
CustomFont, Cutout, CutoutMode, Enhanced, Framing, KeyEase, KeyProperty, MediaItem, MediaKind,
- MediaOrigin, Project, ShapeStyle, SpeedPoint, Stabilize, Stroke, TextStyle, Timeline, Track,
- Transition, VideoSettings,
+ MediaOrigin, Project, RunStyle, ShapeStyle, SpeedPoint, Stabilize, Stroke, TextStyle, Timeline,
+ Track, Transition, VideoSettings,
};
mod audio;
@@ -688,6 +688,38 @@ pub enum Command {
/// Which properties change, and to what.
patch: ClipPatch,
},
+ /// Gives some of a title's words a look of their own: each field of
+ /// `patch` is laid over the characters `start..end` of its words, and
+ /// each it leaves out stays as it was there - the title's own look, or
+ /// what an earlier run gave them. `start` and `end` count characters
+ /// (Unicode scalar values), not bytes, and are clamped to the words; an
+ /// empty range, an empty patch, a clip that is not a title or an
+ /// unknown clip is a no-op. The title's own style is untouched, so the
+ /// words left out keep following it. See `TextStyle::runs`.
+ StyleTextRange {
+ /// The title.
+ clip_id: String,
+ /// The first character to style.
+ start: usize,
+ /// One past the last.
+ end: usize,
+ /// The overrides to lay over them.
+ patch: RunStyle,
+ },
+ /// Gives a title's words back to its own look: every run is cut out of
+ /// the characters `start..end`, or out of all of them when either end
+ /// is absent. Counted and clamped as in `styleTextRange`; a clip that
+ /// is not a title or an unknown clip is a no-op.
+ ClearTextStyles {
+ /// The title.
+ clip_id: String,
+ /// The first character, absent for the start of the words.
+ #[serde(default)]
+ start: Option<usize>,
+ /// One past the last, absent for the end of the words.
+ #[serde(default)]
+ end: Option<usize>,
+ },
/// Changes playback rate while holding the amount of source covered
/// constant - the clip's timeline duration is what stretches, which is
/// what makes this a speed change rather than a trim.
@@ -1245,6 +1277,8 @@ pub fn apply(
| Command::ConsolidateClips { .. }
| Command::RemoveClips { .. }) => clips::apply(project, mint, command),
command @ (Command::UpdateClip { .. }
+ | Command::StyleTextRange { .. }
+ | Command::ClearTextStyles { .. }
| Command::MatchClip { .. }
| Command::SetClipSpeed { .. }
| Command::SetClipCutout { .. }
diff --git a/src/crates/concat-project/src/commands/properties.rs b/src/crates/concat-project/src/commands/properties.rs
index 65b66b29..ae9ca902 100644
--- a/src/crates/concat-project/src/commands/properties.rs
+++ b/src/crates/concat-project/src/commands/properties.rs
@@ -93,6 +93,54 @@ pub(super) fn apply(
})
}
+ Command::StyleTextRange {
+ clip_id,
+ start,
+ end,
+ patch,
+ } => {
+ let Some(clip) = project.active_mut().clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ if clip.kind != ClipKind::Text {
+ return Ok(Outcome::default());
+ }
+ let Some(text) = clip.text.as_mut() else {
+ return Ok(Outcome::default());
+ };
+ let before = text.runs.clone();
+ text.style_range(start, end, &patch);
+ Ok(Outcome {
+ created_id: None,
+ applied: text.runs != before,
+ })
+ }
+
+ Command::ClearTextStyles {
+ clip_id,
+ start,
+ end,
+ } => {
+ let Some(clip) = project.active_mut().clip_mut(&clip_id) else {
+ return Ok(Outcome::default());
+ };
+ if clip.kind != ClipKind::Text {
+ return Ok(Outcome::default());
+ }
+ let Some(text) = clip.text.as_mut() else {
+ return Ok(Outcome::default());
+ };
+ let before = text.runs.clone();
+ match (start, end) {
+ (Some(start), Some(end)) => text.clear_range(start, end),
+ _ => text.runs.clear(),
+ }
+ Ok(Outcome {
+ created_id: None,
+ applied: text.runs != before,
+ })
+ }
+
Command::SetClipSpeed {
clip_id,
speed,
diff --git a/src/crates/concat-project/src/lib.rs b/src/crates/concat-project/src/lib.rs
index 7645482c..379dd01e 100644
--- a/src/crates/concat-project/src/lib.rs
+++ b/src/crates/concat-project/src/lib.rs
@@ -26,6 +26,7 @@ pub mod doc;
pub mod editor;
pub mod model;
pub mod placement;
+pub mod runs;
pub mod speed;
pub mod srt;
@@ -68,6 +69,101 @@ mod tests {
assert_eq!(style.display_content(), original);
}
+ /// Words styled over a range, and cleared, as undoable steps from the
+ /// wire; the title's own look is left alone, and the runs survive a
+ /// save and a reopen.
+ #[test]
+ fn a_range_of_a_titles_words_is_styled_undone_and_saved() {
+ use crate::commands::Command;
+ use crate::editor::Editor;
+ use crate::model::{RunStyle, TextStyle};
+ let mut editor = Editor::new();
+ let id = editor
+ .apply(Command::AddTextClip {
+ track_id: None,
+ above: true,
+ start: 0.0,
+ style: Some(TextStyle {
+ content: "make this red".into(),
+ ..TextStyle::default()
+ }),
+ duration: Some(3.0),
+ offset_y: None,
+ })
+ .unwrap()
+ .created_id
+ .unwrap();
+ let command: Command = serde_json::from_value(json!({
+ "op": "styleTextRange", "clipId": id, "start": 10, "end": 13,
+ "patch": { "color": "#ff0000", "fontWeight": 800 }
+ }))
+ .expect("the wire shape parses");
+ assert!(editor.apply(command).unwrap().applied);
+ let text = |editor: &Editor| {
+ editor
+ .project()
+ .active()
+ .clip(&id)
+ .unwrap()
+ .text
+ .clone()
+ .unwrap()
+ };
+ let styled = text(&editor);
+ assert_eq!(styled.color, "#ffffff", "the title's own look is untouched");
+ assert_eq!(styled.runs.len(), 1);
+ assert_eq!((styled.runs[0].start, styled.runs[0].end), (10, 13));
+ assert_eq!(styled.runs[0].style.font_weight, Some(800.0));
+
+ let document = editor.to_document(&settings());
+ let restored = Editor::from_document(&document).expect("loads");
+ assert_eq!(restored.project(), editor.project());
+
+ assert!(editor.undo());
+ assert!(text(&editor).runs.is_empty());
+ assert!(editor.redo());
+ assert!(
+ editor
+ .apply(Command::ClearTextStyles {
+ clip_id: id.clone(),
+ start: Some(10),
+ end: Some(11),
+ })
+ .unwrap()
+ .applied
+ );
+ assert_eq!(
+ (text(&editor).runs[0].start, text(&editor).runs[0].end),
+ (11, 13)
+ );
+ assert!(
+ editor
+ .apply(Command::ClearTextStyles {
+ clip_id: id.clone(),
+ start: None,
+ end: None,
+ })
+ .unwrap()
+ .applied
+ );
+ assert!(text(&editor).runs.is_empty());
+ // Nothing to do is nothing done, and not a step to undo.
+ assert!(
+ !editor
+ .apply(Command::StyleTextRange {
+ clip_id: id,
+ start: 4,
+ end: 4,
+ patch: RunStyle {
+ italic: Some(true),
+ ..RunStyle::default()
+ },
+ })
+ .unwrap()
+ .applied
+ );
+ }
+
#[test]
fn old_styles_keep_their_original_appearance() {
use crate::model::{TextCase, TextStyle};
diff --git a/src/crates/concat-project/src/model.rs b/src/crates/concat-project/src/model.rs
index dafd3e1e..0c631748 100644
--- a/src/crates/concat-project/src/model.rs
+++ b/src/crates/concat-project/src/model.rs
@@ -1482,8 +1482,89 @@ pub enum TextCase {
Original,
}
+/// What a stretch of a title's words wears over the title's own look: each
+/// field is an override, and one left out is the title's. Every word of a
+/// title is the title's style until a run says otherwise, so a title with
+/// no runs is exactly the title it always was.
+#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
+#[derive(Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct RunStyle {
+ /// Fill colour as `#rrggbb`, over the title's `color`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub color: Option<String>,
+ /// CSS-scale weight, 100..=900, over the title's `fontWeight`; bold is
+ /// 700, regular 400.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub font_weight: Option<f64>,
+ /// Italic or upright, over the title's `italic`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub italic: Option<bool>,
+ /// Underlined or not, over the title's `underline`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub underline: Option<bool>,
+ /// Struck through or not, over the title's `strikethrough`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub strikethrough: Option<bool>,
+ /// Size as a multiple of the title's `fontSize`, 0.1..=10: 1.5 is half
+ /// as big again. Relative, not a size of its own, so a word made bigger
+ /// stays bigger by as much when the whole title is resized.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub font_scale: Option<f64>,
+ /// Outline colour, over the title's `strokeColor`; shows where the
+ /// title has an outline at all.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub stroke_color: Option<String>,
+}
+
+impl RunStyle {
+ /// No override at all: the title's own look.
+ pub fn is_empty(&self) -> bool {
+ *self == RunStyle::default()
+ }
+
+ /// `over` laid on top of this one: what it says wins, what it leaves
+ /// out stays as this one has it.
+ pub fn and(&self, over: &RunStyle) -> RunStyle {
+ RunStyle {
+ color: over.color.clone().or_else(|| self.color.clone()),
+ font_weight: over.font_weight.or(self.font_weight),
+ italic: over.italic.or(self.italic),
+ underline: over.underline.or(self.underline),
+ strikethrough: over.strikethrough.or(self.strikethrough),
+ font_scale: over.font_scale.or(self.font_scale),
+ stroke_color: over
+ .stroke_color
+ .clone()
+ .or_else(|| self.stroke_color.clone()),
+ }
+ }
+}
+
+/// A stretch of a title's words with a look of its own: some words in
+/// another colour, one in bold. `start` and `end` count characters - Unicode
+/// scalar values, what `str::chars` yields - into the title's `content`,
+/// not bytes, so a caller in any language counts them the way it counts a
+/// string; `end` is one past the last. Kept sorted, apart and non-empty;
+/// see `TextStyle::style_range` and `TextStyle::edit_content`.
+#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
+#[derive(Clone, PartialEq, Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TextRun {
+ /// The first character the look covers.
+ pub start: usize,
+ /// One past the last.
+ pub end: usize,
+ /// The look.
+ #[serde(flatten)]
+ pub style: RunStyle,
+}
+
/// A title's styling. Sizes are fractions of the frame, so a title composed
-/// against 1080p lands correctly exported at 4K. Missing fields use defaults.
+/// against 1080p lands correctly exported at 4K. A style arriving in a
+/// command needs only the fields it changes; the rest are the default's, so
+/// a caller can say `{ "content": "Hello" }` and get a title that looks like
+/// one the window would place.
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
@@ -1558,32 +1639,22 @@ pub struct TextStyle {
/// can be a band of a fixed size whatever is written on it.
/// https://github.com/jub0t/Concat/issues/119
pub max_height: f64,
+ /// Stretches of the words with a look of their own over the rest of
+ /// this style - a word in another colour, in bold, bigger. Empty for a
+ /// title in one look, and then not written at all, so a document
+ /// without runs is the document it always was and an older build reads
+ /// a document with them as the title in its own look.
+ #[serde(skip_serializing_if = "Vec::is_empty", deserialize_with = "wire::list")]
+ pub runs: Vec<TextRun>,
}
impl TextStyle {
- /// The displayed text, without rewriting the source or saved captions.
+ /// The words as they are painted: the content in the style's case,
+ /// leaving the content itself - what is typed, saved and exported as
+ /// subtitles - as it was written. See [`TextStyle::display`] for the
+ /// runs that go with it.
pub fn display_content(&self) -> String {
- match self.text_case {
- TextCase::Original => self.content.clone(),
- TextCase::Upper => self.content.to_uppercase(),
- TextCase::Lower => self.content.to_lowercase(),
- TextCase::Sentence => {
- let mut result = String::new();
- let mut initial = true;
- for ch in self.content.to_lowercase().chars() {
- if initial && ch.is_alphabetic() {
- result.extend(ch.to_uppercase());
- initial = false;
- } else {
- result.push(ch);
- }
- if matches!(ch, '.' | '!' | '?' | '。' | '!' | '?') {
- initial = true;
- }
- }
- result
- }
- }
+ self.display().0
}
/// Every number pulled into the range a title can be drawn at: a
@@ -1607,6 +1678,7 @@ impl TextStyle {
finite(self.background_padding_x, base.background_padding_x).max(0.0);
self.background_padding_y =
finite(self.background_padding_y, base.background_padding_y).max(0.0);
+ self.tidy_runs();
self
}
}
@@ -1636,6 +1708,7 @@ impl Default for TextStyle {
tracking: 0.0,
max_width: 0.0,
max_height: 0.0,
+ runs: Vec::new(),
}
}
}
diff --git a/src/crates/concat-project/src/runs.rs b/src/crates/concat-project/src/runs.rs
new file mode 100644
index 00000000..4e98ef37
--- /dev/null
+++ b/src/crates/concat-project/src/runs.rs
@@ -0,0 +1,660 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer Abdullah and Concat contributors
+
+//! A title's runs: stretches of its words with a look of their own.
+//!
+//! A title is one style ([`TextStyle`]) and, over it, a list of
+//! [`TextRun`]s - the third word in yellow, the name in bold. A run is a
+//! range of characters and the fields it overrides; everything it leaves
+//! out is the title's, so changing the title's colour still changes every
+//! word that was not given one of its own.
+//!
+//! The list is kept in one shape whatever wrote it - sorted, apart, none
+//! empty, none that overrides nothing, neighbours that look the same joined
+//! into one - by [`TextStyle::tidy_runs`], which the document reader and
+//! every command run. Two titles that look the same then compare the same,
+//! and the painter's cache does not paint one twice.
+//!
+//! The words change under the runs: a run is pinned to characters, and
+//! when characters are typed or deleted the runs move with the words they
+//! cover. The rules are the ones every word processor has, so nobody has
+//! to learn them: typing inside a coloured word carries on in its colour,
+//! typing just after it does too, typing just before it does not, and
+//! typing over a selection takes the look of the first character it
+//! replaces. See [`TextStyle::edit_runs`].
+
+use crate::model::{RunStyle, TextCase, TextRun, TextStyle};
+
+/// One change to a title's words, in characters: `removed` characters at
+/// `at` gave way to `inserted` new ones. A keystroke is one with nothing
+/// removed, a backspace one with nothing inserted, a paste over a
+/// selection both.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct TextEdit {
+ /// Where the change starts.
+ pub at: usize,
+ /// How many characters went.
+ pub removed: usize,
+ /// How many came in their place.
+ pub inserted: usize,
+}
+
+impl TextEdit {
+ /// The one change that turns `old` into `new`, or `None` when they are
+ /// the same: whatever the two share at the front and at the back is
+ /// untouched, and the middle is what changed.
+ ///
+ /// That alone cannot always tell where a character was typed - an "l"
+ /// typed after "hel" in "hello" reads the same as one typed after
+ /// "hell" - and the difference matters when a run ends between the
+ /// two. `caret`, where the text cursor is after the edit (in
+ /// characters of `new`), settles it: the change is slid back to end at
+ /// the caret whenever the words allow that reading.
+ pub fn between(old: &str, new: &str, caret: Option<usize>) -> Option<TextEdit> {
+ let old: Vec<char> = old.chars().collect();
+ let new: Vec<char> = new.chars().collect();
+ if old == new {
+ return None;
+ }
+ let front = old.iter().zip(&new).take_while(|(a, b)| a == b).count();
+ let room = old.len().min(new.len()) - front;
+ let back = old
+ .iter()
+ .rev()
+ .zip(new.iter().rev())
+ .take(room)
+ .take_while(|(a, b)| a == b)
+ .count();
+ let removed = old.len() - front - back;
+ let inserted = new.len() - front - back;
+ let mut edit = TextEdit {
+ at: front,
+ removed,
+ inserted,
+ };
+ if let Some(caret) = caret {
+ let end = front + inserted;
+ if caret < end && end - caret <= front {
+ let at = front - (end - caret);
+ // The front before `at` is shared by construction; what
+ // follows the change must still be the same in both.
+ if old[at + removed..] == new[at + inserted..] {
+ edit.at = at;
+ }
+ }
+ }
+ Some(edit)
+ }
+}
+
+impl RunStyle {
+ /// Every number in range - a weight on the CSS scale, a size the
+ /// painter can draw - and an override that cannot mean anything, a
+ /// number that is not one or a colour that is empty, dropped back to
+ /// the title's.
+ pub fn tidy(mut self) -> RunStyle {
+ self.font_weight = self
+ .font_weight
+ .filter(|weight| weight.is_finite())
+ .map(|weight| weight.clamp(100.0, 900.0));
+ self.font_scale = self
+ .font_scale
+ .filter(|scale| scale.is_finite())
+ .map(|scale| scale.clamp(0.1, 10.0));
+ self.color = self.color.filter(|colour| !colour.trim().is_empty());
+ self.stroke_color = self.stroke_color.filter(|colour| !colour.trim().is_empty());
+ self
+ }
+}
+
+impl TextStyle {
+ /// How many characters the words are: the end of the last place a run
+ /// can cover.
+ pub fn char_count(&self) -> usize {
+ self.content.chars().count()
+ }
+
+ /// Lays `patch` over the characters `start..end`: each field it has is
+ /// what those characters wear from now on, whatever runs said before,
+ /// and each it leaves out stays as it was there. The ends are clamped
+ /// to the words and may come in either order; an empty range or an
+ /// empty patch changes nothing.
+ pub fn style_range(&mut self, start: usize, end: usize, patch: &RunStyle) {
+ if patch.is_empty() {
+ return;
+ }
+ // Later runs win where they overlap earlier ones (see
+ // `tidy_runs`), so a patch laid over is a patch pushed on.
+ self.runs.push(TextRun {
+ start,
+ end,
+ style: patch.clone(),
+ });
+ self.tidy_runs();
+ }
+
+ /// Gives the characters `start..end` back to the title's own look:
+ /// every run is cut out of the range, and the parts of it outside the
+ /// range keep their look.
+ pub fn clear_range(&mut self, start: usize, end: usize) {
+ let (start, end) = (start.min(end), start.max(end));
+ let mut kept = Vec::with_capacity(self.runs.len() + 1);
+ for run in std::mem::take(&mut self.runs) {
+ if run.end <= start || run.start >= end {
+ kept.push(run);
+ continue;
+ }
+ if run.start < start {
+ kept.push(TextRun {
+ start: run.start,
+ end: start,
+ style: run.style.clone(),
+ });
+ }
+ if run.end > end {
+ kept.push(TextRun {
+ start: end,
+ end: run.end,
+ style: run.style,
+ });
+ }
+ }
+ self.runs = kept;
+ self.tidy_runs();
+ }
+
+ /// The overrides the character at `at` wears; nothing for one in the
+ /// title's own look, or past the end.
+ pub fn run_style_at(&self, at: usize) -> RunStyle {
+ self.runs
+ .iter()
+ .find(|run| run.start <= at && at < run.end)
+ .map(|run| run.style.clone())
+ .unwrap_or_default()
+ }
+
+ /// New words for the title, the runs carried along with the words they
+ /// were on. `caret` is where the text cursor stands after the edit, in
+ /// characters, when the edit came from typing; see [`TextEdit::between`].
+ pub fn set_content(&mut self, content: String, caret: Option<usize>) {
+ let edit = TextEdit::between(&self.content, &content, caret);
+ self.content = content;
+ if let Some(edit) = edit {
+ self.edit_runs(edit);
+ }
+ }
+
+ /// Moves the runs for one change of the words (the content has already
+ /// changed): a run after the change moves by however much the words
+ /// grew or shrank, one the change cuts into loses the characters that
+ /// went, and the new characters join the run whose look they take -
+ ///
+ /// - typed with nothing selected, the look of the character before the
+ /// caret, or at the very start the look of the first character;
+ /// - typed over a selection, the look of the first character replaced.
+ ///
+ /// A run whose every character was deleted is gone.
+ pub fn edit_runs(&mut self, edit: TextEdit) {
+ if self.runs.is_empty() {
+ return;
+ }
+ let TextEdit {
+ at,
+ removed,
+ inserted,
+ } = edit;
+ let owner = if removed > 0 {
+ self.runs
+ .iter()
+ .position(|run| run.start <= at && at < run.end)
+ } else if at > 0 {
+ self.runs
+ .iter()
+ .position(|run| run.start < at && at <= run.end)
+ } else {
+ self.runs
+ .iter()
+ .position(|run| run.start == 0 && run.end > 0)
+ };
+ let cut_end = at + removed;
+ // Where a character boundary lands once the removed ones are gone.
+ let map = |x: usize| {
+ if x <= at {
+ x
+ } else if x <= cut_end {
+ at
+ } else {
+ x - removed
+ }
+ };
+ for (index, run) in self.runs.iter_mut().enumerate() {
+ let (start, end) = (map(run.start), map(run.end));
+ if Some(index) == owner {
+ // It starts at or before the change and reaches it, so the
+ // new characters land inside it.
+ run.start = start;
+ run.end = end + inserted;
+ } else if start >= at && end > at {
+ run.start = start + inserted;
+ run.end = end + inserted;
+ } else {
+ // Wholly before the change, or emptied by it.
+ run.start = start;
+ run.end = end;
+ }
+ }
+ self.tidy_runs();
+ }
+
+ /// The runs in their one shape: clamped to the words, each override
+ /// tidied, the empty ones and those that override nothing dropped,
+ /// overlaps resolved - where two runs cover a character, the later
+ /// one's fields win - and neighbours that look the same joined. Cheap
+ /// for a title without runs, which is nearly every one.
+ pub fn tidy_runs(&mut self) {
+ if self.runs.is_empty() {
+ return;
+ }
+ let count = self.char_count();
+ let runs: Vec<TextRun> = std::mem::take(&mut self.runs)
+ .into_iter()
+ .filter_map(|run| {
+ let style = run.style.tidy();
+ let start = run.start.min(run.end).min(count);
+ let end = run.start.max(run.end).min(count);
+ (start < end && !style.is_empty()).then_some(TextRun { start, end, style })
+ })
+ .collect();
+ let mut cuts: Vec<usize> = runs.iter().flat_map(|run| [run.start, run.end]).collect();
+ cuts.sort_unstable();
+ cuts.dedup();
+ let mut out: Vec<TextRun> = Vec::with_capacity(runs.len());
+ for pair in cuts.windows(2) {
+ let (start, end) = (pair[0], pair[1]);
+ let style = runs
+ .iter()
+ .filter(|run| run.start <= start && end <= run.end)
+ .fold(RunStyle::default(), |held, run| held.and(&run.style));
+ if style.is_empty() {
+ continue;
+ }
+ match out.last_mut() {
+ Some(last) if last.end == start && last.style == style => last.end = end,
+ _ => out.push(TextRun { start, end, style }),
+ }
+ }
+ self.runs = out;
+ }
+
+ /// The words as they are painted, and the runs on them: the content in
+ /// the style's case, with each run moved to the characters its own
+ /// became. Casing can change how many characters there are - "ß" is
+ /// "SS" in capitals - so a run cannot simply keep its numbers.
+ ///
+ /// Sentence case lowercases the words and capitalises the first letter
+ /// of each sentence: the first one, and those after `.`, `!`, `?` and
+ /// their full-width forms. Punctuation alone, with no knowledge of a
+ /// language's abbreviations.
+ pub fn display(&self) -> (String, Vec<TextRun>) {
+ let content = &self.content;
+ let (text, widths): (String, Vec<usize>) = match self.text_case {
+ TextCase::Original => return (content.clone(), self.runs.clone()),
+ TextCase::Upper => (
+ content.to_uppercase(),
+ content
+ .chars()
+ .map(|ch| ch.to_uppercase().count())
+ .collect(),
+ ),
+ TextCase::Lower => (
+ content.to_lowercase(),
+ content
+ .chars()
+ .map(|ch| ch.to_lowercase().count())
+ .collect(),
+ ),
+ TextCase::Sentence => {
+ // The whole string is lowercased at once, as a final
+ // sigma needs, and walked with each source character's
+ // share of it.
+ let lowered: Vec<char> = content.to_lowercase().chars().collect();
+ let mut text = String::with_capacity(content.len());
+ let mut widths = Vec::with_capacity(lowered.len());
+ let mut initial = true;
+ let mut next = 0;
+ for ch in content.chars() {
+ let share = ch.to_lowercase().count();
+ let pieces = lowered.get(next..next + share).unwrap_or(&[]);
+ next += share;
+ let mut width = 0;
+ for &piece in pieces {
+ if initial && piece.is_alphabetic() {
+ for upper in piece.to_uppercase() {
+ text.push(upper);
+ width += 1;
+ }
+ initial = false;
+ } else {
+ text.push(piece);
+ width += 1;
+ }
+ if matches!(piece, '.' | '!' | '?' | '。' | '!' | '?') {
+ initial = true;
+ }
+ }
+ widths.push(width);
+ }
+ (text, widths)
+ }
+ };
+ if self.runs.is_empty() {
+ return (text, Vec::new());
+ }
+ let mut edges = Vec::with_capacity(widths.len() + 1);
+ edges.push(0);
+ for width in widths {
+ edges.push(edges.last().copied().unwrap_or(0) + width);
+ }
+ let last = edges.last().copied().unwrap_or(0);
+ let edge = |at: usize| edges.get(at).copied().unwrap_or(last);
+ let runs = self
+ .runs
+ .iter()
+ .map(|run| TextRun {
+ start: edge(run.start),
+ end: edge(run.end),
+ style: run.style.clone(),
+ })
+ .filter(|run| run.start < run.end)
+ .collect();
+ (text, runs)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn red() -> RunStyle {
+ RunStyle {
+ color: Some("#ff0000".into()),
+ ..RunStyle::default()
+ }
+ }
+
+ fn bold() -> RunStyle {
+ RunStyle {
+ font_weight: Some(700.0),
+ ..RunStyle::default()
+ }
+ }
+
+ fn title(content: &str) -> TextStyle {
+ TextStyle {
+ content: content.into(),
+ ..TextStyle::default()
+ }
+ }
+
+ fn spans(style: &TextStyle) -> Vec<(usize, usize)> {
+ style.runs.iter().map(|run| (run.start, run.end)).collect()
+ }
+
+ /// "hello red world" with "red" red.
+ fn with_red() -> TextStyle {
+ let mut style = title("hello red world");
+ style.style_range(6, 9, &red());
+ style
+ }
+
+ #[test]
+ fn a_range_is_styled_clamped_and_in_either_order() {
+ let mut style = title("hello");
+ style.style_range(10, 3, &red());
+ assert_eq!(spans(&style), [(3, 5)]);
+ style.style_range(2, 2, &bold());
+ assert_eq!(spans(&style), [(3, 5)], "an empty range changes nothing");
+ style.style_range(0, 2, &RunStyle::default());
+ assert_eq!(spans(&style), [(3, 5)], "an empty patch changes nothing");
+ }
+
+ #[test]
+ fn a_patch_over_part_of_a_run_splits_it_and_keeps_what_it_leaves_out() {
+ let mut style = title("one two three");
+ style.style_range(0, 13, &red());
+ style.style_range(4, 7, &bold());
+ assert_eq!(spans(&style), [(0, 4), (4, 7), (7, 13)]);
+ assert_eq!(style.runs[1].style, red().and(&bold()));
+ assert_eq!(style.run_style_at(5).color.as_deref(), Some("#ff0000"));
+ assert_eq!(style.run_style_at(5).font_weight, Some(700.0));
+ assert!(style.run_style_at(13).is_empty(), "past the end");
+ }
+
+ #[test]
+ fn neighbours_that_look_the_same_are_joined() {
+ let mut style = title("abcdef");
+ style.style_range(0, 2, &red());
+ style.style_range(2, 4, &red());
+ assert_eq!(spans(&style), [(0, 4)]);
+ style.style_range(5, 6, &red());
+ assert_eq!(spans(&style), [(0, 4), (5, 6)], "apart stays apart");
+ }
+
+ #[test]
+ fn clearing_cuts_the_range_out_of_every_run() {
+ let mut style = title("one two three");
+ style.style_range(0, 13, &red());
+ style.clear_range(4, 7);
+ assert_eq!(spans(&style), [(0, 4), (7, 13)]);
+ style.clear_range(0, 100);
+ assert!(style.runs.is_empty());
+ }
+
+ #[test]
+ fn overlapping_runs_from_a_file_resolve_with_the_later_winning() {
+ let mut style = title("abcdef");
+ style.runs = vec![
+ TextRun {
+ start: 0,
+ end: 4,
+ style: red(),
+ },
+ TextRun {
+ start: 2,
+ end: 6,
+ style: RunStyle {
+ color: Some("#00ff00".into()),
+ ..RunStyle::default()
+ },
+ },
+ TextRun {
+ start: 4,
+ end: 3,
+ style: RunStyle {
+ font_scale: Some(f64::NAN),
+ ..RunStyle::default()
+ },
+ },
+ ];
+ style.tidy_runs();
+ assert_eq!(spans(&style), [(0, 2), (2, 6)]);
+ assert_eq!(style.runs[1].style.color.as_deref(), Some("#00ff00"));
+ }
+
+ #[test]
+ fn numbers_are_held_in_range() {
+ let mut style = title("abc");
+ style.style_range(
+ 0,
+ 3,
+ &RunStyle {
+ font_weight: Some(5000.0),
+ font_scale: Some(0.0),
+ ..RunStyle::default()
+ },
+ );
+ assert_eq!(style.runs[0].style.font_weight, Some(900.0));
+ assert_eq!(style.runs[0].style.font_scale, Some(0.1));
+ }
+
+ #[test]
+ fn the_edit_between_two_texts_is_their_middle() {
+ assert_eq!(TextEdit::between("same", "same", None), None);
+ assert_eq!(
+ TextEdit::between("hello world", "hello big world", None),
+ Some(TextEdit {
+ at: 6,
+ removed: 0,
+ inserted: 4
+ })
+ );
+ assert_eq!(
+ TextEdit::between("hello red world", "hello blue world", None),
+ Some(TextEdit {
+ at: 6,
+ removed: 3,
+ inserted: 4
+ })
+ );
+ // Characters, not bytes.
+ assert_eq!(
+ TextEdit::between("çà va", "çàx va", None),
+ Some(TextEdit {
+ at: 2,
+ removed: 0,
+ inserted: 1
+ })
+ );
+ }
+
+ #[test]
+ fn the_caret_settles_where_a_repeated_letter_was_typed() {
+ // "hel|lo" + "l": the texts alone read it as typed after "hell".
+ assert_eq!(TextEdit::between("hello", "helllo", None).unwrap().at, 4);
+ assert_eq!(TextEdit::between("hello", "helllo", Some(4)).unwrap().at, 3);
+ // A caret the words cannot agree with is not followed.
+ assert_eq!(TextEdit::between("hello", "helxlo", Some(1)).unwrap().at, 3);
+ // A backspace on the first "l" of two.
+ assert_eq!(TextEdit::between("hello", "helo", Some(2)).unwrap().at, 2);
+ }
+
+ #[test]
+ fn typing_inside_a_coloured_word_keeps_its_colour() {
+ let mut style = with_red();
+ style.set_content("hello rexd world".into(), Some(9));
+ assert_eq!(spans(&style), [(6, 10)]);
+ }
+
+ #[test]
+ fn typing_just_after_a_coloured_word_carries_its_colour_on() {
+ let mut style = with_red();
+ style.set_content("hello reds world".into(), Some(10));
+ assert_eq!(spans(&style), [(6, 10)]);
+ }
+
+ #[test]
+ fn typing_just_before_a_coloured_word_is_in_the_plain_look() {
+ let mut style = with_red();
+ style.set_content("hello xred world".into(), Some(7));
+ assert_eq!(spans(&style), [(7, 10)]);
+ }
+
+ #[test]
+ fn typing_at_the_very_start_takes_the_first_characters_look() {
+ let mut style = title("red rest");
+ style.style_range(0, 3, &red());
+ style.set_content("Xred rest".into(), Some(1));
+ assert_eq!(spans(&style), [(0, 4)]);
+ }
+
+ #[test]
+ fn typing_over_a_selection_takes_the_look_of_its_first_character() {
+ let mut style = with_red();
+ style.set_content("hello blue world".into(), Some(10));
+ assert_eq!(spans(&style), [(6, 10)], "over the red word, red");
+ let mut style = with_red();
+ // "o r" replaced: its first character was plain.
+ style.set_content("hellXed world".into(), Some(5));
+ assert_eq!(spans(&style), [(5, 7)]);
+ }
+
+ #[test]
+ fn a_run_moves_with_the_words_before_it() {
+ let mut style = with_red();
+ style.set_content("oh hello red world".into(), Some(3));
+ assert_eq!(spans(&style), [(9, 12)]);
+ style.set_content("hello red world".into(), Some(0));
+ assert_eq!(spans(&style), [(6, 9)]);
+ }
+
+ #[test]
+ fn a_deletion_shortens_a_run_and_a_whole_one_goes() {
+ let mut style = with_red();
+ // "o r" deleted: the run keeps "ed".
+ style.set_content("helled world".into(), Some(4));
+ assert_eq!(spans(&style), [(4, 6)]);
+ let mut style = with_red();
+ style.set_content("hello world".into(), Some(6));
+ assert!(style.runs.is_empty());
+ let mut style = with_red();
+ style.set_content(String::new(), Some(0));
+ assert!(style.runs.is_empty());
+ }
+
+ #[test]
+ fn edits_after_a_run_leave_it_alone() {
+ let mut style = with_red();
+ style.set_content("hello red world!".into(), Some(16));
+ assert_eq!(spans(&style), [(6, 9)]);
+ }
+
+ #[test]
+ fn case_moves_runs_to_the_characters_they_become() {
+ let mut style = title("straße rot");
+ style.style_range(7, 10, &red());
+ style.text_case = TextCase::Upper;
+ let (text, runs) = style.display();
+ assert_eq!(text, "STRASSE ROT");
+ assert_eq!((runs[0].start, runs[0].end), (8, 11));
+ style.text_case = TextCase::Sentence;
+ let (text, runs) = style.display();
+ assert_eq!(text, "Straße rot");
+ assert_eq!((runs[0].start, runs[0].end), (7, 10));
+ style.text_case = TextCase::Original;
+ assert_eq!(style.display().1, style.runs);
+ }
+
+ #[test]
+ fn sentence_case_reads_the_same_as_it_always_did() {
+ let style = TextStyle {
+ content: "«È UNA PROVA!» POI, UN’ALTRA. già qui? sì! ΟΔΟΣ.".into(),
+ text_case: TextCase::Sentence,
+ ..TextStyle::default()
+ };
+ assert_eq!(
+ style.display_content(),
+ "«È una prova!» Poi, un’altra. Già qui? Sì! Οδος."
+ );
+ }
+
+ #[test]
+ fn runs_round_trip_and_a_title_without_them_writes_none() {
+ let plain = serde_json::to_value(title("hi")).unwrap();
+ assert!(plain.get("runs").is_none());
+ let style = with_red();
+ let saved = serde_json::to_value(&style).unwrap();
+ assert_eq!(
+ saved["runs"],
+ serde_json::json!([{ "start": 6, "end": 9, "color": "#ff0000" }])
+ );
+ let back: TextStyle = serde_json::from_value(saved).unwrap();
+ assert_eq!(back, style);
+ // A run that does not parse is dropped, not the title.
+ let odd: TextStyle = serde_json::from_value(serde_json::json!({
+ "content": "abc",
+ "runs": [{ "start": "x" }, { "start": 0, "end": 1, "italic": true }],
+ }))
+ .unwrap();
+ assert_eq!(odd.runs.len(), 1);
+ }
+}
diff --git a/src/crates/concat-text/src/lib.rs b/src/crates/concat-text/src/lib.rs
index 209181bd..7e1b0107 100644
--- a/src/crates/concat-text/src/lib.rs
+++ b/src/crates/concat-text/src/lib.rs
@@ -108,6 +108,36 @@ pub struct TitleStyle {
/// own. With a height the block is a box that tall, at least, and the
/// words sit centred in it.
pub max_height: f64,
+ /// Stretches of the words in a look of their own over the rest; see
+ /// [`TitleRun`]. Empty for a title in one look.
+ pub runs: Vec<TitleRun>,
+}
+
+/// Some of a title's words in a look of their own: the characters
+/// `start..end` of the content - characters, not bytes - and the fields
+/// they wear instead of the title's. A field left out is the title's. The
+/// document's run, field for field.
+#[derive(Clone, PartialEq, Debug, Default)]
+pub struct TitleRun {
+ /// The first character.
+ pub start: usize,
+ /// One past the last.
+ pub end: usize,
+ /// Fill colour as `#rrggbb[aa]`.
+ pub color: Option<String>,
+ /// CSS-scale weight; the face is picked for it, as for the title's.
+ pub font_weight: Option<f64>,
+ /// Italic or upright.
+ pub italic: Option<bool>,
+ /// Underlined or not.
+ pub underline: Option<bool>,
+ /// Struck through or not.
+ pub strikethrough: Option<bool>,
+ /// The em as a multiple of the title's; a line with a bigger word in
+ /// it is as tall as that word.
+ pub font_scale: Option<f64>,
+ /// Outline colour, where the title has an outline.
+ pub stroke_color: Option<String>,
}
/// One word's box in canvas pixels, top-left origin, in reading order
@@ -470,17 +500,20 @@ fn family_names(db: &fontdb::Database) -> Vec<String> {
impl Fonts {
/// The best face for a style: the named family at the nearest weight and
/// slant, then any sans-serif, then anything at all.
+ #[cfg(test)]
fn pick(&self, style: &TitleStyle) -> Result<fontdb::ID, Error> {
- let mut family = style
- .font_family
- .trim()
- .trim_matches('"')
- .trim_matches('\'');
+ self.pick_face(&style.font_family, style.font_weight, style.italic)
+ }
+
+ /// [`Fonts::pick`] for one look of a title: its family, at a weight
+ /// and slant that may be a run's rather than the title's.
+ fn pick_face(&self, family: &str, weight: f64, italic: bool) -> Result<fontdb::ID, Error> {
+ let mut family = family.trim().trim_matches('"').trim_matches('\'');
if RETIRED.contains(&family) {
family = BUNDLED_FAMILY;
}
- let weight = fontdb::Weight(style.font_weight.clamp(100.0, 900.0).round() as u16);
- let slant = if style.italic {
+ let weight = fontdb::Weight(weight.clamp(100.0, 900.0).round() as u16);
+ let slant = if italic {
fontdb::Style::Italic
} else {
fontdb::Style::Normal
@@ -503,49 +536,98 @@ impl Fonts {
}
/// The faces a title is set in and which of them sets each character.
- ///
- /// The style's own face sets everything it has a glyph for. A character
- /// it lacks is lent by another face that can draw it - one the title
- /// already borrows from if one can, so a line of Japanese is not set in
- /// three faces, else the nearest in weight and slant. What nothing can
- /// draw stays with the style's face, whose .notdef box says so.
+ #[cfg(test)]
fn cast(&self, style: &TitleStyle) -> Result<Casting, Error> {
- let own_id = self.pick(style)?;
+ let (looks, look_of) = looks_of(style);
+ self.cast_looks(style, &looks, &look_of)
+ }
+
+ /// The faces a title is set in and which of them sets each character,
+ /// for its looks (see [`Look`]) and the look of each byte.
+ ///
+ /// Each look's own face - the family at that look's weight and slant,
+ /// the title's own first - sets everything it has a glyph for. A
+ /// character it lacks is lent by another face that can draw it - one
+ /// the title already borrows from if one can, so a line of Japanese is
+ /// not set in three faces, else the nearest in weight and slant. What
+ /// nothing can draw stays with the look's face, whose .notdef box says
+ /// so.
+ fn cast_looks(
+ &self,
+ style: &TitleStyle,
+ looks: &[Look],
+ look_of: &[usize],
+ ) -> Result<Casting, Error> {
+ // Each look's own face, once each however many looks share it; the
+ // title's is first, so index 0 is always the style's face.
+ let mut ids: Vec<fontdb::ID> = Vec::new();
+ let mut owns = Vec::with_capacity(looks.len());
+ for look in looks {
+ let id = self.pick_face(&style.font_family, look.weight, look.italic)?;
+ owns.push(match ids.iter().position(|&held| held == id) {
+ Some(index) => index,
+ None => {
+ ids.push(id);
+ ids.len() - 1
+ }
+ });
+ }
let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
- let own = self.data(&mut cache, own_id).ok_or(Error::BadFont)?;
- let own_face =
+ let own = self.data(&mut cache, ids[0]).ok_or(Error::BadFont)?;
+ // A run's face that will not open sets its characters in the
+ // title's: the right weight lost, the words still there.
+ let own_data: Vec<(FaceData, u32)> = std::iter::once(own.clone())
+ .chain(
+ ids[1..]
+ .iter()
+ .map(|&id| self.data(&mut cache, id).unwrap_or_else(|| own.clone())),
+ )
+ .collect();
+ let title_face =
ttf_parser::Face::parse((*own.0).as_ref(), own.1).map_err(|_| Error::BadFont)?;
+ let own_faces: Vec<ttf_parser::Face<'_>> = own_data
+ .iter()
+ .map(|(data, index)| {
+ ttf_parser::Face::parse((**data).as_ref(), *index)
+ .unwrap_or_else(|_| title_face.clone())
+ })
+ .collect();
+ let own_of = |at: usize| owns[look_of.get(at).copied().unwrap_or(0)];
let mut missing: Vec<char> = style
.content
- .chars()
- .filter(|&ch| {
+ .char_indices()
+ .filter(|&(at, ch)| {
!ch.is_control()
- && own_face.glyph_index(ch).is_none()
+ && own_faces[own_of(at)].glyph_index(ch).is_none()
&& !cache.covers.contains_key(&ch)
})
+ .map(|(_, ch)| ch)
.collect();
missing.sort_unstable();
missing.dedup();
self.learn(&mut cache, &missing);
- let want = Want {
- weight: style.font_weight.clamp(100.0, 900.0).round() as u16,
- italic: style.italic,
- };
- let mut ids = vec![own_id];
let paragraphs = style
.content
.lines()
- .map(|text| self.assign(text, &own_face, &cache, want, &mut ids))
+ .map(|text| {
+ let at = text.as_ptr() as usize - style.content.as_ptr() as usize;
+ let looks_here = look_of.get(at..at + text.len()).unwrap_or(&[]);
+ self.assign(text, looks_here, looks, &owns, &own_faces, &cache, &mut ids)
+ })
.collect();
- let mut faces = vec![own.clone()];
- for &id in &ids[1..] {
+ let mut faces = own_data;
+ for &id in &ids[faces.len()..] {
// A face that will not open sets its characters in the style's
// face instead: boxes, but in the right places.
faces.push(self.data(&mut cache, id).unwrap_or_else(|| own.clone()));
}
- Ok(Casting { faces, paragraphs })
+ Ok(Casting {
+ faces,
+ paragraphs,
+ owns,
+ })
}
/// Reads every face once for the characters in `chars`, and remembers
@@ -586,36 +668,46 @@ impl Fonts {
}
/// Which of `ids` sets each byte of one paragraph, adding the faces it
- /// borrows to `ids`. Index 0 is the style's own face.
+ /// borrows to `ids`. `look_of` is the look of each of its bytes, and
+ /// `owns` each look's own face in `ids`, parsed in `own_faces`.
+ #[allow(clippy::too_many_arguments)]
fn assign(
&self,
text: &str,
- own: &ttf_parser::Face<'_>,
+ look_of: &[usize],
+ looks: &[Look],
+ owns: &[usize],
+ own_faces: &[ttf_parser::Face<'_>],
cache: &Cache,
- want: Want,
ids: &mut Vec<fontdb::ID>,
) -> Vec<usize> {
let mut out = vec![0; text.len()];
let mut last = 0;
for (at, ch) in text.char_indices() {
+ let look = look_of.get(at).copied().unwrap_or(0);
+ let own = owns[look];
+ let want = Want {
+ weight: looks[look].weight.clamp(100.0, 900.0).round() as u16,
+ italic: looks[look].italic,
+ };
let covers = cache.covers.get(&ch);
let lends = |ids: &[fontdb::ID], index: usize| {
- index != 0 && covers.is_some_and(|covers| covers.has(ids[index]))
+ index != own && covers.is_some_and(|covers| covers.has(ids[index]))
};
let index = if joins(ch) && at > 0 {
// A mark, a joiner, a skin tone: with what it modifies.
last
- } else if own.glyph_index(ch).is_some() {
- 0
+ } else if own_faces[own].glyph_index(ch).is_some() {
+ own
} else if lends(ids, last) {
last
- } else if let Some(index) = (1..ids.len()).find(|&index| lends(ids, index)) {
+ } else if let Some(index) = (0..ids.len()).find(|&index| lends(ids, index)) {
index
} else if let Some(id) = self.nearest(covers, want) {
ids.push(id);
ids.len() - 1
} else {
- 0
+ own
};
out[at..at + ch.len_utf8()].fill(index);
last = index;
@@ -670,13 +762,81 @@ struct Want {
italic: bool,
}
-/// A title's faces, and which sets each character; see [`Fonts::cast`].
+/// A title's faces, and which sets each character; see [`Fonts::cast_looks`].
struct Casting {
- /// Each face's bytes and index in its collection, the style's first.
+ /// Each face's bytes and index in its collection: each look's own
+ /// first, the style's at 0, then the ones borrowed.
faces: Vec<(FaceData, u32)>,
/// Per line of the content, per byte, the index of the face that sets
/// it.
paragraphs: Vec<Vec<usize>>,
+ /// Per look, the index of its own face.
+ owns: Vec<usize>,
+}
+
+/// One look a title's characters are set in, resolved: the title's own,
+/// at index 0, or a run's laid over it - each field the run's where it
+/// says and the title's where it does not.
+#[derive(Clone, Debug)]
+struct Look {
+ weight: f64,
+ italic: bool,
+ underline: bool,
+ strikethrough: bool,
+ /// Its em, as a multiple of the title's.
+ scale: f32,
+ fill: Color,
+ /// The outline's colour; none for one that does not parse, which the
+ /// title's outline did not draw either.
+ edge: Option<Color>,
+}
+
+/// The looks a title is set in - its own first, then one per run - and,
+/// per byte of the content, which. A title with no runs is one look, and
+/// is set exactly as it was before runs.
+fn looks_of(style: &TitleStyle) -> (Vec<Look>, Vec<usize>) {
+ let base = Look {
+ weight: style.font_weight,
+ italic: style.italic,
+ underline: style.underline,
+ strikethrough: style.strikethrough,
+ scale: 1.0,
+ fill: colour(&style.color).unwrap_or(Color::WHITE),
+ edge: colour(&style.stroke_color),
+ };
+ let mut look_of = vec![0; style.content.len()];
+ let mut looks = vec![base.clone()];
+ if style.runs.is_empty() {
+ return (looks, look_of);
+ }
+ // Characters to bytes: a run counts characters, the setter bytes.
+ let bytes: Vec<usize> = style
+ .content
+ .char_indices()
+ .map(|(at, _)| at)
+ .chain(std::iter::once(style.content.len()))
+ .collect();
+ let count = bytes.len() - 1;
+ for run in &style.runs {
+ let (start, end) = (run.start.min(count), run.end.min(count));
+ if start >= end {
+ continue;
+ }
+ looks.push(Look {
+ weight: run.font_weight.unwrap_or(base.weight),
+ italic: run.italic.unwrap_or(base.italic),
+ underline: run.underline.unwrap_or(base.underline),
+ strikethrough: run.strikethrough.unwrap_or(base.strikethrough),
+ scale: run
+ .font_scale
+ .filter(|scale| scale.is_finite())
+ .map_or(1.0, |scale| scale.clamp(0.1, 10.0) as f32),
+ fill: run.color.as_deref().and_then(colour).unwrap_or(base.fill),
+ edge: run.stroke_color.as_deref().and_then(colour).or(base.edge),
+ });
+ look_of[bytes[start]..bytes[end]].fill(looks.len() - 1);
+ }
+ (looks, look_of)
}
/// What `face` draws `ch` with, when it draws it: colours of its own, or
@@ -810,17 +970,26 @@ fn joins(ch: char) -> bool {
|| ('\u{E0020}'..='\u{E007F}').contains(&ch)
}
-/// One shaped line: its outline path in pixels, pen at the origin, its
-/// advance width, and each of its words' `(start_x, end_x)` in that same
-/// pen space, left to right.
+/// One shaped line: its outlines in pixels, pen at the origin, one path
+/// per look that has glyphs on it, its advance width, and each of its
+/// words' `(start_x, end_x)` in that same pen space, left to right.
struct Line {
- path: Option<Path>,
+ /// `(look, outlines)`, for the look's fill and outline to paint.
+ paths: Vec<(usize, Path)>,
/// The glyphs that paint their own colours - a picture rather than an
/// outline - at that same pen origin, for laying over the words. The
- /// fill would wash their colours out, so they stay out of `path`.
+ /// fill would wash their colours out, so they stay out of `paths`.
marks: Vec<Mark>,
width: f32,
words: Vec<(f32, f32)>,
+ /// The stretches set in one look, `(look, start_x, end_x)` left to
+ /// right: where a look's underline and strike are ruled.
+ stretches: Vec<(usize, f32, f32)>,
+ /// The tallest of its looks' ascents and descents, and its biggest em,
+ /// in pixels: a line with one big word is as tall as that word.
+ ascent: f32,
+ descent: f32,
+ em: f32,
}
/// A glyph that colours itself, in pen space at its line's origin: an
@@ -905,22 +1074,24 @@ impl ttf_parser::OutlineBuilder for Outliner<'_> {
}
/// What setting a line needs: the title's faces, in [`Casting`]'s order,
-/// and its sizes in pixels.
+/// its looks, and its sizes in pixels.
struct Setter<'a> {
faces: &'a [rustybuzz::Face<'a>],
+ /// The title's em; a look's is this times its scale.
em: f32,
tracking: f32,
- /// The words' colour, for the `COLR` palette entry that means "paint
- /// it with the text's own colour".
- foreground: ttf_parser::RgbaColor,
+ looks: &'a [Look],
+ /// Per look, its own face's ascent and descent at the look's size.
+ metrics: &'a [(f32, f32)],
}
/// One line of the content, ready to be set: its text, its directions,
-/// and the face each byte is set in.
+/// and the face and the look each byte is set in.
struct Paragraph<'a> {
text: &'a str,
bidi: ParagraphBidiInfo<'a>,
face_of: &'a [usize],
+ look_of: &'a [usize],
}
impl Setter<'_> {
@@ -968,35 +1139,72 @@ impl Setter<'_> {
lines
}
+ /// How tall a line of `range` stands: the tallest ascent and descent
+ /// of the looks on it, and the biggest em. An empty line stands as
+ /// tall as the look it would be typed in.
+ fn measure(&self, para: &Paragraph<'_>, range: Range<usize>) -> (f32, f32, f32) {
+ let mut tallest: Option<(f32, f32, f32)> = None;
+ if self.looks.len() > 1 {
+ for at in range.clone() {
+ let Some(&look) = para.look_of.get(at) else {
+ break;
+ };
+ let (ascent, descent) = self.metrics[look];
+ let em = self.em * self.looks[look].scale;
+ tallest = Some(tallest.map_or((ascent, descent, em), |(a, d, e)| {
+ (a.max(ascent), d.max(descent), e.max(em))
+ }));
+ }
+ }
+ tallest.unwrap_or_else(|| {
+ let look = para
+ .look_of
+ .get(range.start)
+ .or_else(|| para.look_of.get(range.start.wrapping_sub(1)))
+ .copied()
+ .unwrap_or(0);
+ let (ascent, descent) = self.metrics[look];
+ (ascent, descent, self.em * self.looks[look].scale)
+ })
+ }
+
/// Shapes `range` of a paragraph as one line, pen starting at (0, 0) on
/// the baseline, and outlines it when `outline` - a line only being
/// measured is not.
///
/// The line's runs are laid left to right in the order they are seen,
/// which for right-to-left text is not the order they are read; each
- /// run is split where its face changes, and shaped piece by piece.
+ /// run is split where its face or its look changes, and shaped piece by
+ /// piece, each at its look's size.
fn set(&self, para: &Paragraph<'_>, range: Range<usize>, outline: bool) -> Line {
+ let (ascent, descent, em) = self.measure(para, range.clone());
if range.is_empty() {
return Line {
- path: None,
+ paths: Vec::new(),
marks: Vec::new(),
width: 0.0,
words: Vec::new(),
+ stretches: Vec::new(),
+ ascent,
+ descent,
+ em,
};
}
+ let look_at = |at: usize| para.look_of.get(at).copied().unwrap_or(0);
let (levels, runs) = para.bidi.visual_runs(range.clone());
- let mut builder = PathBuilder::new();
+ // One outline per look, made as the look first turns up.
+ let mut builders: Vec<Option<PathBuilder>> = self.looks.iter().map(|_| None).collect();
let mut marks: Vec<Mark> = Vec::new();
let mut pen = 0.0_f32;
- // Each glyph's cluster, as a byte into the paragraph, and the span
- // it advances over.
- let mut spans: Vec<(usize, f32, f32)> = Vec::new();
+ // Each glyph's cluster, as a byte into the paragraph, the span it
+ // advances over, and its look.
+ let mut spans: Vec<(usize, f32, f32, usize)> = Vec::new();
for run in runs {
let rtl = levels[run.start].is_rtl();
let mut pieces = Vec::new();
let mut start = run.start;
for at in run.clone() {
- if para.face_of[at] != para.face_of[start] {
+ if para.face_of[at] != para.face_of[start] || look_at(at) != look_at(start) {
pieces.push(start..at);
start = at;
}
@@ -1008,7 +1216,9 @@ impl Setter<'_> {
}
for piece in pieces {
let face = &self.faces[para.face_of[piece.start]];
- let scale = self.em / face.units_per_em() as f32;
+ let look = look_at(piece.start);
+ let em = self.em * self.looks[look].scale;
+ let scale = em / face.units_per_em() as f32;
let mut buffer = rustybuzz::UnicodeBuffer::new();
buffer.push_str(&para.text[piece.clone()]);
buffer.set_direction(if rtl {
@@ -1028,14 +1238,15 @@ impl Setter<'_> {
let y = -(position.y_offset as f32 * scale);
// A glyph that colours itself - a strike's
// picture, layered paints - goes into the line's
- // marks instead of its path: the words' fill
+ // marks instead of its outlines: the words' fill
// would wash its colours out. Anything else is
- // an outline, as always.
- if let Some(mark) = self.mark(face, glyph, x, y, scale) {
+ // an outline in its look's path, as always.
+ let foreground = rgba(self.looks[look].fill);
+ if let Some(mark) = self.mark(face, glyph, x, y, em, foreground) {
marks.push(mark);
} else {
let mut outliner = Outliner {
- builder: &mut builder,
+ builder: builders[look].get_or_insert_with(PathBuilder::new),
scale,
x,
y,
@@ -1044,7 +1255,12 @@ impl Setter<'_> {
}
}
let advance = position.x_advance as f32 * scale;
- spans.push((piece.start + info.cluster as usize, pen, pen + advance));
+ spans.push((
+ piece.start + info.cluster as usize,
+ pen,
+ pen + advance,
+ look,
+ ));
pen += advance + self.tracking;
}
}
@@ -1055,41 +1271,59 @@ impl Setter<'_> {
} else {
(pen - self.tracking).max(0.0)
};
- let words = if outline {
- words(para.text, range)
+ let (words, stretches) = if outline {
+ let words = words(para.text, range)
.into_iter()
.filter_map(|word| {
spans
.iter()
- .filter(|(cluster, _, _)| word.contains(cluster))
- .fold(None, |span: Option<(f32, f32)>, &(_, left, right)| {
+ .filter(|(cluster, _, _, _)| word.contains(cluster))
+ .fold(None, |span: Option<(f32, f32)>, &(_, left, right, _)| {
Some(span.map_or((left, right), |(l, r)| (l.min(left), r.max(right))))
})
})
- .collect()
+ .collect();
+ let mut stretches: Vec<(usize, f32, f32)> = Vec::new();
+ for &(_, left, right, look) in &spans {
+ match stretches.last_mut() {
+ Some((held, _, end)) if *held == look => *end = end.max(right),
+ _ => stretches.push((look, left, right)),
+ }
+ }
+ (words, stretches)
} else {
- Vec::new()
+ (Vec::new(), Vec::new())
};
Line {
- path: builder.finish(),
+ paths: builders
+ .into_iter()
+ .enumerate()
+ .filter_map(|(look, builder)| Some((look, builder?.finish()?)))
+ .collect(),
marks,
width,
words,
+ stretches,
+ ascent,
+ descent,
+ em,
}
}
- /// A glyph's own colours, at its origin `(x, y)` on the baseline: its
- /// font's bitmap, decoded and boxed to the strike's size, or its
- /// `COLR` layers outlined in their palette colours. `None` for a plain
- /// outline - most glyphs - and for a colour glyph this crate does not
- /// follow, which falls back to its outline as before.
+ /// A glyph's own colours, at its origin `(x, y)` on the baseline and
+ /// at `em` pixels: its font's bitmap, decoded and boxed to the strike's
+ /// size, or its `COLR` layers outlined in their palette colours, with
+ /// `foreground` for the palette's "the text's own colour". `None` for a
+ /// plain outline - most glyphs - and for a colour glyph this crate does
+ /// not follow, which falls back to its outline as before.
fn mark(
&self,
face: &rustybuzz::Face<'_>,
glyph: ttf_parser::GlyphId,
x: f32,
y: f32,
- scale: f32,
+ em: f32,
+ foreground: ttf_parser::RgbaColor,
) -> Option<Mark> {
if let Some(image) = face.glyph_raster_image(glyph, u16::MAX)
&& matches!(
@@ -1103,7 +1337,7 @@ impl Setter<'_> {
// the glyph's origin to the bitmap's *bottom* edge - both for
// `CBDT` and for `sbix` - while the canvas goes down. `k`
// turns a strike pixel into canvas pixels at this size.
- let k = self.em / f32::from(image.pixels_per_em.max(1));
+ let k = em / f32::from(image.pixels_per_em.max(1));
let height = f32::from(image.height) * k;
return Some(Mark::Bitmap {
x: x + f32::from(image.x) * k,
@@ -1113,7 +1347,8 @@ impl Setter<'_> {
pixmap,
});
}
- let layers = Layering::of(face, glyph, self.foreground)?;
+ let scale = em / face.units_per_em() as f32;
+ let layers = Layering::of(face, glyph, foreground)?;
let mut placed = Vec::with_capacity(layers.len());
for (glyph_id, colour) in layers {
let mut builder = PathBuilder::new();
@@ -1297,9 +1532,11 @@ fn paint(
let frame_h = height as f32;
let em = (style.font_size.clamp(0.005, 1.0) as f32) * frame_h;
let tracking = style.tracking as f32 * frame_h;
- let pitch = em * (style.line_height.max(0.5) as f32);
+ let line_height = style.line_height.max(0.5) as f32;
- let casting = fonts.cast(style)?;
+ // The title's own look and its runs', and which each byte is in.
+ let (looks, look_of) = looks_of(style);
+ let casting = fonts.cast_looks(style, &looks, &look_of)?;
let own = {
let (data, index) = &casting.faces[0];
rustybuzz::Face::from_slice((**data).as_ref(), *index).ok_or(Error::BadFont)?
@@ -1313,12 +1550,22 @@ fn paint(
rustybuzz::Face::from_slice((**data).as_ref(), *index).unwrap_or_else(|| own.clone())
})
.collect();
- // The line's metrics are the style's face's, whatever it borrows: the
- // pitch and the block should not jump because one character came from
- // elsewhere.
- let upem = own.units_per_em() as f32;
- let ascent = own.ascender() as f32 / upem * em;
- let descent = -(own.descender() as f32) / upem * em;
+ // A line's metrics are its looks' own faces', whatever they borrow:
+ // the pitch and the block should not jump because one character came
+ // from elsewhere. A title in one look is the style's face's.
+ let metrics: Vec<(f32, f32)> = looks
+ .iter()
+ .zip(&casting.owns)
+ .map(|(look, &face)| {
+ let face = &faces[face];
+ let size = em * look.scale / face.units_per_em() as f32;
+ (
+ face.ascender() as f32 * size,
+ -(face.descender() as f32) * size,
+ )
+ })
+ .collect();
+ let (ascent, descent) = metrics[0];
// The box's limits, where the style sets them; zero is a box the words
// size.
@@ -1356,35 +1603,50 @@ fn paint(
};
// Shape every line with the pen at the origin; placement comes after,
- // once the block's width is known. The words' colour goes along: a
+ // once the block's width is known. Each look's colour goes along: a
// `COLR` palette entry of 0xFFFF means "paint it with the text's own".
- let fill = colour(&style.color).unwrap_or(Color::WHITE);
let setter = Setter {
faces: &faces,
em,
tracking,
- foreground: rgba(fill),
+ looks: &looks,
+ metrics: &metrics,
};
let lines: Vec<Line> = style
.content
.lines()
.zip(&casting.paragraphs)
.flat_map(|(text, face_of)| {
+ let at = text.as_ptr() as usize - style.content.as_ptr() as usize;
let para = Paragraph {
text,
bidi: ParagraphBidiInfo::new(text, None),
face_of,
+ look_of: look_of.get(at..at + text.len()).unwrap_or(&[]),
};
setter.wrap(&para, wrap_w)
})
.collect();
- let rows = lines.len().max(1);
let words_w = lines.iter().map(|line| line.width).fold(0.0, f32::max);
- let words_h = (rows as f32 - 1.0) * pitch + ascent + descent;
if words_w <= 0.0 || lines.is_empty() {
// Nothing to paint: an empty, valid canvas.
return Ok((canvas, (0, 0, 0, 0), Vec::new()));
}
+ // Each baseline below the first by the pitch of the bigger of the two
+ // lines it sits between, so a line with a big word in it pushes its
+ // neighbours away rather than running into them. In one look every
+ // pitch is the same, as it always was.
+ let mut drops = Vec::with_capacity(lines.len());
+ let mut drop = 0.0_f32;
+ for (row, line) in lines.iter().enumerate() {
+ if row > 0 {
+ drop += line_height * lines[row - 1].em.max(line.em);
+ }
+ drops.push(drop);
+ }
+ let first_ascent = lines.first().map_or(ascent, |line| line.ascent);
+ let last_descent = lines.last().map_or(descent, |line| line.descent);
+ let words_h = drop + first_ascent + last_descent;
// The box the words sit in. Sized by the style where the style says,
// and by the words where it does not; never smaller than the words,
@@ -1420,66 +1682,86 @@ fn paint(
// The words are centred in a box taller than they are.
let top = (frame_h - outer_h) / 2.0 + pad_y + (box_h - words_h) / 2.0;
let block_dx = (outer_left + outer_w / 2.0 - anchor_x).round() as i32;
-
- // One path for all the words, placed. Each line is aligned within the
- // box's width and sits on its own baseline. A word's box rides the
- // same indent and baseline, in reading order - a line that paints
- // its glyphs' own colours has no path to place but still has words.
- let mut words = PathBuilder::new();
+ let indent_of = |line: &Line| match style.align {
+ Align::Left => 0.0,
+ Align::Center => (box_w - line.width) / 2.0,
+ Align::Right => box_w - line.width,
+ };
+ let baseline_of = |row: usize| top + first_ascent + drops[row];
+
+ // Each look's words as one path, placed, ruled lines included. Each
+ // line is aligned within the box's width and sits on its own
+ // baseline. A word's box rides the same indent and baseline, in
+ // reading order - a line that paints its glyphs' own colours has no
+ // path to place but still has words.
+ let mut placed: Vec<PathBuilder> = looks.iter().map(|_| PathBuilder::new()).collect();
+ // A look's ruled lines in its own face's metrics, at its own size, so
+ // they sit where the face's designer put them; an em-based guess for
+ // a face that does not say.
+ let rules: Vec<[(f32, f32); 2]> = looks
+ .iter()
+ .zip(&casting.owns)
+ .map(|(look, &face)| {
+ let face = &faces[face];
+ let em = em * look.scale;
+ let upem = face.units_per_em() as f32;
+ let metric = |m: Option<ttf_parser::LineMetrics>, fallback: f32| {
+ m.map_or((fallback, (em * 0.05).max(1.0)), |m| {
+ (
+ -f32::from(m.position) / upem * em,
+ (f32::from(m.thickness).abs() / upem * em).max(1.0),
+ )
+ })
+ };
+ [
+ metric(face.underline_metrics(), em * 0.1),
+ metric(face.strikeout_metrics(), -em * 0.3),
+ ]
+ })
+ .collect();
let mut word_rects = Vec::new();
for (row, line) in lines.iter().enumerate() {
- let indent = match style.align {
- Align::Left => 0.0,
- Align::Center => (box_w - line.width) / 2.0,
- Align::Right => box_w - line.width,
- };
- let baseline = top + ascent + row as f32 * pitch;
- if let Some(path) = &line.path {
- let placed = path
+ let indent = indent_of(line);
+ let baseline = baseline_of(row);
+ for (look, path) in &line.paths {
+ let path = path
.clone()
.transform(Transform::from_translate(left + indent, baseline))
.expect("a translated glyph path stays finite");
- words.push_path(&placed);
- }
- // Font metrics keep decorations aligned across faces and resolutions.
- let metric = |m: Option<ttf_parser::LineMetrics>, fallback: f32| {
- m.map_or((fallback, (em * 0.05).max(1.0)), |m| {
- (
- -f32::from(m.position) / upem * em,
- (f32::from(m.thickness).abs() / upem * em).max(1.0),
- )
- })
- };
- for (enabled, (offset, thickness)) in [
- (style.underline, metric(own.underline_metrics(), em * 0.1)),
- (
- style.strikethrough,
- metric(own.strikeout_metrics(), -em * 0.3),
- ),
- ] {
- if enabled
- && line.width > 0.0
- && let Some(rect) = Rect::from_xywh(
- left + indent,
- baseline + offset - thickness / 2.0,
- line.width,
- thickness,
- )
- {
- words.push_rect(rect);
+ placed[*look].push_path(&path);
+ }
+ // Rules share the glyphs' fill, outline and shadow.
+ for &(look, start_x, end_x) in &line.stretches {
+ let wanted = [looks[look].underline, looks[look].strikethrough];
+ for (on, (offset, thickness)) in wanted.into_iter().zip(rules[look]) {
+ if on
+ && line.width > 0.0
+ && let Some(rect) = Rect::from_xywh(
+ left + indent + start_x,
+ baseline + offset - thickness / 2.0,
+ end_x - start_x,
+ thickness,
+ )
+ {
+ placed[look].push_rect(rect);
+ }
}
}
- let line_top = baseline - ascent;
+ let line_top = baseline - line.ascent;
for &(start_x, end_x) in &line.words {
word_rects.push(WordRect {
x: (left + indent + start_x).round() as i32,
y: line_top.round() as i32,
width: (end_x - start_x).max(0.0).round() as u32,
- height: (ascent + descent).round() as u32,
+ height: (line.ascent + line.descent).round() as u32,
});
}
}
- let words = words.finish();
+ let words: Vec<(usize, Path)> = placed
+ .into_iter()
+ .enumerate()
+ .filter_map(|(look, builder)| Some((look, builder.finish()?)))
+ .collect();
let mut paint = Paint {
anti_alias: true,
@@ -1506,9 +1788,10 @@ fn paint(
}
// The shadow: the words again, offset down and right, black, blurred on
- // a layer of their own and laid under the real words.
+ // a layer of their own and laid under the real words - every look's
+ // under all of them, one shadow for the title.
if style.shadow
- && let Some(words) = &words
+ && !words.is_empty()
&& let Some(mut layer) = Pixmap::new(width, height)
{
let mut shade = Paint {
@@ -1517,7 +1800,9 @@ fn paint(
};
shade.set_color(Color::from_rgba8(0, 0, 0, 150));
let offset = Transform::from_translate(em * 0.05, em * 0.07);
- layer.fill_path(words, &shade, FillRule::Winding, offset, None);
+ for (_, path) in &words {
+ layer.fill_path(path, &shade, FillRule::Winding, offset, None);
+ }
blur(&mut layer, (em * 0.04).round().max(1.0) as usize);
canvas.draw_pixmap(
0,
@@ -1530,32 +1815,29 @@ fn paint(
}
// The outline, under the fill so only its outer half shows - which is
- // why it is drawn at twice the asked-for width.
+ // why it is drawn at twice the asked-for width. Every look's outline
+ // goes down before any fill, so one word's outline never covers its
+ // neighbour's letters.
let stroke_w = style.stroke_width.max(0.0) as f32 * frame_h;
- if stroke_w > 0.0
- && let Some(edge) = colour(&style.stroke_color)
- && let Some(words) = &words
- {
- paint.set_color(edge);
+ if stroke_w > 0.0 {
let stroke = Stroke {
width: stroke_w * 2.0,
line_join: LineJoin::Round,
line_cap: LineCap::Round,
..Stroke::default()
};
- canvas.stroke_path(words, &paint, &stroke, Transform::identity(), None);
+ for (look, path) in &words {
+ if let Some(edge) = looks[*look].edge {
+ paint.set_color(edge);
+ canvas.stroke_path(path, &paint, &stroke, Transform::identity(), None);
+ }
+ }
}
- // The words.
- if let Some(words) = &words {
- paint.set_color(fill);
- canvas.fill_path(
- words,
- &paint,
- FillRule::Winding,
- Transform::identity(),
- None,
- );
+ // The words, each look in its own colour.
+ for (look, path) in &words {
+ paint.set_color(looks[*look].fill);
+ canvas.fill_path(path, &paint, FillRule::Winding, Transform::identity(), None);
}
// The glyphs that paint their own colours - an emoji's picture, a
@@ -1567,12 +1849,8 @@ fn paint(
if line.marks.is_empty() {
continue;
}
- let indent = match style.align {
- Align::Left => 0.0,
- Align::Center => (box_w - line.width) / 2.0,
- Align::Right => box_w - line.width,
- };
- let baseline = top + ascent + row as f32 * pitch;
+ let indent = indent_of(line);
+ let baseline = baseline_of(row);
let placed = Transform::from_translate(left + indent, baseline);
for mark in &line.marks {
match mark {
@@ -1960,6 +2238,7 @@ mod tests {
tracking: 0.0,
max_width: 0.0,
max_height: 0.0,
+ runs: Vec::new(),
}
}
@@ -1985,6 +2264,152 @@ mod tests {
}
}
+ /// How many of the canvas's pixels inside `word` pass `test`, read
+ /// straight from the RGBA, only those mostly opaque.
+ fn pixels_in(
+ frame: &RenderedFrame,
+ word: WordRect,
+ test: impl Fn(u8, u8, u8) -> bool,
+ ) -> usize {
+ let mut count = 0;
+ for y in word.y.max(0)..(word.y + word.height as i32).min(frame.height as i32) {
+ for x in word.x.max(0)..(word.x + word.width as i32).min(frame.width as i32) {
+ let at = (y as usize * frame.width as usize + x as usize) * 4;
+ let px = &frame.rgba[at..at + 4];
+ if px[3] > 200 && test(px[0], px[1], px[2]) {
+ count += 1;
+ }
+ }
+ }
+ count
+ }
+
+ fn is_white(r: u8, g: u8, b: u8) -> bool {
+ r > 200 && g > 200 && b > 200
+ }
+
+ /// "Make" in red, "this" in the title's white: each word is painted in
+ /// its own colour, and only its own.
+ #[test]
+ fn a_coloured_run_paints_its_words_and_only_its_words() {
+ let fonts = Fonts::new();
+ let mut styled = style("Make this");
+ styled.shadow = false;
+ styled.runs = vec![TitleRun {
+ start: 0,
+ end: 4,
+ color: Some("#ff0000".into()),
+ ..TitleRun::default()
+ }];
+ let frame = render_frame(&fonts, &styled, 640, 360).expect("renders");
+ assert_eq!(frame.words.len(), 2);
+ let (make, this) = (frame.words[0], frame.words[1]);
+ assert!(pixels_in(&frame, make, is_red) > 50, "the run is red");
+ assert_eq!(pixels_in(&frame, make, is_white), 0, "and nothing else");
+ assert!(
+ pixels_in(&frame, this, is_white) > 50,
+ "its neighbour is white"
+ );
+ assert_eq!(pixels_in(&frame, this, is_red), 0, "and not red");
+ // A colour moves no word: the boxes are the title's in one look.
+ styled.runs.clear();
+ let plain = render_frame(&fonts, &styled, 640, 360).expect("renders");
+ assert_eq!(plain.words, frame.words);
+ assert_eq!(
+ (plain.block_width, plain.block_height),
+ (frame.block_width, frame.block_height)
+ );
+ }
+
+ /// A word twice the size is twice as wide and makes its line taller:
+ /// the block grows to hold it and the next line moves down.
+ #[test]
+ fn a_bigger_run_is_bigger_and_its_line_is_taller() {
+ let fonts = Fonts::new();
+ let plain = style("big word\nnext");
+ let mut styled = plain.clone();
+ styled.runs = vec![TitleRun {
+ start: 0,
+ end: 3,
+ font_scale: Some(2.0),
+ ..TitleRun::default()
+ }];
+ let before = render_frame(&fonts, &plain, 640, 360).expect("renders");
+ let after = render_frame(&fonts, &styled, 640, 360).expect("renders");
+ let ratio = after.words[0].width as f32 / before.words[0].width as f32;
+ assert!((1.8..2.2).contains(&ratio), "twice as wide: {ratio}");
+ assert!(
+ after.words[0].height > before.words[0].height,
+ "its line stands taller"
+ );
+ assert_eq!(after.words[1].width, before.words[1].width, "word is not");
+ assert!(after.block_height > before.block_height);
+ let gap = |frame: &RenderedFrame| frame.words[2].y - frame.words[0].y;
+ assert!(gap(&after) > gap(&before), "the next line moved down");
+ }
+
+ /// An underline on one word is ruled under that word alone, and a
+ /// bold run is set in the heavier face: wider, with more ink.
+ #[test]
+ fn a_runs_rule_and_weight_stay_on_its_words() {
+ let fonts = Fonts::new();
+ let mut plain = style("ruled plain");
+ plain.font_family = BUNDLED_FAMILY.to_owned();
+ plain.font_weight = 400.0;
+ plain.shadow = false;
+ let mut styled = plain.clone();
+ styled.runs = vec![TitleRun {
+ start: 0,
+ end: 5,
+ underline: Some(true),
+ ..TitleRun::default()
+ }];
+ // Full HD: at 360 lines a rule is a pixel thick and never solid.
+ let before = render_frame(&fonts, &plain, 1920, 1080).expect("renders");
+ let after = render_frame(&fonts, &styled, 1920, 1080).expect("renders");
+ let ink =
+ |frame: &RenderedFrame, word: usize| pixels_in(frame, frame.words[word], is_white);
+ assert!(ink(&after, 0) > ink(&before, 0), "the run gained its rule");
+ assert_eq!(ink(&after, 1), ink(&before, 1), "its neighbour did not");
+
+ styled.runs = vec![TitleRun {
+ start: 0,
+ end: 5,
+ font_weight: Some(800.0),
+ ..TitleRun::default()
+ }];
+ let bold = render_frame(&fonts, &styled, 1920, 1080).expect("renders");
+ assert!(ink(&bold, 0) > ink(&before, 0), "a heavier face, more ink");
+ assert!(bold.words[0].width > before.words[0].width, "and wider");
+ // Its neighbour is the same word, moved along by however much
+ // wider the bold one is: only its edges land on other pixels.
+ assert_eq!(bold.words[1].width, before.words[1].width);
+ let (moved, still) = (ink(&bold, 1) as f32, ink(&before, 1) as f32);
+ assert!(
+ (moved / still - 1.0).abs() < 0.03,
+ "{moved} against {still}"
+ );
+ }
+
+ /// Runs count characters, not bytes: a run over "été" covers those
+ /// three letters, accents and all.
+ #[test]
+ fn a_run_counts_characters() {
+ let fonts = Fonts::new();
+ let mut styled = style("été ici");
+ styled.shadow = false;
+ styled.runs = vec![TitleRun {
+ start: 0,
+ end: 3,
+ color: Some("#ff0000".into()),
+ ..TitleRun::default()
+ }];
+ let frame = render_frame(&fonts, &styled, 640, 360).expect("renders");
+ assert!(pixels_in(&frame, frame.words[0], is_red) > 30);
+ assert_eq!(pixels_in(&frame, frame.words[0], is_white), 0);
+ assert_eq!(pixels_in(&frame, frame.words[1], is_red), 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]
diff --git a/src/crates/concat/locales/ar.json b/src/crates/concat/locales/ar.json
index 6891287b..37c034de 100644
--- a/src/crates/concat/locales/ar.json
+++ b/src/crates/concat/locales/ar.json
@@ -813,6 +813,7 @@
"textPanel.padding": "الحشوة",
"textPanel.position": "الموضع",
"textPanel.regular": "عادي",
+ "textPanel.resetWords": "إعادة تعيين",
"textPanel.searchFonts": "البحث في الخطوط",
"textPanel.semibold": "نصف عريض",
"textPanel.sentenceCase": "حالة الجملة",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "يتوسطه خط",
"textPanel.stroke": "الحدّ",
"textPanel.style": "النمط",
+ "textPanel.stylingTitle": "تنسيق العنوان كله. حدّد كلمات أعلاه لتنسيقها وحدها.",
+ "textPanel.stylingWords": "تنسيق الكلمات المحددة",
"textPanel.textAlign": "محاذاة النص",
"textPanel.tracking": "تباعد الأحرف",
"textPanel.typography": "الطباعة",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "أحرف كبيرة",
"textPanel.useForNewTitles": "استخدام للعناوين الجديدة",
"textPanel.vertical": "عمودي",
+ "textPanel.wholeTitle": "العنوان كله",
"timeline.deleteTrackClips": "سيُحذف هذا المسار و{0} مقاطع عليه. يمكنك التراجع عن ذلك.",
"timeline.deleteTrackEmpty": "سيُحذف هذا المسار الفارغ. يمكنك التراجع عن ذلك.",
"timeline.deleteTrackOneClip": "سيُحذف هذا المسار والمقطع الذي عليه. يمكنك التراجع عن ذلك.",
diff --git a/src/crates/concat/locales/az.json b/src/crates/concat/locales/az.json
index d0ca37a1..811a9cef 100644
--- a/src/crates/concat/locales/az.json
+++ b/src/crates/concat/locales/az.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Daxili boşluq",
"textPanel.position": "Mövqe",
"textPanel.regular": "Adi",
+ "textPanel.resetWords": "Sıfırla",
"textPanel.searchFonts": "Şriftlərdə axtar",
"textPanel.semibold": "Yarımqalın",
"textPanel.sentenceCase": "Cümlə registri",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Üstündən xətt",
"textPanel.stroke": "Kontur",
"textPanel.style": "Üslub",
+ "textPanel.stylingTitle": "Bütün başlıq üslublanır. Yalnız onları üslublamaq üçün yuxarıda söz seçin.",
+ "textPanel.stylingWords": "Seçilmiş sözlər üslublanır",
"textPanel.textAlign": "Mətnin düzlənməsi",
"textPanel.tracking": "Hərf aralığı",
"textPanel.typography": "Tipoqrafiya",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Böyük hərflər",
"textPanel.useForNewTitles": "Yeni yazılar üçün istifadə et",
"textPanel.vertical": "Şaquli",
+ "textPanel.wholeTitle": "Bütün başlıq",
"timeline.deleteTrackClips": "Bu trek və üzərindəki {0} klip silinəcək. Bunu geri ala bilərsiniz.",
"timeline.deleteTrackEmpty": "Bu boş trek silinəcək. Bunu geri ala bilərsiniz.",
"timeline.deleteTrackOneClip": "Bu trek və üzərindəki klip silinəcək. Bunu geri ala bilərsiniz.",
diff --git a/src/crates/concat/locales/bn.json b/src/crates/concat/locales/bn.json
index e88f57de..b6db5787 100644
--- a/src/crates/concat/locales/bn.json
+++ b/src/crates/concat/locales/bn.json
@@ -813,6 +813,7 @@
"textPanel.padding": "প্যাডিং",
"textPanel.position": "অবস্থান",
"textPanel.regular": "রেগুলার",
+ "textPanel.resetWords": "রিসেট",
"textPanel.searchFonts": "ফন্ট খুঁজুন",
"textPanel.semibold": "সেমিবোল্ড",
"textPanel.sentenceCase": "বাক্যের ধরন",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "স্ট্রাইকথ্রু",
"textPanel.stroke": "স্ট্রোক",
"textPanel.style": "স্টাইল",
+ "textPanel.stylingTitle": "পুরো শিরোনামের স্টাইল দেওয়া হচ্ছে। শুধু কিছু শব্দের জন্য উপরে সেগুলো নির্বাচন করুন।",
+ "textPanel.stylingWords": "নির্বাচিত শব্দগুলোর স্টাইল দেওয়া হচ্ছে",
"textPanel.textAlign": "টেক্সট অ্যালাইন",
"textPanel.tracking": "ট্র্যাকিং",
"textPanel.typography": "টাইপোগ্রাফি",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "বড় হাতের অক্ষর",
"textPanel.useForNewTitles": "নতুন টাইটেলের জন্য ব্যবহার করুন",
"textPanel.vertical": "উল্লম্ব",
+ "textPanel.wholeTitle": "পুরো শিরোনাম",
"timeline.deleteTrackClips": "এই ট্র্যাক এবং এতে থাকা {0}টি ক্লিপ মুছে যাবে। এটি পূর্বাবস্থায় ফেরাতে পারবেন।",
"timeline.deleteTrackEmpty": "এই খালি ট্র্যাকটি মুছে যাবে। এটি পূর্বাবস্থায় ফেরাতে পারবেন।",
"timeline.deleteTrackOneClip": "এই ট্র্যাক এবং এতে থাকা ক্লিপটি মুছে যাবে। এটি পূর্বাবস্থায় ফেরাতে পারবেন।",
diff --git a/src/crates/concat/locales/de.json b/src/crates/concat/locales/de.json
index 33278592..70bc000d 100644
--- a/src/crates/concat/locales/de.json
+++ b/src/crates/concat/locales/de.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Innenabstand",
"textPanel.position": "Position",
"textPanel.regular": "Normal",
+ "textPanel.resetWords": "Zurücksetzen",
"textPanel.searchFonts": "Schriften suchen",
"textPanel.semibold": "Halbfett",
"textPanel.sentenceCase": "Satzanfang groß",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Durchgestrichen",
"textPanel.stroke": "Strich",
"textPanel.style": "Stil",
+ "textPanel.stylingTitle": "Gestaltet den ganzen Titel. Markiere oben Wörter, um nur diese zu gestalten.",
+ "textPanel.stylingWords": "Gestaltet die markierten Wörter",
"textPanel.textAlign": "Textausrichtung",
"textPanel.tracking": "Laufweite",
"textPanel.typography": "Typografie",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Großbuchstaben",
"textPanel.useForNewTitles": "Für neue Titel verwenden",
"textPanel.vertical": "Vertikal",
+ "textPanel.wholeTitle": "Ganzer Titel",
"timeline.deleteTrackClips": "Diese Spur und die {0} Clips darauf werden gelöscht. Du kannst das rückgängig machen.",
"timeline.deleteTrackEmpty": "Diese leere Spur wird gelöscht. Du kannst das rückgängig machen.",
"timeline.deleteTrackOneClip": "Diese Spur und der Clip darauf werden gelöscht. Du kannst das rückgängig machen.",
diff --git a/src/crates/concat/locales/en.json b/src/crates/concat/locales/en.json
index 639a5508..ffbc2b4b 100644
--- a/src/crates/concat/locales/en.json
+++ b/src/crates/concat/locales/en.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Padding",
"textPanel.position": "Position",
"textPanel.regular": "Regular",
+ "textPanel.resetWords": "Reset",
"textPanel.searchFonts": "Search fonts",
"textPanel.semibold": "SemiBold",
"textPanel.sentenceCase": "Sentence case",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Strikethrough",
"textPanel.stroke": "Stroke",
"textPanel.style": "Style",
+ "textPanel.stylingTitle": "Styling the whole title. Select words above to style just those.",
+ "textPanel.stylingWords": "Styling the selected words",
"textPanel.textAlign": "Text Align",
"textPanel.tracking": "Tracking",
"textPanel.typography": "Typography",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Uppercase",
"textPanel.useForNewTitles": "Use for new titles",
"textPanel.vertical": "Vertical",
+ "textPanel.wholeTitle": "Whole title",
"timeline.deleteTrackClips": "This track and the {0} clips on it will be deleted. You can undo this.",
"timeline.deleteTrackEmpty": "This empty track will be deleted. You can undo this.",
"timeline.deleteTrackOneClip": "This track and the clip on it will be deleted. You can undo this.",
diff --git a/src/crates/concat/locales/es.json b/src/crates/concat/locales/es.json
index 554ab624..e15761bd 100644
--- a/src/crates/concat/locales/es.json
+++ b/src/crates/concat/locales/es.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Relleno",
"textPanel.position": "Posición",
"textPanel.regular": "Regular",
+ "textPanel.resetWords": "Restablecer",
"textPanel.searchFonts": "Buscar fuentes",
"textPanel.semibold": "Seminegrita",
"textPanel.sentenceCase": "Tipo oración",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Tachado",
"textPanel.stroke": "Trazo",
"textPanel.style": "Estilo",
+ "textPanel.stylingTitle": "Estilo para todo el título. Selecciona palabras arriba para dar estilo solo a esas.",
+ "textPanel.stylingWords": "Estilo para las palabras seleccionadas",
"textPanel.textAlign": "Alineación del texto",
"textPanel.tracking": "Espaciado",
"textPanel.typography": "Tipografía",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Mayúsculas",
"textPanel.useForNewTitles": "Usar para títulos nuevos",
"textPanel.vertical": "Vertical",
+ "textPanel.wholeTitle": "Todo el título",
"timeline.deleteTrackClips": "Se eliminarán esta pista y los {0} clips que contiene. Puedes deshacerlo.",
"timeline.deleteTrackEmpty": "Se eliminará esta pista vacía. Puedes deshacerlo.",
"timeline.deleteTrackOneClip": "Se eliminarán esta pista y el clip que contiene. Puedes deshacerlo.",
diff --git a/src/crates/concat/locales/fa.json b/src/crates/concat/locales/fa.json
index 07d93aba..21cb319b 100644
--- a/src/crates/concat/locales/fa.json
+++ b/src/crates/concat/locales/fa.json
@@ -813,6 +813,7 @@
"textPanel.padding": "حاشیهٔ داخلی",
"textPanel.position": "موقعیت",
"textPanel.regular": "معمولی",
+ "textPanel.resetWords": "بازنشانی",
"textPanel.searchFonts": "جستجوی فونت‌ها",
"textPanel.semibold": "نیمه‌پررنگ",
"textPanel.sentenceCase": "حالت جمله",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "خط‌خورده",
"textPanel.stroke": "خط دور",
"textPanel.style": "سبک",
+ "textPanel.stylingTitle": "سبک‌دهی به کل عنوان. برای سبک‌دهی فقط به چند واژه، آن‌ها را در بالا انتخاب کنید.",
+ "textPanel.stylingWords": "سبک‌دهی به واژه‌های انتخاب‌شده",
"textPanel.textAlign": "تراز متن",
"textPanel.tracking": "ردیابی (Tracking)",
"textPanel.typography": "تایپوگرافی",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "حروف بزرگ",
"textPanel.useForNewTitles": "استفاده برای عنوان‌های جدید",
"textPanel.vertical": "عمودی",
+ "textPanel.wholeTitle": "کل عنوان",
"timeline.deleteTrackClips": "این ترک و {0} کلیپ روی آن حذف می‌شوند. می‌توانید آن را برگردانید.",
"timeline.deleteTrackEmpty": "این ترک خالی حذف می‌شود. می‌توانید آن را برگردانید.",
"timeline.deleteTrackOneClip": "این ترک و کلیپ روی آن حذف می‌شوند. می‌توانید آن را برگردانید.",
diff --git a/src/crates/concat/locales/fr.json b/src/crates/concat/locales/fr.json
index c7fff4d7..6ae82f92 100644
--- a/src/crates/concat/locales/fr.json
+++ b/src/crates/concat/locales/fr.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Marge intérieure",
"textPanel.position": "Position",
"textPanel.regular": "Normal",
+ "textPanel.resetWords": "Réinitialiser",
"textPanel.searchFonts": "Rechercher des polices",
"textPanel.semibold": "Demi-gras",
"textPanel.sentenceCase": "Casse de phrase",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Barré",
"textPanel.stroke": "Trait",
"textPanel.style": "Style",
+ "textPanel.stylingTitle": "Mise en forme de tout le titre. Sélectionnez des mots ci-dessus pour ne mettre en forme qu’eux.",
+ "textPanel.stylingWords": "Mise en forme des mots sélectionnés",
"textPanel.textAlign": "Alignement du texte",
"textPanel.tracking": "Approche",
"textPanel.typography": "Typographie",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Majuscules",
"textPanel.useForNewTitles": "Utiliser pour les nouveaux titres",
"textPanel.vertical": "Vertical",
+ "textPanel.wholeTitle": "Tout le titre",
"timeline.deleteTrackClips": "Cette piste et les {0} clips qu'elle contient seront supprimés. Vous pourrez l'annuler.",
"timeline.deleteTrackEmpty": "Cette piste vide sera supprimée. Vous pourrez l'annuler.",
"timeline.deleteTrackOneClip": "Cette piste et le clip qu'elle contient seront supprimés. Vous pourrez l'annuler.",
diff --git a/src/crates/concat/locales/he.json b/src/crates/concat/locales/he.json
index 1d76acab..d72e6404 100644
--- a/src/crates/concat/locales/he.json
+++ b/src/crates/concat/locales/he.json
@@ -813,6 +813,7 @@
"textPanel.padding": "ריפוד",
"textPanel.position": "מיקום",
"textPanel.regular": "רגיל",
+ "textPanel.resetWords": "איפוס",
"textPanel.searchFonts": "חיפוש גופנים",
"textPanel.semibold": "מודגש למחצה",
"textPanel.sentenceCase": "רישיות משפט",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "קו חוצה",
"textPanel.stroke": "קו מתאר",
"textPanel.style": "סגנון",
+ "textPanel.stylingTitle": "מעצב את כל הכותרת. בחרו מילים למעלה כדי לעצב רק אותן.",
+ "textPanel.stylingWords": "מעצב את המילים שנבחרו",
"textPanel.textAlign": "יישור טקסט",
"textPanel.tracking": "ריווח אותיות",
"textPanel.typography": "טיפוגרפיה",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "אותיות גדולות",
"textPanel.useForNewTitles": "שימוש לכותרות חדשות",
"textPanel.vertical": "אנכי",
+ "textPanel.wholeTitle": "כל הכותרת",
"timeline.deleteTrackClips": "הערוץ הזה ו-{0} הקליפים שבו יימחקו. אפשר לבטל את הפעולה.",
"timeline.deleteTrackEmpty": "הערוץ הריק הזה יימחק. אפשר לבטל את הפעולה.",
"timeline.deleteTrackOneClip": "הערוץ הזה והקליפ שבו יימחקו. אפשר לבטל את הפעולה.",
diff --git a/src/crates/concat/locales/hi.json b/src/crates/concat/locales/hi.json
index 3db6310c..035446db 100644
--- a/src/crates/concat/locales/hi.json
+++ b/src/crates/concat/locales/hi.json
@@ -813,6 +813,7 @@
"textPanel.padding": "पैडिंग",
"textPanel.position": "स्थिति",
"textPanel.regular": "सामान्य",
+ "textPanel.resetWords": "रीसेट",
"textPanel.searchFonts": "फ़ॉन्ट खोजें",
"textPanel.semibold": "सेमीबोल्ड",
"textPanel.sentenceCase": "वाक्य केस",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "काटा हुआ",
"textPanel.stroke": "आउटलाइन",
"textPanel.style": "शैली",
+ "textPanel.stylingTitle": "पूरे शीर्षक को स्टाइल किया जा रहा है। सिर्फ़ कुछ शब्दों के लिए ऊपर उन्हें चुनें।",
+ "textPanel.stylingWords": "चुने हुए शब्दों को स्टाइल किया जा रहा है",
"textPanel.textAlign": "टेक्स्ट संरेखण",
"textPanel.tracking": "अक्षर अंतराल",
"textPanel.typography": "टाइपोग्राफ़ी",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "बड़े अक्षर",
"textPanel.useForNewTitles": "नए टाइटल के लिए इस्तेमाल करें",
"textPanel.vertical": "लंबवत",
+ "textPanel.wholeTitle": "पूरा शीर्षक",
"timeline.deleteTrackClips": "यह ट्रैक और इस पर मौजूद {0} क्लिप मिटा दी जाएंगी। आप इसे पहले जैसा कर सकते हैं।",
"timeline.deleteTrackEmpty": "यह खाली ट्रैक मिटा दिया जाएगा। आप इसे पहले जैसा कर सकते हैं।",
"timeline.deleteTrackOneClip": "यह ट्रैक और इस पर मौजूद क्लिप मिटा दी जाएगी। आप इसे पहले जैसा कर सकते हैं।",
diff --git a/src/crates/concat/locales/hr.json b/src/crates/concat/locales/hr.json
index ac2fc8cd..1d2c1362 100644
--- a/src/crates/concat/locales/hr.json
+++ b/src/crates/concat/locales/hr.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Unutarnji razmak",
"textPanel.position": "Položaj",
"textPanel.regular": "Obično",
+ "textPanel.resetWords": "Vrati",
"textPanel.searchFonts": "Pretraži fontove",
"textPanel.semibold": "Polupodebljano",
"textPanel.sentenceCase": "Kao u rečenici",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Precrtano",
"textPanel.stroke": "Potez",
"textPanel.style": "Stil",
+ "textPanel.stylingTitle": "Uređuje se izgled cijelog naslova. Odaberite riječi gore za uređivanje samo njih.",
+ "textPanel.stylingWords": "Uređuje se izgled odabranih riječi",
"textPanel.textAlign": "Poravnanje teksta",
"textPanel.tracking": "Praćenje",
"textPanel.typography": "Tipografija",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Velika slova",
"textPanel.useForNewTitles": "Koristi za nove naslove",
"textPanel.vertical": "Okomito",
+ "textPanel.wholeTitle": "Cijeli naslov",
"timeline.deleteTrackClips": "Ova traka i isječci na njoj ({0}) bit će izbrisani. To možeš poništiti.",
"timeline.deleteTrackEmpty": "Ova prazna traka bit će izbrisana. To možeš poništiti.",
"timeline.deleteTrackOneClip": "Ova traka i isječak na njoj bit će izbrisani. To možeš poništiti.",
diff --git a/src/crates/concat/locales/id.json b/src/crates/concat/locales/id.json
index ea0cb304..cbb4ff7c 100644
--- a/src/crates/concat/locales/id.json
+++ b/src/crates/concat/locales/id.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Jarak tepi",
"textPanel.position": "Posisi",
"textPanel.regular": "Reguler",
+ "textPanel.resetWords": "Atur ulang",
"textPanel.searchFonts": "Cari font",
"textPanel.semibold": "Semi Tebal",
"textPanel.sentenceCase": "Huruf kalimat",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Coret",
"textPanel.stroke": "Garis tepi",
"textPanel.style": "Gaya",
+ "textPanel.stylingTitle": "Menata seluruh judul. Pilih kata di atas untuk menata kata itu saja.",
+ "textPanel.stylingWords": "Menata kata yang dipilih",
"textPanel.textAlign": "Perataan Teks",
"textPanel.tracking": "Spasi huruf",
"textPanel.typography": "Tipografi",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Huruf besar",
"textPanel.useForNewTitles": "Gunakan untuk judul baru",
"textPanel.vertical": "Tegak",
+ "textPanel.wholeTitle": "Seluruh judul",
"timeline.deleteTrackClips": "Trek ini beserta {0} klip di dalamnya akan dihapus. Anda dapat mengurungkannya.",
"timeline.deleteTrackEmpty": "Trek kosong ini akan dihapus. Anda dapat mengurungkannya.",
"timeline.deleteTrackOneClip": "Trek ini beserta klip di dalamnya akan dihapus. Anda dapat mengurungkannya.",
diff --git a/src/crates/concat/locales/it.json b/src/crates/concat/locales/it.json
index c2bd66d2..f75f34ac 100644
--- a/src/crates/concat/locales/it.json
+++ b/src/crates/concat/locales/it.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Spaziatura interna",
"textPanel.position": "Posizione",
"textPanel.regular": "Normale",
+ "textPanel.resetWords": "Ripristina",
"textPanel.searchFonts": "Cerca font",
"textPanel.semibold": "Semigrassetto",
"textPanel.sentenceCase": "Iniziale della frase",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Barrato",
"textPanel.stroke": "Tratto",
"textPanel.style": "Stile",
+ "textPanel.stylingTitle": "Stile di tutto il titolo. Seleziona delle parole qui sopra per dare stile solo a quelle.",
+ "textPanel.stylingWords": "Stile delle parole selezionate",
"textPanel.textAlign": "Allineamento del testo",
"textPanel.tracking": "Spaziatura",
"textPanel.typography": "Tipografia",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Maiuscolo",
"textPanel.useForNewTitles": "Usa per i nuovi titoli",
"textPanel.vertical": "Verticale",
+ "textPanel.wholeTitle": "Tutto il titolo",
"timeline.deleteTrackClips": "Questa traccia e le {0} clip che contiene verranno eliminate. Puoi annullare.",
"timeline.deleteTrackEmpty": "Questa traccia vuota verrà eliminata. Puoi annullare.",
"timeline.deleteTrackOneClip": "Questa traccia e la clip che contiene verranno eliminate. Puoi annullare.",
diff --git a/src/crates/concat/locales/ja.json b/src/crates/concat/locales/ja.json
index f745def8..e87af22c 100644
--- a/src/crates/concat/locales/ja.json
+++ b/src/crates/concat/locales/ja.json
@@ -813,6 +813,7 @@
"textPanel.padding": "余白",
"textPanel.position": "位置",
"textPanel.regular": "標準",
+ "textPanel.resetWords": "リセット",
"textPanel.searchFonts": "フォントを検索",
"textPanel.semibold": "セミボールド",
"textPanel.sentenceCase": "文頭のみ大文字",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "取り消し線",
"textPanel.stroke": "ストローク",
"textPanel.style": "スタイル",
+ "textPanel.stylingTitle": "タイトル全体にスタイルを適用中。上で語を選ぶと、その語だけに適用できます。",
+ "textPanel.stylingWords": "選択した語にスタイルを適用中",
"textPanel.textAlign": "テキストの配置",
"textPanel.tracking": "字間",
"textPanel.typography": "タイポグラフィ",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "大文字",
"textPanel.useForNewTitles": "新しいタイトルに使う",
"textPanel.vertical": "垂直",
+ "textPanel.wholeTitle": "タイトル全体",
"timeline.deleteTrackClips": "このトラックと、その上の {0} 個のクリップを削除します。元に戻すことができます。",
"timeline.deleteTrackEmpty": "この空のトラックを削除します。元に戻すことができます。",
"timeline.deleteTrackOneClip": "このトラックと、その上のクリップを削除します。元に戻すことができます。",
diff --git a/src/crates/concat/locales/ko.json b/src/crates/concat/locales/ko.json
index ded2b6df..4e4bd78d 100644
--- a/src/crates/concat/locales/ko.json
+++ b/src/crates/concat/locales/ko.json
@@ -813,6 +813,7 @@
"textPanel.padding": "여백",
"textPanel.position": "위치",
"textPanel.regular": "보통",
+ "textPanel.resetWords": "초기화",
"textPanel.searchFonts": "글꼴 검색",
"textPanel.semibold": "세미볼드",
"textPanel.sentenceCase": "문장 첫 글자 대문자",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "취소선",
"textPanel.stroke": "외곽선",
"textPanel.style": "스타일",
+ "textPanel.stylingTitle": "제목 전체에 스타일 적용 중. 위에서 단어를 선택하면 그 단어에만 적용됩니다.",
+ "textPanel.stylingWords": "선택한 단어에 스타일 적용 중",
"textPanel.textAlign": "텍스트 정렬",
"textPanel.tracking": "자간",
"textPanel.typography": "타이포그래피",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "대문자",
"textPanel.useForNewTitles": "새 제목에 사용",
"textPanel.vertical": "세로",
+ "textPanel.wholeTitle": "제목 전체",
"timeline.deleteTrackClips": "이 트랙과 그 위의 클립 {0}개가 삭제됩니다. 실행 취소할 수 있습니다.",
"timeline.deleteTrackEmpty": "이 빈 트랙이 삭제됩니다. 실행 취소할 수 있습니다.",
"timeline.deleteTrackOneClip": "이 트랙과 그 위의 클립이 삭제됩니다. 실행 취소할 수 있습니다.",
diff --git a/src/crates/concat/locales/nl.json b/src/crates/concat/locales/nl.json
index a44a29d2..74201189 100644
--- a/src/crates/concat/locales/nl.json
+++ b/src/crates/concat/locales/nl.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Opvulling",
"textPanel.position": "Positie",
"textPanel.regular": "Normaal",
+ "textPanel.resetWords": "Herstellen",
"textPanel.searchFonts": "Lettertypen zoeken",
"textPanel.semibold": "Halfvet",
"textPanel.sentenceCase": "Als in een zin",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Doorhalen",
"textPanel.stroke": "Omlijning",
"textPanel.style": "Stijl",
+ "textPanel.stylingTitle": "Stijl voor de hele titel. Selecteer hierboven woorden om alleen die op te maken.",
+ "textPanel.stylingWords": "Stijl voor de geselecteerde woorden",
"textPanel.textAlign": "Tekstuitlijning",
"textPanel.tracking": "Spatiëring",
"textPanel.typography": "Typografie",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Hoofdletters",
"textPanel.useForNewTitles": "Gebruiken voor nieuwe titels",
"textPanel.vertical": "Verticaal",
+ "textPanel.wholeTitle": "Hele titel",
"timeline.deleteTrackClips": "Dit spoor en de clips erop ({0}) worden verwijderd. Je kunt dit ongedaan maken.",
"timeline.deleteTrackEmpty": "Dit lege spoor wordt verwijderd. Je kunt dit ongedaan maken.",
"timeline.deleteTrackOneClip": "Dit spoor en de clip erop worden verwijderd. Je kunt dit ongedaan maken.",
diff --git a/src/crates/concat/locales/pl.json b/src/crates/concat/locales/pl.json
index fe79ac11..a825650e 100644
--- a/src/crates/concat/locales/pl.json
+++ b/src/crates/concat/locales/pl.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Margines wewnętrzny",
"textPanel.position": "Położenie",
"textPanel.regular": "Zwykła",
+ "textPanel.resetWords": "Resetuj",
"textPanel.searchFonts": "Szukaj czcionek",
"textPanel.semibold": "Półgruba",
"textPanel.sentenceCase": "Jak w zdaniu",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Przekreślenie",
"textPanel.stroke": "Obrys",
"textPanel.style": "Styl",
+ "textPanel.stylingTitle": "Styl całego tytułu. Zaznacz słowa powyżej, aby zmienić tylko je.",
+ "textPanel.stylingWords": "Styl zaznaczonych słów",
"textPanel.textAlign": "Wyrównanie tekstu",
"textPanel.tracking": "Światło między znakami",
"textPanel.typography": "Typografia",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Wielkie litery",
"textPanel.useForNewTitles": "Użyj dla nowych tytułów",
"textPanel.vertical": "W pionie",
+ "textPanel.wholeTitle": "Cały tytuł",
"timeline.deleteTrackClips": "Ta ścieżka i znajdujące się na niej klipy ({0}) zostaną usunięte. Możesz to cofnąć.",
"timeline.deleteTrackEmpty": "Ta pusta ścieżka zostanie usunięta. Możesz to cofnąć.",
"timeline.deleteTrackOneClip": "Ta ścieżka i klip na niej zostaną usunięte. Możesz to cofnąć.",
diff --git a/src/crates/concat/locales/pt-BR.json b/src/crates/concat/locales/pt-BR.json
index d7154275..12d7ffcf 100644
--- a/src/crates/concat/locales/pt-BR.json
+++ b/src/crates/concat/locales/pt-BR.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Preenchimento",
"textPanel.position": "Posição",
"textPanel.regular": "Normal",
+ "textPanel.resetWords": "Redefinir",
"textPanel.searchFonts": "Buscar fontes",
"textPanel.semibold": "Seminegrito",
"textPanel.sentenceCase": "Tipo frase",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Tachado",
"textPanel.stroke": "Traço",
"textPanel.style": "Estilo",
+ "textPanel.stylingTitle": "Estilizando o título inteiro. Selecione palavras acima para estilizar só elas.",
+ "textPanel.stylingWords": "Estilizando as palavras selecionadas",
"textPanel.textAlign": "Alinhamento do texto",
"textPanel.tracking": "Espaçamento",
"textPanel.typography": "Tipografia",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Maiúsculas",
"textPanel.useForNewTitles": "Usar em novos títulos",
"textPanel.vertical": "Vertical",
+ "textPanel.wholeTitle": "Título inteiro",
"timeline.deleteTrackClips": "Esta faixa e os {0} clipes nela serão excluídos. Você pode desfazer isso.",
"timeline.deleteTrackEmpty": "Esta faixa vazia será excluída. Você pode desfazer isso.",
"timeline.deleteTrackOneClip": "Esta faixa e o clipe nela serão excluídos. Você pode desfazer isso.",
diff --git a/src/crates/concat/locales/ru.json b/src/crates/concat/locales/ru.json
index 87f50d91..4d65e10a 100644
--- a/src/crates/concat/locales/ru.json
+++ b/src/crates/concat/locales/ru.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Отступы",
"textPanel.position": "Положение",
"textPanel.regular": "Обычный",
+ "textPanel.resetWords": "Сбросить",
"textPanel.searchFonts": "Поиск шрифтов",
"textPanel.semibold": "Полужирный",
"textPanel.sentenceCase": "Как в предложениях",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Зачёркнутый",
"textPanel.stroke": "Обводка",
"textPanel.style": "Стиль",
+ "textPanel.stylingTitle": "Оформляется весь заголовок. Выделите слова выше, чтобы оформить только их.",
+ "textPanel.stylingWords": "Оформляются выделенные слова",
"textPanel.textAlign": "Выравнивание текста",
"textPanel.tracking": "Трекинг",
"textPanel.typography": "Типографика",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Все прописные",
"textPanel.useForNewTitles": "Использовать для новых титров",
"textPanel.vertical": "По вертикали",
+ "textPanel.wholeTitle": "Весь заголовок",
"timeline.deleteTrackClips": "Эта дорожка и клипы на ней ({0}) будут удалены. Это можно отменить.",
"timeline.deleteTrackEmpty": "Эта пустая дорожка будет удалена. Это можно отменить.",
"timeline.deleteTrackOneClip": "Эта дорожка и клип на ней будут удалены. Это можно отменить.",
diff --git a/src/crates/concat/locales/th.json b/src/crates/concat/locales/th.json
index e6678282..9e16f522 100644
--- a/src/crates/concat/locales/th.json
+++ b/src/crates/concat/locales/th.json
@@ -813,6 +813,7 @@
"textPanel.padding": "ระยะขอบใน",
"textPanel.position": "ตำแหน่ง",
"textPanel.regular": "ปกติ",
+ "textPanel.resetWords": "รีเซ็ต",
"textPanel.searchFonts": "ค้นหาฟอนต์",
"textPanel.semibold": "กึ่งหนา",
"textPanel.sentenceCase": "แบบประโยค",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "ขีดทับ",
"textPanel.stroke": "เส้นขอบ",
"textPanel.style": "สไตล์",
+ "textPanel.stylingTitle": "กำลังจัดรูปแบบทั้งชื่อเรื่อง เลือกคำด้านบนเพื่อจัดรูปแบบเฉพาะคำนั้น",
+ "textPanel.stylingWords": "กำลังจัดรูปแบบคำที่เลือก",
"textPanel.textAlign": "การจัดแนวข้อความ",
"textPanel.tracking": "ระยะห่างตัวอักษร",
"textPanel.typography": "ตัวอักษร",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "ตัวพิมพ์ใหญ่",
"textPanel.useForNewTitles": "ใช้กับไตเติลใหม่",
"textPanel.vertical": "แนวตั้ง",
+ "textPanel.wholeTitle": "ทั้งชื่อเรื่อง",
"timeline.deleteTrackClips": "แทร็กนี้และคลิป {0} คลิปในแทร็กจะถูกลบ คุณเลิกทำได้",
"timeline.deleteTrackEmpty": "แทร็กว่างนี้จะถูกลบ คุณเลิกทำได้",
"timeline.deleteTrackOneClip": "แทร็กนี้และคลิปในแทร็กจะถูกลบ คุณเลิกทำได้",
diff --git a/src/crates/concat/locales/tr.json b/src/crates/concat/locales/tr.json
index 83edae35..c4d9d856 100644
--- a/src/crates/concat/locales/tr.json
+++ b/src/crates/concat/locales/tr.json
@@ -813,6 +813,7 @@
"textPanel.padding": "İç boşluk",
"textPanel.position": "Konum",
"textPanel.regular": "Normal",
+ "textPanel.resetWords": "Sıfırla",
"textPanel.searchFonts": "Yazı tipi ara",
"textPanel.semibold": "Yarı kalın",
"textPanel.sentenceCase": "Cümle düzeni",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Üstü çizili",
"textPanel.stroke": "Kontur",
"textPanel.style": "Stil",
+ "textPanel.stylingTitle": "Başlığın tamamına stil veriliyor. Yalnızca onlara stil vermek için yukarıda sözcük seçin.",
+ "textPanel.stylingWords": "Seçili sözcüklere stil veriliyor",
"textPanel.textAlign": "Metin hizalama",
"textPanel.tracking": "Harf aralığı",
"textPanel.typography": "Tipografi",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Büyük harf",
"textPanel.useForNewTitles": "Yeni başlıklar için kullan",
"textPanel.vertical": "Dikey",
+ "textPanel.wholeTitle": "Tüm başlık",
"timeline.deleteTrackClips": "Bu parça ve üzerindeki {0} klip silinecek. Bunu geri alabilirsiniz.",
"timeline.deleteTrackEmpty": "Bu boş parça silinecek. Bunu geri alabilirsiniz.",
"timeline.deleteTrackOneClip": "Bu parça ve üzerindeki klip silinecek. Bunu geri alabilirsiniz.",
diff --git a/src/crates/concat/locales/uk.json b/src/crates/concat/locales/uk.json
index 5fe7330e..dbdb3526 100644
--- a/src/crates/concat/locales/uk.json
+++ b/src/crates/concat/locales/uk.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Відступ",
"textPanel.position": "Позиція",
"textPanel.regular": "Звичайний",
+ "textPanel.resetWords": "Скинути",
"textPanel.searchFonts": "Пошук шрифтів",
"textPanel.semibold": "Напівжирний",
"textPanel.sentenceCase": "Як у реченні",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Закреслений",
"textPanel.stroke": "Контур",
"textPanel.style": "Стиль",
+ "textPanel.stylingTitle": "Оформлюється весь заголовок. Виділіть слова вище, щоб оформити лише їх.",
+ "textPanel.stylingWords": "Оформлюються виділені слова",
"textPanel.textAlign": "Вирівнювання тексту",
"textPanel.tracking": "Трекінг",
"textPanel.typography": "Типографіка",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Усі великі",
"textPanel.useForNewTitles": "Використовувати для нових титрів",
"textPanel.vertical": "По вертикалі",
+ "textPanel.wholeTitle": "Увесь заголовок",
"timeline.deleteTrackClips": "Цю доріжку й кліпи на ній ({0}) буде видалено. Цю дію можна скасувати.",
"timeline.deleteTrackEmpty": "Цю порожню доріжку буде видалено. Цю дію можна скасувати.",
"timeline.deleteTrackOneClip": "Цю доріжку й кліп на ній буде видалено. Цю дію можна скасувати.",
diff --git a/src/crates/concat/locales/ur.json b/src/crates/concat/locales/ur.json
index 6b28118f..70c38ae5 100644
--- a/src/crates/concat/locales/ur.json
+++ b/src/crates/concat/locales/ur.json
@@ -813,6 +813,7 @@
"textPanel.padding": "پیڈنگ",
"textPanel.position": "پوزیشن",
"textPanel.regular": "عام",
+ "textPanel.resetWords": "ری سیٹ",
"textPanel.searchFonts": "فونٹس تلاش کریں",
"textPanel.semibold": "نیم بولڈ",
"textPanel.sentenceCase": "جملے کی حالت",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "قلم زد",
"textPanel.stroke": "اسٹروک",
"textPanel.style": "انداز",
+ "textPanel.stylingTitle": "پورے عنوان کا انداز بدلا جا رہا ہے۔ صرف کچھ الفاظ کے لیے اوپر انہیں منتخب کریں۔",
+ "textPanel.stylingWords": "منتخب الفاظ کا انداز بدلا جا رہا ہے",
"textPanel.textAlign": "متن کی سیدھ",
"textPanel.tracking": "حروف کا فاصلہ",
"textPanel.typography": "ٹائپوگرافی",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "بڑے حروف",
"textPanel.useForNewTitles": "نئے ٹائٹلز کے لیے استعمال کریں",
"textPanel.vertical": "عمودی",
+ "textPanel.wholeTitle": "پورا عنوان",
"timeline.deleteTrackClips": "یہ ٹریک اور اس پر موجود {0} کلپس حذف ہو جائیں گے۔ آپ اسے واپس لے سکتے ہیں۔",
"timeline.deleteTrackEmpty": "یہ خالی ٹریک حذف ہو جائے گا۔ آپ اسے واپس لے سکتے ہیں۔",
"timeline.deleteTrackOneClip": "یہ ٹریک اور اس پر موجود کلپ حذف ہو جائیں گے۔ آپ اسے واپس لے سکتے ہیں۔",
diff --git a/src/crates/concat/locales/vi.json b/src/crates/concat/locales/vi.json
index 6e450de9..64b274c6 100644
--- a/src/crates/concat/locales/vi.json
+++ b/src/crates/concat/locales/vi.json
@@ -813,6 +813,7 @@
"textPanel.padding": "Lề đệm",
"textPanel.position": "Vị trí",
"textPanel.regular": "Thông thường",
+ "textPanel.resetWords": "Đặt lại",
"textPanel.searchFonts": "Tìm phông chữ",
"textPanel.semibold": "Bán đậm",
"textPanel.sentenceCase": "Kiểu câu",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "Gạch ngang",
"textPanel.stroke": "Viền chữ",
"textPanel.style": "Kiểu",
+ "textPanel.stylingTitle": "Đang tạo kiểu cho cả tiêu đề. Chọn từ ở trên để chỉ tạo kiểu cho những từ đó.",
+ "textPanel.stylingWords": "Đang tạo kiểu cho các từ đã chọn",
"textPanel.textAlign": "Căn chỉnh văn bản",
"textPanel.tracking": "Giãn cách ký tự",
"textPanel.typography": "Kiểu chữ",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "Chữ hoa",
"textPanel.useForNewTitles": "Dùng cho tiêu đề mới",
"textPanel.vertical": "Dọc",
+ "textPanel.wholeTitle": "Cả tiêu đề",
"timeline.deleteTrackClips": "Đường này và {0} clip trên đó sẽ bị xóa. Bạn có thể hoàn tác.",
"timeline.deleteTrackEmpty": "Đường trống này sẽ bị xóa. Bạn có thể hoàn tác.",
"timeline.deleteTrackOneClip": "Đường này và clip trên đó sẽ bị xóa. Bạn có thể hoàn tác.",
diff --git a/src/crates/concat/locales/zh-Hans.json b/src/crates/concat/locales/zh-Hans.json
index 3e9adc70..08721e95 100644
--- a/src/crates/concat/locales/zh-Hans.json
+++ b/src/crates/concat/locales/zh-Hans.json
@@ -813,6 +813,7 @@
"textPanel.padding": "内边距",
"textPanel.position": "位置",
"textPanel.regular": "常规",
+ "textPanel.resetWords": "重置",
"textPanel.searchFonts": "搜索字体",
"textPanel.semibold": "半粗体",
"textPanel.sentenceCase": "句首大写",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "删除线",
"textPanel.stroke": "描边",
"textPanel.style": "样式",
+ "textPanel.stylingTitle": "正在设置整个标题的样式。在上方选中文字,即可只设置这些文字。",
+ "textPanel.stylingWords": "正在设置所选文字的样式",
"textPanel.textAlign": "文本对齐",
"textPanel.tracking": "字距",
"textPanel.typography": "文字排版",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "大写",
"textPanel.useForNewTitles": "用于新标题",
"textPanel.vertical": "竖屏",
+ "textPanel.wholeTitle": "整个标题",
"timeline.deleteTrackClips": "这条轨道及其上的 {0} 个片段将被删除。你可以撤销此操作。",
"timeline.deleteTrackEmpty": "这条空轨道将被删除。你可以撤销此操作。",
"timeline.deleteTrackOneClip": "这条轨道及其上的片段将被删除。你可以撤销此操作。",
diff --git a/src/crates/concat/locales/zh-TW.json b/src/crates/concat/locales/zh-TW.json
index 3fd9ab9e..eea53067 100644
--- a/src/crates/concat/locales/zh-TW.json
+++ b/src/crates/concat/locales/zh-TW.json
@@ -813,6 +813,7 @@
"textPanel.padding": "內邊距",
"textPanel.position": "位置",
"textPanel.regular": "標準",
+ "textPanel.resetWords": "重設",
"textPanel.searchFonts": "搜尋字型",
"textPanel.semibold": "半粗體",
"textPanel.sentenceCase": "句首大寫",
@@ -821,6 +822,8 @@
"textPanel.strikethrough": "刪除線",
"textPanel.stroke": "描邊",
"textPanel.style": "樣式",
+ "textPanel.stylingTitle": "正在設定整個標題的樣式。在上方選取文字,即可只設定這些文字。",
+ "textPanel.stylingWords": "正在設定所選文字的樣式",
"textPanel.textAlign": "文字對齊",
"textPanel.tracking": "字距",
"textPanel.typography": "文字排版",
@@ -829,6 +832,7 @@
"textPanel.uppercase": "大寫",
"textPanel.useForNewTitles": "用於新標題",
"textPanel.vertical": "垂直",
+ "textPanel.wholeTitle": "整個標題",
"timeline.deleteTrackClips": "這條軌道及其上的 {0} 個片段將被刪除。你可以復原此操作。",
"timeline.deleteTrackEmpty": "這條空軌道將被刪除。你可以復原此操作。",
"timeline.deleteTrackOneClip": "這條軌道及其上的片段將被刪除。你可以復原此操作。",
diff --git a/src/crates/concat/src/lib.rs b/src/crates/concat/src/lib.rs
index 5dc9c591..38c97aed 100644
--- a/src/crates/concat/src/lib.rs
+++ b/src/crates/concat/src/lib.rs
@@ -1328,6 +1328,15 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
state.clip_set_text(field, value.as_str());
}
));
+ editor.on_clip_set_words(on_lanes!(|state, text: SharedString, caret: i32| {
+ state.clip_set_words(text.as_str(), caret);
+ }));
+ editor.on_clip_select_words(on_lanes!(|state, anchor: i32, cursor: i32| {
+ state.select_words(anchor, cursor);
+ }));
+ editor.on_clip_reset_words(on_lanes!(|state| {
+ state.reset_words();
+ }));
editor.on_clip_set_colour(on_lanes!(
|state, field: ClipTextField, value: slint::Color| {
state.clip_set_colour(field, value);
diff --git a/src/crates/concat/src/panes/captions.rs b/src/crates/concat/src/panes/captions.rs
index f05344c7..734febc1 100644
--- a/src/crates/concat/src/panes/captions.rs
+++ b/src/crates/concat/src/panes/captions.rs
@@ -754,6 +754,8 @@ fn caption_clip(
font_size,
max_width: 0.0,
max_height: 0.0,
+ // Runs are some words' looks, and these are other words.
+ runs: Vec::new(),
..base.clone()
},
None => TextStyle {
diff --git a/src/crates/concat/src/presets.rs b/src/crates/concat/src/presets.rs
index 28840a44..e09d1a68 100644
--- a/src/crates/concat/src/presets.rs
+++ b/src/crates/concat/src/presets.rs
@@ -29,6 +29,12 @@
//! strokeColor = "#000000"
//! strokeWidth = 0.01
//! align = "center"
+//!
+//! [[style.runs]] # optional: some words in a look of their own,
+//! start = 0 # counted in characters of `content`
+//! end = 3
+//! color = "#ffd400" # and any of fontWeight, italic, underline,
+//! # strikethrough, fontScale, strokeColor
//! ```
//!
//! The font is installed when the preset is first used, not when it is
@@ -113,12 +119,14 @@ struct PresetStyle {
tracking: Option<f64>,
max_width: Option<f64>,
max_height: Option<f64>,
+ /// Some of the words in a look of their own; see `TextStyle::runs`.
+ runs: Option<Vec<concat_project::model::TextRun>>,
}
impl PresetStyle {
fn over(self, name: &str) -> TextStyle {
let base = TextStyle::default();
- TextStyle {
+ let mut style = TextStyle {
content: self.content.unwrap_or_else(|| name.to_owned()),
font_family: self
.font_family
@@ -159,7 +167,12 @@ impl PresetStyle {
tracking: self.tracking.unwrap_or(0.0),
max_width: self.max_width.unwrap_or(0.0).max(0.0),
max_height: self.max_height.unwrap_or(0.0).max(0.0),
- }
+ runs: self.runs.unwrap_or_default(),
+ };
+ // A hand-written run past the words, or on top of another, comes
+ // out in the shape the editor keeps them in.
+ style.tidy_runs();
+ style
}
}
@@ -392,5 +405,35 @@ mod tests {
assert_eq!(style.content, "Red");
assert_eq!(style.font_weight, TextStyle::default().font_weight);
assert_eq!(file.offset_y, Some(0.3));
+ assert!(style.runs.is_empty());
+ }
+
+ /// A preset can give some of its words a look of their own, written
+ /// as a table per run; one that runs past the words is held to them.
+ #[test]
+ fn a_preset_carries_its_styled_words() {
+ let file: PresetFile = toml::from_str(
+ r##"
+ id = "t.breaking"
+ name = "Breaking"
+ [style]
+ content = "BREAKING news"
+ [[style.runs]]
+ start = 0
+ end = 8
+ color = "#ff0000"
+ fontWeight = 900
+ [[style.runs]]
+ start = 9
+ end = 99
+ italic = true
+ "##,
+ )
+ .expect("parses");
+ let style = file.style.over(&file.name);
+ assert_eq!(style.runs.len(), 2);
+ assert_eq!(style.runs[0].style.color.as_deref(), Some("#ff0000"));
+ assert_eq!(style.runs[0].style.font_weight, Some(900.0));
+ assert_eq!((style.runs[1].start, style.runs[1].end), (9, 13));
}
}
diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rs
index 375e3f23..01dccd52 100644
--- a/src/crates/concat/src/studio.rs
+++ b/src/crates/concat/src/studio.rs
@@ -976,6 +976,13 @@ pub struct Studio {
/// The clips the echo was written for; see `commit_now`. Several when
/// the inspector edits every selected title at once.
commit_targets: Vec<String>,
+ /// The words of the selected title that the Text tab's styling
+ /// controls are aimed at - (clip, start, end) in characters of its
+ /// content - while some are selected in its text box. None styles the
+ /// whole title, as the tab always did. Kept when the box loses focus,
+ /// since reaching for the colour swatch is what blurs it; read only
+ /// while that clip is still the one selected.
+ words: Option<(String, usize, usize)>,
commit_timer: slint::Timer,
/// What the catalogue shelves were last built from; while nothing in
/// it changes the shelves are not rebuilt.
@@ -1180,6 +1187,15 @@ fn align_of(align: TextAlign) -> TextAlignment {
}
}
+/// The character a byte offset falls at in `text`, as a text box counts
+/// its caret: bytes, where the document's runs count characters. An
+/// offset inside a character counts that character; one past the end or
+/// below zero is held to the text.
+fn char_at(text: &str, byte: i32) -> usize {
+ let byte = usize::try_from(byte).unwrap_or(0);
+ text.char_indices().take_while(|(at, _)| *at < byte).count()
+}
+
/// A title as it is first placed: the embedded face, centred, white.
fn new_title_style(prefs: &crate::prefs::Preferences) -> TextStyle {
// The look a title was kept as, when one was (see
@@ -1191,6 +1207,7 @@ fn new_title_style(prefs: &crate::prefs::Preferences) -> TextStyle {
});
TextStyle {
content: t("studio.newTitle"),
+ runs: Vec::new(),
..base
}
}
@@ -2402,6 +2419,7 @@ impl Studio {
flat: None,
commit_pending: false,
commit_targets: Vec::new(),
+ words: None,
commit_timer: slint::Timer::default(),
shelf_stamp: std::cell::RefCell::new(None),
look_art: std::cell::RefCell::new(HashMap::new()),
@@ -2866,6 +2884,7 @@ impl Studio {
pub fn undo(&mut self) {
self.flush_commit();
self.echo = None;
+ self.words = None;
if let Some(session) = self.session.as_mut()
&& session.can_undo()
{
@@ -2877,6 +2896,7 @@ impl Studio {
pub fn redo(&mut self) {
self.flush_commit();
self.echo = None;
+ self.words = None;
if let Some(session) = self.session.as_mut()
&& session.can_redo()
{
@@ -5289,6 +5309,14 @@ impl Studio {
/// One field of the selected clip, on the echo. `clip_commit` turns the
/// accumulated edits into commands.
pub fn clip_set(&mut self, field: ClipField, value: f32) {
+ // Some words selected in the text box: the typography they can
+ // wear goes on those words alone.
+ if let Some((id, start, end)) = self.styled_words()
+ && let Some(patch) = self.word_patch(&id, field, f64::from(value))
+ {
+ self.style_words(&id, start, end, &patch);
+ return;
+ }
let mut ids = self.edit_targets();
// A batch of sounds takes the level alone; see `batch_volume`.
let batch_volume = ids.is_empty() && field == ClipField::Volume;
@@ -5567,6 +5595,19 @@ impl Studio {
}
pub fn clip_set_text(&mut self, field: ClipTextField, value: &str) {
+ self.set_text_at(field, value, None);
+ }
+
+ /// The words typed into the Text tab's box, with where the caret ended
+ /// up - a byte into `value`, as the box counts - so a run beside the
+ /// edit knows whether the new letters are its own; see
+ /// `concat_project::runs`.
+ pub fn clip_set_words(&mut self, value: &str, caret: i32) {
+ let caret = (caret >= 0).then(|| char_at(value, caret));
+ self.set_text_at(ClipTextField::Content, value, caret);
+ }
+
+ fn set_text_at(&mut self, field: ClipTextField, value: &str, caret: Option<usize>) {
let ids = self.edit_targets();
if ids.is_empty() {
return;
@@ -5594,7 +5635,8 @@ impl Studio {
let text = clip.text.get_or_insert_with(TextStyle::default);
match field {
ClipTextField::Content => {
- text.content = value.to_owned();
+ // The runs ride along with the words they are on.
+ text.set_content(value.to_owned(), caret);
let first = value.lines().next().unwrap_or("").trim().to_owned();
clip.name = if first.is_empty() {
"Title".into()
@@ -5735,6 +5777,16 @@ impl Studio {
}
pub fn clip_set_colour(&mut self, field: ClipTextField, value: slint::Color) {
+ if field == ClipTextField::Color
+ && let Some((id, start, end)) = self.styled_words()
+ {
+ let patch = model::RunStyle {
+ color: Some(hex_of(value)),
+ ..model::RunStyle::default()
+ };
+ self.style_words(&id, start, end, &patch);
+ return;
+ }
let ids = self.edit_targets();
if ids.is_empty() {
return;
@@ -5758,6 +5810,97 @@ impl Studio {
}
}
+ // ── styled words ──
+ //
+ // A title is one look, and over it some of its words can wear their
+ // own: drag over them in the Text tab's box and the colour, B/I/U/S
+ // and size go on those words alone, the way After Effects recolours
+ // a dragged-over word. They are runs on the title's style, kept
+ // with the words as they are typed; see `concat_project::runs`.
+
+ /// The text box's selection, from the box: where its anchor and its
+ /// cursor are, as bytes into its words. A selection with nothing in it
+ /// - a caret - styles the whole title again.
+ pub fn select_words(&mut self, anchor: i32, cursor: i32) {
+ let Some(id) = self.sole_selection() else {
+ self.words = None;
+ return;
+ };
+ let Some(content) = self
+ .clip(&id)
+ .filter(|clip| clip.kind == model::ClipKind::Text)
+ .and_then(|clip| clip.text.as_ref())
+ .map(|text| text.content.clone())
+ else {
+ self.words = None;
+ return;
+ };
+ let (anchor, cursor) = (char_at(&content, anchor), char_at(&content, cursor));
+ let (start, end) = (anchor.min(cursor), anchor.max(cursor));
+ self.words = (start < end).then_some((id, start, end));
+ }
+
+ /// The selected words the styling controls are aimed at, while there
+ /// are some on the title still selected alone: (clip, start, end) in
+ /// characters, clamped to its words.
+ fn styled_words(&self) -> Option<(String, usize, usize)> {
+ let (id, start, end) = self.words.as_ref()?;
+ if self.sole_selection().as_deref() != Some(id.as_str()) {
+ return None;
+ }
+ let text = self
+ .clip(id)
+ .filter(|clip| clip.kind == model::ClipKind::Text)?
+ .text
+ .as_ref()?;
+ let count = text.char_count();
+ let (start, end) = ((*start).min(count), (*end).min(count));
+ (start < end).then(|| (id.clone(), start, end))
+ }
+
+ /// What a typography control means for some words: the override it
+ /// lays on them, or none for a control that is the whole title's -
+ /// its outline, its box, its alignment. A size is kept relative to the
+ /// title's, so the words stay bigger by as much when the title grows.
+ fn word_patch(&self, id: &str, field: ClipField, value: f64) -> Option<model::RunStyle> {
+ let mut patch = model::RunStyle::default();
+ match field {
+ ClipField::FontSize => {
+ let size = self.clip(id)?.text.as_ref()?.font_size.max(0.005);
+ patch.font_scale = Some(value.clamp(0.01, 0.5) / size);
+ }
+ ClipField::FontWeight => patch.font_weight = Some(value.clamp(100.0, 900.0)),
+ ClipField::Italic => patch.italic = Some(value != 0.0),
+ ClipField::Underline => patch.underline = Some(value != 0.0),
+ ClipField::Strikethrough => patch.strikethrough = Some(value != 0.0),
+ _ => return None,
+ }
+ Some(patch)
+ }
+
+ /// Lays `patch` over the characters `start..end` of a title, on the
+ /// echo, for the inspector's commit to land as one step.
+ fn style_words(&mut self, id: &str, start: usize, end: usize, patch: &model::RunStyle) {
+ self.commit_targets = vec![id.to_owned()];
+ self.begin_echo();
+ if let Some(text) = self.echo_clip_mut(id).and_then(|clip| clip.text.as_mut()) {
+ text.style_range(start, end, patch);
+ }
+ }
+
+ /// The selected words back in the title's own look.
+ pub fn reset_words(&mut self) {
+ let Some((id, start, end)) = self.styled_words() else {
+ return;
+ };
+ self.commit_targets = vec![id.clone()];
+ self.begin_echo();
+ if let Some(text) = self.echo_clip_mut(&id).and_then(|clip| clip.text.as_mut()) {
+ text.clear_range(start, end);
+ }
+ self.clip_commit();
+ }
+
/// The selected title's look becomes the one new titles start from,
/// and the one generated captions are set in: its family, weight,
/// colours, stroke, shadow and background, never its words. Kept in
@@ -5773,7 +5916,10 @@ impl Studio {
else {
return;
};
+ // The words are this title's own, and so are the looks of some of
+ // them: a run says nothing about another title's words.
style.content.clear();
+ style.runs.clear();
self.prefs.title_style = Some(style);
self.prefs.save(&self.host.dirs);
self.notify(&t("textPanel.newTitlesUseThisStyle"), false);
@@ -10809,7 +10955,23 @@ impl Studio {
.font_families()
.iter()
.position(|family| family.eq_ignore_ascii_case(text.font_family.trim_matches('"')));
- let fill = colour_of(&text.color);
+ // Some words selected in the text box: the typography controls
+ // style those words, so they show what the first of them wears -
+ // a run's override where it has one, the title's look elsewhere.
+ let words = self.styled_words().filter(|(id, _, _)| *id == clip.id);
+ let look = words
+ .as_ref()
+ .map(|(_, start, _)| text.run_style_at(*start))
+ .unwrap_or_default();
+ let words_styled = words.as_ref().is_some_and(|(_, start, end)| {
+ text.runs
+ .iter()
+ .any(|run| run.start < *end && *start < run.end)
+ });
+ let fill = look
+ .color
+ .as_deref()
+ .map_or_else(|| colour_of(&text.color), colour_of);
let stroke = colour_of(&text.stroke_color);
let plate = colour_of(&text.background);
let analysis = clip.cutout.as_ref().and_then(|cutout| {
@@ -10894,11 +11056,13 @@ impl Studio {
family_row: family_row.unwrap_or(0) as i32,
font_missing: family_row.is_none()
&& !text.font_family.trim_matches('"').trim().is_empty(),
- font_size: text.font_size as f32,
- font_weight: text.font_weight as f32,
- italic: text.italic,
- underline: text.underline,
- strikethrough: text.strikethrough,
+ font_size: (text.font_size * look.font_scale.unwrap_or(1.0)) as f32,
+ font_weight: look.font_weight.unwrap_or(text.font_weight) as f32,
+ italic: look.italic.unwrap_or(text.italic),
+ underline: look.underline.unwrap_or(text.underline),
+ strikethrough: look.strikethrough.unwrap_or(text.strikethrough),
+ styling_words: words.is_some(),
+ words_styled,
text_case: match text.text_case {
model::TextCase::Original => 0,
model::TextCase::Upper => 1,
@@ -12651,6 +12815,20 @@ mod tests {
wheel_partners, write_keyable,
};
+ /// A text box's caret counts bytes and a run counts characters: an
+ /// accented letter is one character of two bytes, an offset inside a
+ /// character counts it, and one out of the text is held to it.
+ #[test]
+ fn a_caret_byte_is_the_character_it_falls_at() {
+ let text = "été ok";
+ assert_eq!(super::char_at(text, 0), 0);
+ assert_eq!(super::char_at(text, 2), 1, "after é");
+ assert_eq!(super::char_at(text, 1), 1, "inside é");
+ assert_eq!(super::char_at(text, text.len() as i32), 6);
+ assert_eq!(super::char_at(text, 1000), 6);
+ assert_eq!(super::char_at(text, -1), 0);
+ }
+
/// Every built-in picture package ships a card, decodable at the size
/// cards are drawn: one added without running scripts/bundle-cards.sh
/// would show a sparkle on every machine that cannot draw its own.
diff --git a/src/crates/concat/ui/editor.slint b/src/crates/concat/ui/editor.slint
index 98fa31cf..9e99c43d 100644
--- a/src/crates/concat/ui/editor.slint
+++ b/src/crates/concat/ui/editor.slint
@@ -154,6 +154,13 @@ export global Editor {
in-out property <[string]> audio-tracks;
callback clip-set(field: ClipField, value: float);
callback clip-set-text(field: ClipTextField, value: string);
+ /// A title's words as typed, and the caret's byte after the edit.
+ callback clip-set-words(text: string, caret: int);
+ /// The Text tab's box selected some of a title's words (or none, when
+ /// anchor and cursor meet): the bytes either end of the selection.
+ callback clip-select-words(anchor: int, cursor: int);
+ /// The selected words back in the title's own look.
+ callback clip-reset-words();
callback clip-set-colour(field: ClipTextField, value: color);
callback clip-commit();
/// The families a title can be set in: the bundled face, the user's
diff --git a/src/crates/concat/ui/inspector/text-panel.slint b/src/crates/concat/ui/inspector/text-panel.slint
index 151f3577..991d25f1 100644
--- a/src/crates/concat/ui/inspector/text-panel.slint
+++ b/src/crates/concat/ui/inspector/text-panel.slint
@@ -40,6 +40,14 @@ export component TextPanel inherits VerticalLayout {
callback set(field: ClipField, value: float);
callback set-text(field: ClipTextField, value: string);
+ /// The words as typed, and the caret's byte after the edit (-1 when
+ /// not typed), so a coloured word typed into stays coloured.
+ callback set-words(text: string, caret: int);
+ /// Some words selected in the box, by the bytes at either end; the
+ /// two the same is none, and the whole title is styled again.
+ callback select-words(anchor: int, cursor: int);
+ /// The selected words back in the title's own look.
+ callback reset-words();
callback set-colour(field: ClipTextField, value: color);
callback commit();
/// The square beside the font picker: bring a font file of your own in.
@@ -216,6 +224,39 @@ export component TextPanel inherits VerticalLayout {
property <string> typed-for;
changed clip-id => {
self.text = root.selected.content;
+ self.clear-selection();
+ }
+
+ // Words dragged over are the words the typography
+ // below styles. The selection is told while the box
+ // has focus, and held when it goes: reaching for the
+ // colour swatch or B blurs the box, and a blur
+ // collapses its selection - so it is put back, still
+ // showing which words the controls are aimed at.
+ property <int> held-anchor;
+ property <int> held-cursor;
+ function hold() {
+ self.held-anchor = self.anchor-position-byte-offset;
+ self.held-cursor = self.cursor-position-byte-offset;
+ root.select-words(self.held-anchor, self.held-cursor);
+ }
+ changed cursor-position-byte-offset => {
+ if (self.has-focus) {
+ self.hold();
+ }
+ }
+ changed anchor-position-byte-offset => {
+ if (self.has-focus) {
+ self.hold();
+ }
+ }
+ // Let go of from outside - Whole title, an undo - the
+ // highlight goes too.
+ property <bool> styling: root.selected.styling-words;
+ changed styling => {
+ if (!self.styling && !self.has-focus) {
+ self.clear-selection();
+ }
}
// An undo, or the words changed from elsewhere, while the
// field is not being typed in.
@@ -233,7 +274,7 @@ export component TextPanel inherits VerticalLayout {
// for, since the selection cannot change under a key.
edited => {
self.typed-for = root.selected.id;
- root.set-text(ClipTextField.content, self.text);
+ root.set-words(self.text, self.cursor-position-byte-offset);
}
changed has-focus => {
if (!self.has-focus) {
@@ -241,10 +282,13 @@ export component TextPanel inherits VerticalLayout {
// title they were typed for; written again only
// while that title is still the one selected.
if (self.typed-for == root.selected.id) {
- root.set-text(ClipTextField.content, self.text);
+ root.set-words(self.text, -1);
}
self.typed-for = "";
root.commit();
+ if (root.selected.styling-words) {
+ self.set-selection-offsets(self.held-anchor, self.held-cursor);
+ }
}
}
@@ -265,6 +309,34 @@ export component TextPanel inherits VerticalLayout {
}
}
}
+
+ // What the typography below is aimed at, said where the words
+ // are selected: a person who dragged over a word should not
+ // have to guess whether the colour goes on it or on the lot.
+ HorizontalLayout {
+ padding-top: 6px;
+ spacing: 6px;
+ Text {
+ text: root.selected.styling-words
+ ? I18n.t("textPanel.stylingWords")
+ : I18n.t("textPanel.stylingTitle");
+ color: root.selected.styling-words ? Theme.accent : Theme.fg-muted;
+ font-size: Theme.fs-sm;
+ wrap: word-wrap;
+ vertical-alignment: center;
+ horizontal-stretch: 1;
+ }
+ if root.selected.styling-words && root.selected.words-styled: Button {
+ label: I18n.t("textPanel.resetWords");
+ ghost: true;
+ clicked => { root.reset-words(); }
+ }
+ if root.selected.styling-words: Button {
+ label: I18n.t("textPanel.wholeTitle");
+ ghost: true;
+ clicked => { root.select-words(0, 0); }
+ }
+ }
}
}
@@ -282,6 +354,24 @@ export component TextPanel inherits VerticalLayout {
}
if typography.open: SectionBody {
+ // Folded away, the box above cannot show its selection; this says
+ // the controls here still style those words, and lets them go.
+ if root.selected.styling-words: HorizontalLayout {
+ padding-bottom: 4px;
+ spacing: 6px;
+ Text {
+ text: I18n.t("textPanel.stylingWords");
+ color: Theme.accent;
+ font-size: Theme.fs-sm;
+ vertical-alignment: center;
+ horizontal-stretch: 1;
+ }
+ Button {
+ label: I18n.t("textPanel.wholeTitle");
+ ghost: true;
+ clicked => { root.select-words(0, 0); }
+ }
+ }
Row {
label: I18n.t("textPanel.font");
label-width: root.label-w;
diff --git a/src/crates/concat/ui/phone/editor.slint b/src/crates/concat/ui/phone/editor.slint
index 90bbf59c..d4a91a88 100644
--- a/src/crates/concat/ui/phone/editor.slint
+++ b/src/crates/concat/ui/phone/editor.slint
@@ -1500,6 +1500,9 @@ export component PhoneEditor inherits Rectangle {
families: Editor.font-families;
set(field, value) => { Editor.clip-set(field, value); }
set-text(field, value) => { Editor.clip-set-text(field, value); }
+ set-words(text, caret) => { Editor.clip-set-words(text, caret); }
+ select-words(anchor, cursor) => { Editor.clip-select-words(anchor, cursor); }
+ reset-words => { Editor.clip-reset-words(); }
set-colour(field, value) => { Editor.clip-set-colour(field, value); }
commit => { Editor.clip-commit(); }
import-font => { Editor.import-font(); }
diff --git a/src/crates/concat/ui/timeline/model.slint b/src/crates/concat/ui/timeline/model.slint
index 390d3a87..64e68d4c 100644
--- a/src/crates/concat/ui/timeline/model.slint
+++ b/src/crates/concat/ui/timeline/model.slint
@@ -488,6 +488,12 @@ export struct SelectedClipData {
italic: bool,
underline: bool,
strikethrough: bool,
+ /// Some words are selected in the Text tab's box, and the typography
+ /// above - colour, weight, size, B/I/U/S - shows and styles those
+ /// words, not the whole title.
+ styling-words: bool,
+ /// Those words wear a look of their own somewhere, which Reset clears.
+ words-styled: bool,
text-case: int,
fill: color,
fill-hex: string,
diff --git a/src/crates/concat/ui/workspace/config-pane.slint b/src/crates/concat/ui/workspace/config-pane.slint
index 073de42a..d81cd853 100644
--- a/src/crates/concat/ui/workspace/config-pane.slint
+++ b/src/crates/concat/ui/workspace/config-pane.slint
@@ -191,6 +191,9 @@ export component ConfigPane inherits Rectangle {
callback clip-set(field: ClipField, value: float);
callback clip-set-text(field: ClipTextField, value: string);
+ callback clip-set-words(text: string, caret: int);
+ callback clip-select-words(anchor: int, cursor: int);
+ callback clip-reset-words();
callback clip-set-colour(field: ClipTextField, value: color);
callback clip-commit();
/// The Text tab's font picker and its import button; see Editor.
@@ -755,6 +758,9 @@ export component ConfigPane inherits Rectangle {
families: root.font-families;
set(field, value) => { root.clip-set(field, value); }
set-text(field, value) => { root.clip-set-text(field, value); }
+ set-words(text, caret) => { root.clip-set-words(text, caret); }
+ select-words(anchor, cursor) => { root.clip-select-words(anchor, cursor); }
+ reset-words => { root.clip-reset-words(); }
set-colour(field, value) => { root.clip-set-colour(field, value); }
commit => { root.clip-commit(); }
import-font => { root.import-font(); }
diff --git a/src/crates/concat/ui/workspace/seat.slint b/src/crates/concat/ui/workspace/seat.slint
index 4d9de5ff..fcdb54da 100644
--- a/src/crates/concat/ui/workspace/seat.slint
+++ b/src/crates/concat/ui/workspace/seat.slint
@@ -301,6 +301,9 @@ export component Seat inherits Rectangle {
transition-choices: Editor.transition-choices;
clip-set(field, value) => { Editor.clip-set(field, value); }
clip-set-text(field, value) => { Editor.clip-set-text(field, value); }
+ clip-set-words(text, caret) => { Editor.clip-set-words(text, caret); }
+ clip-select-words(anchor, cursor) => { Editor.clip-select-words(anchor, cursor); }
+ clip-reset-words => { Editor.clip-reset-words(); }
clip-set-colour(field, value) => { Editor.clip-set-colour(field, value); }
clip-commit => { Editor.clip-commit(); }
font-families: Editor.font-families;