Skip to main content

iced_code_editor/
theme.rs

1//! Theming support for the code editor widget.
2//!
3//! Defines the [`Style`] appearance record, the [`Catalog`] trait used to
4//! derive a `Style` from an `iced::Theme`, and helpers to build a default
5//! style from any Iced theme's palette.
6
7use iced::Color;
8
9/// The appearance of a code editor.
10#[derive(Debug, Clone, Copy)]
11pub struct Style {
12    /// Main editor background color
13    pub background: Color,
14    /// Text content color
15    pub text_color: Color,
16    /// Line numbers gutter background color
17    pub gutter_background: Color,
18    /// Border color for the gutter
19    pub gutter_border: Color,
20    /// Color for line numbers text
21    pub line_number_color: Color,
22    /// Scrollbar background color
23    pub scrollbar_background: Color,
24    /// Scrollbar scroller (thumb) color
25    pub scroller_color: Color,
26    /// Highlight color for the current line where cursor is located
27    pub current_line_highlight: Color,
28    /// Color for visible whitespace characters (spaces as `·`, tabs as `→`)
29    pub whitespace_color: Color,
30    /// Highlight fill color for non-current search matches
31    pub search_match_color: Color,
32    /// Highlight fill color for the currently active search match
33    pub search_match_current_color: Color,
34    /// Fill color for text selection ranges
35    pub selection_color: Color,
36    /// Fill color used to highlight a matching bracket pair
37    pub bracket_match_color: Color,
38    /// Background fill color for the IME preedit (composition) region
39    pub ime_preedit_background_color: Color,
40}
41
42/// The theme catalog of a code editor.
43pub trait Catalog {
44    /// The item class of the [`Catalog`].
45    type Class<'a>;
46
47    /// The default class produced by the [`Catalog`].
48    fn default<'a>() -> Self::Class<'a>;
49
50    /// The [`Style`] of a class with the given status.
51    fn style(&self, class: &Self::Class<'_>) -> Style;
52}
53
54/// A styling function for a code editor.
55///
56/// This is a shorthand for a function that takes a reference to a
57/// [`Theme`](iced::Theme) and returns a [`Style`].
58pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>;
59
60impl Catalog for iced::Theme {
61    type Class<'a> = StyleFn<'a, Self>;
62
63    fn default<'a>() -> Self::Class<'a> {
64        Box::new(from_iced_theme)
65    }
66
67    fn style(&self, class: &Self::Class<'_>) -> Style {
68        class(self)
69    }
70}
71
72/// Creates a theme style automatically from any Iced theme.
73///
74/// This is the default styling function that adapts to all native Iced themes including:
75/// - Basic themes: Light, Dark
76/// - Popular themes: Dracula, Nord, Solarized, Gruvbox
77/// - Catppuccin variants: Latte, Frappé, Macchiato, Mocha
78/// - Tokyo Night variants: Tokyo Night, Storm, Light
79/// - Kanagawa variants: Wave, Dragon, Lotus
80/// - And more: Moonfly, Nightfly, Oxocarbon, Ferra
81///
82/// The function automatically detects if the theme is dark or light and adjusts
83/// colors accordingly for optimal contrast and readability in code editing.
84///
85/// # Color Mapping
86///
87/// - `background`: Uses the theme's base background color
88/// - `text_color`: Uses the theme's base text color
89/// - `gutter_background`: Slightly darker/lighter than background
90/// - `gutter_border`: Border between gutter and editor
91/// - `line_number_color`: Dimmed text color for subtle line numbers
92/// - `scrollbar_background`: Matches editor background
93/// - `scroller_color`: Uses secondary color for visibility
94/// - `current_line_highlight`: Subtle highlight using primary color
95///
96/// # Example
97///
98/// ```
99/// use iced_code_editor::theme;
100///
101/// let tokyo_night = iced::Theme::TokyoNightStorm;
102/// let style = theme::from_iced_theme(&tokyo_night);
103///
104/// // Or use with any theme variant
105/// let dracula = iced::Theme::Dracula;
106/// let style = theme::from_iced_theme(&dracula);
107/// ```
108pub fn from_iced_theme(theme: &iced::Theme) -> Style {
109    let palette = theme.extended_palette();
110    let is_dark = palette.is_dark;
111
112    // Base colors from theme palette
113    let background = palette.background.base.color;
114    let text_color = palette.background.base.text;
115
116    // Gutter colors: slightly offset from background for subtle distinction
117    let gutter_background = palette.background.weak.color;
118    let gutter_border = if is_dark {
119        darken(palette.background.strong.color, 0.1)
120    } else {
121        lighten(palette.background.strong.color, 0.1)
122    };
123
124    // Line numbers: dimmed text color for subtlety
125    // For dark themes: dim the bright text (make it darker)
126    // For light themes: blend text towards background (make it lighter/grayer)
127    let line_number_color = if is_dark {
128        dim_color(text_color, 0.5)
129    } else {
130        // For light themes, blend text color towards background
131        blend_colors(text_color, background, 0.5)
132    };
133
134    // Scrollbar colors: blend with background
135    let scrollbar_background = background;
136    let scroller_color = palette.secondary.weak.color;
137
138    // Current line highlight: very subtle with primary color
139    let current_line_highlight = with_alpha(
140        palette.primary.weak.color,
141        if is_dark { 0.15 } else { 0.25 },
142    );
143
144    let whitespace_color = if is_dark {
145        dim_color(text_color, 0.65)
146    } else {
147        blend_colors(text_color, background, 0.65)
148    };
149
150    // Search matches: orange for the current match, yellow for the rest.
151    // Fixed values (not palette-derived) to preserve the conventional
152    // search-highlight look regardless of the active theme.
153    let search_match_color = Color { r: 1.0, g: 1.0, b: 0.0, a: 0.3 };
154    let search_match_current_color = Color { r: 1.0, g: 0.6, b: 0.0, a: 0.4 };
155
156    // Text selection fill.
157    let selection_color = Color { r: 0.3, g: 0.5, b: 0.8, a: 0.3 };
158
159    // Matching bracket/quote pair highlight.
160    let bracket_match_color = Color { r: 0.5, g: 0.5, b: 0.5, a: 0.4 };
161
162    // IME preedit (composition) background.
163    let ime_preedit_background_color =
164        Color { r: 1.0, g: 1.0, b: 1.0, a: 0.08 };
165
166    Style {
167        background,
168        text_color,
169        gutter_background,
170        gutter_border,
171        line_number_color,
172        scrollbar_background,
173        scroller_color,
174        current_line_highlight,
175        whitespace_color,
176        search_match_color,
177        search_match_current_color,
178        selection_color,
179        bracket_match_color,
180        ime_preedit_background_color,
181    }
182}
183
184/// Darkens a color by a given factor (0.0 to 1.0).
185fn darken(color: Color, factor: f32) -> Color {
186    Color {
187        r: color.r * (1.0 - factor),
188        g: color.g * (1.0 - factor),
189        b: color.b * (1.0 - factor),
190        a: color.a,
191    }
192}
193
194/// Lightens a color by a given factor (0.0 to 1.0).
195fn lighten(color: Color, factor: f32) -> Color {
196    Color {
197        r: color.r + (1.0 - color.r) * factor,
198        g: color.g + (1.0 - color.g) * factor,
199        b: color.b + (1.0 - color.b) * factor,
200        a: color.a,
201    }
202}
203
204/// Dims a color by reducing its intensity.
205fn dim_color(color: Color, factor: f32) -> Color {
206    Color {
207        r: color.r * factor,
208        g: color.g * factor,
209        b: color.b * factor,
210        a: color.a,
211    }
212}
213
214/// Blends two colors together by a given factor (0.0 = first color, 1.0 = second color).
215fn blend_colors(color1: Color, color2: Color, factor: f32) -> Color {
216    Color {
217        r: color1.r + (color2.r - color1.r) * factor,
218        g: color1.g + (color2.g - color1.g) * factor,
219        b: color1.b + (color2.b - color1.b) * factor,
220        a: color1.a + (color2.a - color1.a) * factor,
221    }
222}
223
224/// Applies an alpha transparency to a color.
225fn with_alpha(color: Color, alpha: f32) -> Color {
226    Color { r: color.r, g: color.g, b: color.b, a: alpha }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn test_from_iced_theme_dark() {
235        let theme = iced::Theme::Dark;
236        let style = from_iced_theme(&theme);
237
238        // Dark theme should have dark background
239        let brightness =
240            (style.background.r + style.background.g + style.background.b)
241                / 3.0;
242        assert!(brightness < 0.5, "Dark theme should have dark background");
243
244        // Text should be bright for contrast
245        let text_brightness =
246            (style.text_color.r + style.text_color.g + style.text_color.b)
247                / 3.0;
248        assert!(text_brightness > 0.5, "Dark theme should have bright text");
249    }
250
251    #[test]
252    fn test_from_iced_theme_light() {
253        let theme = iced::Theme::Light;
254        let style = from_iced_theme(&theme);
255
256        // Light theme should have bright background
257        let brightness =
258            (style.background.r + style.background.g + style.background.b)
259                / 3.0;
260        assert!(brightness > 0.5, "Light theme should have bright background");
261
262        // Text should be dark for contrast
263        let text_brightness =
264            (style.text_color.r + style.text_color.g + style.text_color.b)
265                / 3.0;
266        assert!(text_brightness < 0.5, "Light theme should have dark text");
267    }
268
269    #[test]
270    fn test_all_iced_themes_produce_valid_styles() {
271        // Test all native Iced themes
272        for theme in iced::Theme::ALL {
273            let style = from_iced_theme(theme);
274
275            // All color components should be valid (0.0 to 1.0)
276            assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
277            assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
278            assert!(
279                style.gutter_background.r >= 0.0
280                    && style.gutter_background.r <= 1.0
281            );
282            assert!(
283                style.line_number_color.r >= 0.0
284                    && style.line_number_color.r <= 1.0
285            );
286
287            // Current line highlight should have transparency
288            assert!(
289                style.current_line_highlight.a < 1.0,
290                "Current line highlight should be semi-transparent for theme: {:?}",
291                theme
292            );
293
294            // New overlay colors should have valid components and visible
295            // (but not opaque) alpha for every theme.
296            for (name, color) in [
297                ("search_match_color", style.search_match_color),
298                (
299                    "search_match_current_color",
300                    style.search_match_current_color,
301                ),
302                ("selection_color", style.selection_color),
303                ("bracket_match_color", style.bracket_match_color),
304                (
305                    "ime_preedit_background_color",
306                    style.ime_preedit_background_color,
307                ),
308            ] {
309                assert!(
310                    color.r >= 0.0 && color.r <= 1.0,
311                    "{name}.r out of range for theme: {theme:?}"
312                );
313                assert!(
314                    color.g >= 0.0 && color.g <= 1.0,
315                    "{name}.g out of range for theme: {theme:?}"
316                );
317                assert!(
318                    color.b >= 0.0 && color.b <= 1.0,
319                    "{name}.b out of range for theme: {theme:?}"
320                );
321                assert!(
322                    color.a > 0.0 && color.a < 1.0,
323                    "{name} should be semi-transparent for theme: {theme:?}"
324                );
325            }
326        }
327    }
328
329    #[test]
330    fn test_overlay_colors_are_theme_independent() {
331        // The 5 overlay colors are fixed constants (not palette-derived), so
332        // they must be identical across very different themes.
333        let light = from_iced_theme(&iced::Theme::Light);
334        let dark = from_iced_theme(&iced::Theme::Dark);
335
336        for (light_color, dark_color) in [
337            (light.search_match_color, dark.search_match_color),
338            (light.search_match_current_color, dark.search_match_current_color),
339            (light.selection_color, dark.selection_color),
340            (light.bracket_match_color, dark.bracket_match_color),
341            (
342                light.ime_preedit_background_color,
343                dark.ime_preedit_background_color,
344            ),
345        ] {
346            assert!((light_color.r - dark_color.r).abs() < f32::EPSILON);
347            assert!((light_color.g - dark_color.g).abs() < f32::EPSILON);
348            assert!((light_color.b - dark_color.b).abs() < f32::EPSILON);
349            assert!((light_color.a - dark_color.a).abs() < f32::EPSILON);
350        }
351    }
352
353    #[test]
354    fn test_tokyo_night_themes() {
355        // Test Tokyo Night variants specifically
356        let tokyo_night = iced::Theme::TokyoNight;
357        let style = from_iced_theme(&tokyo_night);
358        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
359
360        let tokyo_storm = iced::Theme::TokyoNightStorm;
361        let style = from_iced_theme(&tokyo_storm);
362        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
363
364        let tokyo_light = iced::Theme::TokyoNightLight;
365        let style = from_iced_theme(&tokyo_light);
366        let brightness =
367            (style.background.r + style.background.g + style.background.b)
368                / 3.0;
369        assert!(
370            brightness > 0.5,
371            "Tokyo Night Light should have bright background"
372        );
373    }
374
375    #[test]
376    fn test_catppuccin_themes() {
377        // Test Catppuccin variants
378        let themes = [
379            iced::Theme::CatppuccinLatte,
380            iced::Theme::CatppuccinFrappe,
381            iced::Theme::CatppuccinMacchiato,
382            iced::Theme::CatppuccinMocha,
383        ];
384
385        for theme in themes {
386            let style = from_iced_theme(&theme);
387            // All should produce valid styles
388            assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
389            assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
390        }
391    }
392
393    #[test]
394    fn test_gutter_colors_distinct_from_background() {
395        let theme = iced::Theme::Dark;
396        let style = from_iced_theme(&theme);
397
398        // Gutter background should be different from editor background
399        let gutter_diff = (style.gutter_background.r - style.background.r)
400            .abs()
401            + (style.gutter_background.g - style.background.g).abs()
402            + (style.gutter_background.b - style.background.b).abs();
403
404        assert!(
405            gutter_diff > 0.0,
406            "Gutter should be visually distinct from background"
407        );
408    }
409
410    #[test]
411    fn test_line_numbers_visible_but_subtle() {
412        for theme in [iced::Theme::Dark, iced::Theme::Light] {
413            let style = from_iced_theme(&theme);
414            let palette = theme.extended_palette();
415
416            // Line numbers should be dimmed compared to text
417            let line_num_brightness = (style.line_number_color.r
418                + style.line_number_color.g
419                + style.line_number_color.b)
420                / 3.0;
421
422            let text_brightness =
423                (style.text_color.r + style.text_color.g + style.text_color.b)
424                    / 3.0;
425
426            let bg_brightness =
427                (style.background.r + style.background.g + style.background.b)
428                    / 3.0;
429
430            // Line numbers should be between text and background (more subtle than text)
431            // For dark themes: text is bright, line numbers dimmer, background dark
432            // For light themes: text is dark, line numbers lighter (gray), background bright
433            if palette.is_dark {
434                // Dark theme: line numbers should be less bright than text
435                assert!(
436                    line_num_brightness < text_brightness,
437                    "Dark theme line numbers should be dimmer than text. Line num: {}, Text: {}",
438                    line_num_brightness,
439                    text_brightness
440                );
441            } else {
442                // Light theme: line numbers should be between text (dark) and background (bright)
443                assert!(
444                    line_num_brightness > text_brightness
445                        && line_num_brightness < bg_brightness,
446                    "Light theme line numbers should be between text and background. Text: {}, Line num: {}, Bg: {}",
447                    text_brightness,
448                    line_num_brightness,
449                    bg_brightness
450                );
451            }
452        }
453    }
454
455    #[test]
456    fn test_color_helper_functions() {
457        let color = Color::from_rgb(0.5, 0.5, 0.5);
458
459        // Test darken
460        let darker = darken(color, 0.5);
461        assert!(darker.r < color.r);
462        assert!(darker.g < color.g);
463        assert!(darker.b < color.b);
464
465        // Test lighten
466        let lighter = lighten(color, 0.5);
467        assert!(lighter.r > color.r);
468        assert!(lighter.g > color.g);
469        assert!(lighter.b > color.b);
470
471        // Test dim_color
472        let dimmed = dim_color(color, 0.5);
473        assert!(dimmed.r < color.r);
474
475        // Test with_alpha
476        let transparent = with_alpha(color, 0.3);
477        assert!((transparent.a - 0.3).abs() < f32::EPSILON);
478        assert!((transparent.r - color.r).abs() < f32::EPSILON);
479    }
480
481    #[test]
482    fn test_style_copy() {
483        let theme = iced::Theme::Dark;
484        let style1 = from_iced_theme(&theme);
485        let style2 = style1;
486
487        // Verify colors are approximately equal (using epsilon for float comparison)
488        assert!(
489            (style1.background.r - style2.background.r).abs() < f32::EPSILON
490        );
491        assert!(
492            (style1.text_color.r - style2.text_color.r).abs() < f32::EPSILON
493        );
494        assert!(
495            (style1.gutter_background.r - style2.gutter_background.r).abs()
496                < f32::EPSILON
497        );
498        assert!(
499            (style1.selection_color.r - style2.selection_color.r).abs()
500                < f32::EPSILON
501        );
502    }
503
504    #[test]
505    fn test_catalog_default() {
506        let theme = iced::Theme::Dark;
507        let class = <iced::Theme as Catalog>::default();
508        let style = theme.style(&class);
509
510        // Should produce a valid style
511        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
512        assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
513    }
514}