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///
11/// Build one with [`from_iced_theme`] to follow the application's Iced theme,
12/// then override individual fields for anything that needs to differ.
13///
14/// # Examples
15///
16/// ```
17/// use iced_code_editor::{CodeEditor, theme};
18///
19/// let mut style = theme::from_iced_theme(&iced::Theme::TokyoNightStorm);
20///
21/// // Tweak one color while keeping the rest of the derived palette.
22/// style.current_line_highlight = iced::Color::from_rgba(1.0, 1.0, 1.0, 0.05);
23///
24/// let mut editor = CodeEditor::new("fn main() {}", "rs");
25/// editor.set_theme(style);
26/// ```
27#[derive(Debug, Clone, Copy)]
28pub struct Style {
29    /// Main editor background color
30    pub background: Color,
31    /// Text content color
32    pub text_color: Color,
33    /// Line numbers gutter background color
34    pub gutter_background: Color,
35    /// Border color for the gutter
36    pub gutter_border: Color,
37    /// Color for line numbers text
38    pub line_number_color: Color,
39    /// Scrollbar background color
40    pub scrollbar_background: Color,
41    /// Scrollbar scroller (thumb) color
42    pub scroller_color: Color,
43    /// Highlight color for the current line where cursor is located
44    pub current_line_highlight: Color,
45    /// Color for visible whitespace characters (spaces as `·`, tabs as `→`)
46    pub whitespace_color: Color,
47    /// Color of the vertical indentation guides drawn behind the text
48    pub indent_guide_color: Color,
49    /// Highlight fill color for non-current search matches
50    pub search_match_color: Color,
51    /// Highlight fill color for the currently active search match
52    pub search_match_current_color: Color,
53    /// Fill color for text selection ranges
54    pub selection_color: Color,
55    /// Fill color used to highlight a matching bracket pair
56    pub bracket_match_color: Color,
57    /// Background fill color for the IME preedit (composition) region
58    pub ime_preedit_background_color: Color,
59}
60
61/// The theme catalog of a code editor.
62///
63/// Implemented for [`iced::Theme`] out of the box, following the same catalog
64/// pattern Iced's own widgets use. Implement it for a custom theme type to
65/// make this editor themable alongside the rest of an application.
66///
67/// # Examples
68///
69/// ```
70/// use iced_code_editor::theme::{Catalog, Style};
71///
72/// // `iced::Theme` implements `Catalog`, so a style comes from the theme
73/// // itself rather than being hardcoded.
74/// let class = <iced::Theme as Catalog>::default();
75/// let style: Style = Catalog::style(&iced::Theme::Dracula, &class);
76///
77/// // A dark theme yields a dark editor background.
78/// assert!(style.background.r < 0.5);
79/// ```
80pub trait Catalog {
81    /// The item class of the [`Catalog`].
82    type Class<'a>;
83
84    /// The default class produced by the [`Catalog`].
85    fn default<'a>() -> Self::Class<'a>;
86
87    /// The [`Style`] of a class with the given status.
88    fn style(&self, class: &Self::Class<'_>) -> Style;
89}
90
91/// A styling function for a code editor.
92///
93/// This is a shorthand for a function that takes a reference to a
94/// [`Theme`](iced::Theme) and returns a [`Style`].
95///
96/// # Examples
97///
98/// ```
99/// use iced_code_editor::theme::{self, Style, StyleFn};
100///
101/// // A styling function that derives from the theme, then dims the gutter.
102/// let styling: StyleFn<'_, iced::Theme> = Box::new(|theme| {
103///     let mut style = theme::from_iced_theme(theme);
104///     style.line_number_color.a *= 0.5;
105///     style
106/// });
107///
108/// let style: Style = styling(&iced::Theme::Dracula);
109/// assert!(style.line_number_color.a < 1.0);
110/// ```
111pub type StyleFn<'a, Theme> = Box<dyn Fn(&Theme) -> Style + 'a>;
112
113impl Catalog for iced::Theme {
114    type Class<'a> = StyleFn<'a, Self>;
115
116    fn default<'a>() -> Self::Class<'a> {
117        Box::new(from_iced_theme)
118    }
119
120    fn style(&self, class: &Self::Class<'_>) -> Style {
121        class(self)
122    }
123}
124
125/// Creates a theme style automatically from any Iced theme.
126///
127/// This is the default styling function that adapts to all native Iced themes including:
128/// - Basic themes: Light, Dark
129/// - Popular themes: Dracula, Nord, Solarized, Gruvbox
130/// - Catppuccin variants: Latte, Frappé, Macchiato, Mocha
131/// - Tokyo Night variants: Tokyo Night, Storm, Light
132/// - Kanagawa variants: Wave, Dragon, Lotus
133/// - And more: Moonfly, Nightfly, Oxocarbon, Ferra
134///
135/// The function automatically detects if the theme is dark or light and adjusts
136/// colors accordingly for optimal contrast and readability in code editing.
137///
138/// # Color Mapping
139///
140/// - `background`: Uses the theme's base background color
141/// - `text_color`: Uses the theme's base text color
142/// - `gutter_background`: Slightly darker/lighter than background
143/// - `gutter_border`: Border between gutter and editor
144/// - `line_number_color`: Dimmed text color for subtle line numbers
145/// - `scrollbar_background`: Matches editor background
146/// - `scroller_color`: Uses secondary color for visibility
147/// - `current_line_highlight`: Subtle highlight using primary color
148///
149/// # Example
150///
151/// ```
152/// use iced_code_editor::theme;
153///
154/// let tokyo_night = iced::Theme::TokyoNightStorm;
155/// let style = theme::from_iced_theme(&tokyo_night);
156///
157/// // Or use with any theme variant
158/// let dracula = iced::Theme::Dracula;
159/// let style = theme::from_iced_theme(&dracula);
160/// ```
161pub fn from_iced_theme(theme: &iced::Theme) -> Style {
162    let palette = theme.extended_palette();
163    let is_dark = palette.is_dark;
164
165    // Base colors from theme palette
166    let background = palette.background.base.color;
167    let text_color = palette.background.base.text;
168
169    // Gutter colors: slightly offset from background for subtle distinction
170    let gutter_background = palette.background.weak.color;
171    let gutter_border = if is_dark {
172        darken(palette.background.strong.color, 0.1)
173    } else {
174        lighten(palette.background.strong.color, 0.1)
175    };
176
177    // Line numbers: dimmed text color for subtlety
178    // For dark themes: dim the bright text (make it darker)
179    // For light themes: blend text towards background (make it lighter/grayer)
180    let line_number_color = if is_dark {
181        dim_color(text_color, 0.5)
182    } else {
183        // For light themes, blend text color towards background
184        blend_colors(text_color, background, 0.5)
185    };
186
187    // Scrollbar colors: blend with background
188    let scrollbar_background = background;
189    let scroller_color = palette.secondary.weak.color;
190
191    // Current line highlight: very subtle with primary color
192    let current_line_highlight = with_alpha(
193        palette.primary.weak.color,
194        if is_dark { 0.15 } else { 0.25 },
195    );
196
197    let whitespace_color = if is_dark {
198        dim_color(text_color, 0.65)
199    } else {
200        blend_colors(text_color, background, 0.65)
201    };
202
203    // Indentation guides: fainter than visible whitespace, since a guide spans
204    // the full line height and would otherwise compete with the code itself.
205    let indent_guide_color =
206        with_alpha(text_color, if is_dark { 0.18 } else { 0.22 });
207
208    // Search matches: orange for the current match, yellow for the rest.
209    // Fixed values (not palette-derived) to preserve the conventional
210    // search-highlight look regardless of the active theme.
211    let search_match_color = Color { r: 1.0, g: 1.0, b: 0.0, a: 0.3 };
212    let search_match_current_color = Color { r: 1.0, g: 0.6, b: 0.0, a: 0.4 };
213
214    // Text selection fill.
215    let selection_color = Color { r: 0.3, g: 0.5, b: 0.8, a: 0.3 };
216
217    // Matching bracket/quote pair highlight.
218    let bracket_match_color = Color { r: 0.5, g: 0.5, b: 0.5, a: 0.4 };
219
220    // IME preedit (composition) background.
221    let ime_preedit_background_color =
222        Color { r: 1.0, g: 1.0, b: 1.0, a: 0.08 };
223
224    Style {
225        background,
226        text_color,
227        gutter_background,
228        gutter_border,
229        line_number_color,
230        scrollbar_background,
231        scroller_color,
232        current_line_highlight,
233        whitespace_color,
234        indent_guide_color,
235        search_match_color,
236        search_match_current_color,
237        selection_color,
238        bracket_match_color,
239        ime_preedit_background_color,
240    }
241}
242
243/// Returns whether `color` is dark enough to need a dark-tuned palette on top
244/// of it.
245///
246/// [`Style`] keeps only the resolved colors, not the `is_dark` flag of the
247/// Iced palette it was derived from, so consumers that must branch on
248/// light/dark -- notably the syntect theme picked by the syntax highlighter --
249/// recover it from the background here. The threshold is applied to the
250/// relative luminance (ITU-R BT.709 coefficients), so a mid-tone yellow reads
251/// as light and a mid-tone blue as dark, the way the eye sees them.
252///
253/// # Arguments
254///
255/// * `color` - The background color to classify
256///
257/// # Returns
258///
259/// `true` when the color is dark, `false` when it is light.
260pub(crate) fn is_dark_background(color: Color) -> bool {
261    let luminance = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
262    luminance < 0.5
263}
264
265/// Darkens a color by a given factor (0.0 to 1.0).
266fn darken(color: Color, factor: f32) -> Color {
267    Color {
268        r: color.r * (1.0 - factor),
269        g: color.g * (1.0 - factor),
270        b: color.b * (1.0 - factor),
271        a: color.a,
272    }
273}
274
275/// Lightens a color by a given factor (0.0 to 1.0).
276fn lighten(color: Color, factor: f32) -> Color {
277    Color {
278        r: color.r + (1.0 - color.r) * factor,
279        g: color.g + (1.0 - color.g) * factor,
280        b: color.b + (1.0 - color.b) * factor,
281        a: color.a,
282    }
283}
284
285/// Dims a color by reducing its intensity.
286fn dim_color(color: Color, factor: f32) -> Color {
287    Color {
288        r: color.r * factor,
289        g: color.g * factor,
290        b: color.b * factor,
291        a: color.a,
292    }
293}
294
295/// Blends two colors together by a given factor (0.0 = first color, 1.0 = second color).
296fn blend_colors(color1: Color, color2: Color, factor: f32) -> Color {
297    Color {
298        r: color1.r + (color2.r - color1.r) * factor,
299        g: color1.g + (color2.g - color1.g) * factor,
300        b: color1.b + (color2.b - color1.b) * factor,
301        a: color1.a + (color2.a - color1.a) * factor,
302    }
303}
304
305/// Applies an alpha transparency to a color.
306fn with_alpha(color: Color, alpha: f32) -> Color {
307    Color { r: color.r, g: color.g, b: color.b, a: alpha }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    #[test]
315    fn test_is_dark_background_classifies_dark_and_light() {
316        // TokyoNightStorm's background.
317        assert!(is_dark_background(Color::from_rgb(0.141, 0.157, 0.231)));
318        assert!(is_dark_background(Color::BLACK));
319
320        // base16-ocean.light's background.
321        assert!(!is_dark_background(Color::from_rgb(0.937, 0.945, 0.961)));
322        assert!(!is_dark_background(Color::WHITE));
323    }
324
325    #[test]
326    fn test_is_dark_background_weights_channels_by_luminance() {
327        // Same numeric intensity in every channel, but green dominates the
328        // luminance formula: pure green reads light, pure blue reads dark.
329        assert!(!is_dark_background(Color::from_rgb(0.0, 1.0, 0.0)));
330        assert!(is_dark_background(Color::from_rgb(0.0, 0.0, 1.0)));
331    }
332
333    #[test]
334    fn test_from_iced_theme_dark() {
335        let theme = iced::Theme::Dark;
336        let style = from_iced_theme(&theme);
337
338        // Dark theme should have dark background
339        let brightness =
340            (style.background.r + style.background.g + style.background.b)
341                / 3.0;
342        assert!(brightness < 0.5, "Dark theme should have dark background");
343
344        // Text should be bright for contrast
345        let text_brightness =
346            (style.text_color.r + style.text_color.g + style.text_color.b)
347                / 3.0;
348        assert!(text_brightness > 0.5, "Dark theme should have bright text");
349    }
350
351    #[test]
352    fn test_from_iced_theme_light() {
353        let theme = iced::Theme::Light;
354        let style = from_iced_theme(&theme);
355
356        // Light theme should have bright background
357        let brightness =
358            (style.background.r + style.background.g + style.background.b)
359                / 3.0;
360        assert!(brightness > 0.5, "Light theme should have bright background");
361
362        // Text should be dark for contrast
363        let text_brightness =
364            (style.text_color.r + style.text_color.g + style.text_color.b)
365                / 3.0;
366        assert!(text_brightness < 0.5, "Light theme should have dark text");
367    }
368
369    #[test]
370    fn test_all_iced_themes_produce_valid_styles() {
371        // Test all native Iced themes
372        for theme in iced::Theme::ALL {
373            let style = from_iced_theme(theme);
374
375            // All color components should be valid (0.0 to 1.0)
376            assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
377            assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
378            assert!(
379                style.gutter_background.r >= 0.0
380                    && style.gutter_background.r <= 1.0
381            );
382            assert!(
383                style.line_number_color.r >= 0.0
384                    && style.line_number_color.r <= 1.0
385            );
386
387            // Current line highlight should have transparency
388            assert!(
389                style.current_line_highlight.a < 1.0,
390                "Current line highlight should be semi-transparent for theme: {:?}",
391                theme
392            );
393
394            // New overlay colors should have valid components and visible
395            // (but not opaque) alpha for every theme.
396            for (name, color) in [
397                ("search_match_color", style.search_match_color),
398                (
399                    "search_match_current_color",
400                    style.search_match_current_color,
401                ),
402                ("selection_color", style.selection_color),
403                ("bracket_match_color", style.bracket_match_color),
404                (
405                    "ime_preedit_background_color",
406                    style.ime_preedit_background_color,
407                ),
408            ] {
409                assert!(
410                    color.r >= 0.0 && color.r <= 1.0,
411                    "{name}.r out of range for theme: {theme:?}"
412                );
413                assert!(
414                    color.g >= 0.0 && color.g <= 1.0,
415                    "{name}.g out of range for theme: {theme:?}"
416                );
417                assert!(
418                    color.b >= 0.0 && color.b <= 1.0,
419                    "{name}.b out of range for theme: {theme:?}"
420                );
421                assert!(
422                    color.a > 0.0 && color.a < 1.0,
423                    "{name} should be semi-transparent for theme: {theme:?}"
424                );
425            }
426        }
427    }
428
429    #[test]
430    fn test_overlay_colors_are_theme_independent() {
431        // The 5 overlay colors are fixed constants (not palette-derived), so
432        // they must be identical across very different themes.
433        let light = from_iced_theme(&iced::Theme::Light);
434        let dark = from_iced_theme(&iced::Theme::Dark);
435
436        for (light_color, dark_color) in [
437            (light.search_match_color, dark.search_match_color),
438            (light.search_match_current_color, dark.search_match_current_color),
439            (light.selection_color, dark.selection_color),
440            (light.bracket_match_color, dark.bracket_match_color),
441            (
442                light.ime_preedit_background_color,
443                dark.ime_preedit_background_color,
444            ),
445        ] {
446            assert!((light_color.r - dark_color.r).abs() < f32::EPSILON);
447            assert!((light_color.g - dark_color.g).abs() < f32::EPSILON);
448            assert!((light_color.b - dark_color.b).abs() < f32::EPSILON);
449            assert!((light_color.a - dark_color.a).abs() < f32::EPSILON);
450        }
451    }
452
453    #[test]
454    fn test_tokyo_night_themes() {
455        // Test Tokyo Night variants specifically
456        let tokyo_night = iced::Theme::TokyoNight;
457        let style = from_iced_theme(&tokyo_night);
458        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
459
460        let tokyo_storm = iced::Theme::TokyoNightStorm;
461        let style = from_iced_theme(&tokyo_storm);
462        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
463
464        let tokyo_light = iced::Theme::TokyoNightLight;
465        let style = from_iced_theme(&tokyo_light);
466        let brightness =
467            (style.background.r + style.background.g + style.background.b)
468                / 3.0;
469        assert!(
470            brightness > 0.5,
471            "Tokyo Night Light should have bright background"
472        );
473    }
474
475    #[test]
476    fn test_catppuccin_themes() {
477        // Test Catppuccin variants
478        let themes = [
479            iced::Theme::CatppuccinLatte,
480            iced::Theme::CatppuccinFrappe,
481            iced::Theme::CatppuccinMacchiato,
482            iced::Theme::CatppuccinMocha,
483        ];
484
485        for theme in themes {
486            let style = from_iced_theme(&theme);
487            // All should produce valid styles
488            assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
489            assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
490        }
491    }
492
493    #[test]
494    fn test_gutter_colors_distinct_from_background() {
495        let theme = iced::Theme::Dark;
496        let style = from_iced_theme(&theme);
497
498        // Gutter background should be different from editor background
499        let gutter_diff = (style.gutter_background.r - style.background.r)
500            .abs()
501            + (style.gutter_background.g - style.background.g).abs()
502            + (style.gutter_background.b - style.background.b).abs();
503
504        assert!(
505            gutter_diff > 0.0,
506            "Gutter should be visually distinct from background"
507        );
508    }
509
510    #[test]
511    fn test_line_numbers_visible_but_subtle() {
512        for theme in [iced::Theme::Dark, iced::Theme::Light] {
513            let style = from_iced_theme(&theme);
514            let palette = theme.extended_palette();
515
516            // Line numbers should be dimmed compared to text
517            let line_num_brightness = (style.line_number_color.r
518                + style.line_number_color.g
519                + style.line_number_color.b)
520                / 3.0;
521
522            let text_brightness =
523                (style.text_color.r + style.text_color.g + style.text_color.b)
524                    / 3.0;
525
526            let bg_brightness =
527                (style.background.r + style.background.g + style.background.b)
528                    / 3.0;
529
530            // Line numbers should be between text and background (more subtle than text)
531            // For dark themes: text is bright, line numbers dimmer, background dark
532            // For light themes: text is dark, line numbers lighter (gray), background bright
533            if palette.is_dark {
534                // Dark theme: line numbers should be less bright than text
535                assert!(
536                    line_num_brightness < text_brightness,
537                    "Dark theme line numbers should be dimmer than text. Line num: {}, Text: {}",
538                    line_num_brightness,
539                    text_brightness
540                );
541            } else {
542                // Light theme: line numbers should be between text (dark) and background (bright)
543                assert!(
544                    line_num_brightness > text_brightness
545                        && line_num_brightness < bg_brightness,
546                    "Light theme line numbers should be between text and background. Text: {}, Line num: {}, Bg: {}",
547                    text_brightness,
548                    line_num_brightness,
549                    bg_brightness
550                );
551            }
552        }
553    }
554
555    #[test]
556    fn test_color_helper_functions() {
557        let color = Color::from_rgb(0.5, 0.5, 0.5);
558
559        // Test darken
560        let darker = darken(color, 0.5);
561        assert!(darker.r < color.r);
562        assert!(darker.g < color.g);
563        assert!(darker.b < color.b);
564
565        // Test lighten
566        let lighter = lighten(color, 0.5);
567        assert!(lighter.r > color.r);
568        assert!(lighter.g > color.g);
569        assert!(lighter.b > color.b);
570
571        // Test dim_color
572        let dimmed = dim_color(color, 0.5);
573        assert!(dimmed.r < color.r);
574
575        // Test with_alpha
576        let transparent = with_alpha(color, 0.3);
577        assert!((transparent.a - 0.3).abs() < f32::EPSILON);
578        assert!((transparent.r - color.r).abs() < f32::EPSILON);
579    }
580
581    #[test]
582    fn test_style_copy() {
583        let theme = iced::Theme::Dark;
584        let style1 = from_iced_theme(&theme);
585        let style2 = style1;
586
587        // Verify colors are approximately equal (using epsilon for float comparison)
588        assert!(
589            (style1.background.r - style2.background.r).abs() < f32::EPSILON
590        );
591        assert!(
592            (style1.text_color.r - style2.text_color.r).abs() < f32::EPSILON
593        );
594        assert!(
595            (style1.gutter_background.r - style2.gutter_background.r).abs()
596                < f32::EPSILON
597        );
598        assert!(
599            (style1.selection_color.r - style2.selection_color.r).abs()
600                < f32::EPSILON
601        );
602    }
603
604    #[test]
605    fn test_catalog_default() {
606        let theme = iced::Theme::Dark;
607        let class = <iced::Theme as Catalog>::default();
608        let style = theme.style(&class);
609
610        // Should produce a valid style
611        assert!(style.background.r >= 0.0 && style.background.r <= 1.0);
612        assert!(style.text_color.r >= 0.0 && style.text_color.r <= 1.0);
613    }
614}