use super::render_tree::BoundingBox;
#[derive(Debug, Clone, serde::Serialize)]
pub struct PdfLink {
pub uri: String,
pub rect: BoundingBox,
}
pub fn export_uri(uri: &str) -> Option<String> {
crate::model::hyperlink::classify_destination(uri)?;
let mut out = String::new();
for byte in uri.bytes() {
if byte.is_ascii() && byte != b' ' {
out.push(byte as char);
} else {
use std::fmt::Write;
let _ = write!(out, "%{byte:02X}");
}
}
Some(out)
}
pub(crate) fn clipped_rect(rect: BoundingBox, clip: BoundingBox) -> Option<BoundingBox> {
if [
rect.x,
rect.y,
rect.width,
rect.height,
clip.x,
clip.y,
clip.width,
clip.height,
]
.iter()
.any(|n| !n.is_finite())
|| rect.width <= 0.0
|| rect.height <= 0.0
{
return None;
}
let x = rect.x.max(clip.x);
let y = rect.y.max(clip.y);
let right = (rect.x + rect.width).min(clip.x + clip.width);
let bottom = (rect.y + rect.height).min(clip.y + clip.height);
(right > x && bottom > y).then_some(BoundingBox {
x,
y,
width: right - x,
height: bottom - y,
})
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn page_links(links: &[PdfLink], width: f64, height: f64) -> Vec<PdfLink> {
let page = BoundingBox {
x: 0.0,
y: 0.0,
width,
height,
};
links
.iter()
.filter_map(|link| {
Some(PdfLink {
uri: {
crate::model::hyperlink::classify_destination(&link.uri)?;
link.uri.clone()
},
rect: clipped_rect(link.rect, page)?,
})
})
.collect()
}
pub(crate) fn append_svg_links(svg: &mut String, links: &[PdfLink]) {
use std::fmt::Write;
fn escape(s: &str) -> String {
s.replace('&', "&")
.replace('"', """)
.replace('<', "<")
.replace('>', ">")
}
if links.is_empty() {
return;
}
let Some(end) = svg.rfind("</svg>") else {
return;
};
let mut overlay = String::from("<g data-rhwp-hyperlinks=\"true\">\n");
for link in links {
let Some(uri) = export_uri(&link.uri) else {
continue;
};
let b = link.rect;
let _ = writeln!(overlay, "<a href=\"{}\"><rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"transparent\" stroke=\"none\"/></a>", escape(&uri), b.x, b.y, b.width, b.height);
}
overlay.push_str("</g>\n");
svg.insert_str(end, &overlay);
}
#[derive(Clone, Debug)]
pub struct PdfNamedDestination {
pub name: String,
pub x: f64,
pub y: f64,
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn pdf_destination_key(name: &str) -> String {
use std::fmt::Write;
let mut output = String::from("rhwp-anchor-");
for byte in name.bytes() {
let _ = write!(output, "{byte:02x}");
}
output
}