use crate::color::Color;
use crate::geometry::{PointF, RectF, SizeF};
use crate::image::Image;
use crate::path::Path;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GradientStop {
pub offset: f32,
pub color: Color,
}
impl GradientStop {
pub const fn new(offset: f32, color: Color) -> Self {
Self { offset, color }
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Brush {
Solid(Color),
Linear { start: PointF, end: PointF, stops: Vec<GradientStop> },
Radial { center: PointF, radius: f32, stops: Vec<GradientStop> },
Sweep { center: PointF, start_angle: f32, stops: Vec<GradientStop> },
}
impl From<Color> for Brush {
fn from(c: Color) -> Self {
Brush::Solid(c)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BlendMode {
#[default]
Normal,
Multiply,
Screen,
Overlay,
Darken,
Lighten,
ColorDodge,
ColorBurn,
HardLight,
SoftLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
}
impl BlendMode {
pub const ALL: [BlendMode; 16] = [
BlendMode::Normal,
BlendMode::Multiply,
BlendMode::Screen,
BlendMode::Overlay,
BlendMode::Darken,
BlendMode::Lighten,
BlendMode::ColorDodge,
BlendMode::ColorBurn,
BlendMode::HardLight,
BlendMode::SoftLight,
BlendMode::Difference,
BlendMode::Exclusion,
BlendMode::Hue,
BlendMode::Saturation,
BlendMode::Color,
BlendMode::Luminosity,
];
pub fn css(self) -> &'static str {
match self {
BlendMode::Normal => "source-over",
BlendMode::Multiply => "multiply",
BlendMode::Screen => "screen",
BlendMode::Overlay => "overlay",
BlendMode::Darken => "darken",
BlendMode::Lighten => "lighten",
BlendMode::ColorDodge => "color-dodge",
BlendMode::ColorBurn => "color-burn",
BlendMode::HardLight => "hard-light",
BlendMode::SoftLight => "soft-light",
BlendMode::Difference => "difference",
BlendMode::Exclusion => "exclusion",
BlendMode::Hue => "hue",
BlendMode::Saturation => "saturation",
BlendMode::Color => "color",
BlendMode::Luminosity => "luminosity",
}
}
}
impl crate::prop::PropEnum for BlendMode {
const NAMES: &'static [&'static str] = &[
"normal",
"multiply",
"screen",
"overlay",
"darken",
"lighten",
"color_dodge",
"color_burn",
"hard_light",
"soft_light",
"difference",
"exclusion",
"hue",
"saturation",
"color",
"luminosity",
];
fn from_index(i: usize) -> Option<Self> {
BlendMode::ALL.get(i).copied()
}
fn index(self) -> usize {
self as usize
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineCap {
#[default]
Butt,
Round,
Square,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineJoin {
#[default]
Miter,
Round,
Bevel,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Stroke {
pub brush: Brush,
pub width: f32,
pub dash: Option<Vec<f32>>,
pub cap: LineCap,
pub join: LineJoin,
}
impl Stroke {
pub fn new(brush: impl Into<Brush>, width: f32) -> Self {
Self { brush: brush.into(), width, dash: None, cap: LineCap::Butt, join: LineJoin::Miter }
}
pub fn dashed(mut self, pattern: Vec<f32>) -> Self {
self.dash = Some(pattern);
self
}
pub fn round(mut self) -> Self {
self.cap = LineCap::Round;
self.join = LineJoin::Round;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Shadow {
pub color: Color,
pub blur: f32,
pub offset: PointF,
pub spread: f32,
}
impl Shadow {
pub fn new(color: Color, blur: f32, dx: f32, dy: f32) -> Self {
Self { color, blur, offset: PointF::new(dx, dy), spread: 0.0 }
}
pub fn reach(&self) -> f32 {
self.blur * 1.5 + self.spread.max(0.0) + self.offset.x.abs().max(self.offset.y.abs())
}
pub fn parse(spec: &str) -> Option<Shadow> {
let mut numbers = Vec::new();
let mut color = None;
for token in spec.split(|c: char| c.is_whitespace() || c == ',').filter(|t| !t.is_empty()) {
let number = token.strip_suffix("px").unwrap_or(token);
if let Ok(v) = number.parse::<f32>() {
numbers.push(v);
} else if color.is_none() {
color = Some(token.parse::<Color>().ok()?);
} else {
return None;
}
}
if !(2..=4).contains(&numbers.len()) {
return None;
}
Some(Shadow {
color: color.unwrap_or(Color::BLACK.with_opacity(0.25)),
blur: numbers.get(2).copied().unwrap_or(0.0).max(0.0),
offset: PointF::new(numbers[0], numbers[1]),
spread: numbers.get(3).copied().unwrap_or(0.0),
})
}
pub fn to_spec(&self) -> String {
let n = |v: f32| format!("{}", (v * 100.0).round() / 100.0);
let mut s = format!("{} {} {}", n(self.offset.x), n(self.offset.y), n(self.blur));
if self.spread != 0.0 {
s += &format!(" {}", n(self.spread));
}
s + " " + &self.color.to_hex()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FontWeight {
Thin,
Light,
#[default]
Normal,
Medium,
SemiBold,
Bold,
Black,
}
#[derive(Clone, Debug, PartialEq)]
pub struct FontSpec {
pub family: String,
pub size: f32,
pub weight: FontWeight,
pub italic: bool,
pub underline: bool,
pub strikeout: bool,
}
impl Default for FontSpec {
fn default() -> Self {
Self { family: String::new(), size: 14.0, weight: FontWeight::Normal, italic: false, underline: false, strikeout: false }
}
}
impl FontSpec {
pub fn new(family: impl Into<String>, size: f32) -> Self {
Self { family: family.into(), size, ..Default::default() }
}
pub fn weight(mut self, weight: FontWeight) -> Self {
self.weight = weight;
self
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextAlign {
#[default]
Leading,
Center,
Trailing,
Justify,
}
impl crate::prop::PropEnum for TextAlign {
const NAMES: &'static [&'static str] = &["leading", "center", "trailing", "justify"];
fn from_index(index: usize) -> Option<Self> {
[TextAlign::Leading, TextAlign::Center, TextAlign::Trailing, TextAlign::Justify].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct TextStyle {
pub font: FontSpec,
pub color: Color,
pub h_align: TextAlign,
pub v_align: TextAlign,
pub wrap: bool,
pub trimming: crate::text::Trimming,
pub letter_spacing: f32,
pub color_glyphs: bool,
}
impl Default for TextStyle {
fn default() -> Self {
Self {
font: FontSpec::default(),
color: Color::BLACK,
h_align: TextAlign::Leading,
v_align: TextAlign::Center,
wrap: false,
trimming: crate::text::Trimming::Character,
letter_spacing: 0.0,
color_glyphs: true,
}
}
}
pub const MONO_EMOJI_FAMILY: &str = "Noto Emoji";
pub const MONO_EMOJI_RANGES: &[(u32, u32)] = &[
(0x00A9, 0x00A9),
(0x00AE, 0x00AE),
(0x200D, 0x200D),
(0x203C, 0x203C),
(0x2049, 0x2049),
(0x20E3, 0x20E3),
(0x2122, 0x2122),
(0x2139, 0x2139),
(0x2194, 0x2199),
(0x21A9, 0x21AA),
(0x231A, 0x231B),
(0x2328, 0x2328),
(0x23CF, 0x23CF),
(0x23E9, 0x23F3),
(0x23F8, 0x23FA),
(0x24C2, 0x24C2),
(0x25AA, 0x25AB),
(0x25B6, 0x25B6),
(0x25C0, 0x25C0),
(0x25FB, 0x25FE),
(0x2600, 0x27BF),
(0x2934, 0x2935),
(0x2B05, 0x2B07),
(0x2B1B, 0x2B1C),
(0x2B50, 0x2B50),
(0x2B55, 0x2B55),
(0x3030, 0x3030),
(0x303D, 0x303D),
(0x3297, 0x3297),
(0x3299, 0x3299),
(0xFE0E, 0xFE0F),
(0x1F000, 0x1FAFF),
(0xE0020, 0xE007F),
];
pub fn is_mono_emoji(c: char) -> bool {
let c = c as u32;
MONO_EMOJI_RANGES.iter().any(|&(a, b)| c >= a && c <= b)
}
pub fn mono_emoji_ranges(text: &str) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = Vec::new();
for (i, c) in text.char_indices() {
if !is_mono_emoji(c) {
continue;
}
let end = i + c.len_utf8();
match out.last_mut() {
Some(last) if last.1 == i => last.1 = end,
_ => out.push((i, end)),
}
}
out
}
pub fn mono_emoji_available() -> bool {
crate::fonts::registered().iter().any(|f| f.family == MONO_EMOJI_FAMILY)
}
pub fn wrapped_size(text: &str, max_width: f32, line_height: f32, measure: &mut dyn FnMut(&str) -> f32) -> SizeF {
if text.is_empty() {
return SizeF::new(0.0, 0.0);
}
let lines = crate::text::layout_lines(text, max_width.max(1.0), usize::MAX, true, crate::text::Trimming::None, measure);
let widest = lines.iter().map(|l| measure(l)).fold(0.0f32, f32::max);
SizeF::new(widest, line_height * lines.len().max(1) as f32)
}
#[derive(Default)]
pub struct WrapCache {
generation: u64,
sizes: std::collections::HashMap<(String, WrapKey), SizeF>,
}
#[derive(Clone, PartialEq, Eq, Hash)]
struct WrapKey {
family: String,
size: u32,
weight: u8,
italic: bool,
letter_spacing: u32,
color_glyphs: bool,
width: u32,
}
impl WrapCache {
const MAX: usize = 4096;
pub fn get_or(&mut self, text: &str, style: &TextStyle, max_width: f32, compute: impl FnOnce() -> SizeF) -> SizeF {
let generation = crate::fonts::generation();
if generation != self.generation || self.sizes.len() >= Self::MAX {
self.sizes.clear();
self.generation = generation;
}
let key = WrapKey {
family: style.font.family.clone(),
size: style.font.size.to_bits(),
weight: style.font.weight as u8,
italic: style.font.italic,
letter_spacing: style.letter_spacing.to_bits(),
color_glyphs: style.color_glyphs,
width: max_width.to_bits(),
};
if let Some(size) = self.sizes.get(&(text.to_string(), key.clone())) {
return *size;
}
let size = compute();
self.sizes.insert((text.to_string(), key), size);
size
}
}
pub trait Canvas {
fn save(&mut self);
fn restore(&mut self);
fn translate(&mut self, dx: f32, dy: f32);
fn scale(&mut self, sx: f32, sy: f32);
fn rotate(&mut self, degrees: f32);
fn clip_rect(&mut self, rect: RectF);
fn save_layer(&mut self, opacity: f32);
fn save_layer_blend(&mut self, opacity: f32, mode: BlendMode, bounds: RectF) {
let _ = (mode, bounds);
self.save_layer(opacity);
}
fn fill_rect(&mut self, rect: RectF, radius: f32, brush: &Brush);
fn stroke_rect(&mut self, rect: RectF, radius: f32, stroke: &Stroke);
fn fill_ellipse(&mut self, rect: RectF, brush: &Brush);
fn stroke_ellipse(&mut self, rect: RectF, stroke: &Stroke);
fn draw_line(&mut self, from: PointF, to: PointF, stroke: &Stroke);
fn draw_text(&mut self, text: &str, rect: RectF, style: &TextStyle);
fn measure_text(&mut self, text: &str, style: &TextStyle) -> SizeF;
fn measure_text_wrapped(&mut self, text: &str, style: &TextStyle, max_width: f32) -> SizeF {
let line_height = self.measure_text("Ag", style).height;
wrapped_size(text, max_width, line_height, &mut |s| self.measure_text(s, style).width)
}
fn draw_image(&mut self, image: &Image, src: RectF, dest: RectF, opacity: f32) {
let _ = (image, src, dest, opacity);
}
fn image_size(&mut self, image: &Image) -> Option<SizeF> {
image.known_size()
}
fn clip_round_rect(&mut self, rect: RectF, radius: f32) {
let _ = radius;
self.clip_rect(rect);
}
fn fill_path(&mut self, path: &Path, brush: &Brush) {
let _ = (path, brush);
}
fn clip_path(&mut self, path: &Path, inverse: bool) {
if !inverse {
self.clip_rect(path.bounds());
}
}
fn backdrop_blur(&mut self, rect: RectF, radius: f32, blur: f32) -> bool {
let _ = (rect, radius, blur);
false
}
fn begin_masked(&mut self, inverse: bool) -> bool {
let _ = inverse;
false
}
fn begin_mask(&mut self) {}
fn begin_luminance_mask(&mut self) {
self.begin_mask();
}
fn end_mask(&mut self) {}
fn begin_cached(&mut self, key: u64, rect: RectF) -> bool {
let _ = (key, rect);
false
}
fn end_cached(&mut self) {}
fn forget_cached(&mut self, key: u64) {
let _ = key;
}
fn stroke_path(&mut self, path: &Path, stroke: &Stroke) {
for (points, closed) in path.flatten(8) {
for w in points.windows(2) {
self.draw_line(w[0], w[1], stroke);
}
if closed && points.len() > 2 {
self.draw_line(points[points.len() - 1], points[0], stroke);
}
}
}
fn draw_shadow(&mut self, rect: RectF, radius: f32, shadow: &Shadow) {
let _ = (rect, radius, shadow);
}
fn device_scale(&self) -> f32 {
1.0
}
fn gpu_device(&self) -> Option<GpuDevice> {
None
}
fn hdr_headroom(&self) -> f32 {
1.0
}
fn draw_gpu_surface(&mut self, dest: RectF, surface: &GpuSurface) -> bool {
let _ = (dest, surface);
false
}
fn gpu_state_changed(&mut self) {}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GpuDevice {
Direct3D11 { adapter_luid: i64 },
OpenGl { loader: usize, context: usize },
Web,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GpuSurface {
D3D12 {
id: u64,
texture: isize,
width: u32,
height: u32,
ready: isize,
ready_value: u64,
release: isize,
release_value: u64,
color: SurfaceColor,
},
GlTexture { id: u64, texture: u32, width: u32, height: u32 },
WebCanvas { element: u32, width: u32, height: u32 },
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SurfaceColor {
#[default]
Srgb,
LinearScrgb,
}
pub trait TextService {
fn measure(&self, text: &str, style: &TextStyle, max_width: Option<f32>) -> SizeF;
}
pub fn decorate_line(canvas: &mut dyn Canvas, font: &FontSpec, color: Color, x: f32, width: f32, top: f32, line_height: f32) {
if !(font.underline || font.strikeout) || width <= 0.0 {
return;
}
let stroke = Stroke::new(color, (font.size / 14.0).max(1.0));
let middle = top + line_height / 2.0;
if font.underline {
let y = middle + font.size * 0.45;
canvas.draw_line(PointF::new(x, y), PointF::new(x + width, y), &stroke);
}
if font.strikeout {
let y = middle + font.size * 0.05;
canvas.draw_line(PointF::new(x, y), PointF::new(x + width, y), &stroke);
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TextAntialias {
#[default]
Grayscale,
ClearType,
}
impl TextAntialias {
pub fn name(self) -> &'static str {
match self {
TextAntialias::Grayscale => "grayscale",
TextAntialias::ClearType => "cleartype",
}
}
pub fn parse(name: &str) -> Option<TextAntialias> {
match name {
"grayscale" => Some(TextAntialias::Grayscale),
"cleartype" => Some(TextAntialias::ClearType),
_ => None,
}
}
}
static TEXT_ANTIALIAS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub fn set_text_antialias(mode: TextAntialias) {
TEXT_ANTIALIAS.store(mode == TextAntialias::ClearType, std::sync::atomic::Ordering::Relaxed);
}
pub fn text_antialias() -> TextAntialias {
if TEXT_ANTIALIAS.load(std::sync::atomic::Ordering::Relaxed) { TextAntialias::ClearType } else { TextAntialias::Grayscale }
}