1use crate::color::Color;
5use crate::geometry::{PointF, RectF, SizeF};
6use crate::image::Image;
7use crate::path::Path;
8
9#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct GradientStop {
12 pub offset: f32,
13 pub color: Color,
14}
15
16impl GradientStop {
17 pub const fn new(offset: f32, color: Color) -> Self {
18 Self { offset, color }
19 }
20}
21
22#[derive(Clone, Debug, PartialEq)]
24pub enum Brush {
25 Solid(Color),
26 Linear { start: PointF, end: PointF, stops: Vec<GradientStop> },
27 Radial { center: PointF, radius: f32, stops: Vec<GradientStop> },
28 Sweep { center: PointF, start_angle: f32, stops: Vec<GradientStop> },
30}
31
32impl From<Color> for Brush {
33 fn from(c: Color) -> Self {
34 Brush::Solid(c)
35 }
36}
37
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
42pub enum BlendMode {
43 #[default]
45 Normal,
46 Multiply,
47 Screen,
48 Overlay,
49 Darken,
50 Lighten,
51 ColorDodge,
52 ColorBurn,
53 HardLight,
54 SoftLight,
55 Difference,
57 Exclusion,
59 Hue,
60 Saturation,
61 Color,
62 Luminosity,
63}
64
65impl BlendMode {
66 pub const ALL: [BlendMode; 16] = [
67 BlendMode::Normal,
68 BlendMode::Multiply,
69 BlendMode::Screen,
70 BlendMode::Overlay,
71 BlendMode::Darken,
72 BlendMode::Lighten,
73 BlendMode::ColorDodge,
74 BlendMode::ColorBurn,
75 BlendMode::HardLight,
76 BlendMode::SoftLight,
77 BlendMode::Difference,
78 BlendMode::Exclusion,
79 BlendMode::Hue,
80 BlendMode::Saturation,
81 BlendMode::Color,
82 BlendMode::Luminosity,
83 ];
84
85 pub fn css(self) -> &'static str {
87 match self {
88 BlendMode::Normal => "source-over",
89 BlendMode::Multiply => "multiply",
90 BlendMode::Screen => "screen",
91 BlendMode::Overlay => "overlay",
92 BlendMode::Darken => "darken",
93 BlendMode::Lighten => "lighten",
94 BlendMode::ColorDodge => "color-dodge",
95 BlendMode::ColorBurn => "color-burn",
96 BlendMode::HardLight => "hard-light",
97 BlendMode::SoftLight => "soft-light",
98 BlendMode::Difference => "difference",
99 BlendMode::Exclusion => "exclusion",
100 BlendMode::Hue => "hue",
101 BlendMode::Saturation => "saturation",
102 BlendMode::Color => "color",
103 BlendMode::Luminosity => "luminosity",
104 }
105 }
106}
107
108impl crate::prop::PropEnum for BlendMode {
109 const NAMES: &'static [&'static str] = &[
110 "normal",
111 "multiply",
112 "screen",
113 "overlay",
114 "darken",
115 "lighten",
116 "color_dodge",
117 "color_burn",
118 "hard_light",
119 "soft_light",
120 "difference",
121 "exclusion",
122 "hue",
123 "saturation",
124 "color",
125 "luminosity",
126 ];
127 fn from_index(i: usize) -> Option<Self> {
128 BlendMode::ALL.get(i).copied()
129 }
130 fn index(self) -> usize {
131 self as usize
132 }
133}
134
135#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
137pub enum LineCap {
138 #[default]
139 Butt,
140 Round,
141 Square,
142}
143
144#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
146pub enum LineJoin {
147 #[default]
148 Miter,
149 Round,
150 Bevel,
151}
152
153#[derive(Clone, Debug, PartialEq)]
155pub struct Stroke {
156 pub brush: Brush,
157 pub width: f32,
158 pub dash: Option<Vec<f32>>,
160 pub cap: LineCap,
161 pub join: LineJoin,
162}
163
164impl Stroke {
165 pub fn new(brush: impl Into<Brush>, width: f32) -> Self {
166 Self { brush: brush.into(), width, dash: None, cap: LineCap::Butt, join: LineJoin::Miter }
167 }
168
169 pub fn dashed(mut self, pattern: Vec<f32>) -> Self {
170 self.dash = Some(pattern);
171 self
172 }
173
174 pub fn round(mut self) -> Self {
176 self.cap = LineCap::Round;
177 self.join = LineJoin::Round;
178 self
179 }
180}
181
182#[derive(Clone, Copy, Debug, PartialEq)]
184pub struct Shadow {
185 pub color: Color,
186 pub blur: f32,
188 pub offset: PointF,
189 pub spread: f32,
191}
192
193impl Shadow {
194 pub fn new(color: Color, blur: f32, dx: f32, dy: f32) -> Self {
195 Self { color, blur, offset: PointF::new(dx, dy), spread: 0.0 }
196 }
197
198 pub fn reach(&self) -> f32 {
201 self.blur * 1.5 + self.spread.max(0.0) + self.offset.x.abs().max(self.offset.y.abs())
202 }
203
204 pub fn parse(spec: &str) -> Option<Shadow> {
207 let mut numbers = Vec::new();
208 let mut color = None;
209 for token in spec.split(|c: char| c.is_whitespace() || c == ',').filter(|t| !t.is_empty()) {
210 let number = token.strip_suffix("px").unwrap_or(token);
211 if let Ok(v) = number.parse::<f32>() {
212 numbers.push(v);
213 } else if color.is_none() {
214 color = Some(token.parse::<Color>().ok()?);
215 } else {
216 return None;
217 }
218 }
219 if !(2..=4).contains(&numbers.len()) {
220 return None;
221 }
222 Some(Shadow {
223 color: color.unwrap_or(Color::BLACK.with_opacity(0.25)),
224 blur: numbers.get(2).copied().unwrap_or(0.0).max(0.0),
225 offset: PointF::new(numbers[0], numbers[1]),
226 spread: numbers.get(3).copied().unwrap_or(0.0),
227 })
228 }
229
230 pub fn to_spec(&self) -> String {
232 let n = |v: f32| format!("{}", (v * 100.0).round() / 100.0);
233 let mut s = format!("{} {} {}", n(self.offset.x), n(self.offset.y), n(self.blur));
234 if self.spread != 0.0 {
235 s += &format!(" {}", n(self.spread));
236 }
237 s + " " + &self.color.to_hex()
238 }
239}
240
241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
242pub enum FontWeight {
243 Thin,
244 Light,
245 #[default]
246 Normal,
247 Medium,
248 SemiBold,
249 Bold,
250 Black,
251}
252
253#[derive(Clone, Debug, PartialEq)]
255pub struct FontSpec {
256 pub family: String,
257 pub size: f32,
258 pub weight: FontWeight,
259 pub italic: bool,
260 pub underline: bool,
261 pub strikeout: bool,
263}
264
265impl Default for FontSpec {
266 fn default() -> Self {
267 Self { family: String::new(), size: 14.0, weight: FontWeight::Normal, italic: false, underline: false, strikeout: false }
268 }
269}
270
271impl FontSpec {
272 pub fn new(family: impl Into<String>, size: f32) -> Self {
273 Self { family: family.into(), size, ..Default::default() }
274 }
275
276 pub fn weight(mut self, weight: FontWeight) -> Self {
277 self.weight = weight;
278 self
279 }
280}
281
282#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
284pub enum TextAlign {
285 #[default]
287 Leading,
288 Center,
289 Trailing,
291 Justify,
295}
296
297impl crate::prop::PropEnum for TextAlign {
298 const NAMES: &'static [&'static str] = &["leading", "center", "trailing", "justify"];
299
300 fn from_index(index: usize) -> Option<Self> {
301 [TextAlign::Leading, TextAlign::Center, TextAlign::Trailing, TextAlign::Justify].get(index).copied()
302 }
303
304 fn index(self) -> usize {
305 self as usize
306 }
307}
308
309#[derive(Clone, Debug, PartialEq)]
310pub struct TextStyle {
311 pub font: FontSpec,
312 pub color: Color,
313 pub h_align: TextAlign,
314 pub v_align: TextAlign,
315 pub wrap: bool,
317 pub trimming: crate::text::Trimming,
319 pub letter_spacing: f32,
324 pub color_glyphs: bool,
330}
331
332impl Default for TextStyle {
333 fn default() -> Self {
334 Self {
335 font: FontSpec::default(),
336 color: Color::BLACK,
337 h_align: TextAlign::Leading,
338 v_align: TextAlign::Center,
339 wrap: false,
340 trimming: crate::text::Trimming::Character,
341 letter_spacing: 0.0,
342 color_glyphs: true,
343 }
344 }
345}
346
347pub const MONO_EMOJI_FAMILY: &str = "Noto Emoji";
350
351pub const MONO_EMOJI_RANGES: &[(u32, u32)] = &[
356 (0x00A9, 0x00A9),
357 (0x00AE, 0x00AE),
358 (0x200D, 0x200D),
359 (0x203C, 0x203C),
360 (0x2049, 0x2049),
361 (0x20E3, 0x20E3),
362 (0x2122, 0x2122),
363 (0x2139, 0x2139),
364 (0x2194, 0x2199),
365 (0x21A9, 0x21AA),
366 (0x231A, 0x231B),
367 (0x2328, 0x2328),
368 (0x23CF, 0x23CF),
369 (0x23E9, 0x23F3),
370 (0x23F8, 0x23FA),
371 (0x24C2, 0x24C2),
372 (0x25AA, 0x25AB),
373 (0x25B6, 0x25B6),
374 (0x25C0, 0x25C0),
375 (0x25FB, 0x25FE),
376 (0x2600, 0x27BF),
377 (0x2934, 0x2935),
378 (0x2B05, 0x2B07),
379 (0x2B1B, 0x2B1C),
380 (0x2B50, 0x2B50),
381 (0x2B55, 0x2B55),
382 (0x3030, 0x3030),
383 (0x303D, 0x303D),
384 (0x3297, 0x3297),
385 (0x3299, 0x3299),
386 (0xFE0E, 0xFE0F),
387 (0x1F000, 0x1FAFF),
388 (0xE0020, 0xE007F),
389];
390
391pub fn is_mono_emoji(c: char) -> bool {
393 let c = c as u32;
394 MONO_EMOJI_RANGES.iter().any(|&(a, b)| c >= a && c <= b)
395}
396
397pub fn mono_emoji_ranges(text: &str) -> Vec<(usize, usize)> {
399 let mut out: Vec<(usize, usize)> = Vec::new();
400 for (i, c) in text.char_indices() {
401 if !is_mono_emoji(c) {
402 continue;
403 }
404 let end = i + c.len_utf8();
405 match out.last_mut() {
406 Some(last) if last.1 == i => last.1 = end,
407 _ => out.push((i, end)),
408 }
409 }
410 out
411}
412
413pub fn mono_emoji_available() -> bool {
415 crate::fonts::registered().iter().any(|f| f.family == MONO_EMOJI_FAMILY)
416}
417
418pub fn wrapped_size(text: &str, max_width: f32, line_height: f32, measure: &mut dyn FnMut(&str) -> f32) -> SizeF {
423 if text.is_empty() {
424 return SizeF::new(0.0, 0.0);
425 }
426 let lines = crate::text::layout_lines(text, max_width.max(1.0), usize::MAX, true, crate::text::Trimming::None, measure);
427 let widest = lines.iter().map(|l| measure(l)).fold(0.0f32, f32::max);
428 SizeF::new(widest, line_height * lines.len().max(1) as f32)
429}
430
431#[derive(Default)]
435pub struct WrapCache {
436 generation: u64,
437 sizes: std::collections::HashMap<(String, WrapKey), SizeF>,
438}
439
440#[derive(Clone, PartialEq, Eq, Hash)]
443struct WrapKey {
444 family: String,
445 size: u32,
446 weight: u8,
447 italic: bool,
448 letter_spacing: u32,
449 color_glyphs: bool,
450 width: u32,
451}
452
453impl WrapCache {
454 const MAX: usize = 4096;
456
457 pub fn get_or(&mut self, text: &str, style: &TextStyle, max_width: f32, compute: impl FnOnce() -> SizeF) -> SizeF {
459 let generation = crate::fonts::generation();
460 if generation != self.generation || self.sizes.len() >= Self::MAX {
461 self.sizes.clear();
462 self.generation = generation;
463 }
464 let key = WrapKey {
465 family: style.font.family.clone(),
466 size: style.font.size.to_bits(),
467 weight: style.font.weight as u8,
468 italic: style.font.italic,
469 letter_spacing: style.letter_spacing.to_bits(),
470 color_glyphs: style.color_glyphs,
471 width: max_width.to_bits(),
472 };
473 if let Some(size) = self.sizes.get(&(text.to_string(), key.clone())) {
474 return *size;
475 }
476 let size = compute();
477 self.sizes.insert((text.to_string(), key), size);
478 size
479 }
480}
481
482pub trait Canvas {
485 fn save(&mut self);
487 fn restore(&mut self);
489 fn translate(&mut self, dx: f32, dy: f32);
490 fn scale(&mut self, sx: f32, sy: f32);
491 fn rotate(&mut self, degrees: f32);
492 fn clip_rect(&mut self, rect: RectF);
493 fn save_layer(&mut self, opacity: f32);
496
497 fn save_layer_blend(&mut self, opacity: f32, mode: BlendMode, bounds: RectF) {
502 let _ = (mode, bounds);
503 self.save_layer(opacity);
504 }
505
506 fn fill_rect(&mut self, rect: RectF, radius: f32, brush: &Brush);
508 fn stroke_rect(&mut self, rect: RectF, radius: f32, stroke: &Stroke);
513 fn fill_ellipse(&mut self, rect: RectF, brush: &Brush);
514 fn stroke_ellipse(&mut self, rect: RectF, stroke: &Stroke);
516 fn draw_line(&mut self, from: PointF, to: PointF, stroke: &Stroke);
517 fn draw_text(&mut self, text: &str, rect: RectF, style: &TextStyle);
518 fn measure_text(&mut self, text: &str, style: &TextStyle) -> SizeF;
520
521 fn measure_text_wrapped(&mut self, text: &str, style: &TextStyle, max_width: f32) -> SizeF {
526 let line_height = self.measure_text("Ag", style).height;
527 wrapped_size(text, max_width, line_height, &mut |s| self.measure_text(s, style).width)
528 }
529
530 fn draw_image(&mut self, image: &Image, src: RectF, dest: RectF, opacity: f32) {
533 let _ = (image, src, dest, opacity);
534 }
535
536 fn image_size(&mut self, image: &Image) -> Option<SizeF> {
538 image.known_size()
539 }
540
541 fn clip_round_rect(&mut self, rect: RectF, radius: f32) {
543 let _ = radius;
544 self.clip_rect(rect);
545 }
546
547 fn fill_path(&mut self, path: &Path, brush: &Brush) {
549 let _ = (path, brush);
550 }
551
552 fn clip_path(&mut self, path: &Path, inverse: bool) {
555 if !inverse {
556 self.clip_rect(path.bounds());
557 }
558 }
559
560 fn backdrop_blur(&mut self, rect: RectF, radius: f32, blur: f32) -> bool {
564 let _ = (rect, radius, blur);
565 false
566 }
567
568 fn begin_masked(&mut self, inverse: bool) -> bool {
574 let _ = inverse;
575 false
576 }
577
578 fn begin_mask(&mut self) {}
580
581 fn begin_luminance_mask(&mut self) {
585 self.begin_mask();
586 }
587
588 fn end_mask(&mut self) {}
590
591 fn begin_cached(&mut self, key: u64, rect: RectF) -> bool {
598 let _ = (key, rect);
599 false
600 }
601
602 fn end_cached(&mut self) {}
604
605 fn forget_cached(&mut self, key: u64) {
609 let _ = key;
610 }
611
612 fn stroke_path(&mut self, path: &Path, stroke: &Stroke) {
614 for (points, closed) in path.flatten(8) {
615 for w in points.windows(2) {
616 self.draw_line(w[0], w[1], stroke);
617 }
618 if closed && points.len() > 2 {
619 self.draw_line(points[points.len() - 1], points[0], stroke);
620 }
621 }
622 }
623
624 fn draw_shadow(&mut self, rect: RectF, radius: f32, shadow: &Shadow) {
626 let _ = (rect, radius, shadow);
627 }
628
629 fn device_scale(&self) -> f32 {
632 1.0
633 }
634
635 fn gpu_device(&self) -> Option<GpuDevice> {
638 None
639 }
640
641 fn draw_gpu_surface(&mut self, dest: RectF, surface: &GpuSurface) -> bool {
645 let _ = (dest, surface);
646 false
647 }
648
649 fn gpu_state_changed(&mut self) {}
653}
654
655#[derive(Clone, Copy, Debug, PartialEq, Eq)]
657pub enum GpuDevice {
658 Direct3D11 { adapter_luid: i64 },
660 OpenGl { loader: usize, context: usize },
665 Web,
668}
669
670#[derive(Clone, Copy, Debug, PartialEq, Eq)]
675pub enum GpuSurface {
676 D3D12 {
685 id: u64,
687 texture: isize,
688 width: u32,
689 height: u32,
690 ready: isize,
691 ready_value: u64,
692 release: isize,
693 release_value: u64,
694 },
695 GlTexture { id: u64, texture: u32, width: u32, height: u32 },
698 WebCanvas { element: u32, width: u32, height: u32 },
700}
701
702pub trait TextService {
704 fn measure(&self, text: &str, style: &TextStyle, max_width: Option<f32>) -> SizeF;
706}
707
708pub fn decorate_line(canvas: &mut dyn Canvas, font: &FontSpec, color: Color, x: f32, width: f32, top: f32, line_height: f32) {
711 if !(font.underline || font.strikeout) || width <= 0.0 {
712 return;
713 }
714 let stroke = Stroke::new(color, (font.size / 14.0).max(1.0));
715 let middle = top + line_height / 2.0;
716 if font.underline {
717 let y = middle + font.size * 0.45;
718 canvas.draw_line(PointF::new(x, y), PointF::new(x + width, y), &stroke);
719 }
720 if font.strikeout {
721 let y = middle + font.size * 0.05;
722 canvas.draw_line(PointF::new(x, y), PointF::new(x + width, y), &stroke);
723 }
724}
725
726#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
733pub enum TextAntialias {
734 #[default]
735 Grayscale,
736 ClearType,
737}
738
739impl TextAntialias {
740 pub fn name(self) -> &'static str {
742 match self {
743 TextAntialias::Grayscale => "grayscale",
744 TextAntialias::ClearType => "cleartype",
745 }
746 }
747
748 pub fn parse(name: &str) -> Option<TextAntialias> {
750 match name {
751 "grayscale" => Some(TextAntialias::Grayscale),
752 "cleartype" => Some(TextAntialias::ClearType),
753 _ => None,
754 }
755 }
756}
757
758static TEXT_ANTIALIAS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
759
760pub fn set_text_antialias(mode: TextAntialias) {
762 TEXT_ANTIALIAS.store(mode == TextAntialias::ClearType, std::sync::atomic::Ordering::Relaxed);
763}
764
765pub fn text_antialias() -> TextAntialias {
767 if TEXT_ANTIALIAS.load(std::sync::atomic::Ordering::Relaxed) { TextAntialias::ClearType } else { TextAntialias::Grayscale }
768}