use super::asvg::{read_entries, write_entries};
use crate::ConvertError;
#[derive(Debug, Clone, Default)]
pub(crate) struct ImageAlt {
pub descr: String,
pub name: Option<String>,
}
pub(crate) fn inject(docx: Vec<u8>, alts: &[ImageAlt]) -> Result<Vec<u8>, ConvertError> {
if alts
.iter()
.all(|a| a.descr.trim().is_empty() && a.name.is_none())
{
return Ok(docx);
}
let mut entries = read_entries(&docx)?;
for (name, bytes) in entries.iter_mut() {
if name == "word/document.xml" {
let mut s = String::from_utf8_lossy(bytes).into_owned();
annotate_all(&mut s, alts);
*bytes = s.into_bytes();
}
}
write_entries(entries)
}
fn annotate_all(xml: &mut String, alts: &[ImageAlt]) {
let mut search_from = 0;
for alt in alts {
let Some(rel) = xml[search_from..].find("<wp:docPr ") else {
break;
};
let dp_start = search_from + rel;
let Some(end_rel) = xml[dp_start..].find("/>") else {
break;
};
let dp_end = dp_start + end_rel + "/>".len();
if alt.descr.trim().is_empty() && alt.name.is_none() {
search_from = dp_end;
continue;
}
let tag = rebuild_tag(&xml[dp_start..dp_end], alt);
let new_len = tag.len();
xml.replace_range(dp_start..dp_end, &tag);
search_from = dp_start + new_len;
}
}
fn rebuild_tag(tag: &str, alt: &ImageAlt) -> String {
let id = extract_attr(tag, "id").unwrap_or_else(|| "1".to_string());
let name = alt
.name
.clone()
.or_else(|| extract_attr(tag, "name"))
.unwrap_or_default();
let mut out = format!("<wp:docPr id=\"{}\"", escape_attr(&id));
if !name.is_empty() {
out.push_str(&format!(" name=\"{}\"", escape_attr(&name)));
}
if !alt.descr.trim().is_empty() {
out.push_str(&format!(" descr=\"{}\"", escape_attr(&alt.descr)));
}
out.push_str(" />");
out
}
fn extract_attr(tag: &str, attr: &str) -> Option<String> {
let key = format!("{attr}=\"");
let start = tag.find(&key)? + key.len();
let rest = &tag[start..];
let end = rest.find('"')?;
Some(rest[..end].to_string())
}
fn escape_attr(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}