lurq 0.65.1

A Rust UI toolkit with typed components, retained state, reactive signals, GPU rendering, and DevTools.
Documentation
use std::{
  collections::{HashMap, VecDeque},
  sync::{Arc, Mutex},
};

use crate::node::color::Color;

/// Parsed trees interned by content hash: re-creating an `SvgData` from the
/// same source (a common per-render pattern in apps) skips the usvg parse
/// and keeps the id stable, which is what lets the raster and GPU caches
/// hit across instances.
static TREE_CACHE: Mutex<Option<TreeCache>> = Mutex::new(None);

const TREE_CACHE_CAP: usize = 256;

#[derive(Default)]
struct TreeCache {
  map: HashMap<u64, Arc<usvg::Tree>>,
  order: VecDeque<u64>,
}

/// FNV-1a over the raw bytes — deterministic within and across processes.
fn content_id(data: &[u8]) -> u64 {
  let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
  for byte in data {
    hash ^= u64::from(*byte);
    hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
  }
  hash
}

/// Fold an override into the id deterministically (splitmix64 finalizer), so
/// identical construction chains produce identical ids.
fn mix_id(id: u64, tag: u64, value: u64) -> u64 {
  let mut x = id ^ tag.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ value.wrapping_mul(0xBF58_476D_1CE4_E5B9);
  x ^= x >> 30;
  x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
  x ^= x >> 27;
  x = x.wrapping_mul(0x94D0_49BB_1331_11EB);
  x ^ (x >> 31)
}

fn color_bits(color: Color) -> u64 {
  let [r, g, b, a] = [color.r(), color.g(), color.b(), color.a()].map(u64::from);
  r << 48 | g << 32 | b << 16 | a
}

#[derive(Clone)]
pub struct SvgData {
  id: u64,
  tree: Arc<usvg::Tree>,
  overrides: SvgOverrides,
}

#[derive(Clone, Default)]
struct SvgOverrides {
  fill: Option<Color>,
  stroke: Option<Color>,
  opacity: Option<f32>,
  /// The fill is painted in the foreground the node inherits.
  current_fill: bool,
  /// The stroke is painted in the foreground the node inherits.
  current_stroke: bool,
}

impl SvgData {
  pub fn from_bytes(data: &[u8]) -> Self {
    Self::parse(data).expect("invalid SVG data")
  }

  /// `data` read as an SVG, or `None` where it is none usvg reads: for bytes from elsewhere, a picture at an
  /// address that may be anything.
  pub(crate) fn parse(data: &[u8]) -> Option<Self> {
    let id = content_id(data);
    let mut guard = TREE_CACHE.lock().unwrap();
    let cache = guard.get_or_insert_with(TreeCache::default);
    let tree = if let Some(tree) = cache.map.get(&id) {
      tree.clone()
    } else {
      let tree = Arc::new(usvg::Tree::from_data(data, &usvg::Options::default()).ok()?);
      if cache.order.len() >= TREE_CACHE_CAP
        && let Some(evicted) = cache.order.pop_front()
      {
        cache.map.remove(&evicted);
      }
      cache.map.insert(id, tree.clone());
      cache.order.push_back(id);
      tree
    };
    drop(guard);
    Some(Self {
      id,
      tree,
      overrides: SvgOverrides::default(),
    })
  }

  // Public constructor that cannot fail; `FromStr` would need an error type and a trait in scope.
  #[allow(clippy::should_implement_trait)]
  pub fn from_str(svg: &str) -> Self {
    Self::from_bytes(svg.as_bytes())
  }

  pub fn with_fill(mut self, color: Color) -> Self {
    self.overrides.fill = Some(color);
    self.id = mix_id(self.id, 1, color_bits(color));
    self
  }

  pub fn with_stroke(mut self, color: Color) -> Self {
    self.overrides.stroke = Some(color);
    self.id = mix_id(self.id, 2, color_bits(color));
    self
  }

  pub fn with_opacity(mut self, opacity: f32) -> Self {
    let opacity = opacity.clamp(0.0, 1.0);
    self.overrides.opacity = Some(opacity);
    self.id = mix_id(self.id, 3, u64::from(opacity.to_bits()));
    self
  }

  /// Paints the fill of every shape in the foreground the node inherits, as a text that names no color is painted:
  /// the color of what it is in, or its own `.foreground(..)`. What [`with_fill`](Self::with_fill) gives is over
  /// it. An icon whose shapes are its color.
  pub fn fill_current_color(mut self) -> Self {
    self.overrides.current_fill = true;
    self.id = mix_id(self.id, 4, 1);
    self
  }

  /// Paints the stroke of every shape in the foreground the node inherits: an icon drawn in lines, as lucide's
  /// are. What [`with_stroke`](Self::with_stroke) gives is over it.
  pub fn stroke_current_color(mut self) -> Self {
    self.overrides.current_stroke = true;
    self.id = mix_id(self.id, 5, 1);
    self
  }

  /// Whether it is painted in the foreground its node inherits, its fill or its stroke.
  pub fn paints_current_color(&self) -> bool {
    (self.overrides.current_fill && self.overrides.fill.is_none())
      || (self.overrides.current_stroke && self.overrides.stroke.is_none())
  }

  /// This data as it is painted in `foreground`: its fill and its stroke that take the inherited foreground in it.
  pub(crate) fn in_foreground(&self, foreground: Color) -> Self {
    let mut painted = self.clone();
    if painted.overrides.current_fill && painted.overrides.fill.is_none() {
      painted = painted.with_fill(foreground);
    }
    if painted.overrides.current_stroke && painted.overrides.stroke.is_none() {
      painted = painted.with_stroke(foreground);
    }
    painted
  }

  pub fn id(&self) -> u64 {
    self.id
  }

  pub fn tree(&self) -> &usvg::Tree {
    &self.tree
  }

  pub fn fill_override(&self) -> Option<Color> {
    self.overrides.fill
  }

  pub fn stroke_override(&self) -> Option<Color> {
    self.overrides.stroke
  }

  pub fn opacity_override(&self) -> Option<f32> {
    self.overrides.opacity
  }

  pub fn viewbox_width(&self) -> f32 {
    self.tree.size().width()
  }

  pub fn viewbox_height(&self) -> f32 {
    self.tree.size().height()
  }
}