Skip to main content

native_theme/model/
border.rs

1// Border specification sub-structs for defaults-level and widget-level border properties
2
3use crate::Rgba;
4use native_theme_derive::ThemeFields;
5use serde::{Deserialize, Serialize};
6
7/// Defaults-level border specification: color, geometry, and the platform's
8/// line opacity.
9///
10/// Used on [`ThemeDefaults`](crate::model::ThemeDefaults) for global border
11/// properties that are inherited by per-widget borders.
12///
13/// **No padding fields:** Padding lives exclusively on [`WidgetBorderSpec`]
14/// because padding is a widget-level layout concern, not a global default.
15///
16/// All fields are optional to support partial overlays -- a DefaultsBorderSpec
17/// with only `color` set will only override the color when merged.
18#[serde_with::skip_serializing_none]
19#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
20#[serde(default)]
21pub struct DefaultsBorderSpec {
22    /// Border color.
23    pub color: Option<Rgba>,
24    /// Corner radius in logical pixels.
25    #[serde(rename = "corner_radius_px")]
26    pub corner_radius: Option<f32>,
27    /// Large corner radius in logical pixels (defaults only).
28    #[serde(rename = "corner_radius_lg_px")]
29    pub corner_radius_lg: Option<f32>,
30    /// Border stroke width in logical pixels.
31    #[serde(rename = "line_width_px")]
32    pub line_width: Option<f32>,
33    /// The platform's line opacity, 0.0-1.0 (defaults only): the share of the
34    /// text colour that makes a border or separator line — KDE's
35    /// `frameContrast` 0.2, libadwaita's `--border-opacity` 0.15
36    /// (docs/platform-facts.md §2.1.6).
37    ///
38    /// It is already folded into every stated border colour, which is the
39    /// final line colour: no connector multiplies any colour by it. It
40    /// documents how the platform derives its lines.
41    pub opacity: Option<f32>,
42    /// Whether the bordered element has a drop shadow.
43    pub shadow_enabled: Option<bool>,
44}
45
46impl_merge!(DefaultsBorderSpec {
47    option { color, corner_radius, corner_radius_lg, line_width, opacity, shadow_enabled }
48});
49
50/// Widget-level border specification: color, geometry, and padding.
51///
52/// Used on per-widget structs for border properties specific to individual
53/// widgets. Unlike [`DefaultsBorderSpec`], includes the four padding sides
54/// (widget-level layout) but omits `corner_radius_lg` and `opacity`
55/// (defaults-only geometry).
56///
57/// Padding fields are widget-only because different widgets need different
58/// internal padding even when sharing the same border geometry from defaults.
59///
60/// **Padding is per side.** A platform states padding side by side, and some
61/// sides differ (Windows' input is 10 left / 6 right, docs/platform-facts.md
62/// §2.4), so the model stores the four sides and nothing else. `None` means
63/// the platform states no value for that side; `Some(0.0)` means it states
64/// zero.
65///
66/// **TOML.** The sides are `padding_top_px`, `padding_right_px`,
67/// `padding_bottom_px` and `padding_left_px`. `padding_horizontal_px` and
68/// `padding_vertical_px` are parse-time shorthand that set both sides of
69/// their axis. A table that states an axis key together with one of that
70/// axis's sides is a parse error naming both keys. Serialisation writes
71/// sides only.
72///
73/// All fields are optional to support partial overlays, and they merge per
74/// field, the overlay winning, so a reader's left side over a preset's
75/// shorthand replaces the left side alone.
76#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, ThemeFields)]
77#[serde(try_from = "WidgetBorderSpecRaw", into = "WidgetBorderSpecRaw")]
78// serde reads and writes this struct through WidgetBorderSpecRaw, which also
79// knows the two shorthand keys. The ThemeFields derive's introspection path
80// cannot see the proxy, so declare the wire-format field names explicitly
81// here, as FontSpec does. Keep in sync with WidgetBorderSpecRaw below.
82#[theme_layer(
83    fields = "color, corner_radius_px, line_width_px, shadow_enabled, padding_top_px, padding_right_px, padding_bottom_px, padding_left_px, padding_horizontal_px, padding_vertical_px"
84)]
85pub struct WidgetBorderSpec {
86    /// Border color.
87    pub color: Option<Rgba>,
88    /// Corner radius in logical pixels.
89    pub corner_radius: Option<f32>,
90    /// Border stroke width in logical pixels.
91    pub line_width: Option<f32>,
92    /// Whether the bordered element has a drop shadow.
93    pub shadow_enabled: Option<bool>,
94    /// Padding inside the border above the content, in logical pixels.
95    pub padding_top: Option<f32>,
96    /// Padding inside the border right of the content, in logical pixels.
97    pub padding_right: Option<f32>,
98    /// Padding inside the border below the content, in logical pixels.
99    pub padding_bottom: Option<f32>,
100    /// Padding inside the border left of the content, in logical pixels.
101    pub padding_left: Option<f32>,
102}
103
104/// Serde proxy for [`WidgetBorderSpec`]: the four side keys and the two axis
105/// shorthands.
106#[serde_with::skip_serializing_none]
107#[derive(Default, Serialize, Deserialize)]
108#[serde(default)]
109struct WidgetBorderSpecRaw {
110    color: Option<Rgba>,
111    corner_radius_px: Option<f32>,
112    line_width_px: Option<f32>,
113    shadow_enabled: Option<bool>,
114    padding_top_px: Option<f32>,
115    padding_right_px: Option<f32>,
116    padding_bottom_px: Option<f32>,
117    padding_left_px: Option<f32>,
118    padding_horizontal_px: Option<f32>,
119    padding_vertical_px: Option<f32>,
120}
121
122/// Expand one axis shorthand into its two sides, rejecting a table that also
123/// states either side.
124fn expand_axis(
125    axis: (&str, Option<f32>),
126    first: (&str, Option<f32>),
127    second: (&str, Option<f32>),
128) -> Result<(Option<f32>, Option<f32>), String> {
129    let Some(v) = axis.1 else {
130        return Ok((first.1, second.1));
131    };
132    for side in [first, second] {
133        if side.1.is_some() {
134            return Err(format!(
135                "border: set `{}` or `{}`, not both",
136                axis.0, side.0
137            ));
138        }
139    }
140    Ok((Some(v), Some(v)))
141}
142
143impl TryFrom<WidgetBorderSpecRaw> for WidgetBorderSpec {
144    type Error = String;
145    fn try_from(raw: WidgetBorderSpecRaw) -> Result<Self, Self::Error> {
146        let (padding_left, padding_right) = expand_axis(
147            ("padding_horizontal_px", raw.padding_horizontal_px),
148            ("padding_left_px", raw.padding_left_px),
149            ("padding_right_px", raw.padding_right_px),
150        )?;
151        let (padding_top, padding_bottom) = expand_axis(
152            ("padding_vertical_px", raw.padding_vertical_px),
153            ("padding_top_px", raw.padding_top_px),
154            ("padding_bottom_px", raw.padding_bottom_px),
155        )?;
156        Ok(WidgetBorderSpec {
157            color: raw.color,
158            corner_radius: raw.corner_radius_px,
159            line_width: raw.line_width_px,
160            shadow_enabled: raw.shadow_enabled,
161            padding_top,
162            padding_right,
163            padding_bottom,
164            padding_left,
165        })
166    }
167}
168
169impl From<WidgetBorderSpec> for WidgetBorderSpecRaw {
170    fn from(b: WidgetBorderSpec) -> Self {
171        WidgetBorderSpecRaw {
172            color: b.color,
173            corner_radius_px: b.corner_radius,
174            line_width_px: b.line_width,
175            shadow_enabled: b.shadow_enabled,
176            padding_top_px: b.padding_top,
177            padding_right_px: b.padding_right,
178            padding_bottom_px: b.padding_bottom,
179            padding_left_px: b.padding_left,
180            padding_horizontal_px: None,
181            padding_vertical_px: None,
182        }
183    }
184}
185
186impl_merge!(WidgetBorderSpec {
187    option {
188        color, corner_radius, line_width, shadow_enabled,
189        padding_top, padding_right, padding_bottom, padding_left
190    }
191});
192
193/// A widget's resolved padding, one field per side.
194///
195/// `None` means the theme states no value for that side, so a connector
196/// leaves the toolkit's own padding in place there; `Some(0.0)` means the
197/// theme states zero.
198#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
199pub struct ResolvedPadding {
200    /// Padding above the content, in logical pixels.
201    pub top: Option<f32>,
202    /// Padding right of the content, in logical pixels.
203    pub right: Option<f32>,
204    /// Padding below the content, in logical pixels.
205    pub bottom: Option<f32>,
206    /// Padding left of the content, in logical pixels.
207    pub left: Option<f32>,
208}
209
210/// The resolved `defaults.border`: the global border geometry and colour
211/// that widget borders inherit.
212///
213/// No `Default` derive: It is constructed from a fully
214/// populated unresolved source.
215#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
216#[non_exhaustive]
217pub struct ResolvedDefaultsBorder {
218    /// Border color.
219    pub color: Rgba,
220    /// Corner radius in logical pixels.
221    pub corner_radius: f32,
222    /// Large corner radius in logical pixels.
223    pub corner_radius_lg: f32,
224    /// Border stroke width in logical pixels.
225    pub line_width: f32,
226    /// The platform's line opacity, 0.0-1.0: the share of the text colour
227    /// already folded into every stated border colour. No connector
228    /// multiplies any colour by it (see [`DefaultsBorderSpec::opacity`]).
229    pub opacity: f32,
230    /// Whether the bordered element has a drop shadow.
231    pub shadow_enabled: bool,
232}
233
234/// A widget's resolved border: its colour, geometry and padding.
235///
236/// No `Default` derive: Any "zero" instance is a
237/// placeholder sentinel built manually (see
238/// `resolve::validate_helpers::resolved_widget_border_sentinel`).
239#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
240pub struct ResolvedWidgetBorder {
241    /// Border color.
242    pub color: Rgba,
243    /// Corner radius in logical pixels.
244    pub corner_radius: f32,
245    /// Border stroke width in logical pixels.
246    pub line_width: f32,
247    /// Whether the bordered element has a drop shadow.
248    pub shadow_enabled: bool,
249    /// Padding inside the border, per side; a side the theme does not state
250    /// is `None`.
251    #[serde(default)]
252    pub padding: ResolvedPadding,
253}
254
255impl ResolvedWidgetBorder {
256    /// The padding measured from the widget's outer edge: each side
257    /// [`padding`](Self::padding) states plus [`line_width`](Self::line_width),
258    /// and `None` where it states none, so the toolkit keeps its own padding
259    /// there.
260    ///
261    /// The theme's padding lies inside the border (outer size = border +
262    /// padding + content, `docs/platform-facts.md:904-906`). A toolkit that
263    /// lays a widget's content out its padding in from the widget's edge and
264    /// paints the border over that padding, as iced and egui do, takes this,
265    /// and the content sits where the platform puts it; one whose box model
266    /// lays the padding inside the border (gpui) takes
267    /// [`padding`](Self::padding).
268    ///
269    /// On a resolved theme every length is finite and non-negative
270    /// (validation rejects any other). A finite side plus a finite width can
271    /// only overflow upwards, and that sum is `f32::MAX`, so a finite padding
272    /// stays finite; a non-finite side or width gives the `f32` sum.
273    #[must_use]
274    pub fn padding_outside(&self) -> ResolvedPadding {
275        let width = self.line_width;
276        let side = |stated: Option<f32>| {
277            stated.map(|v| match v + width {
278                sum if v.is_finite() && width.is_finite() => sum.min(f32::MAX),
279                sum => sum,
280            })
281        };
282        ResolvedPadding {
283            top: side(self.padding.top),
284            right: side(self.padding.right),
285            bottom: side(self.padding.bottom),
286            left: side(self.padding.left),
287        }
288    }
289}
290
291#[cfg(test)]
292#[allow(clippy::unwrap_used, clippy::expect_used)]
293mod tests {
294    use super::*;
295
296    // === DefaultsBorderSpec tests ===
297
298    #[test]
299    fn defaults_border_spec_default_is_empty() {
300        assert!(DefaultsBorderSpec::default().is_empty());
301    }
302
303    #[test]
304    fn defaults_border_spec_not_empty_when_color_set() {
305        let bs = DefaultsBorderSpec {
306            color: Some(Rgba::rgb(100, 100, 100)),
307            ..Default::default()
308        };
309        assert!(!bs.is_empty());
310    }
311
312    #[test]
313    fn defaults_border_spec_toml_round_trip_full() {
314        let bs = DefaultsBorderSpec {
315            color: Some(Rgba::rgb(200, 200, 200)),
316            corner_radius: Some(4.0),
317            corner_radius_lg: Some(8.0),
318            line_width: Some(1.0),
319            opacity: Some(0.15),
320            shadow_enabled: Some(true),
321        };
322        let toml_str = toml::to_string(&bs).unwrap();
323        let deserialized: DefaultsBorderSpec = toml::from_str(&toml_str).unwrap();
324        assert_eq!(deserialized, bs);
325    }
326
327    #[test]
328    fn defaults_border_spec_toml_round_trip_partial() {
329        let bs = DefaultsBorderSpec {
330            color: Some(Rgba::rgb(100, 100, 100)),
331            corner_radius: Some(8.0),
332            corner_radius_lg: None,
333            line_width: None,
334            opacity: None,
335            shadow_enabled: None,
336        };
337        let toml_str = toml::to_string(&bs).unwrap();
338        let deserialized: DefaultsBorderSpec = toml::from_str(&toml_str).unwrap();
339        assert_eq!(deserialized, bs);
340        assert!(deserialized.corner_radius_lg.is_none());
341        assert!(deserialized.line_width.is_none());
342        assert!(deserialized.opacity.is_none());
343        assert!(deserialized.shadow_enabled.is_none());
344    }
345
346    #[test]
347    fn defaults_border_spec_merge_overlay_wins() {
348        let mut base = DefaultsBorderSpec {
349            color: Some(Rgba::rgb(100, 100, 100)),
350            corner_radius: Some(4.0),
351            ..Default::default()
352        };
353        let overlay = DefaultsBorderSpec {
354            color: Some(Rgba::rgb(200, 200, 200)),
355            ..Default::default()
356        };
357        base.merge(&overlay);
358        assert_eq!(base.color, Some(Rgba::rgb(200, 200, 200)));
359        // base corner_radius preserved since overlay corner_radius is None
360        assert_eq!(base.corner_radius, Some(4.0));
361    }
362
363    // === WidgetBorderSpec tests ===
364
365    #[test]
366    fn widget_border_spec_default_is_empty() {
367        assert!(WidgetBorderSpec::default().is_empty());
368    }
369
370    #[test]
371    fn widget_border_spec_not_empty_when_color_set() {
372        let bs = WidgetBorderSpec {
373            color: Some(Rgba::rgb(100, 100, 100)),
374            ..Default::default()
375        };
376        assert!(!bs.is_empty());
377    }
378
379    #[test]
380    fn widget_border_spec_toml_round_trip_full() {
381        let bs = WidgetBorderSpec {
382            color: Some(Rgba::rgb(200, 200, 200)),
383            corner_radius: Some(4.0),
384            line_width: Some(1.0),
385            shadow_enabled: Some(true),
386            padding_top: Some(5.0),
387            padding_right: Some(6.0),
388            padding_bottom: Some(7.0),
389            padding_left: Some(8.0),
390        };
391        let toml_str = toml::to_string(&bs).unwrap();
392        let deserialized: WidgetBorderSpec = toml::from_str(&toml_str).unwrap();
393        assert_eq!(deserialized, bs);
394    }
395
396    #[test]
397    fn widget_border_spec_toml_round_trip_partial() {
398        let bs = WidgetBorderSpec {
399            color: Some(Rgba::rgb(100, 100, 100)),
400            corner_radius: Some(8.0),
401            line_width: None,
402            shadow_enabled: None,
403            padding_top: None,
404            padding_right: None,
405            padding_bottom: None,
406            padding_left: None,
407        };
408        let toml_str = toml::to_string(&bs).unwrap();
409        let deserialized: WidgetBorderSpec = toml::from_str(&toml_str).unwrap();
410        assert_eq!(deserialized, bs);
411        assert!(deserialized.line_width.is_none());
412        assert!(deserialized.shadow_enabled.is_none());
413        assert!(deserialized.padding_top.is_none());
414        assert!(deserialized.padding_right.is_none());
415        assert!(deserialized.padding_bottom.is_none());
416        assert!(deserialized.padding_left.is_none());
417    }
418
419    #[test]
420    fn widget_border_spec_merge_overlay_wins() {
421        let mut base = WidgetBorderSpec {
422            color: Some(Rgba::rgb(100, 100, 100)),
423            corner_radius: Some(4.0),
424            ..Default::default()
425        };
426        let overlay = WidgetBorderSpec {
427            color: Some(Rgba::rgb(200, 200, 200)),
428            ..Default::default()
429        };
430        base.merge(&overlay);
431        assert_eq!(base.color, Some(Rgba::rgb(200, 200, 200)));
432        // base corner_radius preserved since overlay corner_radius is None
433        assert_eq!(base.corner_radius, Some(4.0));
434    }
435
436    // === Per-side padding and its TOML shorthand ===
437
438    #[test]
439    fn padding_horizontal_shorthand_sets_left_and_right_only() {
440        let bs: WidgetBorderSpec = toml::from_str("padding_horizontal_px = 10").unwrap();
441        assert_eq!(bs.padding_left, Some(10.0));
442        assert_eq!(bs.padding_right, Some(10.0));
443        assert_eq!(bs.padding_top, None);
444        assert_eq!(bs.padding_bottom, None);
445    }
446
447    #[test]
448    fn padding_vertical_shorthand_states_a_zero() {
449        let bs: WidgetBorderSpec = toml::from_str("padding_vertical_px = 0.0").unwrap();
450        assert_eq!(bs.padding_top, Some(0.0));
451        assert_eq!(bs.padding_bottom, Some(0.0));
452        assert_eq!(bs.padding_left, None);
453        assert_eq!(bs.padding_right, None);
454    }
455
456    #[test]
457    fn an_axis_key_with_one_of_its_sides_is_rejected_naming_the_table_and_both_keys() {
458        let src = "[light.button.border]\npadding_horizontal_px = 10\npadding_left_px = 4\n";
459        let err = toml::from_str::<toml::Table>(src)
460            .ok()
461            .and_then(|t| t.get("light").cloned())
462            .and_then(|l| l.get("button").cloned())
463            .and_then(|b| b.get("border").cloned())
464            .map(|border| border.try_into::<WidgetBorderSpec>())
465            .expect("the table parses as TOML")
466            .expect_err("an axis key with one of its sides must be rejected")
467            .to_string();
468        assert!(err.contains("padding_horizontal_px"), "{err}");
469        assert!(err.contains("padding_left_px"), "{err}");
470
471        // Through a whole theme, where the error also names the table.
472        let theme = format!("name = \"T\"\n{src}");
473        let err = crate::Theme::from_toml(&theme)
474            .expect_err("the theme must not load")
475            .to_string();
476        assert!(err.contains("padding_horizontal_px"), "{err}");
477        assert!(err.contains("padding_left_px"), "{err}");
478        assert!(err.contains("light.button.border"), "{err}");
479    }
480
481    #[test]
482    fn the_vertical_axis_key_with_a_side_is_rejected_too() {
483        let err =
484            toml::from_str::<WidgetBorderSpec>("padding_vertical_px = 2\npadding_bottom_px = 3")
485                .expect_err("rejected")
486                .to_string();
487        assert!(err.contains("padding_vertical_px"), "{err}");
488        assert!(err.contains("padding_bottom_px"), "{err}");
489    }
490
491    #[test]
492    fn serialisation_writes_sides_never_the_shorthand() {
493        let bs: WidgetBorderSpec =
494            toml::from_str("padding_horizontal_px = 10\npadding_top_px = 3").unwrap();
495        let out = toml::to_string(&bs).unwrap();
496        assert!(out.contains("padding_left_px = 10"), "{out}");
497        assert!(out.contains("padding_right_px = 10"), "{out}");
498        assert!(out.contains("padding_top_px = 3"), "{out}");
499        assert!(!out.contains("padding_horizontal_px"), "{out}");
500        assert!(!out.contains("padding_bottom_px"), "{out}");
501        let back: WidgetBorderSpec = toml::from_str(&out).unwrap();
502        assert_eq!(back, bs);
503    }
504
505    #[test]
506    fn a_readers_left_side_over_a_presets_shorthand_wins_for_left_only() {
507        let mut preset: WidgetBorderSpec = toml::from_str("padding_horizontal_px = 10").unwrap();
508        let reader = WidgetBorderSpec {
509            padding_left: Some(4.0),
510            ..Default::default()
511        };
512        preset.merge(&reader);
513        assert_eq!(preset.padding_left, Some(4.0));
514        assert_eq!(preset.padding_right, Some(10.0));
515        assert_eq!(preset.padding_top, None);
516        assert_eq!(preset.padding_bottom, None);
517    }
518
519    // === Resolved border tests ===
520
521    #[test]
522    fn resolved_border_struct_literals_compile() {
523        // Field-name compile guard: any rename/remove breaks these literals.
524        let defaults = ResolvedDefaultsBorder {
525            color: Rgba::new(0, 0, 0, 0),
526            corner_radius: 0.0,
527            corner_radius_lg: 0.0,
528            line_width: 0.0,
529            opacity: 0.0,
530            shadow_enabled: false,
531        };
532        assert_eq!(defaults.corner_radius_lg, 0.0);
533        let widget = ResolvedWidgetBorder {
534            color: Rgba::new(0, 0, 0, 0),
535            corner_radius: 0.0,
536            line_width: 0.0,
537            shadow_enabled: false,
538            padding: ResolvedPadding {
539                top: None,
540                right: Some(0.0),
541                bottom: None,
542                left: Some(4.0),
543            },
544        };
545        assert_eq!(widget.padding.left, Some(4.0));
546        assert_eq!(widget.padding.top, None);
547        assert_eq!(ResolvedPadding::default().right, None);
548    }
549
550    /// A resolved border serialised without its padding (by a version that
551    /// had none, or by hand) deserialises with every side unstated.
552    #[test]
553    fn resolved_widget_border_without_padding_deserialises_unstated() {
554        let src =
555            "color = \"#000000\"\ncorner_radius = 2.0\nline_width = 1.0\nshadow_enabled = false\n";
556        let border: ResolvedWidgetBorder = toml::from_str(src).unwrap();
557        assert_eq!(border.padding, ResolvedPadding::default());
558    }
559
560    // === padding_outside tests ===
561
562    fn bordered(line_width: f32, padding: [Option<f32>; 4]) -> ResolvedWidgetBorder {
563        let [top, right, bottom, left] = padding;
564        ResolvedWidgetBorder {
565            color: Rgba::rgb(0, 0, 0),
566            corner_radius: 0.0,
567            line_width,
568            shadow_enabled: false,
569            padding: ResolvedPadding {
570                top,
571                right,
572                bottom,
573                left,
574            },
575        }
576    }
577
578    #[test]
579    fn padding_outside_adds_the_line_width_to_each_stated_side() {
580        let border = bordered(1.5, [Some(4.0), Some(8.0), None, Some(0.0)]);
581        assert_eq!(
582            border.padding_outside(),
583            ResolvedPadding {
584                top: Some(5.5),
585                right: Some(9.5),
586                bottom: None,
587                left: Some(1.5),
588            }
589        );
590    }
591
592    #[test]
593    fn padding_outside_with_no_border_is_the_padding() {
594        let border = bordered(0.0, [Some(4.0), None, Some(2.0), None]);
595        assert_eq!(border.padding_outside(), border.padding);
596        assert_eq!(
597            bordered(2.0, [None; 4]).padding_outside(),
598            ResolvedPadding::default()
599        );
600    }
601
602    #[test]
603    fn padding_outside_with_a_huge_width_saturates() {
604        let border = bordered(f32::MAX, [Some(1.0), Some(f32::MAX), None, None]);
605        let padding = border.padding_outside();
606        assert_eq!(padding.top, Some(f32::MAX));
607        assert_eq!(padding.right, Some(f32::MAX));
608        assert_eq!((padding.bottom, padding.left), (None, None));
609        let side =
610            bordered(1.0, [Some(f32::INFINITY), Some(f32::NAN), None, None]).padding_outside();
611        assert_eq!(side.top, Some(f32::INFINITY));
612        assert!(side.right.is_some_and(f32::is_nan));
613    }
614}