mod cascade;
mod property;
mod selector;
mod sheet;
mod value;
mod var;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime};
pub(crate) use cascade::{Candidates, InheritedId, Origin, Resolver, RuleIndex};
pub(crate) use selector::{Element, NodeSelector};
pub use selector::{PseudoClasses, Selector, Specificity};
pub use sheet::{Diagnostic, Severity, Stylesheet};
pub use value::{Corners, Declaration, Sides};
pub const DEFAULT_CSS: &str = include_str!("default.css");
pub const STYLESHEET_POLL_INTERVAL: Duration = Duration::from_millis(250);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct SheetId(usize);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StyleStats {
pub nodes: u32,
pub resolves: u32,
pub definitions: u32,
}
fn default_sheet() -> &'static Stylesheet {
static SHEET: OnceLock<Stylesheet> = OnceLock::new();
SHEET.get_or_init(|| {
let (sheet, diagnostics) = Stylesheet::parse("crcbl-ui/default.css", DEFAULT_CSS);
report(&diagnostics);
sheet
})
}
fn default_index() -> Arc<RuleIndex> {
static INDEX: OnceLock<Arc<RuleIndex>> = OnceLock::new();
INDEX
.get_or_init(|| Arc::new(RuleIndex::build([(Origin::Engine, default_sheet())])))
.clone()
}
fn report(diagnostics: &[Diagnostic]) {
for diagnostic in diagnostics {
crcbl_core::warn!("{diagnostic}");
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Stamp {
modified: Option<SystemTime>,
len: u64,
}
fn stamp(path: &Path) -> Option<Stamp> {
let metadata = std::fs::metadata(path).ok()?;
Some(Stamp {
modified: metadata.modified().ok(),
len: metadata.len(),
})
}
#[derive(Debug)]
struct AppSheet {
sheet: Arc<Stylesheet>,
path: Option<PathBuf>,
stamp: Option<Stamp>,
}
#[derive(Debug)]
pub(crate) struct Styles {
pub resolver: Resolver,
app: Vec<AppSheet>,
pending: bool,
pub generation: u64,
last_poll: Option<Duration>,
pub stats: StyleStats,
}
impl Default for Styles {
fn default() -> Self {
Self {
resolver: Resolver::new(default_index()),
app: Vec::new(),
pending: false,
generation: 0,
last_poll: None,
stats: StyleStats::default(),
}
}
}
impl Styles {
pub fn begin_frame(&mut self) {
self.stats = StyleStats::default();
if self.pending {
self.pending = false;
let sheets = core::iter::once((Origin::Engine, default_sheet()))
.chain(self.app.iter().map(|app| (Origin::App, &*app.sheet)));
self.resolver.set_index(Arc::new(RuleIndex::build(sheets)));
self.generation += 1;
} else {
self.resolver.trim();
}
}
pub fn add(&mut self, name: &str, css: &str) -> SheetId {
let (sheet, diagnostics) = Stylesheet::parse(name, css);
report(&diagnostics);
self.push(AppSheet {
sheet: Arc::new(sheet),
path: None,
stamp: None,
})
}
fn push(&mut self, sheet: AppSheet) -> SheetId {
self.app.push(sheet);
self.pending = true;
SheetId(self.app.len() - 1)
}
pub fn load(&mut self, path: &Path) -> std::io::Result<SheetId> {
let seen = stamp(path);
let css = std::fs::read_to_string(path)?;
let (sheet, diagnostics) = Stylesheet::parse(&path.display().to_string(), &css);
report(&diagnostics);
Ok(self.push(AppSheet {
sheet: Arc::new(sheet),
path: Some(path.to_path_buf()),
stamp: seen,
}))
}
pub fn replace(&mut self, id: SheetId, css: &str) -> Result<(), Vec<Diagnostic>> {
let app = &mut self.app[id.0];
let (sheet, diagnostics) = Stylesheet::parse(app.sheet.name(), css);
report(&diagnostics);
let errors: Vec<Diagnostic> = diagnostics
.into_iter()
.filter(|diagnostic| diagnostic.severity == Severity::Error)
.collect();
if !errors.is_empty() {
crcbl_core::warn!(
"{}: {} error(s); keeping the last good sheet",
app.sheet.name(),
errors.len()
);
return Err(errors);
}
app.sheet = Arc::new(sheet);
self.pending = true;
Ok(())
}
pub fn poll(&mut self, now: Duration) -> usize {
if self
.last_poll
.is_some_and(|last| now.saturating_sub(last) < STYLESHEET_POLL_INTERVAL)
{
return 0;
}
self.last_poll = Some(now);
let mut replaced = 0;
for at in 0..self.app.len() {
let Some(path) = self.app[at].path.clone() else {
continue;
};
let seen = stamp(&path);
if seen == self.app[at].stamp {
continue;
}
self.app[at].stamp = seen;
let read = if seen.is_some() {
std::fs::read_to_string(&path)
} else {
Err(std::io::Error::from(std::io::ErrorKind::NotFound))
};
match read {
Ok(css) => {
if self.replace(SheetId(at), &css).is_ok() {
replaced += 1;
}
}
Err(error) => crcbl_core::warn!(
"{}: cannot be read ({error}); keeping the last good sheet",
path.display()
),
}
}
replaced
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_default_sheet_parses_cleanly() {
let (sheet, diagnostics) = Stylesheet::parse("default.css", DEFAULT_CSS);
assert!(diagnostics.is_empty(), "{diagnostics:#?}");
assert!(sheet.rule_count() > 0, "the default sheet holds no rules");
}
}