use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use crcbl_core::input::CursorIcon;
use super::selector::{Bucket, Element, PseudoClasses, Selector};
use super::sheet::{Decl, Stylesheet, WideKeyword};
use super::var::{CustomProperties, resolve_custom, substitute};
use crate::tree::{
FamilyName, FontFamily, FontStyle, FontWeight, LineHeight, NodeStyle, TextAlign,
TextDecoration, WhiteSpace,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Origin {
Engine,
App,
}
#[derive(Debug)]
struct IndexedRule {
selector: Selector,
declarations: Arc<[Decl]>,
}
#[derive(Debug, Default)]
pub(crate) struct RuleIndex {
rules: Vec<IndexedRule>,
by_id: HashMap<Box<str>, Vec<u32>>,
by_class: HashMap<Box<str>, Vec<u32>>,
by_type: HashMap<Box<str>, Vec<u32>>,
universal: Vec<u32>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Candidates {
pub rules: Vec<u32>,
pub subject_pseudo: PseudoClasses,
pub ancestor_pseudo: PseudoClasses,
pub reads_ancestors: bool,
}
impl RuleIndex {
pub fn build<'a>(sheets: impl IntoIterator<Item = (Origin, &'a Stylesheet)>) -> Self {
let mut ordered = Vec::new();
for (origin, sheet) in sheets {
for rule in &sheet.rules {
for selector in &rule.selectors {
let sequence = ordered.len();
ordered.push((
(origin, selector.specificity(), sequence),
IndexedRule {
selector: selector.clone(),
declarations: rule.declarations.clone(),
},
));
}
}
}
ordered.sort_by_key(|(key, _)| *key);
let mut index = Self::default();
for (at, (_, rule)) in ordered.into_iter().enumerate() {
let at = u32::try_from(at).expect("fewer than four billion rules");
match rule.selector.bucket() {
Bucket::Id(id) => index.by_id.entry(id.into()).or_default().push(at),
Bucket::Class(class) => index.by_class.entry(class.into()).or_default().push(at),
Bucket::Type(name) => index.by_type.entry(name.into()).or_default().push(at),
Bucket::Universal => index.universal.push(at),
}
index.rules.push(rule);
}
index
}
pub fn candidates<'a>(
&self,
type_name: &str,
id: Option<&str>,
classes: impl Iterator<Item = &'a str>,
) -> Candidates {
let mut rules = self.universal.clone();
if let Some(bucket) = id.and_then(|id| self.by_id.get(id)) {
rules.extend(bucket);
}
for class in classes {
if let Some(bucket) = self.by_class.get(class) {
rules.extend(bucket);
}
}
let bucket = self.by_type.get(type_name).or_else(|| {
type_name
.bytes()
.any(|byte| byte.is_ascii_uppercase())
.then(|| self.by_type.get(type_name.to_ascii_lowercase().as_str()))
.flatten()
});
if let Some(bucket) = bucket {
rules.extend(bucket);
}
rules.sort_unstable();
rules.dedup();
let mut candidates = Candidates {
rules,
..Candidates::default()
};
for &at in &candidates.rules {
let selector = &self.rules[at as usize].selector;
candidates.subject_pseudo = candidates.subject_pseudo | selector.subject_pseudo();
candidates.ancestor_pseudo = candidates.ancestor_pseudo | selector.ancestor_pseudo();
candidates.reads_ancestors |= selector.has_ancestors();
}
candidates
}
pub fn matching(&self, candidates: &Candidates, element: &impl Element) -> Vec<u32> {
candidates
.rules
.iter()
.copied()
.filter(|&at| self.rules[at as usize].selector.matches(element))
.collect()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct InheritedId(u32);
impl InheritedId {
pub const ROOT: Self = Self(0);
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct Inherited {
color: [u32; 4],
font_size: u32,
font_family: FontFamily,
family_name: Option<FamilyName>,
font_weight: FontWeight,
font_style: FontStyle,
line_height: (u8, u32),
text_align: TextAlign,
white_space: WhiteSpace,
cursor: Option<CursorIcon>,
text_decoration: TextDecoration,
custom: Arc<CustomProperties>,
}
impl Inherited {
fn new(style: &NodeStyle, custom: Arc<CustomProperties>) -> Self {
Self {
color: style.color.map(f32::to_bits),
font_size: style.font_size.to_bits(),
font_family: style.font_family,
family_name: style.family_name,
font_weight: style.font_weight,
font_style: style.font_style,
line_height: style.line_height.bits(),
text_align: style.text_align,
white_space: style.white_space,
cursor: style.cursor,
text_decoration: style.text_decoration,
custom,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct DefinitionKey {
matched: Box<[u32]>,
pseudo: PseudoClasses,
parent: InheritedId,
}
#[derive(Clone, Debug)]
pub(crate) struct Definition {
pub style: NodeStyle,
pub custom: Arc<CustomProperties>,
}
pub(crate) const CACHE_CAPACITY: usize = 4096;
#[derive(Debug)]
pub(crate) struct Resolver {
pub index: Arc<RuleIndex>,
definitions: HashMap<DefinitionKey, Arc<Definition>>,
inherited: HashMap<Inherited, InheritedId>,
inherited_values: Vec<Inherited>,
pub epoch: u64,
}
impl Resolver {
pub fn new(index: Arc<RuleIndex>) -> Self {
let root = Inherited::new(&NodeStyle::DEFAULT, Arc::default());
Self {
index,
definitions: HashMap::new(),
inherited: HashMap::from([(root.clone(), InheritedId::ROOT)]),
inherited_values: vec![root],
epoch: 0,
}
}
pub fn set_index(&mut self, index: Arc<RuleIndex>) {
self.index = index;
self.clear();
}
pub fn trim(&mut self) {
if self.definitions.len() > CACHE_CAPACITY || self.inherited_values.len() > CACHE_CAPACITY {
self.clear();
}
}
fn clear(&mut self) {
self.definitions.clear();
self.inherited.retain(|_, id| *id == InheritedId::ROOT);
self.inherited_values.truncate(1);
self.epoch += 1;
}
pub fn intern(&mut self, style: &NodeStyle, custom: Arc<CustomProperties>) -> InheritedId {
let key = Inherited::new(style, custom);
if let Some(id) = self.inherited.get(&key) {
return *id;
}
let id =
InheritedId(u32::try_from(self.inherited_values.len()).expect("trimmed long before"));
self.inherited.insert(key.clone(), id);
self.inherited_values.push(key);
id
}
pub fn definition(
&mut self,
matched: Vec<u32>,
pseudo: PseudoClasses,
parent: InheritedId,
) -> (Arc<Definition>, bool) {
let key = DefinitionKey {
matched: matched.into_boxed_slice(),
pseudo,
parent,
};
if let Some(definition) = self.definitions.get(&key) {
return (definition.clone(), false);
}
let inherited = &self.inherited_values[parent.0 as usize];
let definition = Arc::new(compute(&self.index, &key.matched, inherited));
self.definitions.insert(key, definition.clone());
(definition, true)
}
}
fn compute(index: &RuleIndex, matched: &[u32], parent: &Inherited) -> Definition {
let declarations = || {
matched
.iter()
.flat_map(|&at| index.rules[at as usize].declarations.iter())
};
let base = NodeStyle {
color: parent.color.map(f32::from_bits),
font_size: f32::from_bits(parent.font_size),
font_family: parent.font_family,
family_name: parent.family_name,
font_weight: parent.font_weight,
font_style: parent.font_style,
line_height: LineHeight::from_bits(parent.line_height),
text_align: parent.text_align,
white_space: parent.white_space,
cursor: parent.cursor,
text_decoration: parent.text_decoration,
..NodeStyle::DEFAULT
};
let own: BTreeMap<Arc<str>, Arc<str>> = declarations()
.filter_map(|decl| match decl {
Decl::Custom(name, value) => Some((name.clone(), value.clone())),
_ => None,
})
.collect();
let custom = if own.is_empty() {
parent.custom.clone()
} else {
Arc::new(resolve_custom(&parent.custom, own))
};
let mut style = base;
let mut parsed = Vec::new();
for decl in declarations() {
match decl {
Decl::Set(declaration) => declaration.apply(&mut style),
Decl::Keyword(property, WideKeyword::Initial) => {
property.copy(&NodeStyle::DEFAULT, &mut style)
}
Decl::Keyword(property, WideKeyword::Unset) => property.copy(&base, &mut style),
Decl::Custom(..) => {}
Decl::Var {
property,
name,
css,
at,
} => {
parsed.clear();
let valid =
substitute(css, &mut |var| custom.get(var).cloned()).is_some_and(|text| {
let mut input = cssparser::Parser::new(&text);
property.parse(&mut input, &mut parsed).is_ok()
});
if valid {
for declaration in &parsed {
declaration.apply(&mut style);
}
} else {
property.copy(&base, &mut style);
crcbl_core::warn!(
"{}:{}:{}: warning: `{name}: {css}` is not a valid value once its variables \
are substituted; `{name}` is unset",
at.file,
at.line,
at.column,
);
}
}
}
}
Definition { style, custom }
}