Skip to main content

native_theme/resolve/
context.rs

1//! Resolution-time inputs (font DPI, button order, icon theme) captured
2//! once per theme-build and passed by reference through the pipeline.
3//!
4//! Intentionally NO `impl Default` — runtime-detected types must signal
5//! intent at the call site. Use [`ResolutionContext::from_system`] for
6//! production, or [`ResolutionContext::for_tests`] for deterministic
7//! test values.
8
9use std::borrow::Cow;
10
11use crate::model::DialogButtonOrder;
12
13/// Resolution-time inputs captured once per theme-build.
14///
15/// Accessibility preferences live on
16/// [`SystemTheme`](crate::SystemTheme), NOT here — accessibility is a
17/// render-time concern, not a resolve-time concern.
18///
19/// # Examples
20///
21/// ```
22/// use native_theme::resolve::ResolutionContext;
23///
24/// // The running platform's: its constant font DPI, its button order and
25/// // its detected icon theme.
26/// let ctx = ResolutionContext::from_system();
27/// assert!(ctx.font_dpi > 0.0);
28///
29/// // Tests: deterministic values.
30/// let ctx = ResolutionContext::for_tests();
31/// assert_eq!(ctx.font_dpi, 96.0);
32/// assert!(ctx.icon_theme.is_none());
33/// ```
34#[derive(Clone, Debug)]
35pub struct ResolutionContext {
36    /// Font DPI for pt-to-px conversion. It must be finite and positive:
37    /// resolution rejects any other value as one
38    /// [`Error::ResolutionInvalid`](crate::Error::ResolutionInvalid) on the
39    /// path `context.font_dpi`, before any point size is converted.
40    ///
41    /// [`from_system`](Self::from_system) gives the platform's: 72.0 on macOS,
42    /// where a point is a pixel, and 96.0 everywhere else, every Linux desktop
43    /// included. Nothing is detected or cached. On Linux the toolkit's scale
44    /// factor carries the display's scale (from the compositor on Wayland, from
45    /// `Xft.dpi` on X11), so the font DPI carries none of it; GNOME's
46    /// text-scaling factor is carried in
47    /// [`AccessibilityPreferences`](crate::AccessibilityPreferences). When the OS
48    /// theme is read ([`SystemTheme::from_system`](crate::SystemTheme::from_system)),
49    /// the reader's own DPI, the same value, replaces it.
50    ///
51    /// That font DPI is not right in these cases, where the application passes
52    /// a font DPI of its own:
53    ///
54    /// - where the application, not the toolkit, decides the X11 scale
55    ///   (`GPUI_X11_SCALE_FACTOR`, `WINIT_X11_SCALE_FACTOR`);
56    /// - on X11 without `Xft.dpi`, where gpui and winit scale the whole
57    ///   interface by the monitor's size (gpui-fast by `GDK_SCALE` where the
58    ///   session sets it) and Qt does not (text and interface stay in
59    ///   proportion, at the toolkit's size);
60    /// - on Plasma 6.7 X11 with a global scale other than 1 and a forced font
61    ///   DPI that departs from it, where Qt takes its scale from
62    ///   `QT_SCREEN_SCALE_FACTORS` and gpui and winit from `Xft.dpi`;
63    /// - for a toolkit that does not scale by `Xft.dpi` on X11 (none of the
64    ///   three connectors').
65    ///
66    /// On the preset and TOML paths the application builds its own context and
67    /// resolves with it ([`Theme::resolve_with`](crate::Theme::resolve_with),
68    /// [`ThemeMode::into_resolved`](crate::theme::ThemeMode::into_resolved)):
69    ///
70    /// ```
71    /// use native_theme::resolve::ResolutionContext;
72    /// use native_theme::theme::{ColorMode, Resolved, Theme};
73    ///
74    /// /// Resolves `kde-breeze` at the font DPI the application decided.
75    /// fn resolve_at(dpi: f32) -> native_theme::Result<Resolved> {
76    ///     let ctx = ResolutionContext { font_dpi: dpi, ..ResolutionContext::from_system() };
77    ///     Theme::preset("kde-breeze")?.resolve_with(ColorMode::Light, &ctx)
78    /// }
79    /// ```
80    ///
81    /// [`SystemTheme::from_system`](crate::SystemTheme::from_system) takes no
82    /// font DPI, so on that path the application re-derives its sizes from each
83    /// resolved font's
84    /// [`defined_size`](crate::theme::ResolvedFontSpec::defined_size). The text
85    /// scale's entries carry no `defined_size`, so their sizes cannot be
86    /// re-derived.
87    pub font_dpi: f32,
88    /// Dialog button ordering (`PrimaryLeft` on KDE and Windows,
89    /// `PrimaryRight` elsewhere).
90    pub button_order: DialogButtonOrder,
91    /// Runtime-detected icon theme name, used when the preset and
92    /// per-variant `icon_theme` fields are both `None`. Three-tier
93    /// precedence in the pipeline: per-variant → `Theme`-level shared →
94    /// this runtime detection.
95    ///
96    /// [`from_system`](Self::from_system) puts the detected system icon
97    /// theme here, or `None` where detection failed;
98    /// [`system_icon_theme()`](crate::detect::system_icon_theme) gives the
99    /// reason.
100    pub icon_theme: Option<Cow<'static, str>>,
101}
102
103impl ResolutionContext {
104    /// Build the context of the running platform:
105    ///
106    /// - `font_dpi`: 72.0 on macOS and 96.0 everywhere else, a constant per
107    ///   platform (nothing is read);
108    /// - `button_order`: `PrimaryLeft` on Windows and on a KDE desktop,
109    ///   `PrimaryRight` elsewhere;
110    /// - `icon_theme`: the system icon theme
111    ///   ([`crate::detect::system_icon_theme`]), `None` where detection fails.
112    #[must_use]
113    pub fn from_system() -> Self {
114        Self::with_detected_icon_theme(crate::detect::system_icon_theme())
115    }
116
117    /// [`from_system`](Self::from_system), with `detected` as the outcome
118    /// of the icon theme's detection.
119    pub(crate) fn with_detected_icon_theme(detected: crate::Result<String>) -> Self {
120        Self::with_font_dpi(crate::detect::system_font_dpi(), detected)
121    }
122
123    /// [`from_system`](Self::from_system) with a `font_dpi` already known,
124    /// such as the one a platform reader reported.
125    /// `detected` is the outcome of the icon theme's detection.
126    pub(crate) fn with_font_dpi(font_dpi: f32, detected: crate::Result<String>) -> Self {
127        Self {
128            font_dpi,
129            button_order: crate::resolve::inheritance::platform_button_order(),
130            icon_theme: detected.ok().map(Cow::Owned),
131        }
132    }
133
134    /// Deterministic values for tests: 96 DPI, `PrimaryRight` button
135    /// order, no detected `icon_theme`.
136    ///
137    /// Tests that need a specific DPI (e.g. 72.0 for Apple point→pixel)
138    /// can construct the struct via a literal:
139    /// `ResolutionContext { font_dpi: 72.0, ..ResolutionContext::for_tests() }`.
140    #[must_use]
141    pub fn for_tests() -> Self {
142        Self {
143            font_dpi: 96.0,
144            button_order: DialogButtonOrder::PrimaryRight,
145            icon_theme: None,
146        }
147    }
148}
149
150// Intentionally NO `impl Default for ResolutionContext`.
151// See module-level doc comment for the signal-intent rationale.
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn with_font_dpi_is_its_arguments() {
159        // The pipeline's constructor when the reader supplied a DPI: the
160        // context holds that DPI and the given icon-theme outcome, plus
161        // the platform's button order; no DPI detection replaces either.
162        let ctx = ResolutionContext::with_font_dpi(
163            123.3,
164            Err(crate::Error::PlatformUnsupported {
165                platform: "the test's failing detection",
166            }),
167        );
168        assert_eq!(ctx.font_dpi, 123.3);
169        assert!(ctx.icon_theme.is_none());
170        assert_eq!(
171            ctx.button_order,
172            crate::resolve::inheritance::platform_button_order()
173        );
174
175        let ctx = ResolutionContext::with_font_dpi(144.0, Ok("detected-theme".to_string()));
176        assert_eq!(ctx.font_dpi, 144.0);
177        assert_eq!(ctx.icon_theme.as_deref(), Some("detected-theme"));
178    }
179}