diff --git a/crates/docx/src/lib.rs b/crates/docx/src/lib.rs index 19eb1f377..423a76fb5 100644 --- a/crates/docx/src/lib.rs +++ b/crates/docx/src/lib.rs @@ -165,6 +165,12 @@ impl Flavor { } } +/// Bound the tooltip at both file boundaries. A whole link can have many formatted runs. +fn bounded_link_tooltip(text: &str) -> Option<&str> { + const MAX_BYTES: usize = 4096; + text.get(..text.floor_char_boundary(MAX_BYTES)).filter(|tip| !tip.is_empty()) +} + /// Errors from reading or writing a DOCX package. #[derive(Debug, thiserror::Error, Clone, PartialEq)] pub enum DocxError { diff --git a/crates/docx/src/read/story.rs b/crates/docx/src/read/story.rs index 86ceb1651..9b5b04300 100644 --- a/crates/docx/src/read/story.rs +++ b/crates/docx/src/read/story.rs @@ -48,6 +48,7 @@ const MAX_FORM: usize = 64 * 1024; #[derive(Clone, Default)] pub struct RunCtx { link: Option, + link_tooltip: Option>, ins: Option, del: Option, } diff --git a/crates/docx/src/read/story/runs.rs b/crates/docx/src/read/story/runs.rs index 46cf274d9..0c8b69994 100644 --- a/crates/docx/src/read/story/runs.rs +++ b/crates/docx/src/read/story/runs.rs @@ -23,12 +23,16 @@ impl Reader<'_> { let mut c = ctx.clone(); let url = k.attr("r:id").and_then(|id| rels.by_id(id)).map(|r| r.target.trim().to_string()).filter(|u| !u.is_empty()); let anchor = k.attr("w:anchor").filter(|a| !a.is_empty()); - c.link = match (url, anchor) { + let link = match (url, anchor) { (Some(u), Some(a)) => Some(format!("{u}#{a}")), (Some(u), None) => Some(u), (None, Some(a)) => Some(format!("#{a}")), - (None, None) => ctx.link.clone(), + (None, None) => None, }; + if let Some(link) = link { + c.link = Some(link); + c.link_tooltip = k.attr("w:tooltip").and_then(crate::bounded_link_tooltip).map(std::sync::Arc::from); + } self.read_inline_children(sc, pb, k, rels, &c, depth + 1); } "w:ins" | "w:moveTo" => { @@ -133,6 +137,7 @@ impl Reader<'_> { fn run_props(&mut self, rpr: &El, ctx: &RunCtx) -> CharProps { let mut p = self.pc.rpr(rpr); p.link = ctx.link.clone(); + p.link_tooltip = ctx.link_tooltip.clone(); p.ins = ctx.ins; p.del = ctx.del; p.fmt_change = self.rpr_change(rpr); @@ -140,7 +145,7 @@ impl Reader<'_> { } fn run_props_none(&self, ctx: &RunCtx) -> CharProps { - CharProps { link: ctx.link.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() } + CharProps { link: ctx.link.clone(), link_tooltip: ctx.link_tooltip.clone(), ins: ctx.ins, del: ctx.del, ..Default::default() } } fn read_run(&mut self, sc: &mut StoryCtx, pb: &mut PB, r: &El, rels: &Rels, ctx: &RunCtx, depth: usize) { @@ -395,7 +400,10 @@ impl Reader<'_> { /// [`Self::emit_obj`] for a drawing that carries its own `link`: a link around the run wins. fn emit_linked_obj(&mut self, sc: &mut StoryCtx, pb: &mut PB, o: InlineObject, props: &CharProps, link: Option) { match link.filter(|_| props.link.is_none()) { - Some(link) => self.emit_obj(sc, pb, o, &CharProps { link: Some(link), ..props.clone() }), + Some(link) => { + let link_tooltip = if props.link.as_deref() == Some(link.as_str()) { props.link_tooltip.clone() } else { None }; + self.emit_obj(sc, pb, o, &CharProps { link: Some(link), link_tooltip, ..props.clone() }); + } None => self.emit_obj(sc, pb, o, props), } } diff --git a/crates/docx/src/write/story/para.rs b/crates/docx/src/write/story/para.rs index aa973184e..babed9de5 100644 --- a/crates/docx/src/write/story/para.rs +++ b/crates/docx/src/write/story/para.rs @@ -192,7 +192,7 @@ impl Writer<'_> { } } - let mut open_link: Option = None; + let mut open_link = None; let mut i = 0; while i < pieces.len() { let Some((piece, props)) = pieces.get(i) else { break }; @@ -213,21 +213,31 @@ impl Writer<'_> { i += 1; continue; } - // Hyperlink grouping. - if props.link != open_link { + // Hyperlinks with different ScreenTips stay separate even if their target is shared. + let link = props + .link + .as_deref() + .filter(|target| !target.is_empty()) + .map(|target| (target, props.link_tooltip.as_deref().and_then(crate::bounded_link_tooltip))); + if link != open_link { if open_link.is_some() { w.close("w:hyperlink"); } - open_link = None; - if let Some(l) = props.link.as_deref().filter(|l| !l.is_empty()) { - if let Some(anchor) = l.strip_prefix('#') { - w.open("w:hyperlink", &[("w:anchor", anchor), ("w:history", "1")]); + if let Some((link, tip)) = link { + let id; + let target = if let Some(anchor) = link.strip_prefix('#') { + ("w:anchor", anchor) } else { - let id = rels.add(rt::HYPERLINK, l, true); - w.open("w:hyperlink", &[("r:id", &id), ("w:history", "1")]); + id = rels.add(rt::HYPERLINK, link, true); + ("r:id", id.as_str()) + }; + if let Some(tip) = tip { + w.open("w:hyperlink", &[target, ("w:history", "1"), ("w:tooltip", tip)]); + } else { + w.open("w:hyperlink", &[target, ("w:history", "1")]); } - open_link = Some(l.to_string()); } + open_link = link; } match piece { Piece::Obj(o, _) => { diff --git a/crates/docx/tests/it/roundtrip.rs b/crates/docx/tests/it/roundtrip.rs index 758538e90..4927cd09c 100644 --- a/crates/docx/tests/it/roundtrip.rs +++ b/crates/docx/tests/it/roundtrip.rs @@ -142,6 +142,7 @@ fn every_char_prop_round_trips() { vert_compress: Some(true), }), link: None, + link_tooltip: None, ins: None, del: None, fmt_change: None, diff --git a/crates/docx/tests/screentips.rs b/crates/docx/tests/screentips.rs new file mode 100644 index 000000000..5f939b1a3 --- /dev/null +++ b/crates/docx/tests/screentips.rs @@ -0,0 +1,80 @@ +//! Original OOXML fixtures. ScreenTips are hyperlink data, not run formatting. +use std::io::{Read, Write}; + +use craft_wordmodel::{CharProps, Pos}; + +fn package() -> Vec { + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, xml) in [ + ( + "word/document.xml", + r#"Before. FirstSecondInternalTarget."#, + ), + ( + "_rels/.rels", + r#""#, + ), + ( + "word/_rels/document.xml.rels", + r#""#, + ), + ] { + zip.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(xml.as_bytes()).unwrap(); + } + zip.finish().unwrap().into_inner() +} + +#[test] +fn hyperlink_screentips_survive_edited_saves_without_merging_different_hints() { + let mut doc = craft_docx::read(&package()).unwrap(); + for _ in 0..2 { + doc.insert_text(&Pos::body(0, 0), "Edit. ", &CharProps::default()).unwrap(); + let bytes = craft_docx::write(&doc).unwrap(); + let mut xml = String::new(); + zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap().by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap(); + assert_eq!(xml.matches("w:tooltip=").count(), 3, "{xml}"); + for tip in ["Original café & "Ω"", "Different hint", "Internal hint"] { + assert!(xml.contains(&format!("w:tooltip=\"{tip}\"")), "{xml}"); + } + assert!(xml.contains("w:anchor=\"target\"")); + doc = craft_docx::read(&bytes).unwrap(); + let paragraph = doc.body[0].as_para().unwrap(); + for (text, tip) in [("First", "Original café & \"Ω\""), ("Second", "Different hint"), ("Internal", "Internal hint")] { + let offset = paragraph.text.find(text).unwrap(); + assert_eq!(paragraph.props_of_char(offset).link_tooltip.as_deref(), Some(tip), "{text}"); + } + assert!(doc.body[0].as_para().unwrap().plain_text().ends_with("FirstSecondInternal")); + } +} + +#[test] +fn oversized_screentips_share_one_utf8_bounded_value_and_save_at_the_same_size() { + use std::sync::Arc; + + let kept = "a".repeat(4095); + let tip = format!("{kept}Ω trailing text"); + let runs: String = (0..32).map(|i| format!("word ", i % 2)).collect(); + let xml = format!( + r##"{runs}"## + ); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(xml.as_bytes()).unwrap(); + let mut doc = craft_docx::read(&zip.finish().unwrap().into_inner()).unwrap(); + let p = doc.body[0].as_para().unwrap(); + assert_eq!(p.runs.len(), 32); + let first = p.runs[0].props.link_tooltip.as_ref().unwrap(); + assert_eq!(first.as_ref(), kept); + assert!(p.runs.iter().all(|run| Arc::ptr_eq(first, run.props.link_tooltip.as_ref().unwrap()))); + + // Native model data can arrive without going through the XML reader. + let props = CharProps { link: Some("#target".into()), link_tooltip: Some(Arc::from(tip)), ..CharProps::default() }; + doc.insert_text(&Pos::body(0, 0), "Native ", &props).unwrap(); + let saved = craft_docx::write(&doc).unwrap(); + let mut xml = String::new(); + zip::ZipArchive::new(std::io::Cursor::new(&saved)).unwrap().by_name("word/document.xml").unwrap().read_to_string(&mut xml).unwrap(); + assert_eq!(xml.matches("w:tooltip=").count(), 1); + assert!(xml.contains(&format!("w:tooltip=\"{kept}\""))); + assert!(!xml.contains("trailing text")); +} diff --git a/crates/wordmodel/src/props/char_props.rs b/crates/wordmodel/src/props/char_props.rs index a5111dcc6..556d03540 100644 --- a/crates/wordmodel/src/props/char_props.rs +++ b/crates/wordmodel/src/props/char_props.rs @@ -1,3 +1,5 @@ +use std::sync::Arc; + use super::color::{Rgb, TextColor}; use super::para_props::Border; use super::{Deserialize, Serialize}; @@ -430,6 +432,9 @@ pub struct CharProps { /// Hyperlink target: a URL, or `#bookmark` for an internal link. #[serde(skip_serializing_if = "Option::is_none")] pub link: Option, + /// Optional ScreenTip for the hyperlink. Runs from one link can share its text. + #[serde(skip_serializing_if = "Option::is_none")] + pub link_tooltip: Option>, /// Tracked insertion: index into `Document::revisions`. #[serde(skip_serializing_if = "Option::is_none")] pub ins: Option, @@ -566,6 +571,7 @@ impl CharProps { if c.link.take().is_some() && c.style.as_deref() == Some("Hyperlink") { c.style = None; } + c.link_tooltip = None; c } @@ -626,7 +632,11 @@ impl CharProps { } fn minus_document_marks(&mut self, base: &CharProps) { - drop_same_fields!(self, base; link, ins, del, ligatures); + if self.link == base.link && self.link_tooltip == base.link_tooltip { + self.link = None; + self.link_tooltip = None; + } + drop_same_fields!(self, base; ins, del, ligatures); } /// Apply every `Some` field of `patch` on top of `self`. @@ -676,7 +686,11 @@ impl CharProps { } fn overlay_document_marks(&mut self, patch: &CharProps) { - overlay_fields!(self, patch; link, ins, del, fmt_change, ligatures); + if let Some(link) = &patch.link { + self.link = Some(link.clone()); + self.link_tooltip = patch.link_tooltip.clone(); + } + overlay_fields!(self, patch; ins, del, fmt_change, ligatures); } pub fn overlaid(mut self, patch: &CharProps) -> CharProps { self.overlay(patch); @@ -701,6 +715,7 @@ impl CharProps { pub fn cleared(&self) -> CharProps { CharProps { link: self.link.clone(), + link_tooltip: self.link_tooltip.clone(), ins: self.ins, del: self.del, fmt_change: self.fmt_change.clone(), @@ -711,6 +726,6 @@ impl CharProps { } /// Just the formatting: without the link, revision marks and tracked formatting change. pub fn formatting(&self) -> CharProps { - CharProps { link: None, ins: None, del: None, fmt_change: None, ..self.clone() } + CharProps { link: None, link_tooltip: None, ins: None, del: None, fmt_change: None, ..self.clone() } } }