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