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