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, weight, slant, letter spacing and OpenType
193/// features.
194///
195/// The family is resolved through fontconfig, so generic names such as
196/// `"sans-serif"` and `"monospace"` work too.
197///
198/// ```
199/// use crabshell_ui::{Font, FontFeature};
200///
201/// const CLOCK: Font = Font::new("sans-serif", 13.0).features(&[FontFeature::TABULAR_NUMBERS]);
202/// const NOTE: Font = Font::new("sans-serif", 11.0).italic().letter_spacing(0.5);
203/// ```
204#[derive(Clone, Copy, Debug, PartialEq)]
205pub struct Font {
206  /// The family name, such as `"Inter"` or `"sans-serif"`.
207  pub family: &'static str,
208  /// The size in logical pixels.
209  pub size: f32,
210  /// The weight, from 100 (thin) through 400 (regular) and 700 (bold) to
211  /// 900 (black).
212  pub weight: u16,
213  /// Whether the italic face is asked for.
214  pub italic: bool,
215  /// Extra logical pixels after each glyph, at least minus half the
216  /// size; a number that isn't finite counts as 0.
217  pub letter_spacing: f32,
218  /// OpenType features turned on or off, in order.
219  pub features: &'static [FontFeature],
220}
221
222impl Font {
223  /// The font text uses when no ancestor sets one.
224  pub const DEFAULT: Font = Font::new("sans-serif", 13.0);
225
226  /// A regular-weight font of `family` at `size` logical pixels.
227  pub const fn new(family: &'static str, size: f32) -> Font {
228    Font {
229      family,
230      size,
231      weight: 400,
232      italic: false,
233      letter_spacing: 0.0,
234      features: &[],
235    }
236  }
237
238  /// The same font with another weight, such as 700 for bold.
239  pub const fn weight(self, weight: u16) -> Font {
240    Font { weight, ..self }
241  }
242
243  /// The same font in italic. A family without an italic face gets the
244  /// face fontconfig picks, slanted by the renderer if it is upright.
245  pub const fn italic(self) -> Font {
246    Font {
247      italic: true,
248      ..self
249    }
250  }
251
252  /// The same font with `px` extra logical pixels after each glyph, or
253  /// less with a negative number, down to minus half the font size.
254  pub const fn letter_spacing(self, px: f32) -> Font {
255    Font {
256      letter_spacing: px,
257      ..self
258    }
259  }
260
261  /// The same font with these OpenType features, such as
262  /// [`FontFeature::TABULAR_NUMBERS`] for digits of one width.
263  pub const fn features(self, features: &'static [FontFeature]) -> Font {
264    Font { features, ..self }
265  }
266}
267
268/// An OpenType feature: a four-letter tag and its value, 0 for off and
269/// 1 for on, or which alternate for features that have several.
270#[derive(Clone, Copy, Debug, PartialEq, Eq)]
271pub struct FontFeature {
272  /// The tag, such as `*b"tnum"`.
273  pub tag: [u8; 4],
274  /// The value.
275  pub value: u32,
276}
277
278impl FontFeature {
279  /// Digits of one width, so a clock's width holds still (`tnum`).
280  pub const TABULAR_NUMBERS: FontFeature = FontFeature::new(*b"tnum", 1);
281  /// No standard ligatures such as "fi" (`liga` off).
282  pub const NO_LIGATURES: FontFeature = FontFeature::new(*b"liga", 0);
283  /// Lowercase letters as small capitals (`smcp`).
284  pub const SMALL_CAPS: FontFeature = FontFeature::new(*b"smcp", 1);
285  /// A zero with a slash or dot (`zero`).
286  pub const SLASHED_ZERO: FontFeature = FontFeature::new(*b"zero", 1);
287
288  /// The feature `tag` set to `value`.
289  pub const fn new(tag: [u8; 4], value: u32) -> FontFeature {
290    FontFeature { tag, value }
291  }
292}
293
294/// Where each line of text sits in the text's content box. Text one line
295/// long and sized to itself looks the same whichever is set.
296#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
297pub enum TextAlign {
298  /// At the start: the left for left-to-right text. The default.
299  #[default]
300  Start,
301  /// In the middle.
302  Center,
303  /// At the end: the right for left-to-right text.
304  End,
305  /// Stretched to both edges by widening the spaces, except a
306  /// paragraph's last line, which sits at the start.
307  Justify,
308}
309
310/// A border drawn inside a widget's edge. It takes no layout space.
311#[derive(Clone, Copy, Debug, PartialEq)]
312pub struct Border {
313  /// The width in logical pixels.
314  pub width: f32,
315  /// The color.
316  pub color: Color,
317}
318
319/// How round each corner of a widget's box is: the radius in logical
320/// pixels, 0 for a square corner. When two corners on a side need more
321/// than its length, all four shrink by the same factor until they fit,
322/// as in CSS, so two on one side never overlap.
323#[derive(Clone, Copy, Debug, Default, PartialEq)]
324pub struct Radii {
325  /// The top-left corner.
326  pub top_left: f32,
327  /// The top-right corner.
328  pub top_right: f32,
329  /// The bottom-right corner.
330  pub bottom_right: f32,
331  /// The bottom-left corner.
332  pub bottom_left: f32,
333}
334
335impl Radii {
336  /// Every corner `radius` round.
337  pub const fn all(radius: f32) -> Radii {
338    Radii {
339      top_left: radius,
340      top_right: radius,
341      bottom_right: radius,
342      bottom_left: radius,
343    }
344  }
345
346  /// The four, from the top left clockwise.
347  pub const fn corners(&self) -> [f32; 4] {
348    [
349      self.top_left,
350      self.top_right,
351      self.bottom_right,
352      self.bottom_left,
353    ]
354  }
355
356  /// These corners on a `width` by `height` box, as CSS fits them: a
357  /// number that isn't one, or a negative one, is 0, and when two corners
358  /// on a side add up to more than its length, all four are multiplied
359  /// by the one factor that makes the tightest side fit. Drawing and
360  /// pointer input both use it, so they agree.
361  pub fn fit(&self, width: f32, height: f32) -> Radii {
362    let [top_left, top_right, bottom_right, bottom_left] =
363      fit_corners(self.corners(), width, height);
364    Radii {
365      top_left,
366      top_right,
367      bottom_right,
368      bottom_left,
369    }
370  }
371
372  /// `t` of the way to `to`, each corner on its own.
373  pub(crate) fn lerp(&self, to: &Radii, t: f32) -> Radii {
374    Radii {
375      top_left: self.top_left.lerp(&to.top_left, t),
376      top_right: self.top_right.lerp(&to.top_right, t),
377      bottom_right: self.bottom_right.lerp(&to.bottom_right, t),
378      bottom_left: self.bottom_left.lerp(&to.bottom_left, t),
379    }
380  }
381
382  /// Whether `point` is inside `rect` with these corners, [fitted](Self::fit)
383  /// to it, after `inset` is taken off every side and every corner.
384  pub(crate) fn contains(&self, rect: Rect, inset: f32, point: Point) -> bool {
385    let inner = Rect::new(
386      rect.x + inset,
387      rect.y + inset,
388      rect.width - 2.0 * inset,
389      rect.height - 2.0 * inset,
390    );
391    if !inner.contains(point) {
392      return false;
393    }
394    let [top_left, top_right, bottom_right, bottom_left] = self
395      .fit(rect.width, rect.height)
396      .corners()
397      .map(|r| (r - inset).max(0.0));
398    let (left, top, right, bottom) = (inner.x, inner.y, inner.right(), inner.bottom());
399    // Each corner's circle, and the side of its middle the corner is on.
400    [
401      (top_left, left + top_left, top + top_left, -1.0, -1.0),
402      (top_right, right - top_right, top + top_right, 1.0, -1.0),
403      (
404        bottom_right,
405        right - bottom_right,
406        bottom - bottom_right,
407        1.0,
408        1.0,
409      ),
410      (
411        bottom_left,
412        left + bottom_left,
413        bottom - bottom_left,
414        -1.0,
415        1.0,
416      ),
417    ]
418    .into_iter()
419    .all(|(r, cx, cy, sx, sy)| {
420      let (dx, dy) = (point.x - cx, point.y - cy);
421      r <= 0.0 || dx * sx <= 0.0 || dy * sy <= 0.0 || dx.hypot(dy) <= r
422    })
423  }
424}
425
426/// `corners`, from the top left clockwise, fitted to a `width` by
427/// `height` box as [`Radii::fit`] says.
428pub(crate) fn fit_corners(corners: [f32; 4], width: f32, height: f32) -> [f32; 4] {
429  // A radius past this is a pill's either way, and two of them still add
430  // up to a finite number.
431  const MOST: f32 = 1e6;
432  let corners = corners.map(|r| if r.is_nan() { 0.0 } else { r.clamp(0.0, MOST) });
433  let [top_left, top_right, bottom_right, bottom_left] = corners;
434  let sides = [
435    (width, top_left + top_right),
436    (height, top_right + bottom_right),
437    (width, bottom_right + bottom_left),
438    (height, bottom_left + top_left),
439  ];
440  let factor = sides
441    .into_iter()
442    .filter(|&(_, radii)| radii > 0.0)
443    // `max` makes a side that isn't a number 0, leaving no corners.
444    .fold(1.0_f32, |factor, (side, radii)| {
445      factor.min(side.max(0.0) / radii)
446    });
447  corners.map(|r| r * factor)
448}
449
450/// Colors that blend into each other across a widget's box, drawn over
451/// its background with the same corners.
452///
453/// ```
454/// use crabshell_ui::{Color, Gradient, Style};
455///
456/// const DUSK: Style = Style::new().gradient(
457///     Gradient::linear(90.0, Color::hex("#1e1e2e"), Color::hex("#45475a"))
458///         .stop(0.5, Color::hex("#313244")),
459/// );
460/// ```
461#[derive(Clone, Copy, Debug, PartialEq)]
462pub struct Gradient {
463  /// Which way the colors run.
464  pub shape: GradientShape,
465  /// The first `count` hold each color and where it sits, from 0 at the
466  /// start to 1 at the end.
467  stops: [(f32, Color); 4],
468  count: u8,
469}
470
471/// Which way a [`Gradient`]'s colors run.
472#[derive(Clone, Copy, Debug, PartialEq)]
473pub enum GradientShape {
474  /// Along a line through the middle at this many degrees, as in CSS: 0
475  /// runs from the bottom up, 90 from left to right, 180 from the top
476  /// down. Its ends meet the corners.
477  Linear(f32),
478  /// In circles out from the middle to the farthest corner.
479  Radial,
480  /// Around the middle, clockwise from this many degrees, as CSS's
481  /// `conic-gradient(from …)`: 0 starts at 12 o'clock, 90 at 3.
482  Sweep(f32),
483}
484
485impl Gradient {
486  /// A gradient from `from` to `to` along a line at `angle` degrees: 0
487  /// runs from the bottom up, 90 from left to right.
488  pub const fn linear(angle: f32, from: Color, to: Color) -> Gradient {
489    Gradient::new(GradientShape::Linear(angle), from, to)
490  }
491
492  /// A gradient from `from` in the middle to `to` at the farthest corner.
493  pub const fn radial(from: Color, to: Color) -> Gradient {
494    Gradient::new(GradientShape::Radial, from, to)
495  }
496
497  /// A gradient from `from` to `to` once around the middle, clockwise
498  /// from `angle` degrees: 0 starts at 12 o'clock, 90 at 3, as CSS's
499  /// `conic-gradient(from 90deg, …)`. The end meets the start there.
500  ///
501  /// ```
502  /// use crabshell_ui::{Color, Gradient, Style};
503  ///
504  /// const RING: Style = Style::new().radius(20.0).gradient(
505  ///     Gradient::sweep(0.0, Color::hex("#89b4fa"), Color::hex("#89b4fa"))
506  ///         .stop(0.5, Color::hex("#f5c2e7")),
507  /// );
508  /// ```
509  pub const fn sweep(angle: f32, from: Color, to: Color) -> Gradient {
510    Gradient::new(GradientShape::Sweep(angle), from, to)
511  }
512
513  const fn new(shape: GradientShape, from: Color, to: Color) -> Gradient {
514    Gradient {
515      shape,
516      stops: [(0.0, from), (1.0, to), (1.0, to), (1.0, to)],
517      count: 2,
518    }
519  }
520
521  /// Adds `color` at `at`, from 0 to 1, before the end color. Add them
522  /// in order. A gradient has at most four colors, so a third stop
523  /// panics.
524  pub const fn stop(self, at: f32, color: Color) -> Gradient {
525    assert!(self.count < 4, "a gradient has at most four colors");
526    let mut stops = self.stops;
527    let last = self.count as usize - 1;
528    stops[last + 1] = stops[last];
529    stops[last] = (at, color);
530    Gradient {
531      stops,
532      count: self.count + 1,
533      ..self
534    }
535  }
536
537  /// Each color and where it sits, from the start to the end.
538  pub fn stops(&self) -> &[(f32, Color)] {
539    &self.stops[..usize::from(self.count)]
540  }
541
542  /// `t` of the way from this gradient to `to`, or `None` when their
543  /// shapes or numbers of colors differ.
544  fn lerp(&self, to: &Gradient, t: f32) -> Option<Gradient> {
545    let shape = match (self.shape, to.shape) {
546      (GradientShape::Linear(from), GradientShape::Linear(to)) => {
547        GradientShape::Linear(from.lerp(&to, t))
548      }
549      (GradientShape::Radial, GradientShape::Radial) => GradientShape::Radial,
550      (GradientShape::Sweep(from), GradientShape::Sweep(to)) => {
551        GradientShape::Sweep(from.lerp(&to, t))
552      }
553
554      _ => return None,
555    };
556    if self.count != to.count {
557      return None;
558    }
559    let mut stops = to.stops;
560    for (stop, (from, to)) in stops.iter_mut().zip(self.stops.iter().zip(to.stops)) {
561      *stop = (from.0.lerp(&to.0, t), from.1.lerp(&to.1, t));
562    }
563    Some(Gradient {
564      shape,
565      stops,
566      count: to.count,
567    })
568  }
569
570  /// This gradient with every color transparent.
571  fn clear(mut self) -> Gradient {
572    for (_, color) in &mut self.stops {
573      color.a = 0;
574    }
575    self
576  }
577}
578
579/// A shadow cast by a widget's box, as CSS's `box-shadow`: the box's
580/// shape moved by `x` and `y`, grown by `spread` and blurred over `blur`
581/// logical pixels. Unlike CSS's, it is drawn under the box too, so a
582/// translucent background shows it through, unless it is
583/// [`cut_out`](Shadow::cut_out). An [`inset`](Shadow::inset) one is drawn
584/// inside the box instead. A style has one shadow; a second comes from a
585/// box wrapped around the widget.
586///
587/// ```
588/// use crabshell_ui::{Color, Shadow, Style};
589///
590/// const CARD: Style = Style::new()
591///     .background(Color::hex("#1e1e2e"))
592///     .radius(8.0)
593///     .shadow(Shadow::new(0.0, 4.0, 12.0, Color::rgba(0, 0, 0, 96)));
594/// ```
595#[derive(Clone, Copy, Debug, PartialEq)]
596pub struct Shadow {
597  /// How far right it is moved.
598  pub x: f32,
599  /// How far down it is moved.
600  pub y: f32,
601  /// How far its edge is blurred. 0 is a sharp edge.
602  pub blur: f32,
603  /// How much larger than the box it is on each side, or smaller when
604  /// negative.
605  pub spread: f32,
606  /// Its color.
607  pub color: Color,
608  /// Whether it is left out under the box, as under translucent glass.
609  pub cut_out: bool,
610  /// Whether it is cast by what the widget and its children draw,
611  /// through their alpha, instead of by its box.
612  pub follow_content: bool,
613  /// Whether it is drawn inside the box, around a hole of the box's
614  /// shape, instead of outside it.
615  pub inset: bool,
616}
617
618impl Shadow {
619  /// A shadow moved by `x` and `y` and blurred over `blur`, the box's
620  /// size.
621  pub const fn new(x: f32, y: f32, blur: f32, color: Color) -> Shadow {
622    Shadow {
623      x,
624      y,
625      blur,
626      spread: 0.0,
627      color,
628      cut_out: false,
629      follow_content: false,
630      inset: false,
631    }
632  }
633
634  /// The same shadow `spread` larger on each side.
635  pub const fn spread(self, spread: f32) -> Shadow {
636    Shadow { spread, ..self }
637  }
638
639  /// The same shadow left out under the box's own shape, so a translucent
640  /// background, such as glass the compositor blurs, shows what is
641  /// behind it instead of the shadow. CSS's `box-shadow` is always drawn
642  /// this way.
643  pub const fn cut_out(self) -> Shadow {
644    Shadow {
645      cut_out: true,
646      ..self
647    }
648  }
649
650  /// The same shadow cast by what the widget and everything inside it
651  /// draw, through their alpha, instead of by its box, so text and icons
652  /// get a drop shadow, as Qt's `MultiEffect` shadow gives. It is drawn
653  /// under them, offset, spread and blurred as a box shadow is, and
654  /// after a [`mask`](Style::mask), so it follows the masked shape. Cut
655  /// out, it is left out under the content's own alpha.
656  ///
657  /// ```
658  /// use crabshell_ui::{Color, Shadow, Style};
659  ///
660  /// const LABEL: Style = Style::new()
661  ///     .color(Color::hex("#cdd6f4"))
662  ///     .shadow(Shadow::new(0.0, 1.0, 3.0, Color::rgba(0, 0, 0, 160)).follow_content());
663  /// ```
664  pub const fn follow_content(self) -> Shadow {
665    Shadow {
666      follow_content: true,
667      ..self
668    }
669  }
670
671  /// The same shadow drawn inside the box, as CSS's `box-shadow: inset`:
672  /// over the background and under the border and content, everywhere
673  /// inside the border but a hole of the box's shape, moved by `x` and
674  /// `y`, shrunk by `spread` and blurred, so a pressed button or a well
675  /// looks sunk in. It never reaches past the box, and it is always cast
676  /// by the box, so [`follow_content`](Shadow::follow_content) and
677  /// [`cut_out`](Shadow::cut_out) do nothing to it.
678  ///
679  /// ```
680  /// use crabshell_ui::{Color, Shadow, Style};
681  ///
682  /// const PRESSED: Style = Style::new()
683  ///     .background(Color::hex("#313244"))
684  ///     .radius(6.0)
685  ///     .shadow(Shadow::new(0.0, 2.0, 6.0, Color::rgba(0, 0, 0, 128)).inset());
686  /// ```
687  pub const fn inset(self) -> Shadow {
688    Shadow {
689      inset: true,
690      ..self
691    }
692  }
693
694  /// Whether this shadow is cast by the content and can be: its numbers
695  /// are finite and it reaches at most 64 logical pixels past what casts
696  /// it, the size of its spread plus one and a half blurs. One reaching
697  /// farther is left out whole and the content drawn without it, so the
698  /// work of casting it stays bounded.
699  pub fn casts_from_content(&self) -> bool {
700    let reach = self.spread.abs() + 1.5 * self.blur.max(0.0);
701    self.follow_content
702      && !self.inset
703      && [self.x, self.y, reach].iter().all(|n| n.is_finite())
704      && reach <= 64.0
705  }
706
707  /// The area this shadow of `rect` covers: its shape, grown by one and a
708  /// half blurs, past which the blur fades below a 255th. A spread that
709  /// swallows the box still reaches between the edges it would have, so
710  /// a fade from it stays within its start and end. A shadow with a
711  /// number that isn't finite is never drawn, and an inset one stays
712  /// inside, so each reaches only `rect`.
713  pub(crate) fn reach(&self, rect: Rect) -> Rect {
714    let grow = self.spread + 1.5 * self.blur.max(0.0);
715    if self.inset || ![self.x, self.y, grow].iter().all(|n| n.is_finite()) {
716      return rect;
717    }
718    let (left, right) = (rect.x + self.x - grow, rect.right() + self.x + grow);
719    let (top, bottom) = (rect.y + self.y - grow, rect.bottom() + self.y + grow);
720    Rect::new(
721      left.min(right),
722      top.min(bottom),
723      (right - left).abs(),
724      (bottom - top).abs(),
725    )
726  }
727
728  /// `t` of the way to `to`.
729  fn lerp(&self, to: &Shadow, t: f32) -> Shadow {
730    Shadow {
731      x: self.x.lerp(&to.x, t),
732      y: self.y.lerp(&to.y, t),
733      blur: self.blur.lerp(&to.blur, t),
734      spread: self.spread.lerp(&to.spread, t),
735      color: self.color.lerp(&to.color, t),
736      // Not numbers: they change at once.
737      cut_out: to.cut_out,
738      follow_content: to.follow_content,
739      inset: to.inset,
740    }
741  }
742
743  /// This shadow, transparent.
744  fn clear(self) -> Shadow {
745    Shadow {
746      color: Color::rgba(self.color.r, self.color.g, self.color.b, 0),
747      ..self
748    }
749  }
750}
751
752/// Where a widget and everything inside it show, as Qt's `OpacityMask`:
753/// what they draw is kept only where the mask is opaque, its alpha
754/// multiplying theirs, and nothing shows outside the widget's box. Set it
755/// with [`Style::mask`].
756///
757/// ```
758/// use crabshell_ui::{Color, Gradient, Mask, Style};
759///
760/// const AVATAR: Style = Style::new().mask(Mask::ellipse());
761/// // A list that fades out over its last fifth.
762/// const FADING: Style = Style::new().mask(Mask::gradient(
763///     Gradient::linear(180.0, Color::rgb(0, 0, 0), Color::rgba(0, 0, 0, 0))
764///         .stop(0.8, Color::rgb(0, 0, 0)),
765/// ));
766/// const STAR: Style = Style::new().mask(Mask::image("/usr/share/my-shell/star.png"));
767/// ```
768#[derive(Clone, Copy, Debug, PartialEq)]
769pub enum Mask {
770  /// An ellipse filling the box.
771  Ellipse,
772  /// A gradient's alpha, laid over the box as a background's is.
773  Gradient(Gradient),
774  /// A file's alpha, stretched over the box. It is read through the
775  /// [`Image`](crate::Image) loaders and their caps; one that is missing
776  /// or refused is logged once and the widget is drawn unmasked.
777  Image(&'static str),
778}
779
780impl Mask {
781  /// An ellipse filling the box, for round avatars and album art.
782  pub const fn ellipse() -> Mask {
783    Mask::Ellipse
784  }
785
786  /// `gradient`'s alpha laid over the box, for lists and strips that fade
787  /// out at an edge. Only the colors' alpha counts.
788  pub const fn gradient(gradient: Gradient) -> Mask {
789    Mask::Gradient(gradient)
790  }
791
792  /// The alpha of the image file at `path`, stretched over the box.
793  ///
794  /// The path is `&'static str`, so a style holding it can be a `const`.
795  /// For a path made at run time, leak it once, outside any closure: a
796  /// `String::leak` inside a `move || Style` binding leaks again each
797  /// time the binding runs.
798  ///
799  /// ```
800  /// use crabshell_ui::{Mask, Stack, Style};
801  ///
802  /// let home = std::env::var("HOME").unwrap_or_default();
803  /// // Once, here, not in the closure below.
804  /// let face: &'static str = format!("{home}/.face").leak();
805  /// let avatar = Stack::new().style(move || Style::new().mask(Mask::image(face)));
806  /// ```
807  pub const fn image(path: &'static str) -> Mask {
808    Mask::Image(path)
809  }
810}
811
812/// Space between a widget's edge and its content, in logical pixels, on
813/// each side.
814#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
815pub struct Padding {
816  /// Above the content.
817  pub top: u32,
818  /// Right of the content.
819  pub right: u32,
820  /// Below the content.
821  pub bottom: u32,
822  /// Left of the content.
823  pub left: u32,
824}
825
826/// How a widget looks. Every field is optional, and an unset field falls back
827/// to the widget's default: no background, black text in
828/// [`Font::DEFAULT`], no padding, square corners, no border, fully opaque.
829///
830/// [`Text`](crate::Text), [`TextInput`](crate::TextInput) and
831/// [`TextArea`](crate::TextArea) take `color`, `font`, `text_align`,
832/// `line_height`, `underline` and `strikethrough` from the nearest widget
833/// that sets each, starting with itself and going up. Nothing else
834/// inherits.
835///
836/// `font`, `text_align`, `line_height`, `padding`, `clip`, the sizes, the
837/// flex fields, the alignment, the absolute position and `span` change the
838/// layout, at once; the other fields only change how the widget is
839/// painted. A number that isn't finite counts as unset.
840///
841/// `translate`, `scale`, `rotate` and `origin` move the widget and
842/// everything inside it where it is drawn and where the pointer finds it,
843/// without moving anything else: the layout, and popups anchored to the
844/// widget, keep its box where it was laid out.
845///
846/// ```
847/// use crabshell_ui::{Color, Font, Style};
848///
849/// const BAR: Style = Style::new()
850///     .background(Color::rgb(0x1e, 0x1e, 0x2e))
851///     .color(Color::hex("#cdd6f4"))
852///     .font(Font::new("Inter", 13.0));
853/// const WS: Style = Style::new().padding(2, 8).radius(4.0);
854/// const WS_FOCUSED: Style = WS.background(Color::rgb(0x45, 0x47, 0x5a));
855/// ```
856#[derive(Clone, Copy, Debug, Default, PartialEq)]
857pub struct Style {
858  /// Fills the widget's rectangle.
859  pub background: Option<Color>,
860  /// Colors blending across the widget's rectangle, over the background.
861  pub gradient: Option<Gradient>,
862  /// A shadow under the widget's box.
863  pub shadow: Option<Shadow>,
864  /// The text color, inherited by text and text fields.
865  pub color: Option<Color>,
866  /// The text font, inherited by text and text fields.
867  pub font: Option<Font>,
868  /// Where text lines sit in their box, inherited by text and text
869  /// fields.
870  pub text_align: Option<TextAlign>,
871  /// The height of a line of text, as a multiple of the font size,
872  /// inherited by text and text fields. 1.2 by default.
873  pub line_height: Option<f32>,
874  /// Whether text is underlined, inherited by text and text fields.
875  pub underline: Option<bool>,
876  /// Whether text is struck through, inherited by text and text fields.
877  pub strikethrough: Option<bool>,
878  /// Space between the edge and the content.
879  pub padding: Option<Padding>,
880  /// How round each corner is, in logical pixels.
881  pub radius: Option<Radii>,
882  /// A border inside the edge.
883  pub border: Option<Border>,
884  /// Dashes for the border, `on` and `off` logical pixels along its
885  /// middle line, or a solid border when unset. See
886  /// [`border_dash`](Self::border_dash).
887  pub border_dash: Option<(f32, f32)>,
888  /// From 0.0 (invisible) to 1.0 (opaque), applied to the widget and
889  /// everything inside it.
890  pub opacity: Option<f32>,
891  /// Where the widget and everything inside it show.
892  pub mask: Option<Mask>,
893  /// Whether the children are cut to the inside of the border, following
894  /// the rounded corners, like CSS's `overflow: hidden`.
895  pub clip: Option<bool>,
896  /// The width in logical pixels, instead of what the content needs.
897  pub width: Option<f32>,
898  /// The height in logical pixels, instead of what the content needs.
899  pub height: Option<f32>,
900  /// The least width in logical pixels.
901  pub min_width: Option<f32>,
902  /// The least height in logical pixels.
903  pub min_height: Option<f32>,
904  /// The most width in logical pixels.
905  pub max_width: Option<f32>,
906  /// The most height in logical pixels.
907  pub max_height: Option<f32>,
908  /// How much of a row's or column's free space it takes, against its
909  /// siblings', as CSS's `flex-grow`. 0 by default.
910  pub grow: Option<f32>,
911  /// How much it gives up when a row or column is too small, against its
912  /// siblings', as CSS's `flex-shrink`. 1 by default.
913  pub shrink: Option<f32>,
914  /// Its size along a row or column before growing or shrinking, in
915  /// logical pixels, as CSS's `flex-basis`.
916  pub basis: Option<f32>,
917  /// How it is placed across its row's or column's direction, or
918  /// vertically in a stack's or grid's cell, instead of the parent's
919  /// `align`.
920  pub align_self: Option<Align>,
921  /// How it is placed horizontally in a stack's or grid's cell. Rows and
922  /// columns ignore it, as CSS's flexbox does.
923  pub justify_self: Option<Align>,
924  /// Logical pixels from its parent's left edge, inside the border.
925  /// Any of `left`, `top`, `right` and `bottom` takes the widget out of
926  /// its parent's flow, as CSS's `position: absolute`: it is placed from
927  /// those edges and no longer sizes its parent.
928  pub left: Option<f32>,
929  /// Logical pixels from its parent's top edge, as `left`.
930  pub top: Option<f32>,
931  /// Logical pixels from its parent's right edge, as `left`.
932  pub right: Option<f32>,
933  /// Logical pixels from its parent's bottom edge, as `left`.
934  pub bottom: Option<f32>,
935  /// The order it is drawn and found by the pointer among its siblings,
936  /// lowest first; siblings of equal `z` keep their order, later on top.
937  /// 0 by default. It changes no layout.
938  pub z: Option<i32>,
939  /// The columns and rows of a [`Grid`](crate::Grid) it takes, each at
940  /// least 1.
941  pub span: Option<(u32, u32)>,
942  /// How far the widget is moved, right and down, in logical pixels,
943  /// after it is scaled and turned.
944  pub translate: Option<Point>,
945  /// How many times its size it is drawn, around `origin`. 0 draws
946  /// nothing, and a negative scale also turns it upside down.
947  pub scale: Option<f32>,
948  /// How many degrees it is turned clockwise, around `origin`.
949  pub rotate: Option<f32>,
950  /// The point it is scaled and turned around, as fractions of its box:
951  /// `(0, 0)` is the top-left corner, and the default `(0.5, 0.5)` the
952  /// middle.
953  pub origin: Option<Point>,
954  /// How a change to the paint fields fades in: background, gradient,
955  /// shadow, color, border, radius, opacity and the transform. Other
956  /// fields change at once.
957  pub transition: Option<Transition>,
958  /// How a button's style fades back to its own once no hover, pressed
959  /// or focus style is laid over it; `transition` when unset. Read from
960  /// the button's own style only, so [`merge`](Self::merge) keeps this
961  /// style's.
962  pub transition_out: Option<Transition>,
963}
964
965impl Style {
966  /// A style that sets nothing.
967  pub const fn new() -> Style {
968    Style {
969      background: None,
970      gradient: None,
971      shadow: None,
972      color: None,
973      font: None,
974      text_align: None,
975      line_height: None,
976      underline: None,
977      strikethrough: None,
978      padding: None,
979      radius: None,
980      border: None,
981      border_dash: None,
982      opacity: None,
983      mask: None,
984      clip: None,
985      width: None,
986      height: None,
987      min_width: None,
988      min_height: None,
989      max_width: None,
990      max_height: None,
991      grow: None,
992      shrink: None,
993      basis: None,
994      align_self: None,
995      justify_self: None,
996      left: None,
997      top: None,
998      right: None,
999      bottom: None,
1000      z: None,
1001      span: None,
1002      translate: None,
1003      scale: None,
1004      rotate: None,
1005      origin: None,
1006      transition: None,
1007      transition_out: None,
1008    }
1009  }
1010
1011  /// Sets the background color.
1012  pub const fn background(self, color: Color) -> Style {
1013    Style {
1014      background: Some(color),
1015      ..self
1016    }
1017  }
1018
1019  /// Sets a gradient, drawn over the background.
1020  pub const fn gradient(self, gradient: Gradient) -> Style {
1021    Style {
1022      gradient: Some(gradient),
1023      ..self
1024    }
1025  }
1026
1027  /// Sets a shadow under the box.
1028  pub const fn shadow(self, shadow: Shadow) -> Style {
1029    Style {
1030      shadow: Some(shadow),
1031      ..self
1032    }
1033  }
1034
1035  /// Sets the text color.
1036  pub const fn color(self, color: Color) -> Style {
1037    Style {
1038      color: Some(color),
1039      ..self
1040    }
1041  }
1042
1043  /// Sets the text font.
1044  pub const fn font(self, font: Font) -> Style {
1045    Style {
1046      font: Some(font),
1047      ..self
1048    }
1049  }
1050
1051  /// Sets where text lines sit in their box. It shows on text given a
1052  /// width, a `grow` or more than one line.
1053  pub const fn text_align(self, align: TextAlign) -> Style {
1054    Style {
1055      text_align: Some(align),
1056      ..self
1057    }
1058  }
1059
1060  /// Sets the height of a line of text as a multiple of the font size,
1061  /// rounded to whole logical pixels. A number that isn't finite or
1062  /// isn't above 0 counts as unset.
1063  pub const fn line_height(self, multiple: f32) -> Style {
1064    Style {
1065      line_height: Some(multiple),
1066      ..self
1067    }
1068  }
1069
1070  /// Sets whether text is underlined, in its color.
1071  pub const fn underline(self, on: bool) -> Style {
1072    Style {
1073      underline: Some(on),
1074      ..self
1075    }
1076  }
1077
1078  /// Sets whether text is struck through, in its color.
1079  pub const fn strikethrough(self, on: bool) -> Style {
1080    Style {
1081      strikethrough: Some(on),
1082      ..self
1083    }
1084  }
1085
1086  /// Sets the padding: `vertical` above and below, `horizontal` left and
1087  /// right, in logical pixels.
1088  pub const fn padding(self, vertical: u32, horizontal: u32) -> Style {
1089    Style {
1090      padding: Some(Padding {
1091        top: vertical,
1092        right: horizontal,
1093        bottom: vertical,
1094        left: horizontal,
1095      }),
1096      ..self
1097    }
1098  }
1099
1100  /// Sets the padding above the content, in logical pixels, keeping the
1101  /// other sides this style sets, or 0 where it sets none. As with every
1102  /// field, [`merge`](Self::merge) takes the whole padding of the style on
1103  /// top, so a hover style built from `Style::new()` sets the rest to 0.
1104  ///
1105  /// ```
1106  /// use crabshell_ui::Style;
1107  ///
1108  /// const PILL: Style = Style::new().padding(2, 8).padding_left(12);
1109  /// ```
1110  pub const fn padding_top(self, top: u32) -> Style {
1111    let mut padding = self.sides();
1112    padding.top = top;
1113    Style {
1114      padding: Some(padding),
1115      ..self
1116    }
1117  }
1118
1119  /// Sets the padding right of the content, keeping the other sides, as
1120  /// [`padding_top`](Self::padding_top) does.
1121  pub const fn padding_right(self, right: u32) -> Style {
1122    let mut padding = self.sides();
1123    padding.right = right;
1124    Style {
1125      padding: Some(padding),
1126      ..self
1127    }
1128  }
1129
1130  /// Sets the padding below the content, keeping the other sides, as
1131  /// [`padding_top`](Self::padding_top) does.
1132  pub const fn padding_bottom(self, bottom: u32) -> Style {
1133    let mut padding = self.sides();
1134    padding.bottom = bottom;
1135    Style {
1136      padding: Some(padding),
1137      ..self
1138    }
1139  }
1140
1141  /// Sets the padding left of the content, keeping the other sides, as
1142  /// [`padding_top`](Self::padding_top) does.
1143  pub const fn padding_left(self, left: u32) -> Style {
1144    let mut padding = self.sides();
1145    padding.left = left;
1146    Style {
1147      padding: Some(padding),
1148      ..self
1149    }
1150  }
1151
1152  /// The padding this style sets, or 0 on every side.
1153  const fn sides(self) -> Padding {
1154    match self.padding {
1155      Some(padding) => padding,
1156      None => Padding {
1157        top: 0,
1158        right: 0,
1159        bottom: 0,
1160        left: 0,
1161      },
1162    }
1163  }
1164
1165  /// Rounds every corner by `radius` logical pixels.
1166  pub const fn radius(self, radius: f32) -> Style {
1167    Style {
1168      radius: Some(Radii::all(radius)),
1169      ..self
1170    }
1171  }
1172
1173  /// Rounds each corner on its own, in logical pixels, as CSS's
1174  /// `border-radius` with four values. When two on a side need more than
1175  /// its length, all four shrink by one factor, as in CSS
1176  /// ([`Radii::fit`]). Everything that follows the corners follows each one:
1177  /// the background, gradient, border, shadow, a clip and the scroll
1178  /// bar's cut.
1179  ///
1180  /// ```
1181  /// use crabshell_ui::Style;
1182  ///
1183  /// // A tab, round on top only.
1184  /// const TAB: Style = Style::new().radii(8.0, 8.0, 0.0, 0.0);
1185  /// ```
1186  pub const fn radii(
1187    self,
1188    top_left: f32,
1189    top_right: f32,
1190    bottom_right: f32,
1191    bottom_left: f32,
1192  ) -> Style {
1193    Style {
1194      radius: Some(Radii {
1195        top_left,
1196        top_right,
1197        bottom_right,
1198        bottom_left,
1199      }),
1200      ..self
1201    }
1202  }
1203
1204  /// Sets a border of `width` logical pixels.
1205  pub const fn border(self, width: f32, color: Color) -> Style {
1206    Style {
1207      border: Some(Border { width, color }),
1208      ..self
1209    }
1210  }
1211
1212  /// Dashes the border: `on` logical pixels drawn, `off` left out, along
1213  /// the middle of the border, so the dashes follow its corners. An `on`
1214  /// of 0 draws round dots the border's width across, `off` apart from
1215  /// middle to middle. The dashes are stretched or squeezed a little so a
1216  /// whole number of them goes around. A number that isn't finite, a
1217  /// negative one, an `off` of 0 or a pattern shorter than a pixel draws
1218  /// the border solid. It is a field of its own, so a hover style can
1219  /// dash a border the style under it sets, and with no border it draws
1220  /// nothing. A fade takes the end style's dash at once.
1221  ///
1222  /// ```
1223  /// use crabshell_ui::{Color, Style};
1224  ///
1225  /// const DROP_ZONE: Style = Style::new()
1226  ///     .border(2.0, Color::hex("#89b4fa"))
1227  ///     .border_dash(6.0, 4.0)
1228  ///     .radius(8.0);
1229  /// const DOTTED: Style = DROP_ZONE.border_dash(0.0, 5.0);
1230  /// ```
1231  pub const fn border_dash(self, on: f32, off: f32) -> Style {
1232    Style {
1233      border_dash: Some((on, off)),
1234      ..self
1235    }
1236  }
1237
1238  /// Sets the opacity, from 0.0 to 1.0.
1239  pub const fn opacity(self, opacity: f32) -> Style {
1240    Style {
1241      opacity: Some(opacity),
1242      ..self
1243    }
1244  }
1245
1246  /// Keeps the widget and everything inside it only where `mask` is
1247  /// opaque, as Qt's `OpacityMask`. They are drawn into one layer, the
1248  /// one opacity and a transform use, so stacking them costs no extra
1249  /// layer, and a clip still cuts inside it. A fade takes the end
1250  /// style's mask at once.
1251  pub const fn mask(self, mask: Mask) -> Style {
1252    Style {
1253      mask: Some(mask),
1254      ..self
1255    }
1256  }
1257
1258  /// Sets whether the children are cut to the inside of the border,
1259  /// following the rounded corners. Nothing is cut by default.
1260  pub const fn clip(self, clip: bool) -> Style {
1261    Style {
1262      clip: Some(clip),
1263      ..self
1264    }
1265  }
1266
1267  /// Sets the width in logical pixels, instead of what the content needs.
1268  pub const fn width(self, width: f32) -> Style {
1269    Style {
1270      width: Some(width),
1271      ..self
1272    }
1273  }
1274
1275  /// Sets the height in logical pixels, instead of what the content
1276  /// needs.
1277  pub const fn height(self, height: f32) -> Style {
1278    Style {
1279      height: Some(height),
1280      ..self
1281    }
1282  }
1283
1284  /// Sets the least width in logical pixels.
1285  pub const fn min_width(self, width: f32) -> Style {
1286    Style {
1287      min_width: Some(width),
1288      ..self
1289    }
1290  }
1291
1292  /// Sets the least height in logical pixels.
1293  pub const fn min_height(self, height: f32) -> Style {
1294    Style {
1295      min_height: Some(height),
1296      ..self
1297    }
1298  }
1299
1300  /// Sets the most width in logical pixels.
1301  pub const fn max_width(self, width: f32) -> Style {
1302    Style {
1303      max_width: Some(width),
1304      ..self
1305    }
1306  }
1307
1308  /// Sets the most height in logical pixels.
1309  pub const fn max_height(self, height: f32) -> Style {
1310    Style {
1311      max_height: Some(height),
1312      ..self
1313    }
1314  }
1315
1316  /// Sets how much of a row's or column's free space the widget takes,
1317  /// against its siblings': two children with a grow of 1 and 3 take a
1318  /// quarter and three quarters. A [`Spacer`](crate::Spacer) grows by 1.
1319  ///
1320  /// ```
1321  /// use crabshell_ui::Style;
1322  ///
1323  /// const FILL: Style = Style::new().grow(1.0).basis(0.0);
1324  /// ```
1325  pub const fn grow(self, grow: f32) -> Style {
1326    Style {
1327      grow: Some(grow),
1328      ..self
1329    }
1330  }
1331
1332  /// Sets how much the widget gives up, against its siblings', when its
1333  /// row or column is too small for them all. 0 keeps its size.
1334  pub const fn shrink(self, shrink: f32) -> Style {
1335    Style {
1336      shrink: Some(shrink),
1337      ..self
1338    }
1339  }
1340
1341  /// Sets the widget's size along its row or column, in logical pixels,
1342  /// before it grows or shrinks.
1343  pub const fn basis(self, basis: f32) -> Style {
1344    Style {
1345      basis: Some(basis),
1346      ..self
1347    }
1348  }
1349
1350  /// Sets how the widget is placed across its row's or column's
1351  /// direction, or vertically in a stack's or grid's cell, instead of
1352  /// the parent's `align`.
1353  pub const fn align_self(self, align: Align) -> Style {
1354    Style {
1355      align_self: Some(align),
1356      ..self
1357    }
1358  }
1359
1360  /// Sets how the widget is placed horizontally in a stack's or grid's
1361  /// cell. Rows and columns ignore it.
1362  pub const fn justify_self(self, justify: Align) -> Style {
1363    Style {
1364      justify_self: Some(justify),
1365      ..self
1366    }
1367  }
1368
1369  /// Places the widget `left` logical pixels from its parent's left edge,
1370  /// inside the border, out of the parent's flow.
1371  ///
1372  /// ```
1373  /// use crabshell_ui::Style;
1374  ///
1375  /// // A badge in a stack's top-right corner.
1376  /// const BADGE: Style = Style::new().top(2.0).right(2.0);
1377  /// ```
1378  pub const fn left(self, left: f32) -> Style {
1379    Style {
1380      left: Some(left),
1381      ..self
1382    }
1383  }
1384
1385  /// Places the widget `top` logical pixels from its parent's top edge,
1386  /// as [`left`](Self::left) does.
1387  pub const fn top(self, top: f32) -> Style {
1388    Style {
1389      top: Some(top),
1390      ..self
1391    }
1392  }
1393
1394  /// Places the widget `right` logical pixels from its parent's right
1395  /// edge, as [`left`](Self::left) does.
1396  pub const fn right(self, right: f32) -> Style {
1397    Style {
1398      right: Some(right),
1399      ..self
1400    }
1401  }
1402
1403  /// Places the widget `bottom` logical pixels from its parent's bottom
1404  /// edge, as [`left`](Self::left) does.
1405  pub const fn bottom(self, bottom: f32) -> Style {
1406    Style {
1407      bottom: Some(bottom),
1408      ..self
1409    }
1410  }
1411
1412  /// Sets the order the widget is drawn and hit in among its siblings,
1413  /// lowest first. Equal ones keep their order.
1414  pub const fn z(self, z: i32) -> Style {
1415    Style { z: Some(z), ..self }
1416  }
1417
1418  /// Makes the widget take `columns` columns and `rows` rows of its
1419  /// [`Grid`](crate::Grid). 0 counts as 1.
1420  pub const fn span(self, columns: u32, rows: u32) -> Style {
1421    Style {
1422      span: Some((columns, rows)),
1423      ..self
1424    }
1425  }
1426
1427  /// Moves the widget and everything inside it `x` logical pixels right
1428  /// and `y` down where it is drawn, after it is scaled and turned. The
1429  /// layout doesn't move.
1430  ///
1431  /// ```
1432  /// use crabshell_ui::Style;
1433  ///
1434  /// const HIDDEN: Style = Style::new().translate(0.0, -40.0);
1435  /// ```
1436  pub const fn translate(self, x: f32, y: f32) -> Style {
1437    Style {
1438      translate: Some(Point::new(x, y)),
1439      ..self
1440    }
1441  }
1442
1443  /// Draws the widget and everything inside it `scale` times its size,
1444  /// around its [`origin`](Self::origin), without changing the layout.
1445  /// 0 draws nothing and is never under the pointer; a negative scale
1446  /// also turns it upside down. A number that isn't finite is ignored.
1447  pub const fn scale(self, scale: f32) -> Style {
1448    Style {
1449      scale: Some(scale),
1450      ..self
1451    }
1452  }
1453
1454  /// Turns the widget and everything inside it `degrees` clockwise,
1455  /// around its [`origin`](Self::origin), without changing the layout. A
1456  /// number that isn't finite is ignored.
1457  pub const fn rotate(self, degrees: f32) -> Style {
1458    Style {
1459      rotate: Some(degrees),
1460      ..self
1461    }
1462  }
1463
1464  /// Sets the point the widget is scaled and turned around, as fractions
1465  /// of its box: `(0.0, 0.0)` is the top-left corner, `(1.0, 1.0)` the
1466  /// bottom-right. The default is the middle, `(0.5, 0.5)`.
1467  pub const fn origin(self, x: f32, y: f32) -> Style {
1468    Style {
1469      origin: Some(Point::new(x, y)),
1470      ..self
1471    }
1472  }
1473
1474  /// Sets how a change to the paint fields fades in, as when a hover
1475  /// style takes over: background, gradient, shadow, color, border,
1476  /// radius, opacity, translate, scale, rotate and origin move over
1477  /// `transition`. The style being changed to says how.
1478  pub const fn transition(self, transition: Transition) -> Style {
1479    Style {
1480      transition: Some(transition),
1481      ..self
1482    }
1483  }
1484
1485  /// Sets how a button's style fades back to its own, once no hover,
1486  /// pressed or focus style is laid over it, so the way out can take a
1487  /// different curve from the way in. Without it the way back takes
1488  /// `transition` too. Only the button's own style's is read: one in a
1489  /// hover, pressed or focus style does nothing.
1490  pub const fn transition_out(self, transition: Transition) -> Style {
1491    Style {
1492      transition_out: Some(transition),
1493      ..self
1494    }
1495  }
1496
1497  /// This style with every field that `over` sets replaced by its value,
1498  /// except `transition_out`, which stays this style's.
1499  /// Buttons use it to lay their hover and pressed styles over the normal
1500  /// one.
1501  pub const fn merge(self, over: Style) -> Style {
1502    Style {
1503      background: or(over.background, self.background),
1504      gradient: or(over.gradient, self.gradient),
1505      shadow: or(over.shadow, self.shadow),
1506      color: or(over.color, self.color),
1507      font: or(over.font, self.font),
1508      text_align: or(over.text_align, self.text_align),
1509      line_height: or(over.line_height, self.line_height),
1510      underline: or(over.underline, self.underline),
1511      strikethrough: or(over.strikethrough, self.strikethrough),
1512      padding: or(over.padding, self.padding),
1513      radius: or(over.radius, self.radius),
1514      border: or(over.border, self.border),
1515      border_dash: or(over.border_dash, self.border_dash),
1516      opacity: or(over.opacity, self.opacity),
1517      mask: or(over.mask, self.mask),
1518      clip: or(over.clip, self.clip),
1519      width: or(over.width, self.width),
1520      height: or(over.height, self.height),
1521      min_width: or(over.min_width, self.min_width),
1522      min_height: or(over.min_height, self.min_height),
1523      max_width: or(over.max_width, self.max_width),
1524      max_height: or(over.max_height, self.max_height),
1525      grow: or(over.grow, self.grow),
1526      shrink: or(over.shrink, self.shrink),
1527      basis: or(over.basis, self.basis),
1528      align_self: or(over.align_self, self.align_self),
1529      justify_self: or(over.justify_self, self.justify_self),
1530      left: or(over.left, self.left),
1531      top: or(over.top, self.top),
1532      right: or(over.right, self.right),
1533      bottom: or(over.bottom, self.bottom),
1534      z: or(over.z, self.z),
1535      span: or(over.span, self.span),
1536      translate: or(over.translate, self.translate),
1537      scale: or(over.scale, self.scale),
1538      rotate: or(over.rotate, self.rotate),
1539      origin: or(over.origin, self.origin),
1540      transition: or(over.transition, self.transition),
1541      // Read only from a button's own style, so a state style's is dropped.
1542      transition_out: self.transition_out,
1543    }
1544  }
1545
1546  /// Whether the children are cut to the widget's box.
1547  pub fn clips(&self) -> bool {
1548    self.clip == Some(true)
1549  }
1550
1551  /// Whether the two styles lay out the same: same font, text alignment
1552  /// and line height, padding, sizes, flex fields, alignment, position
1553  /// and span, and clipping, which changes how far the children's
1554  /// painting reaches.
1555  pub(crate) fn same_layout(&self, other: &Style) -> bool {
1556    self.font == other.font
1557      && self.text_align == other.text_align
1558      && self.line_height == other.line_height
1559      && self.padding == other.padding
1560      && self.width == other.width
1561      && self.height == other.height
1562      && self.min_width == other.min_width
1563      && self.min_height == other.min_height
1564      && self.max_width == other.max_width
1565      && self.max_height == other.max_height
1566      && self.grow == other.grow
1567      && self.shrink == other.shrink
1568      && self.basis == other.basis
1569      && self.align_self == other.align_self
1570      && self.justify_self == other.justify_self
1571      && self.left == other.left
1572      && self.top == other.top
1573      && self.right == other.right
1574      && self.bottom == other.bottom
1575      && self.span == other.span
1576      && self.clips() == other.clips()
1577  }
1578
1579  /// Whether any of `left`, `top`, `right` and `bottom` is set to a
1580  /// finite number, which takes the widget out of its parent's flow.
1581  pub(crate) fn absolute(&self) -> bool {
1582    [self.left, self.top, self.right, self.bottom]
1583      .into_iter()
1584      .flatten()
1585      .any(f32::is_finite)
1586  }
1587
1588  /// Whether the two styles move the widget the same way where it is
1589  /// drawn.
1590  pub(crate) fn same_transform(&self, other: &Style) -> bool {
1591    self.translate == other.translate
1592      && self.scale == other.scale
1593      && self.rotate == other.rotate
1594      && self.origin == other.origin
1595  }
1596
1597  /// Where this style moves a widget laid out at `rect`, from its own
1598  /// coordinates into its parent's, or `None` when it doesn't. It is
1599  /// scaled and turned around its origin, then translated. A number that
1600  /// isn't finite counts as unset.
1601  pub(crate) fn transform(&self, rect: Rect) -> Option<Affine> {
1602    let finite = |value: f32, default: f32| if value.is_finite() { value } else { default };
1603    let translate = self.translate.unwrap_or_default();
1604    let (x, y) = (finite(translate.x, 0.0), finite(translate.y, 0.0));
1605    let scale = finite(self.scale.unwrap_or(1.0), 1.0);
1606    let degrees = finite(self.rotate.unwrap_or(0.0), 0.0).rem_euclid(360.0);
1607    if x == 0.0 && y == 0.0 && scale == 1.0 && degrees == 0.0 {
1608      return None;
1609    }
1610    // Quarter turns are exact, so a chevron turned over stays crisp.
1611    let (sin, cos) = match degrees {
1612      90.0 => (1.0, 0.0),
1613      180.0 => (0.0, -1.0),
1614      270.0 => (-1.0, 0.0),
1615      _ => degrees.to_radians().sin_cos(),
1616    };
1617    let origin = self.origin.unwrap_or(Point::new(0.5, 0.5));
1618    let ox = rect.x + finite(origin.x, 0.5) * rect.width;
1619    let oy = rect.y + finite(origin.y, 0.5) * rect.height;
1620    // A point p goes to origin + turn(scale(p - origin)) + translate.
1621    let (sx, ky, kx, sy) = (cos * scale, sin * scale, -sin * scale, cos * scale);
1622    // One too large for f32 maps every area to an empty one, so it is
1623    // drawn nowhere and never hit.
1624    Some(Affine {
1625      sx,
1626      ky,
1627      kx,
1628      sy,
1629      tx: ox + x - (sx * ox + kx * oy),
1630      ty: oy + y - (ky * ox + sy * oy),
1631    })
1632  }
1633}
1634
1635/// `Option::or`, which isn't a `const fn` on stable Rust.
1636const fn or<T: Copy>(first: Option<T>, second: Option<T>) -> Option<T> {
1637  match first {
1638    Some(value) => Some(value),
1639    None => second,
1640  }
1641}
1642
1643impl Style {
1644  /// The paint fields `t` of the way from `self` to `to`; every other
1645  /// field is `to`'s. A field only one side sets fades from or to nothing:
1646  /// a color from or to its transparent self, a border from or to 0 wide.
1647  /// A text color only one sets changes at once, as the other comes
1648  /// from an ancestor. Gradients of different shapes or numbers of colors
1649  /// change at once. An unset translate is 0, scale 1, rotate 0 and
1650  /// origin the middle.
1651  pub(crate) fn lerp(&self, to: &Style, t: f32) -> Style {
1652    let color = |from: Option<Color>, to: Option<Color>| match (from, to) {
1653      (Some(from), Some(to)) => Some(from.lerp(&to, t)),
1654      (None, Some(to)) => Some(Color::rgba(to.r, to.g, to.b, 0).lerp(&to, t)),
1655      (Some(from), None) => Some(from.lerp(&Color::rgba(from.r, from.g, from.b, 0), t)),
1656      (None, None) => None,
1657    };
1658    let border = match (self.border, to.border) {
1659      (None, None) => None,
1660      (from, to) => {
1661        let from = from.or(to.map(|b| Border {
1662          width: 0.0,
1663          color: Color::rgba(b.color.r, b.color.g, b.color.b, 0),
1664        }));
1665        let to = to.or(from.map(|b| Border {
1666          width: 0.0,
1667          color: Color::rgba(b.color.r, b.color.g, b.color.b, 0),
1668        }));
1669        match (from, to) {
1670          (Some(from), Some(to)) => Some(Border {
1671            width: from.width.lerp(&to.width, t),
1672            color: from.color.lerp(&to.color, t),
1673          }),
1674
1675          _ => None,
1676        }
1677      }
1678    };
1679    let number = |from: Option<f32>, to: Option<f32>, none: f32| match (from, to) {
1680      (None, None) => None,
1681      (from, to) => Some(from.unwrap_or(none).lerp(&to.unwrap_or(none), t)),
1682    };
1683    let point = |from: Option<Point>, to: Option<Point>, none: Point| match (from, to) {
1684      (None, None) => None,
1685      (from, to) => Some(from.unwrap_or(none).lerp(&to.unwrap_or(none), t)),
1686    };
1687    let gradient = match (self.gradient, to.gradient) {
1688      (Some(from), Some(end)) => from.lerp(&end, t).or(to.gradient),
1689      (None, Some(end)) => end.clear().lerp(&end, t),
1690      (Some(from), None) => from.lerp(&from.clear(), t),
1691      (None, None) => None,
1692    };
1693    let shadow = match (self.shadow, to.shadow) {
1694      (Some(from), Some(end)) => Some(from.lerp(&end, t)),
1695      (None, Some(end)) => Some(end.clear().lerp(&end, t)),
1696      (Some(from), None) => Some(from.lerp(&from.clear(), t)),
1697      (None, None) => None,
1698    };
1699    Style {
1700      background: color(self.background, to.background),
1701      gradient,
1702      shadow,
1703      color: match (self.color, to.color) {
1704        (Some(from), Some(to)) => Some(from.lerp(&to, t)),
1705        _ => to.color,
1706      },
1707      border,
1708      radius: match (self.radius, to.radius) {
1709        (None, None) => None,
1710        (from, to) => Some(from.unwrap_or_default().lerp(&to.unwrap_or_default(), t)),
1711      },
1712      opacity: number(self.opacity, to.opacity, 1.0),
1713      translate: point(self.translate, to.translate, Point::default()),
1714      scale: number(self.scale, to.scale, 1.0),
1715      rotate: number(self.rotate, to.rotate, 0.0),
1716      origin: point(self.origin, to.origin, Point::new(0.5, 0.5)),
1717      ..*to
1718    }
1719  }
1720}