Skip to main content

iced_code_editor/canvas_editor/
metrics.rs

1//! Layout metrics: font/character/line dimensions, viewport size, and the
2//! gutter-width constants and calculations derived from them.
3
4use iced::advanced::text::{
5    Alignment, Paragraph, Renderer as TextRenderer, Text,
6};
7use std::cmp::Ordering as CmpOrdering;
8use unicode_width::UnicodeWidthChar;
9
10use crate::canvas_editor::CodeEditor;
11
12/// Canvas-based text editor constants
13pub(crate) const FONT_SIZE: f32 = 14.0;
14pub(crate) const LINE_HEIGHT: f32 = 20.0;
15pub(crate) const CHAR_WIDTH: f32 = 8.4; // Monospace character width
16pub(crate) const TAB_WIDTH: usize = 4;
17pub(crate) const GUTTER_WIDTH: f32 = 45.0;
18/// Width in pixels of the fold margin (chevron column) added to the gutter when
19/// code folding is enabled.
20pub(crate) const FOLD_MARGIN_WIDTH: f32 = 14.0;
21pub(crate) const CURSOR_BLINK_INTERVAL: std::time::Duration =
22    std::time::Duration::from_millis(530);
23
24/// Measures the width of a single character.
25///
26/// # Arguments
27///
28/// * `c` - The character to measure
29/// * `full_char_width` - The width of a full-width character
30/// * `char_width` - The width of the character
31///
32/// # Returns
33///
34/// The calculated width of the character as a `f32`
35pub(crate) fn measure_char_width(
36    c: char,
37    full_char_width: f32,
38    char_width: f32,
39) -> f32 {
40    if c == '\t' {
41        return char_width * TAB_WIDTH as f32;
42    }
43    match c.width() {
44        Some(w) if w > 1 => full_char_width,
45        Some(_) => char_width,
46        None => 0.0,
47    }
48}
49
50/// Measures rendered text width, accounting for CJK wide characters.
51///
52/// - Wide characters (e.g. Chinese) use FONT_SIZE.
53/// - Narrow characters (e.g. Latin) use CHAR_WIDTH.
54/// - Control characters (except tab) have width 0.
55///
56/// # Arguments
57///
58/// * `text` - The text string to measure
59/// * `full_char_width` - The width of a full-width character
60/// * `char_width` - The width of a regular character
61///
62/// # Returns
63///
64/// The total calculated width of the text as a `f32`
65pub(crate) fn measure_text_width(
66    text: &str,
67    full_char_width: f32,
68    char_width: f32,
69) -> f32 {
70    text.chars()
71        .map(|c| measure_char_width(c, full_char_width, char_width))
72        .sum()
73}
74
75/// Epsilon value for floating-point comparisons in text layout.
76pub(crate) const EPSILON: f32 = 0.001;
77/// Multiplier used to extend the cached render window beyond the visible range.
78/// The cache window margin is computed as:
79///     margin = visible_lines_count * CACHE_WINDOW_MARGIN_MULTIPLIER
80/// A larger margin reduces how often we clear and rebuild the canvas cache when
81/// scrolling, improving performance on very large files while still ensuring
82/// correct initial rendering during the first scroll.
83pub(crate) const CACHE_WINDOW_MARGIN_MULTIPLIER: usize = 2;
84/// Maximum number of previously unseen logical lines syntect may parse while
85/// rebuilding one content frame.
86///
87/// Syntax state is sequential, so jumping far into a large file can otherwise
88/// parse every line from the start in one blocking draw call. Lines beyond this
89/// budget temporarily use the editor's plain text color and will be highlighted
90/// as later content redraws advance the cached parser state.
91pub(crate) const HIGHLIGHT_LINES_PER_FRAME: usize = 2_000;
92
93/// Compares two floating point numbers with a small epsilon tolerance.
94///
95/// # Arguments
96///
97/// * `a` - first float number
98/// * `b` - second float number
99///
100/// # Returns
101///
102/// * `Ordering::Equal` if `abs(a - b) < EPSILON`
103/// * `Ordering::Greater` if `a > b` (and not equal)
104/// * `Ordering::Less` if `a < b` (and not equal)
105pub(crate) fn compare_floats(a: f32, b: f32) -> CmpOrdering {
106    if (a - b).abs() < EPSILON {
107        CmpOrdering::Equal
108    } else if a > b {
109        CmpOrdering::Greater
110    } else {
111        CmpOrdering::Less
112    }
113}
114
115impl CodeEditor {
116    /// Sets the font used by the editor
117    ///
118    /// Character dimensions are re-measured with the new font, but the line
119    /// height is left alone — use [`Self::set_line_height`] to change it.
120    ///
121    /// # Arguments
122    ///
123    /// * `font` - The iced font to set for the editor
124    ///
125    /// # Example
126    ///
127    /// ```
128    /// use iced_code_editor::CodeEditor;
129    ///
130    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
131    /// editor.set_font(iced::Font::MONOSPACE);
132    ///
133    /// // Character widths are re-measured for the new font.
134    /// assert!(editor.char_width() > 0.0);
135    /// ```
136    pub fn set_font(&mut self, font: iced::Font) {
137        self.font = font;
138        self.recalculate_char_dimensions(false);
139    }
140
141    /// Sets the font size and recalculates character dimensions.
142    ///
143    /// If `auto_adjust_line_height` is true, `line_height` will also be scaled to maintain
144    /// the default proportion (Line Height ~ 1.43x).
145    ///
146    /// # Arguments
147    ///
148    /// * `size` - The font size in pixels
149    /// * `auto_adjust_line_height` - Whether to automatically adjust the line height
150    ///
151    /// # Example
152    ///
153    /// ```
154    /// use iced_code_editor::CodeEditor;
155    ///
156    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
157    ///
158    /// // Scale the line height along with the font, the usual "zoom" case.
159    /// editor.set_font_size(28.0, true);
160    /// assert!((editor.font_size() - 28.0).abs() < f32::EPSILON);
161    /// // Doubling 14px doubles the 20px default line height.
162    /// assert!((editor.line_height() - 40.0).abs() < f32::EPSILON);
163    ///
164    /// // Or keep a line height the host controls itself.
165    /// editor.set_font_size(14.0, false);
166    /// assert!((editor.line_height() - 40.0).abs() < f32::EPSILON);
167    /// ```
168    pub fn set_font_size(&mut self, size: f32, auto_adjust_line_height: bool) {
169        self.font_size = size;
170        self.recalculate_char_dimensions(auto_adjust_line_height);
171    }
172
173    /// Recalculates character dimensions based on current font and size.
174    pub(crate) fn recalculate_char_dimensions(
175        &mut self,
176        auto_adjust_line_height: bool,
177    ) {
178        self.char_width = self.measure_single_char_width("a");
179        // Use '汉' as a standard reference for CJK (Chinese, Japanese, Korean) wide characters
180        self.full_char_width = self.measure_single_char_width("汉");
181
182        // Fallback for infinite width measurements
183        if self.char_width.is_infinite() {
184            self.char_width = self.font_size / 2.0; // Rough estimate for monospace
185        }
186
187        if self.full_char_width.is_infinite() {
188            self.full_char_width = self.font_size;
189        }
190
191        if auto_adjust_line_height {
192            let line_height_ratio = LINE_HEIGHT / FONT_SIZE;
193            self.line_height = self.font_size * line_height_ratio;
194        }
195
196        self.content_cache.clear();
197        self.overlay_cache.clear();
198        *self.max_content_width_cache.borrow_mut() = None;
199    }
200
201    /// Measures the width of a single character string using the current font settings.
202    fn measure_single_char_width(&self, content: &str) -> f32 {
203        let text = Text {
204            content,
205            font: self.font,
206            size: iced::Pixels(self.font_size),
207            line_height: iced::advanced::text::LineHeight::default(),
208            bounds: iced::Size::new(f32::INFINITY, f32::INFINITY),
209            align_x: Alignment::Left,
210            align_y: iced::alignment::Vertical::Top,
211            shaping: iced::advanced::text::Shaping::Advanced,
212            wrapping: iced::advanced::text::Wrapping::default(),
213        };
214        let p = <iced::Renderer as TextRenderer>::Paragraph::with_text(text);
215        p.min_width()
216    }
217
218    /// Returns the current font size.
219    ///
220    /// # Returns
221    ///
222    /// The font size in pixels
223    ///
224    /// # Example
225    ///
226    /// ```
227    /// use iced_code_editor::CodeEditor;
228    ///
229    /// let editor = CodeEditor::new("fn main() {}", "rs");
230    /// assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
231    /// ```
232    pub fn font_size(&self) -> f32 {
233        self.font_size
234    }
235
236    /// Returns the width of a standard narrow character in pixels.
237    ///
238    /// Measured from the current font rather than assumed, so it stays correct
239    /// after [`Self::set_font`] or [`Self::set_font_size`].
240    ///
241    /// # Returns
242    ///
243    /// The character width in pixels
244    ///
245    /// # Example
246    ///
247    /// ```
248    /// use iced_code_editor::CodeEditor;
249    ///
250    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
251    /// let narrow = editor.char_width();
252    /// assert!(narrow > 0.0);
253    ///
254    /// // A larger font measures wider characters.
255    /// editor.set_font_size(28.0, true);
256    /// assert!(editor.char_width() > narrow);
257    /// ```
258    pub fn char_width(&self) -> f32 {
259        self.char_width
260    }
261
262    /// Returns the width of a wide character (e.g. CJK) in pixels.
263    ///
264    /// Measured from `汉` as the reference glyph. Kept separate from
265    /// [`Self::char_width`] so mixed-script lines are measured correctly
266    /// instead of assuming every character is one cell wide.
267    ///
268    /// # Returns
269    ///
270    /// The full character width in pixels
271    ///
272    /// # Example
273    ///
274    /// ```
275    /// use iced_code_editor::CodeEditor;
276    ///
277    /// let editor = CodeEditor::new("fn main() {}", "rs");
278    /// // A wide glyph is never narrower than a narrow one.
279    /// assert!(editor.full_char_width() >= editor.char_width());
280    /// ```
281    pub fn full_char_width(&self) -> f32 {
282        self.full_char_width
283    }
284
285    /// Measures the rendered width for a given text snippet using editor metrics.
286    ///
287    /// Each character counts as either [`Self::char_width`] or
288    /// [`Self::full_char_width`] depending on whether it is a wide glyph, so
289    /// the result is correct for mixed-script text.
290    ///
291    /// # Arguments
292    ///
293    /// * `text` - The snippet to measure
294    ///
295    /// # Returns
296    ///
297    /// The width in pixels
298    ///
299    /// # Example
300    ///
301    /// ```
302    /// use iced_code_editor::CodeEditor;
303    ///
304    /// let editor = CodeEditor::new("fn main() {}", "rs");
305    /// assert!((editor.measure_text_width("") - 0.0).abs() < f32::EPSILON);
306    ///
307    /// // Width grows with the text.
308    /// assert!(editor.measure_text_width("hello") > editor.measure_text_width("hi"));
309    /// ```
310    pub fn measure_text_width(&self, text: &str) -> f32 {
311        measure_text_width(text, self.full_char_width, self.char_width)
312    }
313
314    /// Sets the line height used by the editor
315    ///
316    /// # Arguments
317    ///
318    /// * `height` - The line height in pixels
319    ///
320    /// # Example
321    ///
322    /// ```
323    /// use iced_code_editor::CodeEditor;
324    ///
325    /// let mut editor = CodeEditor::new("fn main() {}", "rs");
326    /// editor.set_line_height(24.0);
327    /// assert!((editor.line_height() - 24.0).abs() < f32::EPSILON);
328    /// ```
329    pub fn set_line_height(&mut self, height: f32) {
330        self.line_height = height;
331        self.content_cache.clear();
332        self.overlay_cache.clear();
333    }
334
335    /// Returns the current line height.
336    ///
337    /// # Returns
338    ///
339    /// The line height in pixels
340    ///
341    /// # Example
342    ///
343    /// ```
344    /// use iced_code_editor::CodeEditor;
345    ///
346    /// let editor = CodeEditor::new("fn main() {}", "rs");
347    /// assert!((editor.line_height() - 20.0).abs() < f32::EPSILON);
348    /// ```
349    pub fn line_height(&self) -> f32 {
350        self.line_height
351    }
352
353    /// Returns the current viewport height in pixels.
354    ///
355    /// Set by the layout each frame; the default applies only until the
356    /// editor has been drawn once.
357    ///
358    /// # Returns
359    ///
360    /// The viewport height in pixels
361    ///
362    /// # Example
363    ///
364    /// ```
365    /// use iced_code_editor::CodeEditor;
366    ///
367    /// let editor = CodeEditor::new("fn main() {}", "rs")
368    ///     .with_viewport_height(480.0);
369    /// assert!((editor.viewport_height() - 480.0).abs() < f32::EPSILON);
370    /// ```
371    pub fn viewport_height(&self) -> f32 {
372        self.viewport_height
373    }
374
375    /// Returns the current viewport width in pixels.
376    ///
377    /// This is the width line wrapping is computed against when no fixed wrap
378    /// column is configured.
379    ///
380    /// # Returns
381    ///
382    /// The viewport width in pixels
383    ///
384    /// # Example
385    ///
386    /// ```
387    /// use iced_code_editor::CodeEditor;
388    ///
389    /// let editor = CodeEditor::new("fn main() {}", "rs");
390    /// assert!(editor.viewport_width() > 0.0);
391    /// ```
392    pub fn viewport_width(&self) -> f32 {
393        self.viewport_width
394    }
395
396    /// Returns the current vertical scroll offset in pixels.
397    ///
398    /// Zero means the first line is at the top of the viewport.
399    ///
400    /// # Returns
401    ///
402    /// The scroll offset in pixels
403    ///
404    /// # Example
405    ///
406    /// ```
407    /// use iced_code_editor::CodeEditor;
408    ///
409    /// let editor = CodeEditor::new("fn main() {}", "rs");
410    /// // A fresh editor is scrolled to the top.
411    /// assert!((editor.viewport_scroll() - 0.0).abs() < f32::EPSILON);
412    /// ```
413    pub fn viewport_scroll(&self) -> f32 {
414        self.viewport_scroll
415    }
416
417    /// Sets the viewport height for the editor.
418    ///
419    /// This determines the minimum height of the canvas, ensuring proper
420    /// background rendering even when content is smaller than the viewport.
421    ///
422    /// # Arguments
423    ///
424    /// * `height` - The viewport height in pixels
425    ///
426    /// # Returns
427    ///
428    /// Self for method chaining
429    ///
430    /// # Example
431    ///
432    /// ```
433    /// use iced_code_editor::CodeEditor;
434    ///
435    /// let editor = CodeEditor::new("fn main() {}", "rs")
436    ///     .with_viewport_height(500.0);
437    /// ```
438    #[must_use]
439    pub fn with_viewport_height(mut self, height: f32) -> Self {
440        self.viewport_height = height;
441        self
442    }
443
444    /// Returns the total gutter width, including the line-number area and the
445    /// fold margin.
446    ///
447    /// The fold margin is added when folding is enabled, independently of line
448    /// numbers, so fold chevrons remain clickable even without line numbers.
449    pub(crate) fn gutter_width(&self) -> f32 {
450        self.line_number_gutter_width() + self.fold_margin_width()
451    }
452
453    /// Returns the width of the line-number area (excluding the fold margin).
454    pub(crate) fn line_number_gutter_width(&self) -> f32 {
455        if self.line_numbers_enabled { GUTTER_WIDTH } else { 0.0 }
456    }
457
458    /// Returns the width of the fold margin (the chevron column), or `0.0` when
459    /// folding is disabled.
460    pub(crate) fn fold_margin_width(&self) -> f32 {
461        if self.folding_enabled { FOLD_MARGIN_WIDTH } else { 0.0 }
462    }
463}
464
465#[cfg(test)]
466mod tests {
467    use super::*;
468
469    #[test]
470    fn test_compare_floats() {
471        // Equal cases
472        assert_eq!(
473            compare_floats(1.0, 1.0),
474            CmpOrdering::Equal,
475            "Exact equality"
476        );
477        assert_eq!(
478            compare_floats(1.0, 1.0 + 0.0001),
479            CmpOrdering::Equal,
480            "Within epsilon (positive)"
481        );
482        assert_eq!(
483            compare_floats(1.0, 1.0 - 0.0001),
484            CmpOrdering::Equal,
485            "Within epsilon (negative)"
486        );
487
488        // Greater cases
489        assert_eq!(
490            compare_floats(1.0 + 0.002, 1.0),
491            CmpOrdering::Greater,
492            "Definitely greater"
493        );
494        assert_eq!(
495            compare_floats(1.0011, 1.0),
496            CmpOrdering::Greater,
497            "Just above epsilon"
498        );
499
500        // Less cases
501        assert_eq!(
502            compare_floats(1.0, 1.0 + 0.002),
503            CmpOrdering::Less,
504            "Definitely less"
505        );
506        assert_eq!(
507            compare_floats(1.0, 1.0011),
508            CmpOrdering::Less,
509            "Just below negative epsilon"
510        );
511    }
512
513    #[test]
514    fn test_measure_text_width_ascii() {
515        // "abc" (3 chars) -> 3 * CHAR_WIDTH
516        let text = "abc";
517        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
518        let expected = CHAR_WIDTH * 3.0;
519        assert_eq!(
520            compare_floats(width, expected),
521            CmpOrdering::Equal,
522            "Width mismatch for ASCII"
523        );
524    }
525
526    #[test]
527    fn test_measure_text_width_cjk() {
528        // "你好" (2 chars) -> 2 * FONT_SIZE
529        // Chinese characters are typically full-width.
530        // width = 2 * FONT_SIZE
531        let text = "你好";
532        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
533        let expected = FONT_SIZE * 2.0;
534        assert_eq!(
535            compare_floats(width, expected),
536            CmpOrdering::Equal,
537            "Width mismatch for CJK"
538        );
539    }
540
541    #[test]
542    fn test_measure_text_width_mixed() {
543        // "Hi" (2 chars) -> 2 * CHAR_WIDTH
544        // "你好" (2 chars) -> 2 * FONT_SIZE
545        let text = "Hi你好";
546        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
547        let expected = CHAR_WIDTH * 2.0 + FONT_SIZE * 2.0;
548        assert_eq!(
549            compare_floats(width, expected),
550            CmpOrdering::Equal,
551            "Width mismatch for mixed content"
552        );
553    }
554
555    #[test]
556    fn test_measure_text_width_control_chars() {
557        // "\t\n" (2 chars)
558        // width = 4 * CHAR_WIDTH (tab) + 0 (newline)
559        let text = "\t\n";
560        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
561        let expected = CHAR_WIDTH * TAB_WIDTH as f32;
562        assert_eq!(
563            compare_floats(width, expected),
564            CmpOrdering::Equal,
565            "Width mismatch for control chars"
566        );
567    }
568
569    #[test]
570    fn test_measure_text_width_empty() {
571        let text = "";
572        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
573        assert!(
574            (width - 0.0).abs() < f32::EPSILON,
575            "Width should be 0 for empty string"
576        );
577    }
578
579    #[test]
580    fn test_measure_text_width_emoji() {
581        // "👋" (1 char, width > 1) -> FONT_SIZE
582        let text = "👋";
583        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
584        let expected = FONT_SIZE;
585        assert_eq!(
586            compare_floats(width, expected),
587            CmpOrdering::Equal,
588            "Width mismatch for emoji"
589        );
590    }
591
592    #[test]
593    fn test_measure_text_width_korean() {
594        // "안녕하세요" (5 chars)
595        // Korean characters are typically full-width.
596        // width = 5 * FONT_SIZE
597        let text = "안녕하세요";
598        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
599        let expected = FONT_SIZE * 5.0;
600        assert_eq!(
601            compare_floats(width, expected),
602            CmpOrdering::Equal,
603            "Width mismatch for Korean"
604        );
605    }
606
607    #[test]
608    fn test_measure_text_width_japanese() {
609        // "こんにちは" (Hiragana, 5 chars) -> 5 * FONT_SIZE
610        // "カタカナ" (Katakana, 4 chars) -> 4 * FONT_SIZE
611        // "漢字" (Kanji, 2 chars) -> 2 * FONT_SIZE
612
613        let text_hiragana = "こんにちは";
614        let width_hiragana =
615            measure_text_width(text_hiragana, FONT_SIZE, CHAR_WIDTH);
616        let expected_hiragana = FONT_SIZE * 5.0;
617        assert_eq!(
618            compare_floats(width_hiragana, expected_hiragana),
619            CmpOrdering::Equal,
620            "Width mismatch for Hiragana"
621        );
622
623        let text_katakana = "カタカナ";
624        let width_katakana =
625            measure_text_width(text_katakana, FONT_SIZE, CHAR_WIDTH);
626        let expected_katakana = FONT_SIZE * 4.0;
627        assert_eq!(
628            compare_floats(width_katakana, expected_katakana),
629            CmpOrdering::Equal,
630            "Width mismatch for Katakana"
631        );
632
633        let text_kanji = "漢字";
634        let width_kanji = measure_text_width(text_kanji, FONT_SIZE, CHAR_WIDTH);
635        let expected_kanji = FONT_SIZE * 2.0;
636        assert_eq!(
637            compare_floats(width_kanji, expected_kanji),
638            CmpOrdering::Equal,
639            "Width mismatch for Kanji"
640        );
641    }
642
643    #[test]
644    fn test_set_font_size() {
645        let mut editor = CodeEditor::new("", "rs");
646
647        // Initial state (defaults)
648        assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
649        assert!((editor.line_height() - 20.0).abs() < f32::EPSILON);
650
651        // Test auto adjust = true
652        editor.set_font_size(28.0, true);
653        assert!((editor.font_size() - 28.0).abs() < f32::EPSILON);
654        // Line height should double: 20.0 * (28.0/14.0) = 40.0
655        assert_eq!(
656            compare_floats(editor.line_height(), 40.0),
657            CmpOrdering::Equal
658        );
659
660        // Test auto adjust = false
661        // First set line height to something custom
662        editor.set_line_height(50.0);
663        // Change font size but keep line height
664        editor.set_font_size(14.0, false);
665        assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
666        // Line height should stay 50.0
667        assert_eq!(
668            compare_floats(editor.line_height(), 50.0),
669            CmpOrdering::Equal
670        );
671        // Char width should have scaled back to roughly default (but depends on measurement)
672        // We check if it is close to the expected value, but since measurement can vary,
673        // we just ensure it is positive and close to what we expect (around 8.4)
674        assert!(editor.char_width > 0.0);
675        assert!((editor.char_width - CHAR_WIDTH).abs() < 0.5);
676    }
677
678    #[test]
679    fn test_measure_single_char_width() {
680        let editor = CodeEditor::new("", "rs");
681
682        // Measure 'a'
683        let width_a = editor.measure_single_char_width("a");
684        assert!(width_a > 0.0, "Width of 'a' should be positive");
685
686        // Measure Chinese char
687        let width_cjk = editor.measure_single_char_width("汉");
688        assert!(width_cjk > 0.0, "Width of '汉' should be positive");
689
690        assert!(
691            width_cjk > width_a,
692            "Width of '汉' should be greater than 'a'"
693        );
694
695        // Check that width_cjk is roughly double of width_a (common in terminal fonts)
696        // but we just check it is significantly larger
697        assert!(width_cjk >= width_a * 1.5);
698    }
699
700    #[test]
701    fn test_set_line_height() {
702        let mut editor = CodeEditor::new("", "rs");
703
704        // Initial state
705        assert!((editor.line_height() - LINE_HEIGHT).abs() < f32::EPSILON);
706
707        // Set custom line height
708        editor.set_line_height(35.0);
709        assert!((editor.line_height() - 35.0).abs() < f32::EPSILON);
710
711        // Font size should remain unchanged
712        assert!((editor.font_size() - FONT_SIZE).abs() < f32::EPSILON);
713    }
714}