Skip to main content

crabshell_ui/
style.rs

1//! Colors, fonts and [`Style`]. Everything here is `Copy` and built with
2//! `const fn`s, so a theme is a set of constants.
3
4use crate::animation::{Animate, Transition};
5use crate::geometry::{Affine, Point, Rect};
6use crate::widgets::Align;
7
8/// An sRGB color with straight (not premultiplied) alpha.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub struct Color {
11  /// Red, 0 to 255.
12  pub r: u8,
13  /// Green, 0 to 255.
14  pub g: u8,
15  /// Blue, 0 to 255.
16  pub b: u8,
17  /// Alpha: 0 is transparent, 255 is opaque.
18  pub a: u8,
19}
20
21impl Color {
22  /// An opaque color.
23  pub const fn rgb(r: u8, g: u8, b: u8) -> Color {
24    Color { r, g, b, a: 255 }
25  }
26
27  /// A color with alpha: 0 is transparent, 255 is opaque.
28  pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
29    Color { r, g, b, a }
30  }
31
32  /// Parses `"#rrggbb"` or `"#rrggbbaa"`, in upper or lower case.
33  ///
34  /// # Panics
35  ///
36  /// If `hex` has any other form. In a `const`, that is a compile error:
37  ///
38  /// ```compile_fail
39  /// const BAD: crabshell_ui::Color = crabshell_ui::Color::hex("#12345");
40  /// ```
41  pub const fn hex(hex: &str) -> Color {
42    let bytes = hex.as_bytes();
43    if bytes.is_empty() || bytes[0] != b'#' || (bytes.len() != 7 && bytes.len() != 9) {
44      panic!("Color::hex takes \"#rrggbb\" or \"#rrggbbaa\"");
45    }
46    let a = if bytes.len() == 9 {
47      hex_byte(bytes[7], bytes[8])
48    } else {
49      255
50    };
51    Color {
52      r: hex_byte(bytes[1], bytes[2]),
53      g: hex_byte(bytes[3], bytes[4]),
54      b: hex_byte(bytes[5], bytes[6]),
55      a,
56    }
57  }
58
59  /// An opaque color from a hue in degrees, a saturation and a lightness
60  /// from 0 to 1, as CSS's `hsl()`: `Color::hsl(210.0, 0.5, 0.4)` is
61  /// `hsl(210 50% 40%)`. The hue wraps around, the others clamp, and a
62  /// number that isn't finite gives opaque black.
63  pub const fn hsl(hue: f32, saturation: f32, lightness: f32) -> Color {
64    Color::hsla(hue, saturation, lightness, 1.0)
65  }
66
67  /// [`hsl`](Self::hsl) with an alpha from 0 (transparent) to 1 (opaque).
68  pub const fn hsla(hue: f32, saturation: f32, lightness: f32, alpha: f32) -> Color {
69    if !(hue.is_finite() && saturation.is_finite() && lightness.is_finite() && alpha.is_finite()) {
70      return Color::rgb(0, 0, 0);
71    }
72    let hue = hue - (hue / 360.0).floor() * 360.0;
73    let saturation = saturation.clamp(0.0, 1.0);
74    let lightness = lightness.clamp(0.0, 1.0);
75    // CSS Color 4's conversion: the chroma, then where the hue puts it.
76    let chroma = (1.0 - (2.0 * lightness - 1.0).abs()) * saturation;
77    let sector = hue / 60.0;
78    let second = chroma * (1.0 - (sector - (sector / 2.0).floor() * 2.0 - 1.0).abs());
79    let (r, g, b) = match sector as u8 {
80      0 => (chroma, second, 0.0),
81      1 => (second, chroma, 0.0),
82      2 => (0.0, chroma, second),
83      3 => (0.0, second, chroma),
84      4 => (second, 0.0, chroma),
85      _ => (chroma, 0.0, second),
86    };
87    let lowest = lightness - chroma / 2.0;
88    Color {
89      r: unit_byte(r + lowest),
90      g: unit_byte(g + lowest),
91      b: unit_byte(b + lowest),
92      a: unit_byte(alpha),
93    }
94  }
95
96  /// The same color with an alpha from 0 (transparent) to 1 (opaque),
97  /// clamped. NaN leaves it as it is.
98  pub const fn with_alpha(self, alpha: f32) -> Color {
99    if alpha.is_nan() {
100      return self;
101    }
102    Color {
103      a: unit_byte(alpha),
104      ..self
105    }
106  }
107
108  /// `t` of the way from this color to `other`, from 0 to 1, clamped,
109  /// each sRGB channel and the alpha on their own, as a style fade
110  /// blends. NaN leaves this color as it is.
111  pub const fn mix(self, other: Color, t: f32) -> Color {
112    if t.is_nan() {
113      return self;
114    }
115    let t = t.clamp(0.0, 1.0);
116    Color {
117      r: mix_channel(self.r, other.r, t),
118      g: mix_channel(self.g, other.g, t),
119      b: mix_channel(self.b, other.b, t),
120      a: mix_channel(self.a, other.a, t),
121    }
122  }
123
124  /// The same color with its HSL lightness raised by `amount`, from 0 to
125  /// 1, as Sass's `lighten`: `lighter(0.1)` takes `hsl(210 50% 40%)` to
126  /// `hsl(210 50% 50%)`. The amount and the lightness clamp, and NaN
127  /// leaves the color as it is.
128  pub const fn lighter(self, amount: f32) -> Color {
129    self.lightness_by(amount.clamp(0.0, 1.0))
130  }
131
132  /// The same color with its HSL lightness lowered by `amount`, as
133  /// [`lighter`](Self::lighter) raises it.
134  pub const fn darker(self, amount: f32) -> Color {
135    self.lightness_by(-amount.clamp(0.0, 1.0))
136  }
137
138  /// This color with `change` added to its HSL lightness.
139  const fn lightness_by(self, change: f32) -> Color {
140    if change.is_nan() {
141      return self;
142    }
143    let (r, g, b) = (
144      self.r as f32 / 255.0,
145      self.g as f32 / 255.0,
146      self.b as f32 / 255.0,
147    );
148    let (high, low) = (r.max(g).max(b), r.min(g).min(b));
149    let lightness = (high + low) / 2.0;
150    let chroma = high - low;
151    let (hue, saturation) = if chroma == 0.0 {
152      (0.0, 0.0)
153    } else {
154      let hue = if high == r {
155        (g - b) / chroma
156      } else if high == g {
157        (b - r) / chroma + 2.0
158      } else {
159        (r - g) / chroma + 4.0
160      };
161      (hue * 60.0, chroma / (1.0 - (2.0 * lightness - 1.0).abs()))
162    };
163    let lightness = lightness + change;
164    Color::hsla(hue, saturation, lightness, self.a as f32 / 255.0)
165  }
166}
167
168/// `t` of the way from one channel to another, rounded. Closures can't
169/// be called in a `const fn`.
170const fn mix_channel(from: u8, to: u8, t: f32) -> u8 {
171  (from as f32 + (to as f32 - from as f32) * t).round() as u8
172}
173
174/// A fraction from 0 to 1, clamped, as a channel from 0 to 255.
175const fn unit_byte(value: f32) -> u8 {
176  (value.clamp(0.0, 1.0) * 255.0).round() as u8
177}
178
179const fn hex_byte(high: u8, low: u8) -> u8 {
180  hex_digit(high) * 16 + hex_digit(low)
181}
182
183const fn hex_digit(digit: u8) -> u8 {
184  match digit {
185    b'0'..=b'9' => digit - b'0',
186    b'a'..=b'f' => digit - b'a' + 10,
187    b'A'..=b'F' => digit - b'A' + 10,
188    _ => panic!("Color::hex found a character that isn't a hex digit"),
189  }
190}
191
192/// A font: family, size and weight.
193///
194/// The family is resolved through fontconfig, so generic names such as
195/// `"sans-serif"` and `"monospace"` work too.
196#[derive(Clone, Copy, Debug, PartialEq)]
197pub struct Font {
198  /// The family name, such as `"Inter"` or `"sans-serif"`.
199  pub family: &'static str,
200  /// The size in logical pixels.
201  pub size: f32,
202  /// The weight, from 100 (thin) through 400 (regular) and 700 (bold) to
203  /// 900 (black).
204  pub weight: u16,
205}
206
207impl Font {
208  /// The font text uses when no ancestor sets one.
209  pub const DEFAULT: Font = Font::new("sans-serif", 13.0);
210
211  /// A regular-weight font of `family` at `size` logical pixels.
212  pub const fn new(family: &'static str, size: f32) -> Font {
213    Font {
214      family,
215      size,
216      weight: 400,
217    }
218  }
219
220  /// The same font with another weight, such as 700 for bold.
221  pub const fn weight(self, weight: u16) -> Font {
222    Font { weight, ..self }
223  }
224}
225
226/// A border drawn inside a widget's edge. It takes no layout space.
227#[derive(Clone, Copy, Debug, PartialEq)]
228pub struct Border {
229  /// The width in logical pixels.
230  pub width: f32,
231  /// The color.
232  pub color: Color,
233}
234
235/// How round each corner of a widget's box is: the radius in logical
236/// pixels, 0 for a square corner. Each is clamped to half the box's
237/// shorter side, so two on one side never overlap.
238#[derive(Clone, Copy, Debug, Default, PartialEq)]
239pub struct Radii {
240  /// The top-left corner.
241  pub top_left: f32,
242  /// The top-right corner.
243  pub top_right: f32,
244  /// The bottom-right corner.
245  pub bottom_right: f32,
246  /// The bottom-left corner.
247  pub bottom_left: f32,
248}
249
250impl Radii {
251  /// Every corner `radius` round.
252  pub const fn all(radius: f32) -> Radii {
253    Radii {
254      top_left: radius,
255      top_right: radius,
256      bottom_right: radius,
257      bottom_left: radius,
258    }
259  }
260
261  /// The four, from the top left clockwise.
262  pub const fn corners(&self) -> [f32; 4] {
263    [
264      self.top_left,
265      self.top_right,
266      self.bottom_right,
267      self.bottom_left,
268    ]
269  }
270
271  /// `t` of the way to `to`, each corner on its own.
272  pub(crate) fn lerp(&self, to: &Radii, t: f32) -> Radii {
273    Radii {
274      top_left: self.top_left.lerp(&to.top_left, t),
275      top_right: self.top_right.lerp(&to.top_right, t),
276      bottom_right: self.bottom_right.lerp(&to.bottom_right, t),
277      bottom_left: self.bottom_left.lerp(&to.bottom_left, t),
278    }
279  }
280
281  /// Whether `point` is inside `rect` with these corners, each clamped
282  /// to half its shorter side, after `inset` is taken off every side and
283  /// every corner.
284  pub(crate) fn contains(&self, rect: Rect, inset: f32, point: Point) -> bool {
285    let most = rect.width.min(rect.height) / 2.0;
286    let inner = Rect::new(
287      rect.x + inset,
288      rect.y + inset,
289      rect.width - 2.0 * inset,
290      rect.height - 2.0 * inset,
291    );
292    if !inner.contains(point) {
293      return false;
294    }
295    let [top_left, top_right, bottom_right, bottom_left] = self
296      .corners()
297      .map(|r| (if r.is_nan() { 0.0 } else { r.clamp(0.0, most) } - inset).max(0.0));
298    let (left, top, right, bottom) = (inner.x, inner.y, inner.right(), inner.bottom());
299    // Each corner's circle, and the side of its middle the corner is on.
300    [
301      (top_left, left + top_left, top + top_left, -1.0, -1.0),
302      (top_right, right - top_right, top + top_right, 1.0, -1.0),
303      (
304        bottom_right,
305        right - bottom_right,
306        bottom - bottom_right,
307        1.0,
308        1.0,
309      ),
310      (
311        bottom_left,
312        left + bottom_left,
313        bottom - bottom_left,
314        -1.0,
315        1.0,
316      ),
317    ]
318    .into_iter()
319    .all(|(r, cx, cy, sx, sy)| {
320      let (dx, dy) = (point.x - cx, point.y - cy);
321      r <= 0.0 || dx * sx <= 0.0 || dy * sy <= 0.0 || dx.hypot(dy) <= r
322    })
323  }
324}
325
326/// Colors that blend into each other across a widget's box, drawn over
327/// its background with the same corners.
328///
329/// ```
330/// use crabshell_ui::{Color, Gradient, Style};
331///
332/// const DUSK: Style = Style::new().gradient(
333///     Gradient::linear(90.0, Color::hex("#1e1e2e"), Color::hex("#45475a"))
334///         .stop(0.5, Color::hex("#313244")),
335/// );
336/// ```
337#[derive(Clone, Copy, Debug, PartialEq)]
338pub struct Gradient {
339  /// Which way the colors run.
340  pub shape: GradientShape,
341  /// The first `count` hold each color and where it sits, from 0 at the
342  /// start to 1 at the end.
343  stops: [(f32, Color); 4],
344  count: u8,
345}
346
347/// Which way a [`Gradient`]'s colors run.
348#[derive(Clone, Copy, Debug, PartialEq)]
349pub enum GradientShape {
350  /// Along a line through the middle at this many degrees, as in CSS: 0
351  /// runs from the bottom up, 90 from left to right, 180 from the top
352  /// down. Its ends meet the corners.
353  Linear(f32),
354  /// In circles out from the middle to the farthest corner.
355  Radial,
356  /// Around the middle, clockwise from this many degrees, as CSS's
357  /// `conic-gradient(from …)`: 0 starts at 12 o'clock, 90 at 3.
358  Sweep(f32),
359}
360
361impl Gradient {
362  /// A gradient from `from` to `to` along a line at `angle` degrees: 0
363  /// runs from the bottom up, 90 from left to right.
364  pub const fn linear(angle: f32, from: Color, to: Color) -> Gradient {
365    Gradient::new(GradientShape::Linear(angle), from, to)
366  }
367
368  /// A gradient from `from` in the middle to `to` at the farthest corner.
369  pub const fn radial(from: Color, to: Color) -> Gradient {
370    Gradient::new(GradientShape::Radial, from, to)
371  }
372
373  /// A gradient from `from` to `to` once around the middle, clockwise
374  /// from `angle` degrees: 0 starts at 12 o'clock, 90 at 3, as CSS's
375  /// `conic-gradient(from 90deg, …)`. The end meets the start there.
376  ///
377  /// ```
378  /// use crabshell_ui::{Color, Gradient, Style};
379  ///
380  /// const RING: Style = Style::new().radius(20.0).gradient(
381  ///     Gradient::sweep(0.0, Color::hex("#89b4fa"), Color::hex("#89b4fa"))
382  ///         .stop(0.5, Color::hex("#f5c2e7")),
383  /// );
384  /// ```
385  pub const fn sweep(angle: f32, from: Color, to: Color) -> Gradient {
386    Gradient::new(GradientShape::Sweep(angle), from, to)
387  }
388
389  const fn new(shape: GradientShape, from: Color, to: Color) -> Gradient {
390    Gradient {
391      shape,
392      stops: [(0.0, from), (1.0, to), (1.0, to), (1.0, to)],
393      count: 2,
394    }
395  }
396
397  /// Adds `color` at `at`, from 0 to 1, before the end color. Add them
398  /// in order. A gradient has at most four colors, so a third stop
399  /// panics.
400  pub const fn stop(self, at: f32, color: Color) -> Gradient {
401    assert!(self.count < 4, "a gradient has at most four colors");
402    let mut stops = self.stops;
403    let last = self.count as usize - 1;
404    stops[last + 1] = stops[last];
405    stops[last] = (at, color);
406    Gradient {
407      stops,
408      count: self.count + 1,
409      ..self
410    }
411  }
412
413  /// Each color and where it sits, from the start to the end.
414  pub fn stops(&self) -> &[(f32, Color)] {
415    &self.stops[..usize::from(self.count)]
416  }
417
418  /// `t` of the way from this gradient to `to`, or `None` when their
419  /// shapes or numbers of colors differ.
420  fn lerp(&self, to: &Gradient, t: f32) -> Option<Gradient> {
421    let shape = match (self.shape, to.shape) {
422      (GradientShape::Linear(from), GradientShape::Linear(to)) => {
423        GradientShape::Linear(from.lerp(&to, t))
424      }
425      (GradientShape::Radial, GradientShape::Radial) => GradientShape::Radial,
426      (GradientShape::Sweep(from), GradientShape::Sweep(to)) => {
427        GradientShape::Sweep(from.lerp(&to, t))
428      }
429
430      _ => return None,
431    };
432    if self.count != to.count {
433      return None;
434    }
435    let mut stops = to.stops;
436    for (stop, (from, to)) in stops.iter_mut().zip(self.stops.iter().zip(to.stops)) {
437      *stop = (from.0.lerp(&to.0, t), from.1.lerp(&to.1, t));
438    }
439    Some(Gradient {
440      shape,
441      stops,
442      count: to.count,
443    })
444  }
445
446  /// This gradient with every color transparent.
447  fn clear(mut self) -> Gradient {
448    for (_, color) in &mut self.stops {
449      color.a = 0;
450    }
451    self
452  }
453}
454
455/// A shadow cast by a widget's box, as CSS's `box-shadow`: the box's
456/// shape moved by `x` and `y`, grown by `spread` and blurred over `blur`
457/// logical pixels. Unlike CSS's, it is drawn under the box too, so a
458/// translucent background shows it through, unless it is
459/// [`cut_out`](Shadow::cut_out).
460///
461/// ```
462/// use crabshell_ui::{Color, Shadow, Style};
463///
464/// const CARD: Style = Style::new()
465///     .background(Color::hex("#1e1e2e"))
466///     .radius(8.0)
467///     .shadow(Shadow::new(0.0, 4.0, 12.0, Color::rgba(0, 0, 0, 96)));
468/// ```
469#[derive(Clone, Copy, Debug, PartialEq)]
470pub struct Shadow {
471  /// How far right it is moved.
472  pub x: f32,
473  /// How far down it is moved.
474  pub y: f32,
475  /// How far its edge is blurred. 0 is a sharp edge.
476  pub blur: f32,
477  /// How much larger than the box it is on each side, or smaller when
478  /// negative.
479  pub spread: f32,
480  /// Its color.
481  pub color: Color,
482  /// Whether it is left out under the box, as under translucent glass.
483  pub cut_out: bool,
484  /// Whether it is cast by what the widget and its children draw,
485  /// through their alpha, instead of by its box.
486  pub follow_content: bool,
487}
488
489impl Shadow {
490  /// A shadow moved by `x` and `y` and blurred over `blur`, the box's
491  /// size.
492  pub const fn new(x: f32, y: f32, blur: f32, color: Color) -> Shadow {
493    Shadow {
494      x,
495      y,
496      blur,
497      spread: 0.0,
498      color,
499      cut_out: false,
500      follow_content: false,
501    }
502  }
503
504  /// The same shadow `spread` larger on each side.
505  pub const fn spread(self, spread: f32) -> Shadow {
506    Shadow { spread, ..self }
507  }
508
509  /// The same shadow left out under the box's own shape, so a translucent
510  /// background, such as glass the compositor blurs, shows what is
511  /// behind it instead of the shadow. CSS's `box-shadow` is always drawn
512  /// this way.
513  pub const fn cut_out(self) -> Shadow {
514    Shadow {
515      cut_out: true,
516      ..self
517    }
518  }
519
520  /// The same shadow cast by what the widget and everything inside it
521  /// draw, through their alpha, instead of by its box, so text and icons
522  /// get a drop shadow, as Qt's `MultiEffect` shadow gives. It is drawn
523  /// under them, offset, spread and blurred as a box shadow is, and
524  /// after a [`mask`](Style::mask), so it follows the masked shape. Cut
525  /// out, it is left out under the content's own alpha.
526  ///
527  /// ```
528  /// use crabshell_ui::{Color, Shadow, Style};
529  ///
530  /// const LABEL: Style = Style::new()
531  ///     .color(Color::hex("#cdd6f4"))
532  ///     .shadow(Shadow::new(0.0, 1.0, 3.0, Color::rgba(0, 0, 0, 160)).follow_content());
533  /// ```
534  pub const fn follow_content(self) -> Shadow {
535    Shadow {
536      follow_content: true,
537      ..self
538    }
539  }
540
541  /// Whether this shadow is cast by the content and can be: its numbers
542  /// are finite and it reaches at most 64 logical pixels past what casts
543  /// it, the size of its spread plus one and a half blurs. One reaching
544  /// farther is left out whole and the content drawn without it, so the
545  /// work of casting it stays bounded.
546  pub fn casts_from_content(&self) -> bool {
547    let reach = self.spread.abs() + 1.5 * self.blur.max(0.0);
548    self.follow_content && [self.x, self.y, reach].iter().all(|n| n.is_finite()) && reach <= 64.0
549  }
550
551  /// The area this shadow of `rect` covers: its shape, grown by one and a
552  /// half blurs, past which the blur fades below a 255th. A spread that
553  /// swallows the box still reaches between the edges it would have, so
554  /// a fade from it stays within its start and end. A shadow with a
555  /// number that isn't finite is never drawn, so it reaches only `rect`.
556  pub(crate) fn reach(&self, rect: Rect) -> Rect {
557    let grow = self.spread + 1.5 * self.blur.max(0.0);
558    if ![self.x, self.y, grow].iter().all(|n| n.is_finite()) {
559      return rect;
560    }
561    let (left, right) = (rect.x + self.x - grow, rect.right() + self.x + grow);
562    let (top, bottom) = (rect.y + self.y - grow, rect.bottom() + self.y + grow);
563    Rect::new(
564      left.min(right),
565      top.min(bottom),
566      (right - left).abs(),
567      (bottom - top).abs(),
568    )
569  }
570
571  /// `t` of the way to `to`.
572  fn lerp(&self, to: &Shadow, t: f32) -> Shadow {
573    Shadow {
574      x: self.x.lerp(&to.x, t),
575      y: self.y.lerp(&to.y, t),
576      blur: self.blur.lerp(&to.blur, t),
577      spread: self.spread.lerp(&to.spread, t),
578      color: self.color.lerp(&to.color, t),
579      // Not numbers: they change at once.
580      cut_out: to.cut_out,
581      follow_content: to.follow_content,
582    }
583  }
584
585  /// This shadow, transparent.
586  fn clear(self) -> Shadow {
587    Shadow {
588      color: Color::rgba(self.color.r, self.color.g, self.color.b, 0),
589      ..self
590    }
591  }
592}
593
594/// Where a widget and everything inside it show, as Qt's `OpacityMask`:
595/// what they draw is kept only where the mask is opaque, its alpha
596/// multiplying theirs, and nothing shows outside the widget's box. Set it
597/// with [`Style::mask`].
598///
599/// ```
600/// use crabshell_ui::{Color, Gradient, Mask, Style};
601///
602/// const AVATAR: Style = Style::new().mask(Mask::ellipse());
603/// // A list that fades out over its last fifth.
604/// const FADING: Style = Style::new().mask(Mask::gradient(
605///     Gradient::linear(180.0, Color::rgb(0, 0, 0), Color::rgba(0, 0, 0, 0))
606///         .stop(0.8, Color::rgb(0, 0, 0)),
607/// ));
608/// const STAR: Style = Style::new().mask(Mask::image("/usr/share/my-shell/star.png"));
609/// ```
610#[derive(Clone, Copy, Debug, PartialEq)]
611pub enum Mask {
612  /// An ellipse filling the box.
613  Ellipse,
614  /// A gradient's alpha, laid over the box as a background's is.
615  Gradient(Gradient),
616  /// A file's alpha, stretched over the box. It is read through the
617  /// [`Image`](crate::Image) loaders and their caps; one that is missing
618  /// or refused is logged once and the widget is drawn unmasked.
619  Image(&'static str),
620}
621
622impl Mask {
623  /// An ellipse filling the box, for round avatars and album art.
624  pub const fn ellipse() -> Mask {
625    Mask::Ellipse
626  }
627
628  /// `gradient`'s alpha laid over the box, for lists and strips that fade
629  /// out at an edge. Only the colors' alpha counts.
630  pub const fn gradient(gradient: Gradient) -> Mask {
631    Mask::Gradient(gradient)
632  }
633
634  /// The alpha of the image file at `path`, stretched over the box.
635  ///
636  /// The path is `&'static str`, so a style holding it can be a `const`.
637  /// For a path made at run time, leak it once, outside any closure: a
638  /// `String::leak` inside a `move || Style` binding leaks again each
639  /// time the binding runs.
640  ///
641  /// ```
642  /// use crabshell_ui::{Mask, Stack, Style};
643  ///
644  /// let home = std::env::var("HOME").unwrap_or_default();
645  /// // Once, here, not in the closure below.
646  /// let face: &'static str = format!("{home}/.face").leak();
647  /// let avatar = Stack::new().style(move || Style::new().mask(Mask::image(face)));
648  /// ```
649  pub const fn image(path: &'static str) -> Mask {
650    Mask::Image(path)
651  }
652}
653
654/// Space between a widget's edge and its content, in logical pixels, on
655/// each side.
656#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
657pub struct Padding {
658  /// Above the content.
659  pub top: u32,
660  /// Right of the content.
661  pub right: u32,
662  /// Below the content.
663  pub bottom: u32,
664  /// Left of the content.
665  pub left: u32,
666}
667
668/// How a widget looks. Every field is optional, and an unset field falls back
669/// to the widget's default: no background, black text in
670/// [`Font::DEFAULT`], no padding, square corners, no border, fully opaque.
671///
672/// [`Text`](crate::Text) takes `color` and `font` from the nearest widget
673/// that sets them, starting with itself and going up. Nothing else inherits.
674///
675/// `font`, `padding`, `clip`, the sizes, the flex fields, the alignment,
676/// the absolute position and `span` change the layout, at once; the other
677/// fields only change how the widget is painted. A number that isn't
678/// finite counts as unset.
679///
680/// `translate`, `scale`, `rotate` and `origin` move the widget and
681/// everything inside it where it is drawn and where the pointer finds it,
682/// without moving anything else: the layout, and popups anchored to the
683/// widget, keep its box where it was laid out.
684///
685/// ```
686/// use crabshell_ui::{Color, Font, Style};
687///
688/// const BAR: Style = Style::new()
689///     .background(Color::rgb(0x1e, 0x1e, 0x2e))
690///     .color(Color::hex("#cdd6f4"))
691///     .font(Font::new("Inter", 13.0));
692/// const WS: Style = Style::new().padding(2, 8).radius(4.0);
693/// const WS_FOCUSED: Style = WS.background(Color::rgb(0x45, 0x47, 0x5a));
694/// ```
695#[derive(Clone, Copy, Debug, Default, PartialEq)]
696pub struct Style {
697  /// Fills the widget's rectangle.
698  pub background: Option<Color>,
699  /// Colors blending across the widget's rectangle, over the background.
700  pub gradient: Option<Gradient>,
701  /// A shadow under the widget's box.
702  pub shadow: Option<Shadow>,
703  /// The text color, inherited by [`Text`](crate::Text).
704  pub color: Option<Color>,
705  /// The text font, inherited by [`Text`](crate::Text).
706  pub font: Option<Font>,
707  /// Space between the edge and the content.
708  pub padding: Option<Padding>,
709  /// How round each corner is, in logical pixels.
710  pub radius: Option<Radii>,
711  /// A border inside the edge.
712  pub border: Option<Border>,
713  /// Dashes for the border, `on` and `off` logical pixels along its
714  /// middle line, or a solid border when unset. See
715  /// [`border_dash`](Self::border_dash).
716  pub border_dash: Option<(f32, f32)>,
717  /// From 0.0 (invisible) to 1.0 (opaque), applied to the widget and
718  /// everything inside it.
719  pub opacity: Option<f32>,
720  /// Where the widget and everything inside it show.
721  pub mask: Option<Mask>,
722  /// Whether the children are cut to the inside of the border, following
723  /// the rounded corners, like CSS's `overflow: hidden`.
724  pub clip: Option<bool>,
725  /// The width in logical pixels, instead of what the content needs.
726  pub width: Option<f32>,
727  /// The height in logical pixels, instead of what the content needs.
728  pub height: Option<f32>,
729  /// The least width in logical pixels.
730  pub min_width: Option<f32>,
731  /// The least height in logical pixels.
732  pub min_height: Option<f32>,
733  /// The most width in logical pixels.
734  pub max_width: Option<f32>,
735  /// The most height in logical pixels.
736  pub max_height: Option<f32>,
737  /// How much of a row's or column's free space it takes, against its
738  /// siblings', as CSS's `flex-grow`. 0 by default.
739  pub grow: Option<f32>,
740  /// How much it gives up when a row or column is too small, against its
741  /// siblings', as CSS's `flex-shrink`. 1 by default.
742  pub shrink: Option<f32>,
743  /// Its size along a row or column before growing or shrinking, in
744  /// logical pixels, as CSS's `flex-basis`.
745  pub basis: Option<f32>,
746  /// How it is placed across its row's or column's direction, or
747  /// vertically in a stack's or grid's cell, instead of the parent's
748  /// `align`.
749  pub align_self: Option<Align>,
750  /// How it is placed horizontally in a stack's or grid's cell. Rows and
751  /// columns ignore it, as CSS's flexbox does.
752  pub justify_self: Option<Align>,
753  /// Logical pixels from its parent's left edge, inside the border.
754  /// Any of `left`, `top`, `right` and `bottom` takes the widget out of
755  /// its parent's flow, as CSS's `position: absolute`: it is placed from
756  /// those edges and no longer sizes its parent.
757  pub left: Option<f32>,
758  /// Logical pixels from its parent's top edge, as `left`.
759  pub top: Option<f32>,
760  /// Logical pixels from its parent's right edge, as `left`.
761  pub right: Option<f32>,
762  /// Logical pixels from its parent's bottom edge, as `left`.
763  pub bottom: Option<f32>,
764  /// The order it is drawn and found by the pointer among its siblings,
765  /// lowest first; siblings of equal `z` keep their order, later on top.
766  /// 0 by default. It changes no layout.
767  pub z: Option<i32>,
768  /// The columns and rows of a [`Grid`](crate::Grid) it takes, each at
769  /// least 1.
770  pub span: Option<(u32, u32)>,
771  /// How far the widget is moved, right and down, in logical pixels,
772  /// after it is scaled and turned.
773  pub translate: Option<Point>,
774  /// How many times its size it is drawn, around `origin`. 0 draws
775  /// nothing, and a negative scale also turns it upside down.
776  pub scale: Option<f32>,
777  /// How many degrees it is turned clockwise, around `origin`.
778  pub rotate: Option<f32>,
779  /// The point it is scaled and turned around, as fractions of its box:
780  /// `(0, 0)` is the top-left corner, and the default `(0.5, 0.5)` the
781  /// middle.
782  pub origin: Option<Point>,
783  /// How a change to the paint fields fades in: background, gradient,
784  /// shadow, color, border, radius, opacity and the transform. Other
785  /// fields change at once.
786  pub transition: Option<Transition>,
787}
788
789impl Style {
790  /// A style that sets nothing.
791  pub const fn new() -> Style {
792    Style {
793      background: None,
794      gradient: None,
795      shadow: None,
796      color: None,
797      font: None,
798      padding: None,
799      radius: None,
800      border: None,
801      border_dash: None,
802      opacity: None,
803      mask: None,
804      clip: None,
805      width: None,
806      height: None,
807      min_width: None,
808      min_height: None,
809      max_width: None,
810      max_height: None,
811      grow: None,
812      shrink: None,
813      basis: None,
814      align_self: None,
815      justify_self: None,
816      left: None,
817      top: None,
818      right: None,
819      bottom: None,
820      z: None,
821      span: None,
822      translate: None,
823      scale: None,
824      rotate: None,
825      origin: None,
826      transition: None,
827    }
828  }
829
830  /// Sets the background color.
831  pub const fn background(self, color: Color) -> Style {
832    Style {
833      background: Some(color),
834      ..self
835    }
836  }
837
838  /// Sets a gradient, drawn over the background.
839  pub const fn gradient(self, gradient: Gradient) -> Style {
840    Style {
841      gradient: Some(gradient),
842      ..self
843    }
844  }
845
846  /// Sets a shadow under the box.
847  pub const fn shadow(self, shadow: Shadow) -> Style {
848    Style {
849      shadow: Some(shadow),
850      ..self
851    }
852  }
853
854  /// Sets the text color.
855  pub const fn color(self, color: Color) -> Style {
856    Style {
857      color: Some(color),
858      ..self
859    }
860  }
861
862  /// Sets the text font.
863  pub const fn font(self, font: Font) -> Style {
864    Style {
865      font: Some(font),
866      ..self
867    }
868  }
869
870  /// Sets the padding: `vertical` above and below, `horizontal` left and
871  /// right, in logical pixels.
872  pub const fn padding(self, vertical: u32, horizontal: u32) -> Style {
873    Style {
874      padding: Some(Padding {
875        top: vertical,
876        right: horizontal,
877        bottom: vertical,
878        left: horizontal,
879      }),
880      ..self
881    }
882  }
883
884  /// Sets the padding above the content, in logical pixels, keeping the
885  /// other sides this style sets, or 0 where it sets none. As with every
886  /// field, [`merge`](Self::merge) takes the whole padding of the style on
887  /// top, so a hover style built from `Style::new()` sets the rest to 0.
888  ///
889  /// ```
890  /// use crabshell_ui::Style;
891  ///
892  /// const PILL: Style = Style::new().padding(2, 8).padding_left(12);
893  /// ```
894  pub const fn padding_top(self, top: u32) -> Style {
895    let mut padding = self.sides();
896    padding.top = top;
897    Style {
898      padding: Some(padding),
899      ..self
900    }
901  }
902
903  /// Sets the padding right of the content, keeping the other sides, as
904  /// [`padding_top`](Self::padding_top) does.
905  pub const fn padding_right(self, right: u32) -> Style {
906    let mut padding = self.sides();
907    padding.right = right;
908    Style {
909      padding: Some(padding),
910      ..self
911    }
912  }
913
914  /// Sets the padding below the content, keeping the other sides, as
915  /// [`padding_top`](Self::padding_top) does.
916  pub const fn padding_bottom(self, bottom: u32) -> Style {
917    let mut padding = self.sides();
918    padding.bottom = bottom;
919    Style {
920      padding: Some(padding),
921      ..self
922    }
923  }
924
925  /// Sets the padding left of the content, keeping the other sides, as
926  /// [`padding_top`](Self::padding_top) does.
927  pub const fn padding_left(self, left: u32) -> Style {
928    let mut padding = self.sides();
929    padding.left = left;
930    Style {
931      padding: Some(padding),
932      ..self
933    }
934  }
935
936  /// The padding this style sets, or 0 on every side.
937  const fn sides(self) -> Padding {
938    match self.padding {
939      Some(padding) => padding,
940      None => Padding {
941        top: 0,
942        right: 0,
943        bottom: 0,
944        left: 0,
945      },
946    }
947  }
948
949  /// Rounds every corner by `radius` logical pixels.
950  pub const fn radius(self, radius: f32) -> Style {
951    Style {
952      radius: Some(Radii::all(radius)),
953      ..self
954    }
955  }
956
957  /// Rounds each corner on its own, in logical pixels, as CSS's
958  /// `border-radius` with four values. Each is clamped to half the box's
959  /// shorter side. Everything that follows the corners follows each one:
960  /// the background, gradient, border, shadow, a clip and the scroll
961  /// bar's cut.
962  ///
963  /// ```
964  /// use crabshell_ui::Style;
965  ///
966  /// // A tab, round on top only.
967  /// const TAB: Style = Style::new().radii(8.0, 8.0, 0.0, 0.0);
968  /// ```
969  pub const fn radii(
970    self,
971    top_left: f32,
972    top_right: f32,
973    bottom_right: f32,
974    bottom_left: f32,
975  ) -> Style {
976    Style {
977      radius: Some(Radii {
978        top_left,
979        top_right,
980        bottom_right,
981        bottom_left,
982      }),
983      ..self
984    }
985  }
986
987  /// Sets a border of `width` logical pixels.
988  pub const fn border(self, width: f32, color: Color) -> Style {
989    Style {
990      border: Some(Border { width, color }),
991      ..self
992    }
993  }
994
995  /// Dashes the border: `on` logical pixels drawn, `off` left out, along
996  /// the middle of the border, so the dashes follow its corners. An `on`
997  /// of 0 draws round dots the border's width across, `off` apart from
998  /// middle to middle. The dashes are stretched or squeezed a little so a
999  /// whole number of them goes around. A number that isn't finite, a
1000  /// negative one, an `off` of 0 or a pattern shorter than a pixel draws
1001  /// the border solid. It is a field of its own, so a hover style can
1002  /// dash a border the style under it sets, and with no border it draws
1003  /// nothing. A fade takes the end style's dash at once.
1004  ///
1005  /// ```
1006  /// use crabshell_ui::{Color, Style};
1007  ///
1008  /// const DROP_ZONE: Style = Style::new()
1009  ///     .border(2.0, Color::hex("#89b4fa"))
1010  ///     .border_dash(6.0, 4.0)
1011  ///     .radius(8.0);
1012  /// const DOTTED: Style = DROP_ZONE.border_dash(0.0, 5.0);
1013  /// ```
1014  pub const fn border_dash(self, on: f32, off: f32) -> Style {
1015    Style {
1016      border_dash: Some((on, off)),
1017      ..self
1018    }
1019  }
1020
1021  /// Sets the opacity, from 0.0 to 1.0.
1022  pub const fn opacity(self, opacity: f32) -> Style {
1023    Style {
1024      opacity: Some(opacity),
1025      ..self
1026    }
1027  }
1028
1029  /// Keeps the widget and everything inside it only where `mask` is
1030  /// opaque, as Qt's `OpacityMask`. They are drawn into one layer, the
1031  /// one opacity and a transform use, so stacking them costs no extra
1032  /// layer, and a clip still cuts inside it. A fade takes the end
1033  /// style's mask at once.
1034  pub const fn mask(self, mask: Mask) -> Style {
1035    Style {
1036      mask: Some(mask),
1037      ..self
1038    }
1039  }
1040
1041  /// Sets whether the children are cut to the inside of the border,
1042  /// following the rounded corners. Nothing is cut by default.
1043  pub const fn clip(self, clip: bool) -> Style {
1044    Style {
1045      clip: Some(clip),
1046      ..self
1047    }
1048  }
1049
1050  /// Sets the width in logical pixels, instead of what the content needs.
1051  pub const fn width(self, width: f32) -> Style {
1052    Style {
1053      width: Some(width),
1054      ..self
1055    }
1056  }
1057
1058  /// Sets the height in logical pixels, instead of what the content
1059  /// needs.
1060  pub const fn height(self, height: f32) -> Style {
1061    Style {
1062      height: Some(height),
1063      ..self
1064    }
1065  }
1066
1067  /// Sets the least width in logical pixels.
1068  pub const fn min_width(self, width: f32) -> Style {
1069    Style {
1070      min_width: Some(width),
1071      ..self
1072    }
1073  }
1074
1075  /// Sets the least height in logical pixels.
1076  pub const fn min_height(self, height: f32) -> Style {
1077    Style {
1078      min_height: Some(height),
1079      ..self
1080    }
1081  }
1082
1083  /// Sets the most width in logical pixels.
1084  pub const fn max_width(self, width: f32) -> Style {
1085    Style {
1086      max_width: Some(width),
1087      ..self
1088    }
1089  }
1090
1091  /// Sets the most height in logical pixels.
1092  pub const fn max_height(self, height: f32) -> Style {
1093    Style {
1094      max_height: Some(height),
1095      ..self
1096    }
1097  }
1098
1099  /// Sets how much of a row's or column's free space the widget takes,
1100  /// against its siblings': two children with a grow of 1 and 3 take a
1101  /// quarter and three quarters. A [`Spacer`](crate::Spacer) grows by 1.
1102  ///
1103  /// ```
1104  /// use crabshell_ui::Style;
1105  ///
1106  /// const FILL: Style = Style::new().grow(1.0).basis(0.0);
1107  /// ```
1108  pub const fn grow(self, grow: f32) -> Style {
1109    Style {
1110      grow: Some(grow),
1111      ..self
1112    }
1113  }
1114
1115  /// Sets how much the widget gives up, against its siblings', when its
1116  /// row or column is too small for them all. 0 keeps its size.
1117  pub const fn shrink(self, shrink: f32) -> Style {
1118    Style {
1119      shrink: Some(shrink),
1120      ..self
1121    }
1122  }
1123
1124  /// Sets the widget's size along its row or column, in logical pixels,
1125  /// before it grows or shrinks.
1126  pub const fn basis(self, basis: f32) -> Style {
1127    Style {
1128      basis: Some(basis),
1129      ..self
1130    }
1131  }
1132
1133  /// Sets how the widget is placed across its row's or column's
1134  /// direction, or vertically in a stack's or grid's cell, instead of
1135  /// the parent's `align`.
1136  pub const fn align_self(self, align: Align) -> Style {
1137    Style {
1138      align_self: Some(align),
1139      ..self
1140    }
1141  }
1142
1143  /// Sets how the widget is placed horizontally in a stack's or grid's
1144  /// cell. Rows and columns ignore it.
1145  pub const fn justify_self(self, justify: Align) -> Style {
1146    Style {
1147      justify_self: Some(justify),
1148      ..self
1149    }
1150  }
1151
1152  /// Places the widget `left` logical pixels from its parent's left edge,
1153  /// inside the border, out of the parent's flow.
1154  ///
1155  /// ```
1156  /// use crabshell_ui::Style;
1157  ///
1158  /// // A badge in a stack's top-right corner.
1159  /// const BADGE: Style = Style::new().top(2.0).right(2.0);
1160  /// ```
1161  pub const fn left(self, left: f32) -> Style {
1162    Style {
1163      left: Some(left),
1164      ..self
1165    }
1166  }
1167
1168  /// Places the widget `top` logical pixels from its parent's top edge,
1169  /// as [`left`](Self::left) does.
1170  pub const fn top(self, top: f32) -> Style {
1171    Style {
1172      top: Some(top),
1173      ..self
1174    }
1175  }
1176
1177  /// Places the widget `right` logical pixels from its parent's right
1178  /// edge, as [`left`](Self::left) does.
1179  pub const fn right(self, right: f32) -> Style {
1180    Style {
1181      right: Some(right),
1182      ..self
1183    }
1184  }
1185
1186  /// Places the widget `bottom` logical pixels from its parent's bottom
1187  /// edge, as [`left`](Self::left) does.
1188  pub const fn bottom(self, bottom: f32) -> Style {
1189    Style {
1190      bottom: Some(bottom),
1191      ..self
1192    }
1193  }
1194
1195  /// Sets the order the widget is drawn and hit in among its siblings,
1196  /// lowest first. Equal ones keep their order.
1197  pub const fn z(self, z: i32) -> Style {
1198    Style { z: Some(z), ..self }
1199  }
1200
1201  /// Makes the widget take `columns` columns and `rows` rows of its
1202  /// [`Grid`](crate::Grid). 0 counts as 1.
1203  pub const fn span(self, columns: u32, rows: u32) -> Style {
1204    Style {
1205      span: Some((columns, rows)),
1206      ..self
1207    }
1208  }
1209
1210  /// Moves the widget and everything inside it `x` logical pixels right
1211  /// and `y` down where it is drawn, after it is scaled and turned. The
1212  /// layout doesn't move.
1213  ///
1214  /// ```
1215  /// use crabshell_ui::Style;
1216  ///
1217  /// const HIDDEN: Style = Style::new().translate(0.0, -40.0);
1218  /// ```
1219  pub const fn translate(self, x: f32, y: f32) -> Style {
1220    Style {
1221      translate: Some(Point::new(x, y)),
1222      ..self
1223    }
1224  }
1225
1226  /// Draws the widget and everything inside it `scale` times its size,
1227  /// around its [`origin`](Self::origin), without changing the layout.
1228  /// 0 draws nothing and is never under the pointer; a negative scale
1229  /// also turns it upside down. A number that isn't finite is ignored.
1230  pub const fn scale(self, scale: f32) -> Style {
1231    Style {
1232      scale: Some(scale),
1233      ..self
1234    }
1235  }
1236
1237  /// Turns the widget and everything inside it `degrees` clockwise,
1238  /// around its [`origin`](Self::origin), without changing the layout. A
1239  /// number that isn't finite is ignored.
1240  pub const fn rotate(self, degrees: f32) -> Style {
1241    Style {
1242      rotate: Some(degrees),
1243      ..self
1244    }
1245  }
1246
1247  /// Sets the point the widget is scaled and turned around, as fractions
1248  /// of its box: `(0.0, 0.0)` is the top-left corner, `(1.0, 1.0)` the
1249  /// bottom-right. The default is the middle, `(0.5, 0.5)`.
1250  pub const fn origin(self, x: f32, y: f32) -> Style {
1251    Style {
1252      origin: Some(Point::new(x, y)),
1253      ..self
1254    }
1255  }
1256
1257  /// Sets how a change to the paint fields fades in, as when a hover
1258  /// style takes over: background, gradient, shadow, color, border,
1259  /// radius, opacity, translate, scale, rotate and origin move over
1260  /// `transition`. The style being changed to says how.
1261  pub const fn transition(self, transition: Transition) -> Style {
1262    Style {
1263      transition: Some(transition),
1264      ..self
1265    }
1266  }
1267
1268  /// This style with every field that `over` sets replaced by its value.
1269  /// Buttons use it to lay their hover and pressed styles over the normal
1270  /// one.
1271  pub const fn merge(self, over: Style) -> Style {
1272    Style {
1273      background: or(over.background, self.background),
1274      gradient: or(over.gradient, self.gradient),
1275      shadow: or(over.shadow, self.shadow),
1276      color: or(over.color, self.color),
1277      font: or(over.font, self.font),
1278      padding: or(over.padding, self.padding),
1279      radius: or(over.radius, self.radius),
1280      border: or(over.border, self.border),
1281      border_dash: or(over.border_dash, self.border_dash),
1282      opacity: or(over.opacity, self.opacity),
1283      mask: or(over.mask, self.mask),
1284      clip: or(over.clip, self.clip),
1285      width: or(over.width, self.width),
1286      height: or(over.height, self.height),
1287      min_width: or(over.min_width, self.min_width),
1288      min_height: or(over.min_height, self.min_height),
1289      max_width: or(over.max_width, self.max_width),
1290      max_height: or(over.max_height, self.max_height),
1291      grow: or(over.grow, self.grow),
1292      shrink: or(over.shrink, self.shrink),
1293      basis: or(over.basis, self.basis),
1294      align_self: or(over.align_self, self.align_self),
1295      justify_self: or(over.justify_self, self.justify_self),
1296      left: or(over.left, self.left),
1297      top: or(over.top, self.top),
1298      right: or(over.right, self.right),
1299      bottom: or(over.bottom, self.bottom),
1300      z: or(over.z, self.z),
1301      span: or(over.span, self.span),
1302      translate: or(over.translate, self.translate),
1303      scale: or(over.scale, self.scale),
1304      rotate: or(over.rotate, self.rotate),
1305      origin: or(over.origin, self.origin),
1306      transition: or(over.transition, self.transition),
1307    }
1308  }
1309
1310  /// Whether the children are cut to the widget's box.
1311  pub fn clips(&self) -> bool {
1312    self.clip == Some(true)
1313  }
1314
1315  /// Whether the two styles lay out the same: same font, padding, sizes,
1316  /// flex fields, alignment, position and span, and clipping, which
1317  /// changes how far the children's painting reaches.
1318  pub(crate) fn same_layout(&self, other: &Style) -> bool {
1319    self.font == other.font
1320      && self.padding == other.padding
1321      && self.width == other.width
1322      && self.height == other.height
1323      && self.min_width == other.min_width
1324      && self.min_height == other.min_height
1325      && self.max_width == other.max_width
1326      && self.max_height == other.max_height
1327      && self.grow == other.grow
1328      && self.shrink == other.shrink
1329      && self.basis == other.basis
1330      && self.align_self == other.align_self
1331      && self.justify_self == other.justify_self
1332      && self.left == other.left
1333      && self.top == other.top
1334      && self.right == other.right
1335      && self.bottom == other.bottom
1336      && self.span == other.span
1337      && self.clips() == other.clips()
1338  }
1339
1340  /// Whether any of `left`, `top`, `right` and `bottom` is set to a
1341  /// finite number, which takes the widget out of its parent's flow.
1342  pub(crate) fn absolute(&self) -> bool {
1343    [self.left, self.top, self.right, self.bottom]
1344      .into_iter()
1345      .flatten()
1346      .any(f32::is_finite)
1347  }
1348
1349  /// Whether the two styles move the widget the same way where it is
1350  /// drawn.
1351  pub(crate) fn same_transform(&self, other: &Style) -> bool {
1352    self.translate == other.translate
1353      && self.scale == other.scale
1354      && self.rotate == other.rotate
1355      && self.origin == other.origin
1356  }
1357
1358  /// Where this style moves a widget laid out at `rect`, from its own
1359  /// coordinates into its parent's, or `None` when it doesn't. It is
1360  /// scaled and turned around its origin, then translated. A number that
1361  /// isn't finite counts as unset.
1362  pub(crate) fn transform(&self, rect: Rect) -> Option<Affine> {
1363    let finite = |value: f32, default: f32| if value.is_finite() { value } else { default };
1364    let translate = self.translate.unwrap_or_default();
1365    let (x, y) = (finite(translate.x, 0.0), finite(translate.y, 0.0));
1366    let scale = finite(self.scale.unwrap_or(1.0), 1.0);
1367    let degrees = finite(self.rotate.unwrap_or(0.0), 0.0).rem_euclid(360.0);
1368    if x == 0.0 && y == 0.0 && scale == 1.0 && degrees == 0.0 {
1369      return None;
1370    }
1371    // Quarter turns are exact, so a chevron turned over stays crisp.
1372    let (sin, cos) = match degrees {
1373      90.0 => (1.0, 0.0),
1374      180.0 => (0.0, -1.0),
1375      270.0 => (-1.0, 0.0),
1376      _ => degrees.to_radians().sin_cos(),
1377    };
1378    let origin = self.origin.unwrap_or(Point::new(0.5, 0.5));
1379    let ox = rect.x + finite(origin.x, 0.5) * rect.width;
1380    let oy = rect.y + finite(origin.y, 0.5) * rect.height;
1381    // A point p goes to origin + turn(scale(p - origin)) + translate.
1382    let (sx, ky, kx, sy) = (cos * scale, sin * scale, -sin * scale, cos * scale);
1383    // One too large for f32 maps every area to an empty one, so it is
1384    // drawn nowhere and never hit.
1385    Some(Affine {
1386      sx,
1387      ky,
1388      kx,
1389      sy,
1390      tx: ox + x - (sx * ox + kx * oy),
1391      ty: oy + y - (ky * ox + sy * oy),
1392    })
1393  }
1394}
1395
1396/// `Option::or`, which isn't a `const fn` on stable Rust.
1397const fn or<T: Copy>(first: Option<T>, second: Option<T>) -> Option<T> {
1398  match first {
1399    Some(value) => Some(value),
1400    None => second,
1401  }
1402}
1403
1404impl Style {
1405  /// The paint fields `t` of the way from `self` to `to`; every other
1406  /// field is `to`'s. A field only one side sets fades from or to nothing:
1407  /// a color from or to its transparent self, a border from or to 0 wide.
1408  /// A text color only one sets changes at once, as the other comes
1409  /// from an ancestor. Gradients of different shapes or numbers of colors
1410  /// change at once. An unset translate is 0, scale 1, rotate 0 and
1411  /// origin the middle.
1412  pub(crate) fn lerp(&self, to: &Style, t: f32) -> Style {
1413    let color = |from: Option<Color>, to: Option<Color>| match (from, to) {
1414      (Some(from), Some(to)) => Some(from.lerp(&to, t)),
1415      (None, Some(to)) => Some(Color::rgba(to.r, to.g, to.b, 0).lerp(&to, t)),
1416      (Some(from), None) => Some(from.lerp(&Color::rgba(from.r, from.g, from.b, 0), t)),
1417      (None, None) => None,
1418    };
1419    let border = match (self.border, to.border) {
1420      (None, None) => None,
1421      (from, to) => {
1422        let from = from.or(to.map(|b| Border {
1423          width: 0.0,
1424          color: Color::rgba(b.color.r, b.color.g, b.color.b, 0),
1425        }));
1426        let to = to.or(from.map(|b| Border {
1427          width: 0.0,
1428          color: Color::rgba(b.color.r, b.color.g, b.color.b, 0),
1429        }));
1430        match (from, to) {
1431          (Some(from), Some(to)) => Some(Border {
1432            width: from.width.lerp(&to.width, t),
1433            color: from.color.lerp(&to.color, t),
1434          }),
1435
1436          _ => None,
1437        }
1438      }
1439    };
1440    let number = |from: Option<f32>, to: Option<f32>, none: f32| match (from, to) {
1441      (None, None) => None,
1442      (from, to) => Some(from.unwrap_or(none).lerp(&to.unwrap_or(none), t)),
1443    };
1444    let point = |from: Option<Point>, to: Option<Point>, none: Point| match (from, to) {
1445      (None, None) => None,
1446      (from, to) => Some(from.unwrap_or(none).lerp(&to.unwrap_or(none), t)),
1447    };
1448    let gradient = match (self.gradient, to.gradient) {
1449      (Some(from), Some(end)) => from.lerp(&end, t).or(to.gradient),
1450      (None, Some(end)) => end.clear().lerp(&end, t),
1451      (Some(from), None) => from.lerp(&from.clear(), t),
1452      (None, None) => None,
1453    };
1454    let shadow = match (self.shadow, to.shadow) {
1455      (Some(from), Some(end)) => Some(from.lerp(&end, t)),
1456      (None, Some(end)) => Some(end.clear().lerp(&end, t)),
1457      (Some(from), None) => Some(from.lerp(&from.clear(), t)),
1458      (None, None) => None,
1459    };
1460    Style {
1461      background: color(self.background, to.background),
1462      gradient,
1463      shadow,
1464      color: match (self.color, to.color) {
1465        (Some(from), Some(to)) => Some(from.lerp(&to, t)),
1466        _ => to.color,
1467      },
1468      border,
1469      radius: match (self.radius, to.radius) {
1470        (None, None) => None,
1471        (from, to) => Some(from.unwrap_or_default().lerp(&to.unwrap_or_default(), t)),
1472      },
1473      opacity: number(self.opacity, to.opacity, 1.0),
1474      translate: point(self.translate, to.translate, Point::default()),
1475      scale: number(self.scale, to.scale, 1.0),
1476      rotate: number(self.rotate, to.rotate, 0.0),
1477      origin: point(self.origin, to.origin, Point::new(0.5, 0.5)),
1478      ..*to
1479    }
1480  }
1481}