use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::Path;
use std::time::Duration;
use super::focus::InputMode;
use super::store::StoredCandidates;
use super::{FrameNode, NodeStyle, Ui};
use crate::style::{
Declaration, Diagnostic, Element, InheritedId, NodeSelector, PseudoClasses, SheetId, StyleStats,
};
pub(super) struct Resolved {
pub style: NodeStyle,
pub pseudo: PseudoClasses,
pub inherited: InheritedId,
}
#[derive(Clone, Copy)]
struct FrameElement<'a> {
nodes: &'a [FrameNode],
selectors: &'a str,
node: Node<'a>,
}
#[derive(Clone, Copy)]
enum Node<'a> {
Building {
selector: NodeSelector<'a>,
span: bool,
pseudo: PseudoClasses,
parent: Option<usize>,
},
Built(usize),
}
impl<'a> FrameElement<'a> {
fn selector(&self) -> NodeSelector<'a> {
match self.node {
Node::Building { selector, .. } => selector,
Node::Built(at) => {
let (start, end) = self.nodes[at].selector;
NodeSelector::parse(&self.selectors[start..end]).unwrap_or(NodeSelector::EMPTY)
}
}
}
}
const fn default_type(span: bool) -> &'static str {
if span { "span" } else { "block" }
}
impl Element for FrameElement<'_> {
fn type_name(&self) -> &str {
let span = match self.node {
Node::Building { span, .. } => span,
Node::Built(at) => self.nodes[at].content.is_span(),
};
self.selector().type_name.unwrap_or(default_type(span))
}
fn id(&self) -> Option<&str> {
self.selector().id
}
fn has_class(&self, class: &str) -> bool {
self.selector().classes().any(|own| own == class)
}
fn pseudo(&self) -> PseudoClasses {
match self.node {
Node::Building { pseudo, .. } => pseudo,
Node::Built(at) => self.nodes[at].pseudo,
}
}
fn parent(&self) -> Option<Self> {
let parent = match self.node {
Node::Building { parent, .. } => parent,
Node::Built(at) => self.nodes[at].parent,
};
parent.map(|at| Self {
node: Node::Built(at),
..*self
})
}
}
impl Ui {
pub(super) fn resolve_style(
&mut self,
slot: usize,
fresh: bool,
parent: Option<usize>,
selector: NodeSelector<'_>,
span: bool,
inline: &[Declaration],
) -> Resolved {
self.styles.stats.nodes += 1;
let generation = self.styles.generation;
let stored = self.store.get(slot);
let interaction = stored.interaction;
let pointing = self.input_mode() == InputMode::Pointer;
let mut pseudo = stored.state;
for (set, class) in [
(interaction.hovered && pointing, PseudoClasses::HOVER),
(interaction.pressed, PseudoClasses::ACTIVE),
(interaction.focused && !pointing, PseudoClasses::FOCUS),
(interaction.engagement.is_engaged(), PseudoClasses::ENGAGED),
(stored.behavior.disabled, PseudoClasses::DISABLED),
] {
if set {
pseudo = pseudo | class;
}
}
let reused = stored.candidates.as_ref().is_some_and(|held| {
held.generation == generation && held.span == span && held.selector == selector.text()
});
if !reused {
let candidates = self.styles.resolver.index.candidates(
selector.type_name.unwrap_or(default_type(span)),
selector.id,
selector.classes(),
);
self.store.get_mut(slot).candidates = Some(StoredCandidates {
selector: selector.text().to_owned(),
span,
generation,
candidates,
});
}
let stored = self.store.get(slot);
let candidates = &stored
.candidates
.as_ref()
.expect("gathered above")
.candidates;
let parent_inherited = parent.map_or(InheritedId::ROOT, |at| self.nodes[at].inherited);
let own_pseudo = pseudo & candidates.subject_pseudo;
let mut key = DefaultHasher::new();
(
generation,
self.styles.resolver.epoch,
own_pseudo,
parent_inherited,
)
.hash(&mut key);
if candidates.reads_ancestors {
let mut next = parent;
while let Some(at) = next {
let node = &self.nodes[at];
let (start, end) = node.selector;
(
&self.selectors[start..end],
!node.content.is_span(),
node.pseudo & candidates.ancestor_pseudo,
)
.hash(&mut key);
next = node.parent;
}
}
let key = key.finish();
if !fresh && reused && stored.style_key == key && stored.inline == inline {
return Resolved {
style: stored.resolved,
pseudo,
inherited: stored.inherited,
};
}
self.styles.stats.resolves += 1;
let element = FrameElement {
nodes: &self.nodes,
selectors: &self.selectors,
node: Node::Building {
selector,
span,
pseudo,
parent,
},
};
let matched = self.styles.resolver.index.matching(candidates, &element);
let (definition, computed) =
self.styles
.resolver
.definition(matched, own_pseudo, parent_inherited);
if computed {
self.styles.stats.definitions += 1;
}
let mut style = definition.style;
for declaration in inline {
declaration.apply(&mut style);
}
let inherited = if span {
InheritedId::ROOT
} else {
self.styles
.resolver
.intern(&style, definition.custom.clone())
};
let stored = self.store.get_mut(slot);
stored.style_key = key;
stored.inline.clear();
stored.inline.extend_from_slice(inline);
stored.resolved = style;
stored.inherited = inherited;
Resolved {
style,
pseudo,
inherited,
}
}
pub fn add_stylesheet(&mut self, name: &str, css: &str) -> SheetId {
self.styles.add(name, css)
}
pub fn load_stylesheet(&mut self, path: impl AsRef<Path>) -> std::io::Result<SheetId> {
self.styles.load(path.as_ref())
}
pub fn replace_stylesheet(&mut self, sheet: SheetId, css: &str) -> Result<(), Vec<Diagnostic>> {
self.styles.replace(sheet, css)
}
pub fn poll_stylesheets(&mut self, now: Duration) -> usize {
self.styles.poll(now)
}
#[must_use]
pub fn stylesheet_generation(&self) -> u64 {
self.styles.generation
}
#[must_use]
pub fn style_stats(&self) -> StyleStats {
self.styles.stats
}
}