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