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