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    /// # Arguments
119    ///
120    /// * `font` - The iced font to set for the editor
121    pub fn set_font(&mut self, font: iced::Font) {
122        self.font = font;
123        self.recalculate_char_dimensions(false);
124    }
125
126    /// Sets the font size and recalculates character dimensions.
127    ///
128    /// If `auto_adjust_line_height` is true, `line_height` will also be scaled to maintain
129    /// the default proportion (Line Height ~ 1.43x).
130    ///
131    /// # Arguments
132    ///
133    /// * `size` - The font size in pixels
134    /// * `auto_adjust_line_height` - Whether to automatically adjust the line height
135    pub fn set_font_size(&mut self, size: f32, auto_adjust_line_height: bool) {
136        self.font_size = size;
137        self.recalculate_char_dimensions(auto_adjust_line_height);
138    }
139
140    /// Recalculates character dimensions based on current font and size.
141    pub(crate) fn recalculate_char_dimensions(
142        &mut self,
143        auto_adjust_line_height: bool,
144    ) {
145        self.char_width = self.measure_single_char_width("a");
146        // Use '汉' as a standard reference for CJK (Chinese, Japanese, Korean) wide characters
147        self.full_char_width = self.measure_single_char_width("汉");
148
149        // Fallback for infinite width measurements
150        if self.char_width.is_infinite() {
151            self.char_width = self.font_size / 2.0; // Rough estimate for monospace
152        }
153
154        if self.full_char_width.is_infinite() {
155            self.full_char_width = self.font_size;
156        }
157
158        if auto_adjust_line_height {
159            let line_height_ratio = LINE_HEIGHT / FONT_SIZE;
160            self.line_height = self.font_size * line_height_ratio;
161        }
162
163        self.content_cache.clear();
164        self.overlay_cache.clear();
165        *self.max_content_width_cache.borrow_mut() = None;
166    }
167
168    /// Measures the width of a single character string using the current font settings.
169    fn measure_single_char_width(&self, content: &str) -> f32 {
170        let text = Text {
171            content,
172            font: self.font,
173            size: iced::Pixels(self.font_size),
174            line_height: iced::advanced::text::LineHeight::default(),
175            bounds: iced::Size::new(f32::INFINITY, f32::INFINITY),
176            align_x: Alignment::Left,
177            align_y: iced::alignment::Vertical::Top,
178            shaping: iced::advanced::text::Shaping::Advanced,
179            wrapping: iced::advanced::text::Wrapping::default(),
180        };
181        let p = <iced::Renderer as TextRenderer>::Paragraph::with_text(text);
182        p.min_width()
183    }
184
185    /// Returns the current font size.
186    ///
187    /// # Returns
188    ///
189    /// The font size in pixels
190    pub fn font_size(&self) -> f32 {
191        self.font_size
192    }
193
194    /// Returns the width of a standard narrow character in pixels.
195    ///
196    /// # Returns
197    ///
198    /// The character width in pixels
199    pub fn char_width(&self) -> f32 {
200        self.char_width
201    }
202
203    /// Returns the width of a wide character (e.g. CJK) in pixels.
204    ///
205    /// # Returns
206    ///
207    /// The full character width in pixels
208    pub fn full_char_width(&self) -> f32 {
209        self.full_char_width
210    }
211
212    /// Measures the rendered width for a given text snippet using editor metrics.
213    pub fn measure_text_width(&self, text: &str) -> f32 {
214        measure_text_width(text, self.full_char_width, self.char_width)
215    }
216
217    /// Sets the line height used by the editor
218    ///
219    /// # Arguments
220    ///
221    /// * `height` - The line height in pixels
222    pub fn set_line_height(&mut self, height: f32) {
223        self.line_height = height;
224        self.content_cache.clear();
225        self.overlay_cache.clear();
226    }
227
228    /// Returns the current line height.
229    ///
230    /// # Returns
231    ///
232    /// The line height in pixels
233    pub fn line_height(&self) -> f32 {
234        self.line_height
235    }
236
237    /// Returns the current viewport height in pixels.
238    pub fn viewport_height(&self) -> f32 {
239        self.viewport_height
240    }
241
242    /// Returns the current viewport width in pixels.
243    pub fn viewport_width(&self) -> f32 {
244        self.viewport_width
245    }
246
247    /// Returns the current vertical scroll offset in pixels.
248    pub fn viewport_scroll(&self) -> f32 {
249        self.viewport_scroll
250    }
251
252    /// Sets the viewport height for the editor.
253    ///
254    /// This determines the minimum height of the canvas, ensuring proper
255    /// background rendering even when content is smaller than the viewport.
256    ///
257    /// # Arguments
258    ///
259    /// * `height` - The viewport height in pixels
260    ///
261    /// # Returns
262    ///
263    /// Self for method chaining
264    ///
265    /// # Example
266    ///
267    /// ```
268    /// use iced_code_editor::CodeEditor;
269    ///
270    /// let editor = CodeEditor::new("fn main() {}", "rs")
271    ///     .with_viewport_height(500.0);
272    /// ```
273    #[must_use]
274    pub fn with_viewport_height(mut self, height: f32) -> Self {
275        self.viewport_height = height;
276        self
277    }
278
279    /// Returns the total gutter width, including the line-number area and the
280    /// fold margin.
281    ///
282    /// The fold margin is added when folding is enabled, independently of line
283    /// numbers, so fold chevrons remain clickable even without line numbers.
284    pub(crate) fn gutter_width(&self) -> f32 {
285        self.line_number_gutter_width() + self.fold_margin_width()
286    }
287
288    /// Returns the width of the line-number area (excluding the fold margin).
289    pub(crate) fn line_number_gutter_width(&self) -> f32 {
290        if self.line_numbers_enabled { GUTTER_WIDTH } else { 0.0 }
291    }
292
293    /// Returns the width of the fold margin (the chevron column), or `0.0` when
294    /// folding is disabled.
295    pub(crate) fn fold_margin_width(&self) -> f32 {
296        if self.folding_enabled { FOLD_MARGIN_WIDTH } else { 0.0 }
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[test]
305    fn test_compare_floats() {
306        // Equal cases
307        assert_eq!(
308            compare_floats(1.0, 1.0),
309            CmpOrdering::Equal,
310            "Exact equality"
311        );
312        assert_eq!(
313            compare_floats(1.0, 1.0 + 0.0001),
314            CmpOrdering::Equal,
315            "Within epsilon (positive)"
316        );
317        assert_eq!(
318            compare_floats(1.0, 1.0 - 0.0001),
319            CmpOrdering::Equal,
320            "Within epsilon (negative)"
321        );
322
323        // Greater cases
324        assert_eq!(
325            compare_floats(1.0 + 0.002, 1.0),
326            CmpOrdering::Greater,
327            "Definitely greater"
328        );
329        assert_eq!(
330            compare_floats(1.0011, 1.0),
331            CmpOrdering::Greater,
332            "Just above epsilon"
333        );
334
335        // Less cases
336        assert_eq!(
337            compare_floats(1.0, 1.0 + 0.002),
338            CmpOrdering::Less,
339            "Definitely less"
340        );
341        assert_eq!(
342            compare_floats(1.0, 1.0011),
343            CmpOrdering::Less,
344            "Just below negative epsilon"
345        );
346    }
347
348    #[test]
349    fn test_measure_text_width_ascii() {
350        // "abc" (3 chars) -> 3 * CHAR_WIDTH
351        let text = "abc";
352        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
353        let expected = CHAR_WIDTH * 3.0;
354        assert_eq!(
355            compare_floats(width, expected),
356            CmpOrdering::Equal,
357            "Width mismatch for ASCII"
358        );
359    }
360
361    #[test]
362    fn test_measure_text_width_cjk() {
363        // "你好" (2 chars) -> 2 * FONT_SIZE
364        // Chinese characters are typically full-width.
365        // width = 2 * FONT_SIZE
366        let text = "你好";
367        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
368        let expected = FONT_SIZE * 2.0;
369        assert_eq!(
370            compare_floats(width, expected),
371            CmpOrdering::Equal,
372            "Width mismatch for CJK"
373        );
374    }
375
376    #[test]
377    fn test_measure_text_width_mixed() {
378        // "Hi" (2 chars) -> 2 * CHAR_WIDTH
379        // "你好" (2 chars) -> 2 * FONT_SIZE
380        let text = "Hi你好";
381        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
382        let expected = CHAR_WIDTH * 2.0 + FONT_SIZE * 2.0;
383        assert_eq!(
384            compare_floats(width, expected),
385            CmpOrdering::Equal,
386            "Width mismatch for mixed content"
387        );
388    }
389
390    #[test]
391    fn test_measure_text_width_control_chars() {
392        // "\t\n" (2 chars)
393        // width = 4 * CHAR_WIDTH (tab) + 0 (newline)
394        let text = "\t\n";
395        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
396        let expected = CHAR_WIDTH * TAB_WIDTH as f32;
397        assert_eq!(
398            compare_floats(width, expected),
399            CmpOrdering::Equal,
400            "Width mismatch for control chars"
401        );
402    }
403
404    #[test]
405    fn test_measure_text_width_empty() {
406        let text = "";
407        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
408        assert!(
409            (width - 0.0).abs() < f32::EPSILON,
410            "Width should be 0 for empty string"
411        );
412    }
413
414    #[test]
415    fn test_measure_text_width_emoji() {
416        // "👋" (1 char, width > 1) -> FONT_SIZE
417        let text = "👋";
418        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
419        let expected = FONT_SIZE;
420        assert_eq!(
421            compare_floats(width, expected),
422            CmpOrdering::Equal,
423            "Width mismatch for emoji"
424        );
425    }
426
427    #[test]
428    fn test_measure_text_width_korean() {
429        // "안녕하세요" (5 chars)
430        // Korean characters are typically full-width.
431        // width = 5 * FONT_SIZE
432        let text = "안녕하세요";
433        let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
434        let expected = FONT_SIZE * 5.0;
435        assert_eq!(
436            compare_floats(width, expected),
437            CmpOrdering::Equal,
438            "Width mismatch for Korean"
439        );
440    }
441
442    #[test]
443    fn test_measure_text_width_japanese() {
444        // "こんにちは" (Hiragana, 5 chars) -> 5 * FONT_SIZE
445        // "カタカナ" (Katakana, 4 chars) -> 4 * FONT_SIZE
446        // "漢字" (Kanji, 2 chars) -> 2 * FONT_SIZE
447
448        let text_hiragana = "こんにちは";
449        let width_hiragana =
450            measure_text_width(text_hiragana, FONT_SIZE, CHAR_WIDTH);
451        let expected_hiragana = FONT_SIZE * 5.0;
452        assert_eq!(
453            compare_floats(width_hiragana, expected_hiragana),
454            CmpOrdering::Equal,
455            "Width mismatch for Hiragana"
456        );
457
458        let text_katakana = "カタカナ";
459        let width_katakana =
460            measure_text_width(text_katakana, FONT_SIZE, CHAR_WIDTH);
461        let expected_katakana = FONT_SIZE * 4.0;
462        assert_eq!(
463            compare_floats(width_katakana, expected_katakana),
464            CmpOrdering::Equal,
465            "Width mismatch for Katakana"
466        );
467
468        let text_kanji = "漢字";
469        let width_kanji = measure_text_width(text_kanji, FONT_SIZE, CHAR_WIDTH);
470        let expected_kanji = FONT_SIZE * 2.0;
471        assert_eq!(
472            compare_floats(width_kanji, expected_kanji),
473            CmpOrdering::Equal,
474            "Width mismatch for Kanji"
475        );
476    }
477
478    #[test]
479    fn test_set_font_size() {
480        let mut editor = CodeEditor::new("", "rs");
481
482        // Initial state (defaults)
483        assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
484        assert!((editor.line_height() - 20.0).abs() < f32::EPSILON);
485
486        // Test auto adjust = true
487        editor.set_font_size(28.0, true);
488        assert!((editor.font_size() - 28.0).abs() < f32::EPSILON);
489        // Line height should double: 20.0 * (28.0/14.0) = 40.0
490        assert_eq!(
491            compare_floats(editor.line_height(), 40.0),
492            CmpOrdering::Equal
493        );
494
495        // Test auto adjust = false
496        // First set line height to something custom
497        editor.set_line_height(50.0);
498        // Change font size but keep line height
499        editor.set_font_size(14.0, false);
500        assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
501        // Line height should stay 50.0
502        assert_eq!(
503            compare_floats(editor.line_height(), 50.0),
504            CmpOrdering::Equal
505        );
506        // Char width should have scaled back to roughly default (but depends on measurement)
507        // We check if it is close to the expected value, but since measurement can vary,
508        // we just ensure it is positive and close to what we expect (around 8.4)
509        assert!(editor.char_width > 0.0);
510        assert!((editor.char_width - CHAR_WIDTH).abs() < 0.5);
511    }
512
513    #[test]
514    fn test_measure_single_char_width() {
515        let editor = CodeEditor::new("", "rs");
516
517        // Measure 'a'
518        let width_a = editor.measure_single_char_width("a");
519        assert!(width_a > 0.0, "Width of 'a' should be positive");
520
521        // Measure Chinese char
522        let width_cjk = editor.measure_single_char_width("汉");
523        assert!(width_cjk > 0.0, "Width of '汉' should be positive");
524
525        assert!(
526            width_cjk > width_a,
527            "Width of '汉' should be greater than 'a'"
528        );
529
530        // Check that width_cjk is roughly double of width_a (common in terminal fonts)
531        // but we just check it is significantly larger
532        assert!(width_cjk >= width_a * 1.5);
533    }
534
535    #[test]
536    fn test_set_line_height() {
537        let mut editor = CodeEditor::new("", "rs");
538
539        // Initial state
540        assert!((editor.line_height() - LINE_HEIGHT).abs() < f32::EPSILON);
541
542        // Set custom line height
543        editor.set_line_height(35.0);
544        assert!((editor.line_height() - 35.0).abs() < f32::EPSILON);
545
546        // Font size should remain unchanged
547        assert!((editor.font_size() - FONT_SIZE).abs() < f32::EPSILON);
548    }
549}