use crate::dom::ElementId;
use crate::fonts::FontNamespace;
use crate::paint::Rect;
use crate::style::{
Alignment, PageStyleTarget, Size, Style, StyleError,
box_values::unsupported,
component::Component,
grammar::{Keyword, Label, Production, Property},
logical::{BOTTOM, LEFT, RIGHT, TOP},
units::Relative,
};
use std::{
cell::{Cell, RefCell},
collections::HashMap,
sync::Arc,
};
const ANCHOR_FUNCTION: &str = "anchor";
const ANCHOR_SIZE_FUNCTION: &str = "anchor-size";
const CALC_FUNCTION: &str = "calc";
const CENTER_FRACTION: f32 = 0.5;
pub(crate) const HORIZONTAL: usize = 0;
pub(crate) const VERTICAL: usize = 1;
const START_TRACK: usize = 0;
const CENTER_TRACK: usize = 1;
const END_TRACK: usize = 2;
const SIDES: [usize; 4] = [TOP, RIGHT, BOTTOM, LEFT];
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub(crate) struct AnchorName {
pub(crate) name: Arc<str>,
pub(crate) scope: FontNamespace,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) enum AnchorScope {
#[default]
None,
All(FontNamespace),
Names(Arc<[AnchorName]>),
}
impl AnchorScope {
pub(crate) fn covers(&self, name: &AnchorName) -> bool {
match self {
Self::None => false,
Self::All(scope) => *scope == name.scope,
Self::Names(names) => names.contains(name),
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) enum PositionAnchor {
#[default]
Normal,
None,
Auto,
Named(AnchorName),
MatchParent,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub(crate) enum AnchorReference {
Named(AnchorName),
Implicit,
Parent,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AreaReference {
Physical,
Containing,
Own,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct AreaTracks {
first: usize,
last: usize,
reference: AreaReference,
}
impl AreaTracks {
const ALL: Self = Self {
first: START_TRACK,
last: END_TRACK,
reference: AreaReference::Physical,
};
fn physical(self, horizontal: bool, own_rtl: bool, containing_rtl: bool) -> [usize; 2] {
let mirrored = horizontal
&& match self.reference {
AreaReference::Physical => false,
AreaReference::Containing => containing_rtl,
AreaReference::Own => own_rtl,
};
if mirrored {
[END_TRACK - self.last, END_TRACK - self.first]
} else {
[self.first, self.last]
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct PositionArea([AreaTracks; 2]);
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum AreaAlignment {
Start,
Center,
End,
AnchorCenter,
}
impl PositionArea {
pub(crate) fn tracks(self, own_rtl: bool, containing_rtl: bool) -> [[usize; 2]; 2] {
[HORIZONTAL, VERTICAL]
.map(|axis| self.0[axis].physical(axis == HORIZONTAL, own_rtl, containing_rtl))
}
pub(crate) fn rect(
self,
containing: [f32; 2],
anchor: Rect,
own_rtl: bool,
containing_rtl: bool,
) -> Rect {
let tracks = self.tracks(own_rtl, containing_rtl);
let lines = |axis: usize| {
let (start, end) = if axis == HORIZONTAL {
(anchor.x, anchor.x + anchor.width)
} else {
(anchor.y, anchor.y + anchor.height)
};
[start.min(0.0), start, end, end.max(containing[axis])]
};
let [x, y] = [HORIZONTAL, VERTICAL].map(|axis| {
let lines = lines(axis);
let [first, last] = tracks[axis];
[lines[first], lines[last + 1]]
});
Rect {
x: x[0],
y: y[0],
width: x[1] - x[0],
height: y[1] - y[0],
}
}
pub(crate) fn alignment(self, own_rtl: bool, containing_rtl: bool) -> [AreaAlignment; 2] {
self.tracks(own_rtl, containing_rtl)
.map(|tracks| match tracks {
[CENTER_TRACK, CENTER_TRACK] => AreaAlignment::Center,
[START_TRACK, END_TRACK] => AreaAlignment::AnchorCenter,
[START_TRACK, _] => AreaAlignment::End,
_ => AreaAlignment::Start,
})
}
fn transformed(self, tactic: Tactic, own_rtl: bool, containing_rtl: bool) -> Self {
let tracks = self.tracks(own_rtl, containing_rtl);
let mut moved = [AreaTracks::ALL; 2];
for axis in [HORIZONTAL, VERTICAL] {
let start_side = if axis == HORIZONTAL { LEFT } else { TOP };
let side = tactic.side(start_side);
let target = axis_of(side);
let [first, last] = tracks[axis];
let [first, last] = if side == start_side_of(target) {
[first, last]
} else {
[END_TRACK - last, END_TRACK - first]
};
moved[target] = AreaTracks {
first,
last,
reference: AreaReference::Physical,
};
}
Self(moved)
}
}
fn axis_of(side: usize) -> usize {
if side == LEFT || side == RIGHT {
HORIZONTAL
} else {
VERTICAL
}
}
fn start_side_of(axis: usize) -> usize {
if axis == HORIZONTAL { LEFT } else { TOP }
}
fn opposite(side: usize) -> usize {
match side {
TOP => BOTTOM,
BOTTOM => TOP,
LEFT => RIGHT,
_ => LEFT,
}
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum AreaAxis {
X,
Y,
Either,
}
fn area_keyword(keyword: Keyword) -> Option<(AreaAxis, usize, usize, AreaReference)> {
use AreaAxis::{Either, X, Y};
use AreaReference::{Containing, Own, Physical};
use Keyword as K;
let (start, center, end, span_start, span_end) = (
(START_TRACK, START_TRACK),
(CENTER_TRACK, CENTER_TRACK),
(END_TRACK, END_TRACK),
(START_TRACK, CENTER_TRACK),
(CENTER_TRACK, END_TRACK),
);
let ((first, last), axis, reference) = match keyword {
K::Left => (start, X, Physical),
K::Right => (end, X, Physical),
K::SpanLeft => (span_start, X, Physical),
K::SpanRight => (span_end, X, Physical),
K::Top => (start, Y, Physical),
K::Bottom => (end, Y, Physical),
K::SpanTop => (span_start, Y, Physical),
K::SpanBottom => (span_end, Y, Physical),
K::XStart | K::InlineStart => (start, X, Containing),
K::XEnd | K::InlineEnd => (end, X, Containing),
K::SpanXStart | K::SpanInlineStart => (span_start, X, Containing),
K::SpanXEnd | K::SpanInlineEnd => (span_end, X, Containing),
K::SelfXStart | K::SelfInlineStart => (start, X, Own),
K::SelfXEnd | K::SelfInlineEnd => (end, X, Own),
K::SpanSelfXStart | K::SpanSelfInlineStart => (span_start, X, Own),
K::SpanSelfXEnd | K::SpanSelfInlineEnd => (span_end, X, Own),
K::YStart | K::BlockStart => (start, Y, Containing),
K::YEnd | K::BlockEnd => (end, Y, Containing),
K::SpanYStart | K::SpanBlockStart => (span_start, Y, Containing),
K::SpanYEnd | K::SpanBlockEnd => (span_end, Y, Containing),
K::SelfYStart | K::SelfBlockStart => (start, Y, Own),
K::SelfYEnd | K::SelfBlockEnd => (end, Y, Own),
K::SpanSelfYStart | K::SpanSelfBlockStart => (span_start, Y, Own),
K::SpanSelfYEnd | K::SpanSelfBlockEnd => (span_end, Y, Own),
K::Start => (start, Either, Containing),
K::End => (end, Either, Containing),
K::SpanStart => (span_start, Either, Containing),
K::SpanEnd => (span_end, Either, Containing),
K::SelfStart => (start, Either, Own),
K::SelfEnd => (end, Either, Own),
K::SpanSelfStart => (span_start, Either, Own),
K::SpanSelfEnd => (span_end, Either, Own),
K::Center => (center, Either, Physical),
K::SpanAll => ((START_TRACK, END_TRACK), Either, Physical),
_ => return None,
};
Some((axis, first, last, reference))
}
pub(crate) fn position_area(value: &Component) -> Result<Option<PositionArea>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(None);
}
let mut keywords = Vec::new();
value.keywords(&mut keywords);
let parsed = keywords
.iter()
.map(|keyword| area_keyword(*keyword))
.collect::<Option<Vec<_>>>()
.ok_or_else(|| unsupported(value))?;
let tracks =
|(_, first, last, reference): (AreaAxis, usize, usize, AreaReference)| AreaTracks {
first,
last,
reference,
};
let mut axes = [None; 2];
let assign = |axes: &mut [Option<AreaTracks>; 2], axis: usize, keyword| {
axes[axis] = Some(tracks(keyword));
};
match parsed.as_slice() {
[single] if single.0 == AreaAxis::Either => {
assign(&mut axes, VERTICAL, *single);
assign(&mut axes, HORIZONTAL, *single);
}
[single] => {
let axis = if single.0 == AreaAxis::X {
HORIZONTAL
} else {
VERTICAL
};
assign(&mut axes, axis, *single);
axes[1 - axis] = Some(AreaTracks::ALL);
}
[first, second] => {
let (first_axis, second_axis) = match (first.0, second.0) {
(AreaAxis::X, _) | (AreaAxis::Either, AreaAxis::Y) => (HORIZONTAL, VERTICAL),
(AreaAxis::Y, _) | (AreaAxis::Either, AreaAxis::X | AreaAxis::Either) => {
(VERTICAL, HORIZONTAL)
}
};
assign(&mut axes, first_axis, *first);
assign(&mut axes, second_axis, *second);
}
_ => return Err(unsupported(value)),
}
match axes {
[Some(horizontal), Some(vertical)] => Ok(Some(PositionArea([horizontal, vertical]))),
_ => Err(unsupported(value)),
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum TacticKeyword {
FlipBlock,
FlipInline,
FlipStart,
FlipX,
FlipY,
}
impl TacticKeyword {
fn from_keyword(keyword: Keyword) -> Option<Self> {
Some(match keyword {
Keyword::FlipBlock => Self::FlipBlock,
Keyword::FlipInline => Self::FlipInline,
Keyword::FlipStart => Self::FlipStart,
Keyword::FlipX => Self::FlipX,
Keyword::FlipY => Self::FlipY,
_ => return None,
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Tactic([usize; 4]);
impl Default for Tactic {
fn default() -> Self {
Self::IDENTITY
}
}
impl Tactic {
pub(crate) const IDENTITY: Self = Self(SIDES);
pub(crate) fn of(keywords: &[TacticKeyword], containing_rtl: bool) -> Self {
keywords.iter().fold(Self::IDENTITY, |tactic, keyword| {
let swap = |pairs: &[[usize; 2]]| {
let mut sides = SIDES;
for [a, b] in pairs {
sides[*a] = *b;
sides[*b] = *a;
}
Self(sides)
};
let step = match keyword {
TacticKeyword::FlipBlock | TacticKeyword::FlipY => swap(&[[TOP, BOTTOM]]),
TacticKeyword::FlipInline | TacticKeyword::FlipX => swap(&[[LEFT, RIGHT]]),
TacticKeyword::FlipStart if containing_rtl => swap(&[[TOP, RIGHT], [BOTTOM, LEFT]]),
TacticKeyword::FlipStart => swap(&[[TOP, LEFT], [BOTTOM, RIGHT]]),
};
Self(tactic.0.map(|side| step.0[side]))
})
}
pub(crate) fn side(self, side: usize) -> usize {
self.0[side]
}
fn source(self, side: usize) -> usize {
SIDES
.into_iter()
.find(|source| self.0[*source] == side)
.expect("a tactic permutes the sides")
}
pub(crate) fn swaps_axes(self) -> bool {
axis_of(self.0[LEFT]) == VERTICAL
}
pub(crate) fn source_property(self, property: Property) -> Property {
let groups: [[Property; 4]; 2] = [
[
Property::Top,
Property::Right,
Property::Bottom,
Property::Left,
],
[
Property::MarginTop,
Property::MarginRight,
Property::MarginBottom,
Property::MarginLeft,
],
];
for group in groups {
if let Some(side) = group.iter().position(|member| *member == property) {
return group[self.source(side)];
}
}
let pairs = [
[Property::Width, Property::Height],
[Property::MinWidth, Property::MinHeight],
[Property::MaxWidth, Property::MaxHeight],
[Property::JustifySelf, Property::AlignSelf],
];
if self.swaps_axes()
&& let Some(pair) = pairs.iter().find(|pair| pair.contains(&property))
{
return if pair[0] == property {
pair[1]
} else {
pair[0]
};
}
property
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum TryOption {
Rule {
rule: Option<AnchorName>,
tactic: Arc<[TacticKeyword]>,
},
Area(Arc<Component>),
}
pub(crate) fn try_fallbacks(
value: &Component,
scope: FontNamespace,
) -> Result<Arc<[TryOption]>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(Arc::from([]));
}
value
.items()
.iter()
.map(|option| {
if position_area(option).is_ok() {
return Ok(TryOption::Area(Arc::new(option.clone())));
}
let rule = option
.slot(0)
.map(|name| dashed_name(name, scope))
.transpose()?;
let mut keywords = Vec::new();
if let Some(tactic) = option.slot(1) {
tactic.keywords(&mut keywords);
}
let tactic = keywords
.into_iter()
.map(TacticKeyword::from_keyword)
.collect::<Option<Arc<[_]>>>()
.ok_or_else(|| unsupported(option))?;
Ok(TryOption::Rule { rule, tactic })
})
.collect()
}
pub(crate) fn try_order(value: &Component) -> Result<Option<usize>, StyleError> {
match value.keyword() {
Some(Keyword::Normal) => Ok(None),
Some(Keyword::MostWidth | Keyword::MostInlineSize) => Ok(Some(HORIZONTAL)),
Some(Keyword::MostHeight | Keyword::MostBlockSize) => Ok(Some(VERTICAL)),
_ => Err(unsupported(value)),
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct PositionVisibility {
pub(crate) anchors_valid: bool,
pub(crate) anchors_visible: bool,
pub(crate) no_overflow: bool,
}
impl Default for PositionVisibility {
fn default() -> Self {
Self {
anchors_valid: false,
anchors_visible: true,
no_overflow: false,
}
}
}
pub(crate) fn position_visibility(value: &Component) -> Result<PositionVisibility, StyleError> {
let mut keywords = Vec::new();
value.keywords(&mut keywords);
let mut visibility = PositionVisibility {
anchors_valid: false,
anchors_visible: false,
no_overflow: false,
};
for keyword in keywords {
match keyword {
Keyword::Always => {}
Keyword::AnchorsValid => visibility.anchors_valid = true,
Keyword::AnchorsVisible => visibility.anchors_visible = true,
Keyword::NoOverflow => visibility.no_overflow = true,
_ => return Err(unsupported(value)),
}
}
Ok(visibility)
}
fn dashed_name(value: &Component, scope: FontNamespace) -> Result<AnchorName, StyleError> {
match value.unwrap() {
Component::Ident(name) => Ok(AnchorName {
name: Arc::from(name.as_ref()),
scope,
}),
other => Err(unsupported(other)),
}
}
fn names(value: &Component, scope: FontNamespace) -> Result<Arc<[AnchorName]>, StyleError> {
value
.items()
.iter()
.map(|name| dashed_name(name, scope))
.collect()
}
pub(crate) fn anchor_names(
value: &Component,
scope: FontNamespace,
) -> Result<Arc<[AnchorName]>, StyleError> {
if value.keyword() == Some(Keyword::None) {
return Ok(Arc::from([]));
}
names(value, scope)
}
pub(crate) fn anchor_scope(
value: &Component,
scope: FontNamespace,
) -> Result<AnchorScope, StyleError> {
match value.keyword() {
Some(Keyword::None) => Ok(AnchorScope::None),
Some(Keyword::All) => Ok(AnchorScope::All(scope)),
_ => names(value, scope).map(AnchorScope::Names),
}
}
pub(crate) fn position_anchor(
value: &Component,
scope: FontNamespace,
) -> Result<PositionAnchor, StyleError> {
match value.keyword() {
Some(Keyword::Normal) => Ok(PositionAnchor::Normal),
Some(Keyword::None) => Ok(PositionAnchor::None),
Some(Keyword::Auto) => Ok(PositionAnchor::Auto),
Some(Keyword::MatchParent) => Ok(PositionAnchor::MatchParent),
_ => dashed_name(value, scope).map(PositionAnchor::Named),
}
}
pub(crate) fn accepted(property: Property) -> bool {
use Property as P;
matches!(
property,
P::Top
| P::Right
| P::Bottom
| P::Left
| P::InsetBlockStart
| P::InsetBlockEnd
| P::InsetInlineStart
| P::InsetInlineEnd
| P::MarginTop
| P::MarginRight
| P::MarginBottom
| P::MarginLeft
| P::MarginBlockStart
| P::MarginBlockEnd
| P::MarginInlineStart
| P::MarginInlineEnd
| P::Width
| P::MinWidth
| P::MaxWidth
| P::Height
| P::MinHeight
| P::MaxHeight
| P::BlockSize
| P::MinBlockSize
| P::MaxBlockSize
| P::InlineSize
| P::MinInlineSize
| P::MaxInlineSize
| P::AlignSelf
| P::JustifySelf
| P::PositionAnchor
| P::PositionArea
)
}
pub(super) fn namespaced(property: Property, value: &crate::style::declaration::Specified) -> bool {
match value {
crate::style::declaration::Specified::Value(value) => match property {
Property::AnchorName | Property::AnchorScope | Property::PositionTryFallbacks => {
value.keyword() != Some(Keyword::None)
}
Property::PositionAnchor => value.keyword().is_none(),
_ => mentions_anchor(value),
},
crate::style::declaration::Specified::Toggle(values) => values
.iter()
.any(|value| namespaced(property, &value.value)),
_ => false,
}
}
pub(crate) fn valid(property: Property, value: &Component) -> bool {
if !matches!(
property,
Property::PositionTryFallbacks | Property::PositionTry
) {
return true;
}
let mut tactics = Vec::new();
value.references(&[Label::Production(Production::TryTactic)], &mut tactics);
tactics.iter().all(|(_, tactic)| {
let mut keywords = Vec::new();
tactic.keywords(&mut keywords);
keywords
.iter()
.enumerate()
.all(|(index, keyword)| !keywords[..index].contains(keyword))
})
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct AnchorFunctions {
pub(crate) anchor: bool,
pub(crate) size: bool,
}
impl AnchorFunctions {
pub(crate) fn allows(self, name: &str) -> bool {
(self.anchor && name.eq_ignore_ascii_case(ANCHOR_FUNCTION))
|| (self.size && name.eq_ignore_ascii_case(ANCHOR_SIZE_FUNCTION))
}
}
pub(crate) fn functions(property: Property) -> AnchorFunctions {
crate::style::declaration::longhands(property).fold(
AnchorFunctions::default(),
|functions, longhand| {
let target = target(crate::style::logical::physical(
longhand,
crate::style::logical::Flow::default(),
));
let allowed = target.map(AnchorTarget::functions).unwrap_or_default();
AnchorFunctions {
anchor: functions.anchor || allowed.anchor,
size: functions.size || allowed.size,
}
},
)
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum AnchorTarget {
Inset(usize),
Margin(usize),
Size(usize),
}
impl AnchorTarget {
fn functions(self) -> AnchorFunctions {
AnchorFunctions {
anchor: matches!(self, Self::Inset(_)),
size: true,
}
}
fn axis(self) -> usize {
match self {
Self::Inset(side) | Self::Margin(side) => axis_of(side),
Self::Size(axis) => axis,
}
}
fn initial(self) -> Size {
match self {
Self::Margin(_) => Size::ZERO,
Self::Inset(_) | Self::Size(_) => Size::Auto,
}
}
}
fn target(property: Property) -> Option<AnchorTarget> {
use Property as P;
Some(match property {
P::Top => AnchorTarget::Inset(TOP),
P::Right => AnchorTarget::Inset(RIGHT),
P::Bottom => AnchorTarget::Inset(BOTTOM),
P::Left => AnchorTarget::Inset(LEFT),
P::MarginTop => AnchorTarget::Margin(TOP),
P::MarginRight => AnchorTarget::Margin(RIGHT),
P::MarginBottom => AnchorTarget::Margin(BOTTOM),
P::MarginLeft => AnchorTarget::Margin(LEFT),
P::Width | P::MinWidth | P::MaxWidth => AnchorTarget::Size(HORIZONTAL),
P::Height | P::MinHeight | P::MaxHeight => AnchorTarget::Size(VERTICAL),
_ => return None,
})
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum AnchorSide {
Inside,
Outside,
Physical(usize),
Start,
End,
SelfStart,
SelfEnd,
Fraction(f32),
}
impl AnchorSide {
pub(crate) fn from_name(name: &str) -> Option<Self> {
Some(match name.to_ascii_lowercase().as_str() {
"inside" => Self::Inside,
"outside" => Self::Outside,
"top" => Self::Physical(TOP),
"right" => Self::Physical(RIGHT),
"bottom" => Self::Physical(BOTTOM),
"left" => Self::Physical(LEFT),
"start" => Self::Start,
"end" => Self::End,
"self-start" => Self::SelfStart,
"self-end" => Self::SelfEnd,
"center" => Self::Fraction(CENTER_FRACTION),
_ => return None,
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum AnchorDimension {
Width,
Height,
Block,
Inline,
SelfBlock,
SelfInline,
}
impl AnchorDimension {
pub(crate) fn from_name(name: &str) -> Option<Self> {
Some(match name.to_ascii_lowercase().as_str() {
"width" => Self::Width,
"height" => Self::Height,
"block" => Self::Block,
"inline" => Self::Inline,
"self-block" => Self::SelfBlock,
"self-inline" => Self::SelfInline,
_ => return None,
})
}
fn axis(self) -> usize {
match self {
Self::Width | Self::Inline | Self::SelfInline => HORIZONTAL,
Self::Height | Self::Block | Self::SelfBlock => VERTICAL,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum AnchorQuery {
Anchor {
name: Option<Arc<str>>,
side: AnchorSide,
},
Size {
name: Option<Arc<str>>,
dimension: Option<AnchorDimension>,
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct AnchorBox {
pub(crate) rect: Rect,
pub(crate) visible: bool,
}
#[derive(Clone)]
pub(crate) struct AnchorNode {
pub(crate) multicol: bool,
pub(crate) has_box: bool,
pub(crate) visible: bool,
pub(crate) parent: Option<PageStyleTarget>,
pub(crate) order: usize,
pub(crate) position: crate::style::Position,
pub(crate) contains_absolute: bool,
pub(crate) contains_fixed: bool,
pub(crate) names: Arc<[AnchorName]>,
pub(crate) scope: AnchorScope,
pub(crate) default: Option<AnchorReference>,
pub(crate) page_defaults: Arc<[(usize, Option<AnchorReference>)]>,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct AnchorFrame {
pub(crate) page: usize,
pub(crate) containing: [f32; 2],
pub(crate) containing_rtl: bool,
pub(crate) anchors: Vec<(AnchorReference, Option<AnchorBox>)>,
pub(crate) option: usize,
pub(crate) overflows: bool,
}
impl AnchorFrame {
pub(crate) fn anchor(&self, reference: &AnchorReference) -> Option<AnchorBox> {
self.anchors
.iter()
.find(|(candidate, _)| candidate == reference)
.and_then(|(_, anchor)| *anchor)
}
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) struct AnchorKey {
pub(crate) target: PageStyleTarget,
pub(crate) page: usize,
}
pub(crate) type AnchorFrameMap = HashMap<AnchorKey, AnchorFrame>;
type Consultation = (PageStyleTarget, Option<usize>);
#[derive(Clone, Default)]
pub(crate) struct AnchorFrames {
known: AnchorFrameMap,
consulted: RefCell<HashMap<Consultation, Option<AnchorFrame>>>,
consulted_pages: RefCell<HashMap<PageStyleTarget, Vec<usize>>>,
}
impl AnchorFrames {
fn find(
known: &AnchorFrameMap,
target: PageStyleTarget,
page: Option<usize>,
) -> Option<&AnchorFrame> {
if let Some(page) = page {
known.get(&AnchorKey { target, page })
} else {
known
.iter()
.filter(|(key, _)| key.target == target)
.min_by_key(|(key, _)| key.page)
.map(|(_, frame)| frame)
}
}
fn page_list(known: &AnchorFrameMap, target: PageStyleTarget) -> Vec<usize> {
let mut pages: Vec<_> = known
.keys()
.filter_map(|key| (key.target == target).then_some(key.page))
.collect();
pages.sort_unstable();
pages
}
pub(crate) fn pages(&self, target: PageStyleTarget) -> Vec<usize> {
let pages = Self::page_list(&self.known, target);
self.consulted_pages
.borrow_mut()
.insert(target, pages.clone());
pages
}
pub(crate) fn frame(
&self,
target: PageStyleTarget,
page: Option<usize>,
) -> Option<&AnchorFrame> {
let frame = Self::find(&self.known, target, page);
self.consulted
.borrow_mut()
.insert((target, page), frame.cloned());
frame
}
pub(crate) fn settled(&self, measured: &AnchorFrameMap) -> bool {
self.consulted
.borrow()
.iter()
.all(|((target, page), frame)| Self::find(measured, *target, *page) == frame.as_ref())
&& self
.consulted_pages
.borrow()
.iter()
.all(|(target, pages)| Self::page_list(measured, *target) == *pages)
}
pub(crate) fn measured(&mut self, measured: AnchorFrameMap) {
self.known = measured;
self.consulted.get_mut().clear();
self.consulted_pages.get_mut().clear();
}
}
#[derive(Clone, Copy)]
pub(crate) struct Anchoring<'a> {
pub(crate) page: Option<usize>,
pub(crate) scope: Option<FontNamespace>,
pub(crate) frames: &'a AnchorFrames,
pub(crate) key: PageStyleTarget,
pub(crate) tactic: Tactic,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct AnchorStyle {
pub(crate) pages: Arc<[(usize, Style)]>,
pub(crate) namespaces: HashMap<Property, FontNamespace>,
pub(crate) protected: Arc<[Property]>,
pub(crate) option: usize,
pub(crate) frame: Option<Arc<AnchorFrame>>,
pub(crate) names: Arc<[AnchorName]>,
pub(crate) scope: AnchorScope,
pub(crate) position_anchor: PositionAnchor,
pub(crate) area: Option<PositionArea>,
pub(crate) fallbacks: Arc<[TryOption]>,
pub(crate) order: Option<usize>,
pub(crate) visibility: PositionVisibility,
pub(crate) references: Arc<[AnchorReference]>,
pub(crate) invalid_reference: bool,
pub(crate) options: Arc<[Style]>,
pub(crate) tactic: Tactic,
}
impl AnchorStyle {
pub(crate) fn default_reference(&self) -> Option<AnchorReference> {
match &self.position_anchor {
PositionAnchor::Normal => self.area.map(|_| AnchorReference::Implicit),
PositionAnchor::None => None,
PositionAnchor::Auto => Some(AnchorReference::Implicit),
PositionAnchor::Named(name) => Some(AnchorReference::Named(name.clone())),
PositionAnchor::MatchParent => Some(AnchorReference::Parent),
}
}
pub(crate) fn located_references(&self) -> Vec<AnchorReference> {
let mut references: Vec<AnchorReference> = self.default_reference().into_iter().collect();
for reference in self.references.iter() {
if !references.contains(reference) {
references.push(reference.clone());
}
}
for option in self.options.iter() {
for reference in option.anchor.located_references() {
if !references.contains(&reference) {
references.push(reference);
}
}
}
for (_, page) in self.pages.iter() {
for reference in page.anchor.located_references() {
if !references.contains(&reference) {
references.push(reference);
}
}
}
references
}
pub(crate) fn anchors(&self) -> bool {
self.default_reference().is_some()
|| !self.references.is_empty()
|| !self.fallbacks.is_empty()
|| self.invalid_reference
|| self.visibility.no_overflow
}
}
pub(crate) struct AnchorContext<'a> {
frame: Option<&'a AnchorFrame>,
positioned: bool,
default: Option<AnchorReference>,
area: Option<PositionArea>,
own_rtl: bool,
scope: FontNamespace,
tactic: Tactic,
target: AnchorTarget,
references: RefCell<Vec<AnchorReference>>,
unresolved: Cell<bool>,
}
impl AnchorContext<'_> {
fn containing_rtl(&self) -> bool {
self.frame.is_some_and(|frame| frame.containing_rtl)
}
fn reference(&self, name: Option<&Arc<str>>) -> Option<AnchorReference> {
let reference = match name {
Some(name) => AnchorReference::Named(AnchorName {
name: name.clone(),
scope: self.scope,
}),
None => self.default.clone()?,
};
let mut references = self.references.borrow_mut();
if !references.contains(&reference) {
references.push(reference.clone());
}
Some(reference)
}
fn anchor_box(&self, name: Option<&Arc<str>>) -> Option<Rect> {
let reference = self.reference(name);
if !self.positioned {
return None;
}
Some(self.frame?.anchor(&reference?)?.rect)
}
fn containing(&self) -> Option<Rect> {
let frame = self.frame?;
let whole = Rect {
x: 0.0,
y: 0.0,
width: frame.containing[HORIZONTAL],
height: frame.containing[VERTICAL],
};
let area = self.area.and_then(|area| {
let anchor = frame.anchor(self.default.as_ref()?)?;
Some(area.rect(
frame.containing,
anchor.rect,
self.own_rtl,
frame.containing_rtl,
))
});
Some(area.unwrap_or(whole))
}
fn anchor(&self, name: Option<&Arc<str>>, side: AnchorSide) -> Option<f32> {
let AnchorTarget::Inset(property) = self.target else {
return None;
};
let anchor = self.anchor_box(name)?;
let containing = self.containing()?;
let written = self.tactic.source(property);
let axis = axis_of(written);
let containing_start = if axis == HORIZONTAL && self.containing_rtl() {
RIGHT
} else {
start_side_of(axis)
};
let own_start = if axis == HORIZONTAL && self.own_rtl {
RIGHT
} else {
start_side_of(axis)
};
let edge = |side: usize| match side {
TOP => anchor.y,
BOTTOM => anchor.y + anchor.height,
LEFT => anchor.x,
_ => anchor.x + anchor.width,
};
let coordinate = match side {
AnchorSide::Inside => edge(property),
AnchorSide::Outside => edge(opposite(property)),
AnchorSide::Physical(physical) if axis_of(physical) == axis => {
edge(self.tactic.side(physical))
}
AnchorSide::Physical(_) => return None,
AnchorSide::Start => edge(self.tactic.side(containing_start)),
AnchorSide::End => edge(self.tactic.side(opposite(containing_start))),
AnchorSide::SelfStart => edge(self.tactic.side(own_start)),
AnchorSide::SelfEnd => edge(self.tactic.side(opposite(own_start))),
AnchorSide::Fraction(fraction) => {
let start = edge(self.tactic.side(containing_start));
let end = edge(self.tactic.side(opposite(containing_start)));
start + fraction * (end - start)
}
};
Some(match property {
TOP => coordinate - containing.y,
BOTTOM => containing.y + containing.height - coordinate,
LEFT => coordinate - containing.x,
_ => containing.x + containing.width - coordinate,
})
}
fn anchor_size(
&self,
name: Option<&Arc<str>>,
dimension: Option<AnchorDimension>,
) -> Option<f32> {
let anchor = self.anchor_box(name)?;
let axis = match dimension {
Some(dimension) => {
let axis = dimension.axis();
if self.tactic.swaps_axes() {
1 - axis
} else {
axis
}
}
None => self.target.axis(),
};
Some(if axis == HORIZONTAL {
anchor.width
} else {
anchor.height
})
}
pub(crate) fn resolve(&self, query: &AnchorQuery) -> Option<f32> {
match query {
AnchorQuery::Anchor { name, side } => self.anchor(name.as_ref(), *side),
AnchorQuery::Size { name, dimension } => self.anchor_size(name.as_ref(), *dimension),
}
}
pub(crate) fn checkpoint(&self) -> (usize, bool) {
(self.references.borrow().len(), self.unresolved.get())
}
pub(crate) fn restore(&self, (references, unresolved): (usize, bool)) {
self.references.borrow_mut().truncate(references);
self.unresolved.set(unresolved);
}
pub(crate) fn fail(&self) {
self.unresolved.set(true);
}
}
#[derive(Clone, Copy)]
pub(crate) struct AnchorEvaluation<'a> {
pub(crate) functions: AnchorFunctions,
pub(crate) context: Option<&'a AnchorContext<'a>>,
}
fn mentions_anchor(value: &Component) -> bool {
if value
.find(Label::Production(Production::AnchorFn))
.is_some()
|| value
.find(Label::Production(Production::AnchorSizeFn))
.is_some()
{
return true;
}
match value.unwrap() {
Component::Math(source, ..) => {
fn nested(input: &mut cssparser::Parser<'_, '_>) -> bool {
let mut found = false;
while let Ok(token) = input.next().cloned() {
match token {
cssparser::Token::Function(name)
if name.eq_ignore_ascii_case(ANCHOR_FUNCTION)
|| name.eq_ignore_ascii_case(ANCHOR_SIZE_FUNCTION) =>
{
found = true;
}
cssparser::Token::Function(_)
| cssparser::Token::ParenthesisBlock
| cssparser::Token::SquareBracketBlock
| cssparser::Token::CurlyBracketBlock => {
found |= input
.parse_nested_block(|input| {
Ok::<_, cssparser::ParseError<'_, ()>>(nested(input))
})
.unwrap_or(false);
}
_ => {}
}
}
found
}
nested(&mut cssparser::Parser::new(
&mut cssparser::ParserInput::new(source),
))
}
_ => false,
}
}
pub(crate) fn size(
value: &Component,
style: &mut Style,
relative: &Relative<'_>,
target: AnchorTarget,
) -> Result<Size, StyleError> {
if !mentions_anchor(value) {
return Size::from_component(value, relative);
}
let frame = relative
.anchoring
.and_then(|anchoring| anchoring.frames.frame(anchoring.key, anchoring.page));
let context = AnchorContext {
frame,
positioned: style.position.is_out_of_flow(),
default: style.anchor.default_reference(),
area: style.anchor.area,
own_rtl: style.rtl,
scope: relative
.anchoring
.and_then(|anchoring| anchoring.scope)
.unwrap_or_else(|| style.element_font_namespace()),
tactic: relative
.anchoring
.map_or(Tactic::IDENTITY, |anchoring| anchoring.tactic),
target,
references: RefCell::default(),
unresolved: Cell::new(false),
};
let evaluation = AnchorEvaluation {
functions: target.functions(),
context: Some(&context),
};
let computed = match value.unwrap() {
Component::Math(..) => {
crate::style::box_values::anchored_length_percentage(value, relative, evaluation)?
}
function => crate::style::values::anchored_math(
&format!("{CALC_FUNCTION}({function})"),
relative,
evaluation,
)?
.length_percentage(crate::style::calc::Range::ALL),
};
let missing = context.references.borrow().is_empty()
|| frame.is_none_or(|frame| {
context
.references
.borrow()
.iter()
.any(|reference| frame.anchor(reference).is_none())
});
let recorded = context.references.into_inner();
if !recorded.is_empty() {
let mut references = style.anchor.references.to_vec();
for reference in recorded {
if !references.contains(&reference) {
references.push(reference);
}
}
style.anchor.references = Arc::from(references);
}
if context.unresolved.get() {
style.anchor.invalid_reference |= missing;
return Ok(target.initial());
}
Ok(Size::Value(computed))
}
pub(crate) fn supports(value: &Component, relative: &Relative<'_>, target: AnchorTarget) -> bool {
size(value, &mut Style::default(), relative, target).is_ok()
}
pub(crate) fn transformed_alignment(
alignment: Alignment,
tactic: Tactic,
horizontal: bool,
own_rtl: bool,
containing_rtl: bool,
) -> Alignment {
let source_axis = if horizontal == tactic.swaps_axes() {
VERTICAL
} else {
HORIZONTAL
};
let target_axis = if horizontal { HORIZONTAL } else { VERTICAL };
let start = |axis: usize, rtl: bool| {
if axis == HORIZONTAL && rtl {
RIGHT
} else {
start_side_of(axis)
}
};
let moved = |side: usize| tactic.side(side);
let logical = |side: usize, rtl: bool, start_keyword, end_keyword| {
if moved(side) == start(target_axis, rtl) {
start_keyword
} else {
end_keyword
}
};
let containing = containing_rtl;
match alignment {
Alignment::Start => logical(
start(source_axis, containing),
containing,
Alignment::Start,
Alignment::End,
),
Alignment::End => logical(
opposite(start(source_axis, containing)),
containing,
Alignment::Start,
Alignment::End,
),
Alignment::FlexStart => logical(
start(source_axis, containing),
containing,
Alignment::FlexStart,
Alignment::FlexEnd,
),
Alignment::FlexEnd => logical(
opposite(start(source_axis, containing)),
containing,
Alignment::FlexStart,
Alignment::FlexEnd,
),
Alignment::SelfStart => logical(
start(source_axis, own_rtl),
own_rtl,
Alignment::SelfStart,
Alignment::SelfEnd,
),
Alignment::SelfEnd => logical(
opposite(start(source_axis, own_rtl)),
own_rtl,
Alignment::SelfStart,
Alignment::SelfEnd,
),
Alignment::Left | Alignment::Right => {
let side = if alignment == Alignment::Left {
LEFT
} else {
RIGHT
};
match moved(side) {
LEFT => Alignment::Left,
RIGHT => Alignment::Right,
TOP => Alignment::Start,
_ => Alignment::End,
}
}
other => other,
}
}
pub(crate) fn transform_computed(style: &mut Style, tactic: Tactic, containing_rtl: bool) {
if tactic == Tactic::IDENTITY {
return;
}
let original = style.clone();
let own_rtl = style.rtl;
style.grid.justify_self = transformed_alignment(
style.grid.justify_self,
tactic,
true,
own_rtl,
containing_rtl,
);
style.flex.align_self = transformed_alignment(
style.flex.align_self,
tactic,
false,
own_rtl,
containing_rtl,
);
style.anchor.area = style
.anchor
.area
.map(|area| area.transformed(tactic, own_rtl, containing_rtl));
style.anchor.tactic = tactic;
for property in style.anchor.protected.clone().iter() {
crate::style::properties::copy(*property, style, &original);
}
}
pub(crate) fn finish(style: &mut Style, frame: Option<&AnchorFrame>) {
let visibility = style.anchor.visibility;
let hidden_anchor = visibility.anchors_visible
&& style.position.is_out_of_flow()
&& style
.anchor
.default_reference()
.zip(frame)
.and_then(|(reference, frame)| frame.anchor(&reference))
.is_some_and(|anchor| !anchor.visible);
let overflowing = visibility.no_overflow
&& style.position.is_out_of_flow()
&& frame.is_some_and(|frame| frame.overflows);
let invalid = visibility.anchors_valid
&& style.position.is_out_of_flow()
&& style.anchor.invalid_reference;
if hidden_anchor || overflowing || invalid {
style.force_hidden = true;
}
if style.force_hidden {
style.visibility = crate::style::Visibility::Hidden;
}
}
pub(crate) fn key(
element: ElementId,
pseudo: Option<crate::style::PseudoElement>,
) -> PageStyleTarget {
PageStyleTarget { element, pseudo }
}