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