feat: [no ci] write tags for links and use quadpoints in link annotations

This commit is contained in:
Tobias Schmitz 2025-06-20 15:55:24 +02:00
parent ae3e029481
commit e10050a23f
No known key found for this signature in database
14 changed files with 238 additions and 193 deletions

View File

@ -36,9 +36,9 @@ pub fn jump_from_click(
) -> Option<Jump> { ) -> Option<Jump> {
// Try to find a link first. // Try to find a link first.
for (pos, item) in frame.items() { for (pos, item) in frame.items() {
if let FrameItem::Link(_, dest, size) = item { if let FrameItem::Link(link, size) = item {
if is_in_rect(*pos, *size, click) { if is_in_rect(*pos, *size, click) {
return Some(match dest { return Some(match &link.dest {
Destination::Url(url) => Jump::Url(url.clone()), Destination::Url(url) => Jump::Url(url.clone()),
Destination::Position(pos) => Jump::Position(*pos), Destination::Position(pos) => Jump::Position(*pos),
Destination::Location(loc) => { Destination::Location(loc) => {

View File

@ -1,7 +1,6 @@
use ecow::EcoString; use typst_library::foundations::{LinkMarker, Packed, StyleChain};
use typst_library::foundations::StyleChain;
use typst_library::layout::{Abs, Fragment, Frame, FrameItem, HideElem, Point, Sides}; use typst_library::layout::{Abs, Fragment, Frame, FrameItem, HideElem, Point, Sides};
use typst_library::model::{Destination, LinkElem, ParElem}; use typst_library::model::ParElem;
/// Frame-level modifications resulting from styles that do not impose any /// Frame-level modifications resulting from styles that do not impose any
/// layout structure. /// layout structure.
@ -21,8 +20,7 @@ use typst_library::model::{Destination, LinkElem, ParElem};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct FrameModifiers { pub struct FrameModifiers {
/// A destination to link to. /// A destination to link to.
dest: Option<Destination>, link: Option<Packed<LinkMarker>>,
alt: Option<EcoString>,
/// Whether the contents of the frame should be hidden. /// Whether the contents of the frame should be hidden.
hidden: bool, hidden: bool,
} }
@ -32,8 +30,7 @@ impl FrameModifiers {
pub fn get_in(styles: StyleChain) -> Self { pub fn get_in(styles: StyleChain) -> Self {
// TODO: maybe verify that an alt text was provided here // TODO: maybe verify that an alt text was provided here
Self { Self {
dest: LinkElem::current_in(styles), link: LinkMarker::current_in(styles),
alt: LinkElem::alt_in(styles),
hidden: HideElem::hidden_in(styles), hidden: HideElem::hidden_in(styles),
} }
} }
@ -98,7 +95,7 @@ fn modify_frame(
modifiers: &FrameModifiers, modifiers: &FrameModifiers,
link_box_outset: Option<Sides<Abs>>, link_box_outset: Option<Sides<Abs>>,
) { ) {
if let Some(dest) = &modifiers.dest { if let Some(link) = &modifiers.link {
let mut pos = Point::zero(); let mut pos = Point::zero();
let mut size = frame.size(); let mut size = frame.size();
if let Some(outset) = link_box_outset { if let Some(outset) = link_box_outset {
@ -106,7 +103,7 @@ fn modify_frame(
pos.x -= outset.left; pos.x -= outset.left;
size += outset.sum_by_axis(); size += outset.sum_by_axis();
} }
frame.push(pos, FrameItem::Link(modifiers.alt.clone(), dest.clone(), size)); frame.push(pos, FrameItem::Link(link.clone(), size));
} }
if modifiers.hidden { if modifiers.hidden {
@ -133,8 +130,8 @@ where
let reset; let reset;
let outer = styles; let outer = styles;
let mut styles = styles; let mut styles = styles;
if modifiers.dest.is_some() { if modifiers.link.is_some() {
reset = LinkElem::set_current(None).wrap(); reset = LinkMarker::set_current(None).wrap();
styles = outer.chain(&reset); styles = outer.chain(&reset);
} }

View File

@ -16,12 +16,12 @@ use crate::diag::{SourceResult, StrResult};
use crate::engine::Engine; use crate::engine::Engine;
use crate::foundations::{ use crate::foundations::{
elem, func, scope, ty, Context, Dict, Element, Fields, IntoValue, Label, elem, func, scope, ty, Context, Dict, Element, Fields, IntoValue, Label,
NativeElement, Recipe, RecipeIndex, Repr, Selector, Str, Style, StyleChain, Styles, NativeElement, Recipe, RecipeIndex, Repr, Selector, Show, Str, Style, StyleChain,
Value, Styles, Value,
}; };
use crate::introspection::Location; use crate::introspection::{Locatable, Location};
use crate::layout::{AlignElem, Alignment, Axes, Length, MoveElem, PadElem, Rel, Sides}; use crate::layout::{AlignElem, Alignment, Axes, Length, MoveElem, PadElem, Rel, Sides};
use crate::model::{Destination, EmphElem, LinkElem, StrongElem}; use crate::model::{Destination, EmphElem, StrongElem};
use crate::pdf::{ArtifactElem, ArtifactKind}; use crate::pdf::{ArtifactElem, ArtifactKind};
use crate::text::UnderlineElem; use crate::text::UnderlineElem;
@ -504,9 +504,13 @@ impl Content {
} }
/// Link the content somewhere. /// Link the content somewhere.
pub fn linked(self, alt: Option<EcoString>, dest: Destination) -> Self { pub fn linked(self, dest: Destination, alt: Option<EcoString>) -> Self {
self.styled(LinkElem::set_alt(alt)) let span = self.span();
.styled(LinkElem::set_current(Some(dest))) let link = Packed::new(LinkMarker::new(self, dest, alt));
link.clone()
.pack()
.spanned(span)
.styled(LinkMarker::set_current(Some(link)))
} }
/// Set alignments for this content. /// Set alignments for this content.
@ -988,6 +992,29 @@ pub trait PlainText {
fn plain_text(&self, text: &mut EcoString); fn plain_text(&self, text: &mut EcoString);
} }
/// An element that associates the body of a link with the destination.
#[elem(Show, Locatable)]
pub struct LinkMarker {
/// The content.
#[required]
pub body: Content,
#[required]
pub dest: Destination,
#[required]
pub alt: Option<EcoString>,
/// A link style that should be applied to elements.
#[internal]
#[ghost]
pub current: Option<Packed<LinkMarker>>,
}
impl Show for Packed<LinkMarker> {
fn show(&self, _: &mut Engine, _: StyleChain) -> SourceResult<Content> {
Ok(self.body.clone())
}
}
/// An error arising when trying to access a field of content. /// An error arising when trying to access a field of content.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum FieldAccessError { pub enum FieldAccessError {

View File

@ -4,14 +4,12 @@ use std::fmt::{self, Debug, Formatter};
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::sync::Arc; use std::sync::Arc;
use ecow::EcoString;
use typst_syntax::Span; use typst_syntax::Span;
use typst_utils::{LazyHash, Numeric}; use typst_utils::{LazyHash, Numeric};
use crate::foundations::{cast, dict, Dict, Label, Value}; use crate::foundations::{cast, dict, Dict, Label, LinkMarker, Packed, Value};
use crate::introspection::{Location, Tag}; use crate::introspection::{Location, Tag};
use crate::layout::{Abs, Axes, FixedAlignment, Length, Point, Size, Transform}; use crate::layout::{Abs, Axes, FixedAlignment, Length, Point, Size, Transform};
use crate::model::Destination;
use crate::text::TextItem; use crate::text::TextItem;
use crate::visualize::{Color, Curve, FixedStroke, Geometry, Image, Paint, Shape}; use crate::visualize::{Color, Curve, FixedStroke, Geometry, Image, Paint, Shape};
@ -474,7 +472,7 @@ pub enum FrameItem {
/// An image and its size. /// An image and its size.
Image(Image, Size, Span), Image(Image, Size, Span),
/// An internal or external link to a destination. /// An internal or external link to a destination.
Link(Option<EcoString>, Destination, Size), Link(Packed<LinkMarker>, Size),
/// An introspectable element that produced something within this frame. /// An introspectable element that produced something within this frame.
Tag(Tag), Tag(Tag),
} }
@ -486,7 +484,7 @@ impl Debug for FrameItem {
Self::Text(text) => write!(f, "{text:?}"), Self::Text(text) => write!(f, "{text:?}"),
Self::Shape(shape, _) => write!(f, "{shape:?}"), Self::Shape(shape, _) => write!(f, "{shape:?}"),
Self::Image(image, _, _) => write!(f, "{image:?}"), Self::Image(image, _, _) => write!(f, "{image:?}"),
Self::Link(alt, dest, _) => write!(f, "Link({alt:?}, {dest:?})"), Self::Link(link, _) => write!(f, "Link({:?}, {:?})", link.dest, link.alt),
Self::Tag(tag) => write!(f, "{tag:?}"), Self::Tag(tag) => write!(f, "{tag:?}"),
} }
} }

View File

@ -874,7 +874,7 @@ impl<'a> Generator<'a> {
if let Some(location) = first_occurrences.get(item.key.as_str()) { if let Some(location) = first_occurrences.get(item.key.as_str()) {
let dest = Destination::Location(*location); let dest = Destination::Location(*location);
// TODO: accept user supplied alt text // TODO: accept user supplied alt text
content = content.linked(None, dest); content = content.linked(dest, None);
} }
StrResult::Ok(content) StrResult::Ok(content)
}) })
@ -1010,7 +1010,7 @@ impl ElemRenderer<'_> {
if let Some(location) = (self.link)(i) { if let Some(location) = (self.link)(i) {
let dest = Destination::Location(location); let dest = Destination::Location(location);
// TODO: accept user supplied alt text // TODO: accept user supplied alt text
content = content.linked(None, dest); content = content.linked(dest, None);
} }
} }

View File

@ -148,7 +148,7 @@ impl Show for Packed<FootnoteElem> {
let loc = loc.variant(1); let loc = loc.variant(1);
// Add zero-width weak spacing to make the footnote "sticky". // Add zero-width weak spacing to make the footnote "sticky".
// TODO: accept user supplied alt text // TODO: accept user supplied alt text
Ok(HElem::hole().pack() + sup.linked(None, Destination::Location(loc))) Ok(HElem::hole().pack() + sup.linked(Destination::Location(loc), None))
} }
} }
@ -298,7 +298,7 @@ impl Show for Packed<FootnoteEntry> {
.pack() .pack()
.spanned(span) .spanned(span)
// TODO: accept user supplied alt text // TODO: accept user supplied alt text
.linked(None, Destination::Location(loc)) .linked(Destination::Location(loc), None)
.located(loc.variant(1)); .located(loc.variant(1));
Ok(Content::sequence([ Ok(Content::sequence([

View File

@ -91,11 +91,6 @@ pub struct LinkElem {
_ => args.expect("body")?, _ => args.expect("body")?,
})] })]
pub body: Content, pub body: Content,
/// A destination style that should be applied to elements.
#[internal]
#[ghost]
pub current: Option<Destination>,
} }
impl LinkElem { impl LinkElem {
@ -128,11 +123,11 @@ impl Show for Packed<LinkElem> {
} else { } else {
let alt = self.alt(styles); let alt = self.alt(styles);
match &self.dest { match &self.dest {
LinkTarget::Dest(dest) => body.linked(alt, dest.clone()), LinkTarget::Dest(dest) => body.linked(dest.clone(), alt),
LinkTarget::Label(label) => { LinkTarget::Label(label) => {
let elem = engine.introspector.query_label(*label).at(self.span())?; let elem = engine.introspector.query_label(*label).at(self.span())?;
let dest = Destination::Location(elem.location().unwrap()); let dest = Destination::Location(elem.location().unwrap());
body.clone().linked(alt, dest) body.linked(dest, alt)
} }
} }
}) })

View File

@ -445,7 +445,7 @@ impl Show for Packed<OutlineEntry> {
}; };
let loc = self.element_location().at(span)?; let loc = self.element_location().at(span)?;
Ok(block.linked(Some(alt), Destination::Location(loc))) Ok(block.linked(Destination::Location(loc), Some(alt)))
} }
} }

View File

@ -317,7 +317,7 @@ fn show_reference(
} }
// TODO: accept user supplied alt text // TODO: accept user supplied alt text
Ok(content.linked(None, Destination::Location(loc))) Ok(content.linked(Destination::Location(loc), None))
} }
/// Turn a reference into a citation. /// Turn a reference into a citation.

View File

@ -1,8 +1,7 @@
use std::collections::{BTreeMap, HashMap, HashSet}; use std::collections::{BTreeMap, HashMap, HashSet};
use std::num::NonZeroU64; use std::num::NonZeroU64;
use ecow::{eco_format, EcoString, EcoVec}; use ecow::{eco_format, EcoVec};
use krilla::annotation::Annotation;
use krilla::configure::{Configuration, ValidationError, Validator}; use krilla::configure::{Configuration, ValidationError, Validator};
use krilla::destination::{NamedDestination, XyzDestination}; use krilla::destination::{NamedDestination, XyzDestination};
use krilla::embed::EmbedError; use krilla::embed::EmbedError;
@ -25,12 +24,12 @@ use typst_syntax::Span;
use crate::embed::embed_files; use crate::embed::embed_files;
use crate::image::handle_image; use crate::image::handle_image;
use crate::link::handle_link; use crate::link::{handle_link, LinkAnnotation};
use crate::metadata::build_metadata; use crate::metadata::build_metadata;
use crate::outline::build_outline; use crate::outline::build_outline;
use crate::page::PageLabelExt; use crate::page::PageLabelExt;
use crate::shape::handle_shape; use crate::shape::handle_shape;
use crate::tags::{self, Placeholder, Tags}; use crate::tags::{self, Tags};
use crate::text::handle_text; use crate::text::handle_text;
use crate::util::{convert_path, display_font, AbsExt, TransformExt}; use crate::util::{convert_path, display_font, AbsExt, TransformExt};
use crate::PdfOptions; use crate::PdfOptions;
@ -111,7 +110,7 @@ fn convert_pages(gc: &mut GlobalContext, document: &mut Document) -> SourceResul
let mut surface = page.surface(); let mut surface = page.surface();
let mut fc = FrameContext::new(typst_page.frame.size()); let mut fc = FrameContext::new(typst_page.frame.size());
tags::restart(gc, &mut surface); tags::restart_open(gc, &mut surface);
handle_frame( handle_frame(
&mut fc, &mut fc,
@ -125,7 +124,7 @@ fn convert_pages(gc: &mut GlobalContext, document: &mut Document) -> SourceResul
surface.finish(); surface.finish();
tags::add_annotations(gc, &mut page, fc.annotations); tags::add_annotations(gc, &mut page, fc.link_annotations);
} }
} }
@ -179,14 +178,14 @@ impl State {
/// Context needed for converting a single frame. /// Context needed for converting a single frame.
pub(crate) struct FrameContext { pub(crate) struct FrameContext {
states: Vec<State>, states: Vec<State>,
annotations: Vec<(Placeholder, Annotation)>, pub(crate) link_annotations: HashMap<tags::LinkId, LinkAnnotation>,
} }
impl FrameContext { impl FrameContext {
pub(crate) fn new(size: Size) -> Self { pub(crate) fn new(size: Size) -> Self {
Self { Self {
states: vec![State::new(size)], states: vec![State::new(size)],
annotations: vec![], link_annotations: HashMap::new(),
} }
} }
@ -205,14 +204,6 @@ impl FrameContext {
pub(crate) fn state_mut(&mut self) -> &mut State { pub(crate) fn state_mut(&mut self) -> &mut State {
self.states.last_mut().unwrap() self.states.last_mut().unwrap()
} }
pub(crate) fn push_annotation(
&mut self,
placeholder: Placeholder,
annotation: Annotation,
) {
self.annotations.push((placeholder, annotation));
}
} }
/// Globally needed context for converting a typst document. /// Globally needed context for converting a typst document.
@ -294,14 +285,12 @@ pub(crate) fn handle_frame(
FrameItem::Image(image, size, span) => { FrameItem::Image(image, size, span) => {
handle_image(gc, fc, image, *size, surface, *span)? handle_image(gc, fc, image, *size, surface, *span)?
} }
FrameItem::Link(alt, dest, size) => { FrameItem::Link(link, size) => handle_link(fc, gc, link, *size),
handle_link(fc, gc, alt.as_ref().map(EcoString::to_string), dest, *size)
}
FrameItem::Tag(introspection::Tag::Start(elem)) => { FrameItem::Tag(introspection::Tag::Start(elem)) => {
tags::handle_start(gc, surface, elem) tags::handle_start(gc, surface, elem)
} }
FrameItem::Tag(introspection::Tag::End(loc, _)) => { FrameItem::Tag(introspection::Tag::End(loc, _)) => {
tags::handle_end(gc, surface, loc); tags::handle_end(gc, surface, *loc);
} }
} }

View File

@ -30,10 +30,6 @@ pub(crate) fn handle_image(
let interpolate = image.scaling() == Smart::Custom(ImageScaling::Smooth); let interpolate = image.scaling() == Smart::Custom(ImageScaling::Smooth);
if let Some(alt) = image.alt() {
surface.start_alt_text(alt);
}
gc.image_spans.insert(span); gc.image_spans.insert(span);
match image.kind() { match image.kind() {
@ -62,10 +58,6 @@ pub(crate) fn handle_image(
} }
} }
if image.alt().is_some() {
surface.end_alt_text();
}
surface.pop(); surface.pop();
surface.reset_location(); surface.reset_location();

View File

@ -1,52 +1,33 @@
use std::collections::hash_map::Entry;
use ecow::EcoString;
use krilla::action::{Action, LinkAction}; use krilla::action::{Action, LinkAction};
use krilla::annotation::{Annotation, LinkAnnotation, Target}; use krilla::annotation::Target;
use krilla::destination::XyzDestination; use krilla::destination::XyzDestination;
use krilla::geom::Rect; use krilla::geom as kg;
use typst_library::foundations::LinkMarker;
use typst_library::layout::{Abs, Point, Position, Size}; use typst_library::layout::{Abs, Point, Position, Size};
use typst_library::model::Destination; use typst_library::model::Destination;
use crate::convert::{FrameContext, GlobalContext}; use crate::convert::{FrameContext, GlobalContext};
use crate::tags::TagNode; use crate::tags::{Placeholder, TagNode};
use crate::util::{AbsExt, PointExt}; use crate::util::{AbsExt, PointExt};
pub(crate) struct LinkAnnotation {
pub(crate) placeholder: Placeholder,
pub(crate) alt: Option<String>,
pub(crate) rect: kg::Rect,
pub(crate) quad_points: Vec<kg::Point>,
pub(crate) target: Target,
}
pub(crate) fn handle_link( pub(crate) fn handle_link(
fc: &mut FrameContext, fc: &mut FrameContext,
gc: &mut GlobalContext, gc: &mut GlobalContext,
alt: Option<String>, link: &LinkMarker,
dest: &Destination,
size: Size, size: Size,
) { ) {
let mut min_x = Abs::inf(); let target = match &link.dest {
let mut min_y = Abs::inf();
let mut max_x = -Abs::inf();
let mut max_y = -Abs::inf();
let pos = Point::zero();
// Compute the bounding box of the transformed link.
for point in [
pos,
pos + Point::with_x(size.x),
pos + Point::with_y(size.y),
pos + size.to_point(),
] {
let t = point.transform(fc.state().transform());
min_x.set_min(t.x);
min_y.set_min(t.y);
max_x.set_max(t.x);
max_y.set_max(t.y);
}
let x1 = min_x.to_f32();
let x2 = max_x.to_f32();
let y1 = min_y.to_f32();
let y2 = max_y.to_f32();
let rect = Rect::from_ltrb(x1, y1, x2, y2).unwrap();
// TODO: Support quad points.
let target = match dest {
Destination::Url(u) => { Destination::Url(u) => {
Target::Action(Action::Link(LinkAction::new(u.to_string()))) Target::Action(Action::Link(LinkAction::new(u.to_string())))
} }
@ -69,13 +50,81 @@ pub(crate) fn handle_link(
} }
}; };
let placeholder = gc.tags.reserve_placeholder(); let entry = gc.tags.stack.last_mut().expect("a link parent");
gc.tags.push(TagNode::Placeholder(placeholder)); let link_id = entry.link_id.expect("a link parent");
fc.push_annotation( let rect = to_rect(fc, size);
placeholder, let quadpoints = quadpoints(rect);
Annotation::new_link(LinkAnnotation::new(rect, None, target), alt),
); match fc.link_annotations.entry(link_id) {
Entry::Occupied(occupied) => {
// Update the bounding box and add the quadpoints of an existing link annotation.
let annotation = occupied.into_mut();
annotation.rect = bounding_rect(annotation.rect, rect);
annotation.quad_points.extend_from_slice(&quadpoints);
}
Entry::Vacant(vacant) => {
let placeholder = gc.tags.reserve_placeholder();
gc.tags.push(TagNode::Placeholder(placeholder));
vacant.insert(LinkAnnotation {
placeholder,
rect,
quad_points: quadpoints.to_vec(),
alt: link.alt.as_ref().map(EcoString::to_string),
target,
});
}
}
}
// Compute the bounding box of the transformed link.
fn to_rect(fc: &FrameContext, size: Size) -> kg::Rect {
let mut min_x = Abs::inf();
let mut min_y = Abs::inf();
let mut max_x = -Abs::inf();
let mut max_y = -Abs::inf();
let pos = Point::zero();
for point in [
pos,
pos + Point::with_x(size.x),
pos + Point::with_y(size.y),
pos + size.to_point(),
] {
let t = point.transform(fc.state().transform());
min_x.set_min(t.x);
min_y.set_min(t.y);
max_x.set_max(t.x);
max_y.set_max(t.y);
}
let x1 = min_x.to_f32();
let x2 = max_x.to_f32();
let y1 = min_y.to_f32();
let y2 = max_y.to_f32();
kg::Rect::from_ltrb(x1, y1, x2, y2).unwrap()
}
fn bounding_rect(a: kg::Rect, b: kg::Rect) -> kg::Rect {
kg::Rect::from_ltrb(
a.left().min(b.left()),
a.top().min(b.top()),
a.right().max(b.right()),
a.bottom().max(b.bottom()),
)
.unwrap()
}
fn quadpoints(rect: kg::Rect) -> [kg::Point; 4] {
[
kg::Point::from_xy(rect.left(), rect.bottom()),
kg::Point::from_xy(rect.right(), rect.bottom()),
kg::Point::from_xy(rect.right(), rect.top()),
kg::Point::from_xy(rect.left(), rect.top()),
]
} }
fn pos_to_target(gc: &mut GlobalContext, pos: Position) -> Option<Target> { fn pos_to_target(gc: &mut GlobalContext, pos: Position) -> Option<Target> {

View File

@ -1,28 +1,43 @@
use std::cell::OnceCell; use std::cell::OnceCell;
use std::collections::HashMap;
use krilla::annotation::Annotation;
use krilla::page::Page; use krilla::page::Page;
use krilla::surface::Surface; use krilla::surface::Surface;
use krilla::tagging::{ use krilla::tagging::{
ArtifactType, ContentTag, Identifier, Node, Tag, TagGroup, TagTree, ArtifactType, ContentTag, Identifier, Node, Tag, TagGroup, TagTree,
}; };
use typst_library::foundations::{Content, StyleChain}; use typst_library::foundations::{Content, LinkMarker, StyleChain};
use typst_library::introspection::Location; use typst_library::introspection::Location;
use typst_library::model::{HeadingElem, OutlineElem, OutlineEntry}; use typst_library::model::{
Destination, HeadingElem, Outlinable, OutlineElem, OutlineEntry,
};
use typst_library::pdf::{ArtifactElem, ArtifactKind}; use typst_library::pdf::{ArtifactElem, ArtifactKind};
use crate::convert::GlobalContext; use crate::convert::GlobalContext;
use crate::link::LinkAnnotation;
pub(crate) struct Tags { pub(crate) struct Tags {
/// The intermediary stack of nested tag groups. /// The intermediary stack of nested tag groups.
pub(crate) stack: Vec<(Location, Tag, Vec<TagNode>)>, pub(crate) stack: Vec<StackEntry>,
/// A list of placeholders corresponding to a [`TagNode::Placeholder`].
pub(crate) placeholders: Vec<OnceCell<Node>>, pub(crate) placeholders: Vec<OnceCell<Node>>,
pub(crate) in_artifact: Option<(Location, ArtifactKind)>, pub(crate) in_artifact: Option<(Location, ArtifactKind)>,
pub(crate) link_id: LinkId,
/// The output. /// The output.
pub(crate) tree: Vec<TagNode>, pub(crate) tree: Vec<TagNode>,
} }
pub(crate) struct StackEntry {
pub(crate) loc: Location,
pub(crate) link_id: Option<LinkId>,
/// A list of tags that are wrapped around this tag when it is inserted into
/// the tag tree.
pub(crate) wrappers: Vec<Tag>,
pub(crate) tag: Tag,
pub(crate) nodes: Vec<TagNode>,
}
pub(crate) enum TagNode { pub(crate) enum TagNode {
Group(Tag, Vec<TagNode>), Group(Tag, Vec<TagNode>),
Leaf(Identifier), Leaf(Identifier),
@ -31,6 +46,9 @@ pub(crate) enum TagNode {
Placeholder(Placeholder), Placeholder(Placeholder),
} }
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct LinkId(u32);
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub(crate) struct Placeholder(usize); pub(crate) struct Placeholder(usize);
@ -42,6 +60,7 @@ impl Tags {
in_artifact: None, in_artifact: None,
tree: Vec::new(), tree: Vec::new(),
link_id: LinkId(0),
} }
} }
@ -64,14 +83,20 @@ impl Tags {
.expect("initialized placeholder node") .expect("initialized placeholder node")
} }
pub(crate) fn push(&mut self, node: TagNode) { /// Returns the current parent's list of children and the structure type ([Tag]).
if let Some((_, _, nodes)) = self.stack.last_mut() { /// In case of the document root the structure type will be `None`.
nodes.push(node); pub(crate) fn parent(&mut self) -> (Option<&mut Tag>, &mut Vec<TagNode>) {
if let Some(entry) = self.stack.last_mut() {
(Some(&mut entry.tag), &mut entry.nodes)
} else { } else {
self.tree.push(node); (None, &mut self.tree)
} }
} }
pub(crate) fn push(&mut self, node: TagNode) {
self.parent().1.push(node);
}
pub(crate) fn build_tree(&mut self) -> TagTree { pub(crate) fn build_tree(&mut self) -> TagTree {
let mut tree = TagTree::new(); let mut tree = TagTree::new();
let nodes = std::mem::take(&mut self.tree); let nodes = std::mem::take(&mut self.tree);
@ -98,73 +123,26 @@ impl Tags {
} }
} }
/// Returns the current parent's list of children and whether it is the tree root. fn context_supports(&self, _tag: &Tag) -> bool {
fn parent_nodes(&mut self) -> (bool, &mut Vec<TagNode>) { // TODO: generate using: https://pdfa.org/resource/iso-ts-32005-hierarchical-inclusion-rules/
if let Some((_, _, parent_nodes)) = self.stack.last_mut() { true
(false, parent_nodes)
} else {
(true, &mut self.tree)
}
} }
fn context_supports(&self, tag: &Tag) -> bool { fn next_link_id(&mut self) -> LinkId {
let Some((_, parent, _)) = self.stack.last() else { return true }; self.link_id.0 += 1;
self.link_id
use Tag::*;
match parent {
Part => true,
Article => !matches!(tag, Article),
Section => true,
BlockQuote => todo!(),
Caption => todo!(),
TOC => matches!(tag, TOC | TOCI),
// TODO: NonStruct is allowed to but (currently?) not supported by krilla
TOCI => matches!(tag, TOC | Lbl | Reference | P),
Index => todo!(),
P => todo!(),
H1(_) => todo!(),
H2(_) => todo!(),
H3(_) => todo!(),
H4(_) => todo!(),
H5(_) => todo!(),
H6(_) => todo!(),
L(_list_numbering) => todo!(),
LI => todo!(),
Lbl => todo!(),
LBody => todo!(),
Table => todo!(),
TR => todo!(),
TH(_table_header_scope) => todo!(),
TD => todo!(),
THead => todo!(),
TBody => todo!(),
TFoot => todo!(),
InlineQuote => todo!(),
Note => todo!(),
Reference => todo!(),
BibEntry => todo!(),
Code => todo!(),
Link => todo!(),
Annot => todo!(),
Figure(_) => todo!(),
Formula(_) => todo!(),
Datetime => todo!(),
Terms => todo!(),
Title => todo!(),
}
} }
} }
/// Marked-content may not cross page boundaries: restart tag that was still open /// Marked-content may not cross page boundaries: restart tag that was still open
/// at the end of the last page. /// at the end of the last page.
pub(crate) fn restart(gc: &mut GlobalContext, surface: &mut Surface) { pub(crate) fn restart_open(gc: &mut GlobalContext, surface: &mut Surface) {
// TODO: somehow avoid empty marked-content sequences // TODO: somehow avoid empty marked-content sequences
if let Some((_, kind)) = gc.tags.in_artifact { if let Some((_, kind)) = gc.tags.in_artifact {
start_artifact(gc, surface, kind); start_artifact(gc, surface, kind);
} else if let Some((_, _, nodes)) = gc.tags.stack.last_mut() { } else if let Some(entry) = gc.tags.stack.last_mut() {
let id = surface.start_tagged(ContentTag::Other); let id = surface.start_tagged(ContentTag::Other);
nodes.push(TagNode::Leaf(id)); entry.nodes.push(TagNode::Leaf(id));
} }
} }
@ -179,11 +157,16 @@ pub(crate) fn end_open(gc: &mut GlobalContext, surface: &mut Surface) {
pub(crate) fn add_annotations( pub(crate) fn add_annotations(
gc: &mut GlobalContext, gc: &mut GlobalContext,
page: &mut Page, page: &mut Page,
annotations: Vec<(Placeholder, Annotation)>, annotations: HashMap<LinkId, LinkAnnotation>,
) { ) {
for (placeholder, annotation) in annotations { for annotation in annotations.into_values() {
let annotation_id = page.add_tagged_annotation(annotation); let LinkAnnotation { placeholder, alt, rect, quad_points, target } = annotation;
gc.tags.init_placeholder(placeholder, Node::Leaf(annotation_id)); let annot = krilla::annotation::Annotation::new_link(
krilla::annotation::LinkAnnotation::new(rect, Some(quad_points), target),
alt,
);
let annot_id = page.add_tagged_annotation(annot);
gc.tags.init_placeholder(placeholder, Node::Leaf(annot_id));
} }
} }
@ -209,8 +192,10 @@ pub(crate) fn handle_start(
return; return;
} }
let mut link_id = None;
let mut wrappers = Vec::new();
let tag = if let Some(heading) = elem.to_packed::<HeadingElem>() { let tag = if let Some(heading) = elem.to_packed::<HeadingElem>() {
let level = heading.resolve_level(StyleChain::default()); let level = heading.level();
let name = heading.body.plain_text().to_string(); let name = heading.body.plain_text().to_string();
match level.get() { match level.get() {
1 => Tag::H1(Some(name)), 1 => Tag::H1(Some(name)),
@ -223,8 +208,14 @@ pub(crate) fn handle_start(
} }
} else if let Some(_) = elem.to_packed::<OutlineElem>() { } else if let Some(_) = elem.to_packed::<OutlineElem>() {
Tag::TOC Tag::TOC
} else if let Some(_outline_entry) = elem.to_packed::<OutlineEntry>() { } else if let Some(_) = elem.to_packed::<OutlineEntry>() {
Tag::TOCI Tag::TOCI
} else if let Some(link) = elem.to_packed::<LinkMarker>() {
link_id = Some(gc.tags.next_link_id());
if let Destination::Position(_) | Destination::Location(_) = link.dest {
wrappers.push(Tag::Reference);
}
Tag::Link
} else { } else {
return; return;
}; };
@ -234,35 +225,43 @@ pub(crate) fn handle_start(
} }
// close previous marked-content and open a nested tag. // close previous marked-content and open a nested tag.
if !gc.tags.stack.is_empty() { end_open(gc, surface);
surface.end_tagged();
}
let id = surface.start_tagged(krilla::tagging::ContentTag::Other); let id = surface.start_tagged(krilla::tagging::ContentTag::Other);
gc.tags.stack.push((loc, tag, vec![TagNode::Leaf(id)])); gc.tags.stack.push(StackEntry {
loc,
link_id,
wrappers,
tag,
nodes: vec![TagNode::Leaf(id)],
});
} }
pub(crate) fn handle_end(gc: &mut GlobalContext, surface: &mut Surface, loc: &Location) { pub(crate) fn handle_end(gc: &mut GlobalContext, surface: &mut Surface, loc: Location) {
if let Some((l, _)) = &gc.tags.in_artifact { if let Some((l, _)) = gc.tags.in_artifact {
if l == loc { if l == loc {
gc.tags.in_artifact = None; gc.tags.in_artifact = None;
surface.end_tagged(); surface.end_tagged();
if let Some((_, _, nodes)) = gc.tags.stack.last_mut() { if let Some(entry) = gc.tags.stack.last_mut() {
let id = surface.start_tagged(ContentTag::Other); let id = surface.start_tagged(ContentTag::Other);
nodes.push(TagNode::Leaf(id)); entry.nodes.push(TagNode::Leaf(id));
} }
} }
return; return;
} }
let Some((_, tag, nodes)) = gc.tags.stack.pop_if(|(l, ..)| l == loc) else { let Some(entry) = gc.tags.stack.pop_if(|e| e.loc == loc) else {
return; return;
}; };
surface.end_tagged(); surface.end_tagged();
let (is_root, parent_nodes) = gc.tags.parent_nodes(); let (parent_tag, parent_nodes) = gc.tags.parent();
parent_nodes.push(TagNode::Group(tag, nodes)); let mut node = TagNode::Group(entry.tag, entry.nodes);
if !is_root { for tag in entry.wrappers {
node = TagNode::Group(tag, vec![node]);
}
parent_nodes.push(node);
if parent_tag.is_some() {
// TODO: somehow avoid empty marked-content sequences // TODO: somehow avoid empty marked-content sequences
let id = surface.start_tagged(ContentTag::Other); let id = surface.start_tagged(ContentTag::Other);
parent_nodes.push(TagNode::Leaf(id)); parent_nodes.push(TagNode::Leaf(id));
@ -273,8 +272,7 @@ fn start_artifact(gc: &mut GlobalContext, surface: &mut Surface, kind: ArtifactK
let ty = artifact_type(kind); let ty = artifact_type(kind);
let id = surface.start_tagged(ContentTag::Artifact(ty)); let id = surface.start_tagged(ContentTag::Artifact(ty));
let (_, parent_nodes) = gc.tags.parent_nodes(); gc.tags.push(TagNode::Leaf(id));
parent_nodes.push(TagNode::Leaf(id));
} }
fn artifact_type(kind: ArtifactKind) -> ArtifactType { fn artifact_type(kind: ArtifactKind) -> ArtifactType {

View File

@ -524,7 +524,7 @@ fn render_links(canvas: &mut sk::Pixmap, ts: sk::Transform, frame: &Frame) {
let ts = ts.pre_concat(to_sk_transform(&group.transform)); let ts = ts.pre_concat(to_sk_transform(&group.transform));
render_links(canvas, ts, &group.frame); render_links(canvas, ts, &group.frame);
} }
FrameItem::Link(_, _, size) => { FrameItem::Link(_, size) => {
let w = size.x.to_pt() as f32; let w = size.x.to_pt() as f32;
let h = size.y.to_pt() as f32; let h = size.y.to_pt() as f32;
let rect = sk::Rect::from_xywh(0.0, 0.0, w, h).unwrap(); let rect = sk::Rect::from_xywh(0.0, 0.0, w, h).unwrap();