Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

Bold and italic keep the paragraph's rows; menus read the page once (#158)

chethan616afdb2d341587
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt
index a38b6f9..927b159 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/AppViewModel.kt
@@ -1896,13 +1896,15 @@ class AppViewModel(app: Application, private val saved: SavedStateHandle) : Andr
val end = range.max.coerceIn(start, words.length)
if (start == end) return
val bytes = { upTo: Int -> words.substring(0, upTo).toByteArray(Charsets.UTF_8).size }
- val name = para.font.lowercase()
- val family = editFont[para.page to para.number] ?: when {
- "courier" in name || "mono" in name || "consol" in name -> "courier"
- "times" in name || "serif" in name && "sans" !in name || "roman" in name || "georgia" in name || "garamond" in name -> "times"
- else -> "helvetica"
+ // In the text's own face unless a family was chosen for the paragraph: the engine takes the
+ // page's own bold or italic of it, else draws the same glyphs stroked or slanted, so the
+ // words keep their widths and the paragraph its rows (#158; a standard family re-wrapped it).
+ val one = buildMap<String, Any?> {
+ put("range", listOf(bytes(start), bytes(end)))
+ editFont[para.page to para.number]?.let { put("font", it) }
+ put("bold", bold)
+ put("italic", italic)
}
- val one = mapOf("range" to listOf(bytes(start), bytes(end)), "font" to family, "bold" to bold, "italic" to italic)
// the editor shows it at once; the page follows from the engine
val chars = com.chethan616.clearpdf.ui.viewer.StyleRun.perChar(editRuns, words.length, para.bold, para.italic)
for (i in start until end) chars[i] = bold to italic
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveGlass.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveGlass.kt
index 2c87ab0..cd5bdb7 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveGlass.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/AdaptiveGlass.kt
@@ -46,7 +46,7 @@ import kotlin.math.sign
* (which ink) is composition state, and it flips with hysteresis so mid-grey never flickers.
*/
@Stable
-class GlassLuminance internal constructor(initial: Float, internal val layer: GraphicsLayer) {
+class GlassLuminance internal constructor(initial: Float, internal val layer: GraphicsLayer, private val once: Boolean = false) {
private val anim = Animatable(initial)
private var recorded = false
// how many times the backdrop has been recorded; the reading skips a record it has already read
@@ -132,6 +132,10 @@ class GlassLuminance internal constructor(initial: Float, internal val layer: Gr
// theme) and then swing to black.
anim.snapTo(lum)
measured = true
+ // a menu reads what is behind it once, as it opens, and keeps it while it is up:
+ // read again and again, the page under it (the viewer's header stepping aside,
+ // its tiles sharpening) moved its glass and ink, and it seemed to breathe (#158)
+ if (once) return@coroutineScope
} else if (kotlin.math.abs(lum - anim.targetValue) > 0.07f) {
// only a real change behind it moves it (a small one, read again and again, made it breathe)
anim.animateTo(lum, tween(420))
@@ -192,14 +196,14 @@ private const val BusyTo = 0.15
* [GlassCard]) and take the ink from [adaptiveInk].
*/
@Composable
-fun rememberGlassLuminance(enabled: Boolean = GlassSettings.adaptive): GlassLuminance? {
+fun rememberGlassLuminance(enabled: Boolean = GlassSettings.adaptive, once: Boolean = false): GlassLuminance? {
if (!enabled || clear.clean) return null
val layer = rememberGraphicsLayer()
val dark = clear.dark
// the first guess: what the screen as a whole looks like now (the window's sampler, running
// while Adaptive luminance is on), else the theme
val screen = LocalScreenInk.current
- val state = remember(layer) { GlassLuminance(screen?.frame?.average() ?: if (dark) 0.14f else 0.86f, layer) }
+ val state = remember(layer) { GlassLuminance(screen?.frame?.average() ?: if (dark) 0.14f else 0.86f, layer, once) }
LaunchedEffect(state) { state.run() }
return state
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/LiquidMorph.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/LiquidMorph.kt
index 59d381d..cbd3129 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/LiquidMorph.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/LiquidMorph.kt
@@ -344,7 +344,7 @@ internal fun LiquidMorphSurface(
return Geo(menu, radius, k, circleR, motion)
}
- val luminance = rememberGlassLuminance(enabled = true)
+ val luminance = rememberGlassLuminance(enabled = true, once = true)
// Adaptive luminance on: at the button's end the glass is the button's own adaptive glass (its
// reading of what is around it, its frost, colour and milk or smoke), so neither the opening nor
// the landing ever shows a moment of plain glass where the adaptive button was
@@ -554,5 +554,7 @@ private fun com.kyant.backdrop.BackdropEffectScope.morphEffects(style: GlassStyl
)
val buttonBlur = 2f * dp * style.blur * (if (b == null) 1f else if (b > 0f) lerp(1f, 1.5f, b) else lerp(1f, 0.6f, -b))
val menuBlur = 16f * dp * style.blur * (if (l > 0f) lerp(1f, 1.35f, l) else lerp(1f, 0.75f, -l)) + 18f * dp * k
- blur(lerp(buttonBlur, menuBlur, o) + 5f * dp * motion.coerceIn(0f, 1f))
+ // A steady frost: it used to rise with the jelly's swing, and over a page of print the words
+ // behind pulsed sharp and blurred as the menu settled (#158). The shape still swings.
+ blur(lerp(buttonBlur, menuBlur, o))
}
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/MorphButton.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/MorphButton.kt
index 8d59977..8901cfd 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/MorphButton.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/glass/MorphButton.kt
@@ -319,7 +319,7 @@ private fun RectMorphSurface(
val frost = lerp(2f, 14f, tall.value.coerceIn(0f, 1f)).dp
// the glass reads what is behind it and takes dark ink over light, white over dark (Night mode's
// black pages, a white document, the aurora): the glyph and rows always stand out
- val luminance = rememberGlassLuminance(enabled = true)
+ val luminance = rememberGlassLuminance(enabled = true, once = true)
val inkColor = adaptiveInk(luminance, clear.ink)
Layout(
content = {
diff --git a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt
index 11f2a8e..24d3f28 100644
--- a/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt
+++ b/android/app/src/main/java/com/chethan616/clearpdf/ui/viewer/Edit.kt
@@ -253,12 +253,17 @@ private fun EditFormatBar(vm: AppViewModel, doc: OpenDocument, para: Paragraph)
val picked = vm.editRange?.takeIf { vm.editing != null }
val boldNow = if (picked != null) vm.rangeStyled(para, picked) else para.bold
val italicNow = if (picked != null) vm.rangeStyled(para, picked, italic = true) else para.italic
+ // the whole paragraph, as a range over all of it: in its own face, keeping its rows (#158)
+ val whole = androidx.compose.ui.text.TextRange(0, (vm.editDraft?.takeIf { vm.editing != null } ?: para.text).length)
+ val rtl = para.text.any { Character.getDirectionality(it).let { d -> d == Character.DIRECTIONALITY_RIGHT_TO_LEFT || d == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC } }
LetterButton("T", stringResource(R.string.edit_bold), boldNow, weight = FontWeight.Black) {
if (picked != null) vm.styleRange(doc, para, picked, bold = !boldNow, italic = italicNow)
+ else if (!rtl) vm.styleRange(doc, para, whole, bold = !para.bold, italic = para.italic)
else vm.styleParagraph(doc, para, mapOf("bold" to !para.bold))
}
LetterButton("T", stringResource(R.string.edit_italic), italicNow, italic = true) {
if (picked != null) vm.styleRange(doc, para, picked, bold = boldNow, italic = !italicNow)
+ else if (!rtl) vm.styleRange(doc, para, whole, bold = para.bold, italic = !para.italic)
else vm.styleParagraph(doc, para, mapOf("italic" to !para.italic))
}
LetterButton("T", stringResource(R.string.edit_underline), underline, underline = true) {
diff --git a/engine/crates/automation/src/lib.rs b/engine/crates/automation/src/lib.rs
index ac62f09..633b032 100644
--- a/engine/crates/automation/src/lib.rs
+++ b/engine/crates/automation/src/lib.rs
@@ -2477,6 +2477,10 @@ fn parse_style_ranges(value: Option<&Value>) -> Result<Vec<pdfcraft_engine::Rang
underline: a.opt_bool("underline")?,
char_spacing: a.opt_num("char_spacing")?,
scale: a.opt_num("scale")?,
+ // with a font, bold and italic choose its face (above); without one they apply
+ // in the run's own face
+ bold: if a.get("font").is_none() { a.opt_bool("bold")? } else { None },
+ italic: if a.get("font").is_none() { a.opt_bool("italic")? } else { None },
})
})
.collect()
diff --git a/engine/crates/automation/tests/it/automation.rs b/engine/crates/automation/tests/it/automation.rs
index d6a9d57..4013423 100644
--- a/engine/crates/automation/tests/it/automation.rs
+++ b/engine/crates/automation/tests/it/automation.rs
@@ -9304,6 +9304,79 @@ fn bold_range_is_one_word_and_listed_as_a_run() {
std::fs::remove_dir_all(dir).unwrap();
}
+/// A wrapped body paragraph above another one, for bolding a word in it (#158).
+fn bold_rows_fixture(dir: &std::path::Path) -> String {
+ use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, Stream, write_full};
+ use std::sync::Arc;
+ // Four full rows of 10 pt Helvetica 12 pt apart, then a paragraph of its own well below.
+ let content = "BT /F1 10 Tf 20 250 Td (The quick brown fox jumps over the lazy) Tj ET \
+ BT /F1 10 Tf 20 238 Td (dog while the small cat watches from a) Tj ET \
+ BT /F1 10 Tf 20 226 Td (window and the bird sings a happy song) Tj ET \
+ BT /F1 10 Tf 20 214 Td (all through the long summer afternoon.) Tj ET \
+ BT /F1 10 Tf 20 180 Td (Next paragraph stays where it was.) Tj ET";
+ let mut doc = Document::open(Arc::new(fixture(1))).unwrap();
+ doc.set(ObjRef::new(5, 0), Object::Stream(Stream::flate(Dict::new(), content.as_bytes())));
+ std::fs::write(dir.join("rows.pdf"), write_full(&doc, &SaveOptions::default()).unwrap()).unwrap();
+ "rows.pdf".into()
+}
+
+/// Bolds `word` in the first paragraph (as the viewer's Bold does: its editor text and a byte
+/// range, with `font` or in the run's own face), and checks nothing else moved (#158): the same
+/// rows, the untouched rows' text as it was, and the paragraph below where it was.
+fn bold_keeps_rows(name: &str, word: &str, font: Option<&str>) {
+ let dir = workdir(name);
+ let path = bold_rows_fixture(&dir);
+ let mut a = auto(&dir);
+ let id = ok(&mut a, "doc_open", json!({"path":path}))["doc"].as_u64().unwrap();
+ let before = ok(&mut a, "text_paragraphs", json!({"doc":id,"page":1}));
+ let p = &before["paragraphs"][0];
+ let rows = p["rows"].as_array().unwrap().len();
+ assert_eq!(rows, 4, "one wrapped paragraph of four rows: {before}");
+ let below = before["paragraphs"][1]["rect"].clone();
+ let text = p["edit_text"].as_str().unwrap().to_owned();
+ let at = text.find(word).unwrap();
+ let mut range = json!({"range":[at, at + word.len()],"bold":true,"italic":false});
+ if let Some(f) = font {
+ range["font"] = json!(f);
+ }
+ ok(&mut a, "text_edit", json!({"doc":id,"page":1,"paragraph":1,"text":text,"ranges":[range]}));
+ let after = ok(&mut a, "text_paragraphs", json!({"doc":id,"page":1}));
+ let q = &after["paragraphs"][0];
+ assert_eq!(q["rows"].as_array().unwrap().len(), rows, "bolding a word keeps the paragraph's rows: {after}");
+ assert_eq!(after["paragraphs"][1]["rect"], below, "the paragraph below stays: {after}");
+ assert_eq!(after["paragraphs"][1]["text"], "Next paragraph stays where it was.", "{after}");
+ // the paragraph doesn't grow down into the one below (view space: y grows down)
+ assert!(q["rect"][3].as_f64().unwrap() < below[1].as_f64().unwrap(), "no overlap: {after}");
+ let lines = ok(&mut a, "text_lines", json!({"doc":id,"page":1}));
+ let shown: Vec<String> = lines["lines"].as_array().unwrap().iter().map(|l| l["text"].as_str().unwrap().trim().to_owned()).collect();
+ for row in ["window and the bird sings a happy song", "all through the long summer afternoon."] {
+ assert!(shown.iter().any(|t| t == row), "an untouched row is left as it was: {row:?} in {shown:?}");
+ }
+ let editor = q["editor_text"].as_str().unwrap();
+ let bold: String = q["runs"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|r| r["bold"] == true)
+ .map(|r| &editor[r["range"][0].as_u64().unwrap() as usize..r["range"][1].as_u64().unwrap() as usize])
+ .collect();
+ assert_eq!(bold.trim(), word, "only the word is bold: {after}");
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
+/// #158: bold in the run's own face (no family): synthetic bold, the face's own widths, no re-wrap.
+#[test]
+fn bolding_a_word_in_its_own_face_keeps_the_rows() {
+ bold_keeps_rows("bold-own-face", "lazy", None);
+}
+
+/// #158: bold in a standard family, wider than the source's face: the rows stay (a full row is
+/// narrowed to the paragraph's width rather than wrapped onto a new one).
+#[test]
+fn bolding_a_word_in_a_wider_face_keeps_the_rows() {
+ bold_keeps_rows("bold-wider-face", "watches", Some("times"));
+}
+
/// A heading over a short line and two body lines, read as one paragraph: adding a word at its end
/// keeps the heading and the short line on rows of their own (#144). The editor's text breaks
/// where the source ended a row on purpose and joins the rows it wrapped.
diff --git a/engine/crates/edit/src/tests.rs b/engine/crates/edit/src/tests.rs
index 5afd017..a569ba3 100644
--- a/engine/crates/edit/src/tests.rs
+++ b/engine/crates/edit/src/tests.rs
@@ -1792,6 +1792,8 @@ fn styled_fallback_batches_keep_face_choices_and_range_styles() {
underline: None,
char_spacing: None,
scale: None,
+ bold: None,
+ italic: None,
};
let style = text::BlockStyle {
width: Some(520.0),
@@ -5211,6 +5213,8 @@ fn disjoint_style_ranges_preserve_unselected_runs_and_validate_utf8_atomically()
underline: Some(true),
char_spacing: None,
scale: None,
+ bold: None,
+ italic: None,
},
RangeStyle {
range: b..b + 4,
@@ -5221,6 +5225,8 @@ fn disjoint_style_ranges_preserve_unselected_runs_and_validate_utf8_atomically()
underline: None,
char_spacing: Some(0.2),
scale: Some(90.0),
+ bold: None,
+ italic: None,
},
],
width: Some(300.0),
@@ -5250,6 +5256,8 @@ fn disjoint_style_ranges_preserve_unselected_runs_and_validate_utf8_atomically()
underline: None,
char_spacing: None,
scale: None,
+ bold: None,
+ italic: None,
}],
..Default::default()
};
@@ -5889,6 +5897,8 @@ fn turned_paragraph_keeps_its_line_breaks_when_a_word_is_added() {
underline: None,
char_spacing: None,
scale: None,
+ bold: None,
+ italic: None,
};
let style = text::BlockStyle { ranges: vec![range], ..Default::default() };
assert!(text::rewrite_block(&mut doc, 0, 0, Some("Only line"), &style).is_err());
@@ -6162,6 +6172,8 @@ fn rows_the_edit_does_not_reach_keep_their_source_operators() {
underline: None,
char_spacing: None,
scale: None,
+ bold: None,
+ italic: None,
};
text::rewrite_block(&mut doc, 0, block, Some(&draft), &text::BlockStyle { ranges: vec![range], ..Default::default() }).unwrap();
let bytes = String::from_utf8_lossy(&page_content_bytes(&doc, 0)).into_owned();
@@ -7995,6 +8007,8 @@ fn carriage_returns_break_rows_on_the_styled_path() {
underline: None,
char_spacing: None,
scale: None,
+ bold: None,
+ italic: None,
};
for style in [text::BlockStyle::default(), text::BlockStyle { ranges: vec![red], ..Default::default() }] {
let mut doc = text_page("BT /F1 12 Tf 72 700 Td (Hello world) Tj ET");
diff --git a/engine/crates/edit/src/text.rs b/engine/crates/edit/src/text.rs
index 71dd4b6..7c2caee 100644
--- a/engine/crates/edit/src/text.rs
+++ b/engine/crates/edit/src/text.rs
@@ -1564,8 +1564,10 @@ fn interpret(
base_font: m.base_font.clone(),
face: ts.face.clone(),
size: if size_user > 0.0 { size_user } else { ts.size },
- bold: m.bold,
- italic: m.italic,
+ // Drawn filled and stroked (synthetic bold), or slanted by its matrix (synthetic
+ // italic): what a weight or slant applied in the run's own face writes.
+ bold: m.bold || (ts.render_mode == 2 && ts.line_width.unwrap_or(1.0) > 0.0),
+ italic: m.italic || slanted(&tm.0),
visual_order: m.visual_order,
decodable,
scope: marked.last().copied().flatten(),
@@ -2533,6 +2535,27 @@ fn source_program_completes(doc: &Document, fonts: &Dict, line: &TextLine, text:
/// A subset may contain all the letters but no space glyph: producers use another subset
/// or a positioning operator for spaces. Do the same instead of substituting the whole font.
+/// Whether a text matrix leans its glyphs (a shear along the baseline, as a synthetic italic is).
+fn slanted(tm: &[f64; 6]) -> bool {
+ let along = tm[0] * tm[0] + tm[1] * tm[1];
+ along > 1e-12 && ((tm[0] * tm[2] + tm[1] * tm[3]) / along) > 0.12
+}
+
+/// A face's family without its subset tag, weight and slant words: "ABCDEF+Calibri-BoldItalic"
+/// and "Calibri" are one family, so a bold run can be drawn in the page's own bold of it.
+pub(crate) fn family_key(base_font: &str) -> String {
+ let mut key: String = base_font.rsplit('+').next().unwrap_or(base_font).chars().filter(char::is_ascii_alphanumeric).flat_map(char::to_lowercase).collect();
+ for word in ["bolditalic", "boldoblique", "semibold", "demibold", "bold", "italic", "oblique", "regular", "roman", "book", "medium", "normal"] {
+ key = key.replace(word, "");
+ }
+ for suffix in ["mt", "ps"] {
+ if key.len() > suffix.len() + 2 && key.ends_with(suffix) {
+ key.truncate(key.len() - suffix.len());
+ }
+ }
+ key
+}
+
fn source_encodes(metrics: &Metrics, text: &str) -> bool {
text.split(' ').all(|word| metrics.encode(word).is_some())
}
@@ -3010,6 +3033,12 @@ pub struct RangeStyle {
pub underline: Option<bool>,
pub char_spacing: Option<f64>,
pub scale: Option<f64>,
+ /// Bold (or not) in the run's own face, with no family chosen: the page's own bold (regular)
+ /// font of the same face when it has one that shows the text, else the same glyphs drawn
+ /// filled and stroked (synthetic bold), whose advances are the face's own, so nothing moves.
+ pub bold: Option<bool>,
+ /// Italic (or not) the same way: the page's own italic face, else the same glyphs slanted.
+ pub italic: Option<bool>,
}
/// Rewrite paragraph `block` with new text (or its own) and formatting, rewrapped to its width.
diff --git a/engine/crates/edit/src/text_regions.rs b/engine/crates/edit/src/text_regions.rs
index 007fa33..1c019b4 100644
--- a/engine/crates/edit/src/text_regions.rs
+++ b/engine/crates/edit/src/text_regions.rs
@@ -444,8 +444,14 @@ pub(super) fn rewrite_styled_block(
max_glyphs: usize,
) -> Result<LineEdit, EditError> {
let first = block.lines.first().and_then(|i| lines.get(*i)).ok_or_else(|| EditError::Invalid("the paragraph has no source runs".into()))?;
+ // The editor's own form of the paragraph (rows the source wrapped joined by spaces, rows it
+ // ended kept as breaks) is the unchanged text too: the source's, with a break at every row.
+ let unchanged = |t: &str| {
+ let e = block.editor_text.as_bytes();
+ t.len() == e.len() && t.bytes().zip(e).all(|(a, b)| a == *b || (a == b' ' && *b == b'\n'))
+ };
let draft = match text {
- Some(t) if t != block.text => t,
+ Some(t) if t != block.text && !unchanged(t) => t,
_ => &block.editor_text,
};
if draft.len() > 4_000_000 {
@@ -473,6 +479,21 @@ pub(super) fn rewrite_styled_block(
let mut styled_spans = Vec::new();
let mut underlines = HashMap::new();
let mut overrides = HashMap::new();
+ // The page's fonts, read once, for a weight or slant in a run's own face.
+ let page_fonts: Vec<(String, Metrics)> = {
+ let pd = page_dict(doc, page)?;
+ let res = pd.dict.get(b"Resources").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
+ let fonts = res.get(b"Font").and_then(|r| doc.resolve(r).as_dict().cloned()).unwrap_or_default();
+ fonts
+ .iter()
+ .take(256)
+ .filter_map(|(name, object)| doc.resolve(object).as_dict().map(|d| (String::from_utf8_lossy(name).into_owned(), Metrics::from_dict(doc, d))))
+ .collect()
+ };
+ // Styled runs drawn in another of the page's faces (their widths are that face's own) and
+ // runs slanted by their matrix (synthetic italic).
+ let mut own_variant = std::collections::HashSet::new();
+ let mut slant = std::collections::HashSet::new();
for (span, source) in block.edited_spans(draft) {
let mut edges = vec![span.start, span.end];
for r in &ranges {
@@ -498,6 +519,8 @@ pub(super) fn rewrite_styled_block(
underline: None,
char_spacing: None,
scale: None,
+ bold: None,
+ italic: None,
};
let r = selected.unwrap_or(&default_range);
let mut line = lines.get(source).unwrap_or(first).clone();
@@ -510,6 +533,62 @@ pub(super) fn rewrite_styled_block(
line.bold = bold;
line.italic = italic;
}
+ // A weight or slant in the run's own face (no family chosen): the page's own bold or
+ // italic of that face if one shows the text, else the same glyphs stroked or slanted.
+ // Either way the face's widths stay, so a style alone never re-wraps the paragraph.
+ if r.family.is_none() && style.family.is_none() && (r.bold.is_some() || r.italic.is_some()) {
+ let want_bold = r.bold.unwrap_or(line.bold);
+ let want_italic = r.italic.unwrap_or(line.italic);
+ let synthetic_bold = line.origin.state.render_mode == 2;
+ let piece = draft.get(start..end).unwrap_or_default();
+ let family = crate::text::family_key(&line.base_font);
+ let native = page_fonts.iter().find(|(_, m)| {
+ m.bold == want_bold && m.italic == want_italic && crate::text::family_key(&m.base_font) == family && source_encodes(m, piece)
+ });
+ if want_bold == line.bold && want_italic == line.italic {
+ // nothing to change
+ } else if let Some((name, m)) = native {
+ line.font = name.clone();
+ line.base_font = m.base_font.clone();
+ line.bold = want_bold;
+ line.italic = want_italic;
+ if synthetic_bold {
+ line.origin.state.render_mode = 0;
+ }
+ own_variant.insert(styled_lines.len());
+ } else {
+ // Bold: filled and stroked in the text's colour, about a thirtieth of its size
+ // wide. Not bold: a synthetic bold stops stroking (a face that is itself
+ // bold, with no regular on the page, takes the standard family's regular).
+ if want_bold && !line.bold {
+ let [r, g, b] = line.color;
+ line.origin.state.render_mode = 2;
+ line.origin.state.stroke = vec![Op::new("RG", vec![Object::Real(r), Object::Real(g), Object::Real(b)])];
+ line.origin.state.line_width = Some((line.size * 0.03).max(0.05) / line.origin.ctm[0].hypot(line.origin.ctm[1]).max(1e-6));
+ line.bold = true;
+ } else if !want_bold && line.bold && synthetic_bold {
+ line.origin.state.render_mode = 0;
+ line.bold = false;
+ } else if !want_bold && line.bold {
+ let base = source_family(&line.base_font).base_font(false, want_italic && line.italic);
+ line.font = format!("PCRange{}", base.replace('-', ""));
+ line.base_font = base.to_owned();
+ line.bold = false;
+ own_variant.insert(styled_lines.len());
+ }
+ if want_italic && !line.italic {
+ slant.insert(styled_lines.len());
+ line.italic = true;
+ } else if !want_italic && line.italic && !line.font.starts_with("PCRange") {
+ // an italic face with no upright on the page: the standard family's upright
+ let base = source_family(&line.base_font).base_font(line.bold && line.origin.state.render_mode != 2, false);
+ line.font = format!("PCRange{}", base.replace('-', ""));
+ line.base_font = base.to_owned();
+ line.italic = false;
+ own_variant.insert(styled_lines.len());
+ }
+ }
+ }
if let Some(resource) = &r.resource {
line.font = resource.clone();
}
@@ -775,7 +854,8 @@ pub(super) fn rewrite_styled_block(
source.origin.state.word_spacing,
) * source.origin.state.scale
* across(source);
- let changed_face = style.resource.is_some() || overrides.get(&index).is_some_and(|r| r.family.is_some() || r.resource.is_some());
+ let changed_face =
+ style.resource.is_some() || own_variant.contains(&index) || overrides.get(&index).is_some_and(|r| r.family.is_some() || r.resource.is_some());
let factor = if nominal > 0.0 && !changed_face { ((source.rect[2] - source.rect[0]) / nominal).clamp(0.5, 2.0) } else { 1.0 };
calibration.insert(index, factor);
}
@@ -871,6 +951,40 @@ pub(super) fn rewrite_styled_block(
close_row(&mut items, row_index)?;
}
let slack = slack.clamp(0.0, width * 0.15);
+ // A change of style alone (the same text, no new size, spacing, scale or width) keeps the
+ // paragraph's own rows: making a word bold used to re-wrap it, a row became two and ran into
+ // the paragraph below. A row a wider face pushes past the paragraph's width is narrowed to it.
+ let style_only = draft == block.editor_text
+ && style.width.is_none()
+ && style.size.is_none()
+ && style.char_spacing.is_none()
+ && style.scale.is_none()
+ && style.line_spacing.is_none()
+ && ranges.iter().all(|r| r.size.is_none() && r.char_spacing.is_none() && r.scale.is_none());
+ // Each draft character's visual row in the source, for a style-only change to break exactly
+ // where the source did (the editor's text joins rows the source wrapped, so its newlines
+ // alone don't say where every row ends).
+ let char_row: Vec<usize> = if style_only {
+ let row_of_line: HashMap<usize, usize> = block.rows.iter().enumerate().flat_map(|(r, ls)| ls.iter().map(move |l| (*l, r))).collect();
+ let mut rows_of = Vec::new();
+ let mut span = 0;
+ let mut owner = block.lines.first().copied().unwrap_or(0);
+ for (byte, _) in block.editor_text.char_indices() {
+ while block.spans.get(span).is_some_and(|(r, _)| byte >= r.end) {
+ span += 1;
+ }
+ if let Some((r, i)) = block.spans.get(span)
+ && r.contains(&byte)
+ {
+ owner = *i;
+ }
+ rows_of.push(row_of_line.get(&owner).copied().unwrap_or(0));
+ }
+ rows_of
+ } else {
+ Vec::new()
+ };
+ let mut current_row: Option<usize> = None;
// Wrap at word boundaries, retaining explicit source row breaks and whitespace.
let mut at = 0;
while at < chars.len() {
@@ -886,8 +1000,23 @@ pub(super) fn rewrite_styled_block(
row_width = 0.0;
at += 1;
row_start = at;
+ current_row = None;
continue;
}
+ // A style-only change: a new row where the source began one, and nowhere else.
+ if style_only && !item.0.is_whitespace() {
+ let source_row = char_row.get(at).copied();
+ if !row.is_empty() && current_row.is_some() && source_row != current_row {
+ while row.last().is_some_and(|c: &(char, usize, String)| c.0.is_whitespace()) {
+ row.pop();
+ }
+ row_ranges.push(row_start..row_start + row.len());
+ rows.push(std::mem::take(&mut row));
+ row_width = 0.0;
+ row_start = at;
+ }
+ current_row = source_row;
+ }
let mut end = at + 1;
if !item.0.is_whitespace() {
// A word ends at a space, or where Chinese or Japanese text may break between characters.
@@ -900,7 +1029,7 @@ pub(super) fn rewrite_styled_block(
}
let word = chars.get(at..end).unwrap_or_default();
let w = measure(word)?;
- if !row.is_empty() && !item.0.is_whitespace() && row_width + w > width + 0.5 + slack {
+ if !style_only && !row.is_empty() && !item.0.is_whitespace() && row_width + w > width + 0.5 + slack {
while row.last().is_some_and(|c: &(char, usize, String)| c.0.is_whitespace()) {
row.pop();
}
@@ -923,7 +1052,11 @@ pub(super) fn rewrite_styled_block(
// A row the edit doesn't reach keeps its source operators, so its kerning, TJ word gaps and
// glyph widths stay exactly as they were instead of being rebuilt from the text state.
let plain = BlockStyle { ranges: Vec::new(), ..style.clone() } == BlockStyle::default();
- let mut kept = if plain {
+ let mut kept = if style_only && rows.len() == block.rows.len() {
+ // The rows are the source's own: one with nothing styled in it keeps its operators, so
+ // its words don't shift (rebuilt from the text state they lost their kerning and gaps).
+ rows.iter().map(|row| row.iter().all(|c| c.1 < source_count)).collect()
+ } else if plain {
untouched_rows(block, draft, &row_ranges).into_iter().zip(&rows).map(|(same, row)| same && row.iter().all(|c| c.1 < source_count)).collect()
} else {
vec![false; rows.len()]
@@ -1025,6 +1158,9 @@ pub(super) fn rewrite_styled_block(
continue;
}
let w = measured.get(row_index).copied().unwrap_or(0.0);
+ // A kept row (style alone) a wider face pushed past the paragraph's width: narrowed to it.
+ let squeeze = if style_only && w > width + 0.5 + slack && w > 0.0 { ((width + slack) / w).clamp(0.5, 1.0) } else { 1.0 };
+ let w = w * squeeze;
let align = style.align.unwrap_or(if centered { crate::added::Align::Center } else { crate::added::Align::Left });
let original_rect = block.rows.get(row_index).and_then(|row| row_rect(row, lines)).unwrap_or(block.rect);
let left = if style.width.is_none() && style.align.is_none() { original_rect[0] } else { block.rect[0] };
@@ -1057,6 +1193,7 @@ pub(super) fn rewrite_styled_block(
if !shaped_runs.contains_key(&(row_index, pos)) {
state.scale *= calibration.get(&item.1).copied().unwrap_or(1.0);
}
+ state.scale *= squeeze;
if let Some([r, g, b]) = overrides.get(&item.1).and_then(|r| r.color).or(style.color).filter(|c| !same_colour(*c, source.color)) {
state.fill = vec![Op::new("rg", vec![n(r), n(g), n(b)])];
}
@@ -1065,7 +1202,12 @@ pub(super) fn rewrite_styled_block(
let (ax, ay) = back.apply(x - source.origin.x, baseline - source.origin.baseline);
tm[4] += ax;
tm[5] += ay;
- let mut segment_width = segment_advances.get(&(row_index, pos)).copied().unwrap_or(0.0);
+ if slant.contains(&item.1) {
+ // synthetic italic: the glyphs lean about 12 degrees along the baseline
+ tm[2] += 0.21 * tm[0];
+ tm[3] += 0.21 * tm[1];
+ }
+ let mut segment_width = segment_advances.get(&(row_index, pos)).copied().unwrap_or(0.0) * squeeze;
// Each run in its own graphics state, restating what its source set inside its text
// object (`gs`, stroke, line width, `Tr`; #3508/#3509) from the state the rewrite is
// drawn in: a `gs` has no inverse, so one run's ExtGState would stay for the next.