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 std::collections::HashMap;
9use std::sync::{Mutex, OnceLock};
10use unicode_width::UnicodeWidthChar;
11
12use crate::canvas_editor::CodeEditor;
13
14/// Canvas-based text editor constants
15pub(crate) const FONT_SIZE: f32 = 14.0;
16pub(crate) const LINE_HEIGHT: f32 = 20.0;
17pub(crate) const CHAR_WIDTH: f32 = 8.4; // Monospace character width
18pub(crate) const TAB_WIDTH: usize = 4;
19pub(crate) const GUTTER_WIDTH: f32 = 45.0;
20/// Width in pixels of the fold margin (chevron column) added to the gutter when
21/// code folding is enabled.
22pub(crate) const FOLD_MARGIN_WIDTH: f32 = 14.0;
23pub(crate) const CURSOR_BLINK_INTERVAL: std::time::Duration =
24 std::time::Duration::from_millis(530);
25
26/// Reference glyph used to measure wide (CJK) characters.
27const WIDE_REFERENCE_GLYPH: &str = "汉";
28
29/// Largest narrow-width drift, in pixels, under which a cached wide width is
30/// still trusted (see [`cached_wide_char_width`]).
31const NARROW_WIDTH_TOLERANCE: f32 = 0.01;
32
33/// Wide-glyph widths shared by every editor in the process, keyed by font and
34/// size bits, each stored with the narrow width measured alongside it.
35type WideWidthCache = HashMap<(iced::Font, u32), (f32, f32)>;
36
37/// Process-wide [`WideWidthCache`].
38static WIDE_WIDTHS: OnceLock<Mutex<WideWidthCache>> = OnceLock::new();
39
40#[cfg(test)]
41thread_local! {
42 /// Wide-glyph measurements taken on this thread, counted by the tests.
43 static WIDE_MEASUREMENTS: std::cell::Cell<usize> =
44 const { std::cell::Cell::new(0) };
45}
46
47/// Returns the wide-glyph width of `font` at `size`, measuring it only when
48/// no trustworthy cached value exists.
49///
50/// Measuring the wide reference glyph usually starts a fallback-font search
51/// (most code fonts have no CJK glyphs), which costs far more than measuring
52/// an ASCII letter. Hosts that build many editors (one per tab or request
53/// body) paid it on every construction and every font change.
54///
55/// The cache is validated with `narrow_width`, a fresh measurement of the
56/// narrow glyph: if it no longer matches the narrow width stored with the
57/// entry, the font's glyphs changed since (typically a font loaded after the
58/// first measurement, which had fallen back to another face), so the wide
59/// glyph is measured again and the entry replaced.
60///
61/// # Arguments
62///
63/// * `font` - The font to measure
64/// * `size` - The font size in pixels
65/// * `narrow_width` - The current width of the narrow reference glyph
66/// * `measure` - Measures the wide reference glyph
67fn cached_wide_char_width(
68 font: iced::Font,
69 size: f32,
70 narrow_width: f32,
71 measure: impl FnOnce() -> f32,
72) -> f32 {
73 let key = (font, size.to_bits());
74 let cache = WIDE_WIDTHS.get_or_init(Mutex::default);
75 let cached = cache
76 .lock()
77 .unwrap_or_else(|error| error.into_inner())
78 .get(&key)
79 .copied();
80 if let Some((narrow, wide)) = cached
81 && (narrow - narrow_width).abs() <= NARROW_WIDTH_TOLERANCE
82 {
83 return wide;
84 }
85
86 #[cfg(test)]
87 WIDE_MEASUREMENTS.with(|count| count.set(count.get() + 1));
88 let wide = measure();
89 cache
90 .lock()
91 .unwrap_or_else(|error| error.into_inner())
92 .insert(key, (narrow_width, wide));
93 wide
94}
95
96/// Measures the width of a single character.
97///
98/// # Arguments
99///
100/// * `c` - The character to measure
101/// * `full_char_width` - The width of a full-width character
102/// * `char_width` - The width of the character
103///
104/// # Returns
105///
106/// The calculated width of the character as a `f32`
107pub(crate) fn measure_char_width(
108 c: char,
109 full_char_width: f32,
110 char_width: f32,
111) -> f32 {
112 if c == '\t' {
113 return char_width * TAB_WIDTH as f32;
114 }
115 match c.width() {
116 Some(w) if w > 1 => full_char_width,
117 Some(_) => char_width,
118 None => 0.0,
119 }
120}
121
122/// Computes the visual indentation width of a line, expanding tabs.
123///
124/// Returns `None` for blank lines (empty or whitespace-only), which have no
125/// meaningful indentation and act as "transparent" lines: both code folding and
126/// indentation guides infer their level from the surrounding non-blank lines
127/// instead.
128///
129/// The width is expressed in display columns, not character indices: a tab
130/// counts as [`TAB_WIDTH`] columns, matching what [`measure_char_width`] does
131/// when rendering.
132///
133/// # Arguments
134///
135/// * `line` - The line content (without the trailing newline)
136///
137/// # Returns
138///
139/// The indentation width in display columns, or `None` for a blank line.
140pub(crate) fn indent_width(line: &str) -> Option<usize> {
141 let mut width = 0;
142 for c in line.chars() {
143 match c {
144 '\t' => width += TAB_WIDTH,
145 ' ' => width += 1,
146 _ if c.is_whitespace() => width += 1,
147 _ => return Some(width),
148 }
149 }
150 // Reached end of line without a non-whitespace character: blank line.
151 None
152}
153
154/// Measures rendered text width, accounting for CJK wide characters.
155///
156/// - Wide characters (e.g. Chinese) use FONT_SIZE.
157/// - Narrow characters (e.g. Latin) use CHAR_WIDTH.
158/// - Control characters (except tab) have width 0.
159///
160/// # Arguments
161///
162/// * `text` - The text string to measure
163/// * `full_char_width` - The width of a full-width character
164/// * `char_width` - The width of a regular character
165///
166/// # Returns
167///
168/// The total calculated width of the text as a `f32`, never negative zero
169/// (see the empty-line note below).
170///
171/// # Note
172///
173/// `Iterator::sum` over an empty `f32` sequence — a blank line — yields
174/// `-0.0`, not `0.0` (`[0f32; 0].iter().sum::<f32>().is_sign_negative()` is
175/// `true`). Left as-is, that bit pattern corrupts callers that order widths
176/// by `f32::to_bits` (as [`MaxContentWidthCache`](super::caches::MaxContentWidthCache)
177/// does): `-0.0`'s sign bit makes it sort *above* every positive width as an
178/// unsigned integer, so a single blank line — found in virtually every real
179/// file — silently became the reported "widest line" (issue #26). Normalizing
180/// the result here keeps `measure_text_width` a sound building block for any
181/// such bit-based comparison.
182pub(crate) fn measure_text_width(
183 text: &str,
184 full_char_width: f32,
185 char_width: f32,
186) -> f32 {
187 let width: f32 = text
188 .chars()
189 .map(|c| measure_char_width(c, full_char_width, char_width))
190 .sum();
191 // Every term above is non-negative, so a negative sum is only reachable
192 // as `-0.0` (an empty sum). `.abs()` canonicalizes that one case to
193 // `0.0` without a lossy or lint-unfriendly float equality comparison.
194 if width.is_sign_negative() { width.abs() } else { width }
195}
196
197/// Epsilon value for floating-point comparisons in text layout.
198pub(crate) const EPSILON: f32 = 0.001;
199/// Multiplier used to extend the cached render window beyond the visible range.
200/// The cache window margin is computed as:
201/// margin = visible_lines_count * CACHE_WINDOW_MARGIN_MULTIPLIER
202/// A larger margin reduces how often we clear and rebuild the canvas cache when
203/// scrolling, improving performance on very large files while still ensuring
204/// correct initial rendering during the first scroll.
205pub(crate) const CACHE_WINDOW_MARGIN_MULTIPLIER: usize = 2;
206/// Maximum number of previously unseen logical lines syntect may parse while
207/// rebuilding one content frame.
208///
209/// Syntax state is sequential, so jumping far into a large file can otherwise
210/// parse every line from the start in one blocking draw call. Lines beyond this
211/// budget temporarily use the editor's plain text color and will be highlighted
212/// as later content redraws advance the cached parser state.
213pub(crate) const HIGHLIGHT_LINES_PER_FRAME: usize = 2_000;
214
215/// Wall-clock budget for sequential syntect catch-up within one content frame.
216///
217/// A line count alone cannot bound frame time: a line's cost varies a lot
218/// with syntax, line length and build profile (a debug build is roughly ten
219/// times slower), so [`HIGHLIGHT_LINES_PER_FRAME`] lines can take well over
220/// a frame. This caps the time as well; 8 ms keeps a frame inside a 60 fps
221/// budget while still making steady progress.
222pub(crate) const HIGHLIGHT_TIME_PER_FRAME: std::time::Duration =
223 std::time::Duration::from_millis(8);
224
225/// Lines parsed between two clock reads during highlight catch-up, so the
226/// time check itself stays negligible.
227pub(crate) const HIGHLIGHT_CLOCK_CHECK_INTERVAL: usize = 64;
228
229/// Compares two floating point numbers with a small epsilon tolerance.
230///
231/// # Arguments
232///
233/// * `a` - first float number
234/// * `b` - second float number
235///
236/// # Returns
237///
238/// * `Ordering::Equal` if `abs(a - b) < EPSILON`
239/// * `Ordering::Greater` if `a > b` (and not equal)
240/// * `Ordering::Less` if `a < b` (and not equal)
241pub(crate) fn compare_floats(a: f32, b: f32) -> CmpOrdering {
242 if (a - b).abs() < EPSILON {
243 CmpOrdering::Equal
244 } else if a > b {
245 CmpOrdering::Greater
246 } else {
247 CmpOrdering::Less
248 }
249}
250
251impl CodeEditor {
252 /// Sets the font used by the editor
253 ///
254 /// Character dimensions are re-measured with the new font, but the line
255 /// height is left alone — use [`Self::set_line_height`] to change it.
256 ///
257 /// # Arguments
258 ///
259 /// * `font` - The iced font to set for the editor
260 ///
261 /// # Example
262 ///
263 /// ```
264 /// use iced_code_editor::CodeEditor;
265 ///
266 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
267 /// editor.set_font(iced::Font::MONOSPACE);
268 ///
269 /// // Character widths are re-measured for the new font.
270 /// assert!(editor.char_width() > 0.0);
271 /// ```
272 pub fn set_font(&mut self, font: iced::Font) {
273 self.font = font;
274 self.recalculate_char_dimensions(false);
275 }
276
277 /// Sets the font size and recalculates character dimensions.
278 ///
279 /// If `auto_adjust_line_height` is true, `line_height` will also be scaled to maintain
280 /// the default proportion (Line Height ~ 1.43x).
281 ///
282 /// # Arguments
283 ///
284 /// * `size` - The font size in pixels
285 /// * `auto_adjust_line_height` - Whether to automatically adjust the line height
286 ///
287 /// # Example
288 ///
289 /// ```
290 /// use iced_code_editor::CodeEditor;
291 ///
292 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
293 ///
294 /// // Scale the line height along with the font, the usual "zoom" case.
295 /// editor.set_font_size(28.0, true);
296 /// assert!((editor.font_size() - 28.0).abs() < f32::EPSILON);
297 /// // Doubling 14px doubles the 20px default line height.
298 /// assert!((editor.line_height() - 40.0).abs() < f32::EPSILON);
299 ///
300 /// // Or keep a line height the host controls itself.
301 /// editor.set_font_size(14.0, false);
302 /// assert!((editor.line_height() - 40.0).abs() < f32::EPSILON);
303 /// ```
304 pub fn set_font_size(&mut self, size: f32, auto_adjust_line_height: bool) {
305 self.font_size = size;
306 self.recalculate_char_dimensions(auto_adjust_line_height);
307 }
308
309 /// Recalculates character dimensions based on current font and size.
310 pub(crate) fn recalculate_char_dimensions(
311 &mut self,
312 auto_adjust_line_height: bool,
313 ) {
314 self.char_width = self.measure_single_char_width("a");
315 // Use '汉' as a standard reference for CJK (Chinese, Japanese, Korean)
316 // wide characters. It is the costly one to measure, so it is shared
317 // across editors and validated by the fresh narrow width.
318 self.full_char_width = cached_wide_char_width(
319 self.font,
320 self.font_size,
321 self.char_width,
322 || self.measure_single_char_width(WIDE_REFERENCE_GLYPH),
323 );
324
325 // Fallback for infinite width measurements
326 if self.char_width.is_infinite() {
327 self.char_width = self.font_size / 2.0; // Rough estimate for monospace
328 }
329
330 if self.full_char_width.is_infinite() {
331 self.full_char_width = self.font_size;
332 }
333
334 if auto_adjust_line_height {
335 let line_height_ratio = LINE_HEIGHT / FONT_SIZE;
336 self.line_height = self.font_size * line_height_ratio;
337 }
338
339 self.content_cache.clear();
340 self.overlay_cache.clear();
341 *self.max_content_width_cache.borrow_mut() = None;
342 }
343
344 /// Measures the width of a single character string using the current font settings.
345 fn measure_single_char_width(&self, content: &str) -> f32 {
346 let text = Text {
347 content,
348 font: self.font,
349 size: iced::Pixels(self.font_size),
350 line_height: iced::advanced::text::LineHeight::default(),
351 bounds: iced::Size::new(f32::INFINITY, f32::INFINITY),
352 align_x: Alignment::Left,
353 align_y: iced::alignment::Vertical::Top,
354 shaping: iced::advanced::text::Shaping::Advanced,
355 wrapping: iced::advanced::text::Wrapping::default(),
356 };
357 let p = <iced::Renderer as TextRenderer>::Paragraph::with_text(text);
358 p.min_width()
359 }
360
361 /// Returns the current font size.
362 ///
363 /// # Returns
364 ///
365 /// The font size in pixels
366 ///
367 /// # Example
368 ///
369 /// ```
370 /// use iced_code_editor::CodeEditor;
371 ///
372 /// let editor = CodeEditor::new("fn main() {}", "rs");
373 /// assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
374 /// ```
375 pub fn font_size(&self) -> f32 {
376 self.font_size
377 }
378
379 /// Returns the width of a standard narrow character in pixels.
380 ///
381 /// Measured from the current font rather than assumed, so it stays correct
382 /// after [`Self::set_font`] or [`Self::set_font_size`].
383 ///
384 /// # Returns
385 ///
386 /// The character width in pixels
387 ///
388 /// # Example
389 ///
390 /// ```
391 /// use iced_code_editor::CodeEditor;
392 ///
393 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
394 /// let narrow = editor.char_width();
395 /// assert!(narrow > 0.0);
396 ///
397 /// // A larger font measures wider characters.
398 /// editor.set_font_size(28.0, true);
399 /// assert!(editor.char_width() > narrow);
400 /// ```
401 pub fn char_width(&self) -> f32 {
402 self.char_width
403 }
404
405 /// Returns the width of a wide character (e.g. CJK) in pixels.
406 ///
407 /// Measured from `汉` as the reference glyph. Kept separate from
408 /// [`Self::char_width`] so mixed-script lines are measured correctly
409 /// instead of assuming every character is one cell wide.
410 ///
411 /// # Returns
412 ///
413 /// The full character width in pixels
414 ///
415 /// # Example
416 ///
417 /// ```
418 /// use iced_code_editor::CodeEditor;
419 ///
420 /// let editor = CodeEditor::new("fn main() {}", "rs");
421 /// // A wide glyph is never narrower than a narrow one.
422 /// assert!(editor.full_char_width() >= editor.char_width());
423 /// ```
424 pub fn full_char_width(&self) -> f32 {
425 self.full_char_width
426 }
427
428 /// Measures the rendered width for a given text snippet using editor metrics.
429 ///
430 /// Each character counts as either [`Self::char_width`] or
431 /// [`Self::full_char_width`] depending on whether it is a wide glyph, so
432 /// the result is correct for mixed-script text.
433 ///
434 /// # Arguments
435 ///
436 /// * `text` - The snippet to measure
437 ///
438 /// # Returns
439 ///
440 /// The width in pixels
441 ///
442 /// # Example
443 ///
444 /// ```
445 /// use iced_code_editor::CodeEditor;
446 ///
447 /// let editor = CodeEditor::new("fn main() {}", "rs");
448 /// assert!((editor.measure_text_width("") - 0.0).abs() < f32::EPSILON);
449 ///
450 /// // Width grows with the text.
451 /// assert!(editor.measure_text_width("hello") > editor.measure_text_width("hi"));
452 /// ```
453 pub fn measure_text_width(&self, text: &str) -> f32 {
454 measure_text_width(text, self.full_char_width, self.char_width)
455 }
456
457 /// Sets the line height used by the editor
458 ///
459 /// # Arguments
460 ///
461 /// * `height` - The line height in pixels
462 ///
463 /// # Example
464 ///
465 /// ```
466 /// use iced_code_editor::CodeEditor;
467 ///
468 /// let mut editor = CodeEditor::new("fn main() {}", "rs");
469 /// editor.set_line_height(24.0);
470 /// assert!((editor.line_height() - 24.0).abs() < f32::EPSILON);
471 /// ```
472 pub fn set_line_height(&mut self, height: f32) {
473 self.line_height = height;
474 self.content_cache.clear();
475 self.overlay_cache.clear();
476 }
477
478 /// Returns the current line height.
479 ///
480 /// # Returns
481 ///
482 /// The line height in pixels
483 ///
484 /// # Example
485 ///
486 /// ```
487 /// use iced_code_editor::CodeEditor;
488 ///
489 /// let editor = CodeEditor::new("fn main() {}", "rs");
490 /// assert!((editor.line_height() - 20.0).abs() < f32::EPSILON);
491 /// ```
492 pub fn line_height(&self) -> f32 {
493 self.line_height
494 }
495
496 /// Returns the current viewport height in pixels.
497 ///
498 /// Set by the layout each frame; the default applies only until the
499 /// editor has been drawn once.
500 ///
501 /// # Returns
502 ///
503 /// The viewport height in pixels
504 ///
505 /// # Example
506 ///
507 /// ```
508 /// use iced_code_editor::CodeEditor;
509 ///
510 /// let editor = CodeEditor::new("fn main() {}", "rs")
511 /// .with_viewport_height(480.0);
512 /// assert!((editor.viewport_height() - 480.0).abs() < f32::EPSILON);
513 /// ```
514 pub fn viewport_height(&self) -> f32 {
515 self.viewport_height
516 }
517
518 /// Returns the current viewport width in pixels.
519 ///
520 /// This is the width line wrapping is computed against when no fixed wrap
521 /// column is configured.
522 ///
523 /// # Returns
524 ///
525 /// The viewport width in pixels
526 ///
527 /// # Example
528 ///
529 /// ```
530 /// use iced_code_editor::CodeEditor;
531 ///
532 /// let editor = CodeEditor::new("fn main() {}", "rs");
533 /// assert!(editor.viewport_width() > 0.0);
534 /// ```
535 pub fn viewport_width(&self) -> f32 {
536 self.viewport_width
537 }
538
539 /// Returns the current vertical scroll offset in pixels.
540 ///
541 /// Zero means the first line is at the top of the viewport.
542 ///
543 /// # Returns
544 ///
545 /// The scroll offset in pixels
546 ///
547 /// # Example
548 ///
549 /// ```
550 /// use iced_code_editor::CodeEditor;
551 ///
552 /// let editor = CodeEditor::new("fn main() {}", "rs");
553 /// // A fresh editor is scrolled to the top.
554 /// assert!((editor.viewport_scroll() - 0.0).abs() < f32::EPSILON);
555 /// ```
556 pub fn viewport_scroll(&self) -> f32 {
557 self.viewport_scroll
558 }
559
560 /// Sets the viewport height for the editor.
561 ///
562 /// This determines the minimum height of the canvas, ensuring proper
563 /// background rendering even when content is smaller than the viewport.
564 ///
565 /// # Arguments
566 ///
567 /// * `height` - The viewport height in pixels
568 ///
569 /// # Returns
570 ///
571 /// Self for method chaining
572 ///
573 /// # Example
574 ///
575 /// ```
576 /// use iced_code_editor::CodeEditor;
577 ///
578 /// let editor = CodeEditor::new("fn main() {}", "rs")
579 /// .with_viewport_height(500.0);
580 /// ```
581 #[must_use]
582 pub fn with_viewport_height(mut self, height: f32) -> Self {
583 self.viewport_height = height;
584 self
585 }
586
587 /// Returns the total gutter width, including the line-number area and the
588 /// fold margin.
589 ///
590 /// The fold margin is added when folding is enabled, independently of line
591 /// numbers, so fold chevrons remain clickable even without line numbers.
592 pub(crate) fn gutter_width(&self) -> f32 {
593 self.line_number_gutter_width() + self.fold_margin_width()
594 }
595
596 /// Returns the width of the line-number area (excluding the fold margin).
597 pub(crate) fn line_number_gutter_width(&self) -> f32 {
598 if self.line_numbers_enabled { GUTTER_WIDTH } else { 0.0 }
599 }
600
601 /// Returns the width of the fold margin (the chevron column), or `0.0` when
602 /// folding is disabled or fold markers are never shown.
603 pub(crate) fn fold_margin_width(&self) -> f32 {
604 if self.folding_enabled
605 && self.fold_markers != crate::FoldMarkers::Never
606 {
607 FOLD_MARGIN_WIDTH
608 } else {
609 0.0
610 }
611 }
612
613 /// Returns the horizontal extents of the gutter columns, in canvas
614 /// coordinates.
615 ///
616 /// The single source of truth for the gutter layout: drawing, fold
617 /// clicks, the gutter background and sticky headers all read it, so the
618 /// fold-marker column can move to either side of the line numbers.
619 pub(crate) fn gutter_columns(&self) -> GutterColumns {
620 let numbers = self.line_number_gutter_width();
621 let markers = self.fold_margin_width();
622 match self.fold_marker_position {
623 crate::FoldMarkerPosition::AfterLineNumbers => GutterColumns {
624 line_numbers: 0.0..numbers,
625 fold_markers: numbers..numbers + markers,
626 },
627 crate::FoldMarkerPosition::BeforeLineNumbers => GutterColumns {
628 fold_markers: 0.0..markers,
629 line_numbers: markers..markers + numbers,
630 },
631 }
632 }
633}
634
635/// Horizontal extents of the gutter's two columns, in canvas coordinates.
636///
637/// Either range is empty when its column is hidden (line numbers disabled,
638/// folding disabled or fold markers never shown).
639#[derive(Debug, Clone, PartialEq)]
640pub(crate) struct GutterColumns {
641 /// The line-number column.
642 pub(crate) line_numbers: std::ops::Range<f32>,
643 /// The fold-marker (chevron) column.
644 pub(crate) fold_markers: std::ops::Range<f32>,
645}
646
647#[cfg(test)]
648mod tests {
649 use super::*;
650
651 #[test]
652 fn test_indent_width_blank_lines() {
653 assert_eq!(indent_width(""), None);
654 assert_eq!(indent_width(" "), None);
655 assert_eq!(indent_width("\t"), None);
656 }
657
658 #[test]
659 fn test_indent_width_expands_tabs() {
660 assert_eq!(indent_width("code"), Some(0));
661 assert_eq!(indent_width(" code"), Some(2));
662 assert_eq!(indent_width("\tcode"), Some(TAB_WIDTH));
663 assert_eq!(indent_width("\t code"), Some(TAB_WIDTH + 2));
664 }
665
666 #[test]
667 fn test_compare_floats() {
668 // Equal cases
669 assert_eq!(
670 compare_floats(1.0, 1.0),
671 CmpOrdering::Equal,
672 "Exact equality"
673 );
674 assert_eq!(
675 compare_floats(1.0, 1.0 + 0.0001),
676 CmpOrdering::Equal,
677 "Within epsilon (positive)"
678 );
679 assert_eq!(
680 compare_floats(1.0, 1.0 - 0.0001),
681 CmpOrdering::Equal,
682 "Within epsilon (negative)"
683 );
684
685 // Greater cases
686 assert_eq!(
687 compare_floats(1.0 + 0.002, 1.0),
688 CmpOrdering::Greater,
689 "Definitely greater"
690 );
691 assert_eq!(
692 compare_floats(1.0011, 1.0),
693 CmpOrdering::Greater,
694 "Just above epsilon"
695 );
696
697 // Less cases
698 assert_eq!(
699 compare_floats(1.0, 1.0 + 0.002),
700 CmpOrdering::Less,
701 "Definitely less"
702 );
703 assert_eq!(
704 compare_floats(1.0, 1.0011),
705 CmpOrdering::Less,
706 "Just below negative epsilon"
707 );
708 }
709
710 #[test]
711 fn test_measure_text_width_ascii() {
712 // "abc" (3 chars) -> 3 * CHAR_WIDTH
713 let text = "abc";
714 let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
715 let expected = CHAR_WIDTH * 3.0;
716 assert_eq!(
717 compare_floats(width, expected),
718 CmpOrdering::Equal,
719 "Width mismatch for ASCII"
720 );
721 }
722
723 #[test]
724 fn test_measure_text_width_cjk() {
725 // "你好" (2 chars) -> 2 * FONT_SIZE
726 // Chinese characters are typically full-width.
727 // width = 2 * FONT_SIZE
728 let text = "你好";
729 let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
730 let expected = FONT_SIZE * 2.0;
731 assert_eq!(
732 compare_floats(width, expected),
733 CmpOrdering::Equal,
734 "Width mismatch for CJK"
735 );
736 }
737
738 #[test]
739 fn test_measure_text_width_mixed() {
740 // "Hi" (2 chars) -> 2 * CHAR_WIDTH
741 // "你好" (2 chars) -> 2 * FONT_SIZE
742 let text = "Hi你好";
743 let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
744 let expected = CHAR_WIDTH * 2.0 + FONT_SIZE * 2.0;
745 assert_eq!(
746 compare_floats(width, expected),
747 CmpOrdering::Equal,
748 "Width mismatch for mixed content"
749 );
750 }
751
752 #[test]
753 fn test_measure_text_width_control_chars() {
754 // "\t\n" (2 chars)
755 // width = 4 * CHAR_WIDTH (tab) + 0 (newline)
756 let text = "\t\n";
757 let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
758 let expected = CHAR_WIDTH * TAB_WIDTH as f32;
759 assert_eq!(
760 compare_floats(width, expected),
761 CmpOrdering::Equal,
762 "Width mismatch for control chars"
763 );
764 }
765
766 #[test]
767 fn test_measure_text_width_empty() {
768 let text = "";
769 let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
770 assert!(
771 (width - 0.0).abs() < f32::EPSILON,
772 "Width should be 0 for empty string"
773 );
774 // Regression test for issue #26: `Iterator::sum` over zero `f32`
775 // terms yields `-0.0`, not `0.0`. Left uncorrected, that sign bit
776 // makes an empty line's width sort *above* every real line's width
777 // in code that orders by `f32::to_bits` (as `MaxContentWidthCache`
778 // does), so a single blank line silently won the "widest line"
779 // comparison and hid the horizontal scrollbar entirely.
780 assert!(
781 !width.is_sign_negative(),
782 "an empty line's width must be positive zero, not -0.0"
783 );
784 }
785
786 #[test]
787 fn test_measure_text_width_emoji() {
788 // "👋" (1 char, width > 1) -> FONT_SIZE
789 let text = "👋";
790 let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
791 let expected = FONT_SIZE;
792 assert_eq!(
793 compare_floats(width, expected),
794 CmpOrdering::Equal,
795 "Width mismatch for emoji"
796 );
797 }
798
799 #[test]
800 fn test_measure_text_width_korean() {
801 // "안녕하세요" (5 chars)
802 // Korean characters are typically full-width.
803 // width = 5 * FONT_SIZE
804 let text = "안녕하세요";
805 let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
806 let expected = FONT_SIZE * 5.0;
807 assert_eq!(
808 compare_floats(width, expected),
809 CmpOrdering::Equal,
810 "Width mismatch for Korean"
811 );
812 }
813
814 #[test]
815 fn test_measure_text_width_japanese() {
816 // "こんにちは" (Hiragana, 5 chars) -> 5 * FONT_SIZE
817 // "カタカナ" (Katakana, 4 chars) -> 4 * FONT_SIZE
818 // "漢字" (Kanji, 2 chars) -> 2 * FONT_SIZE
819
820 let text_hiragana = "こんにちは";
821 let width_hiragana =
822 measure_text_width(text_hiragana, FONT_SIZE, CHAR_WIDTH);
823 let expected_hiragana = FONT_SIZE * 5.0;
824 assert_eq!(
825 compare_floats(width_hiragana, expected_hiragana),
826 CmpOrdering::Equal,
827 "Width mismatch for Hiragana"
828 );
829
830 let text_katakana = "カタカナ";
831 let width_katakana =
832 measure_text_width(text_katakana, FONT_SIZE, CHAR_WIDTH);
833 let expected_katakana = FONT_SIZE * 4.0;
834 assert_eq!(
835 compare_floats(width_katakana, expected_katakana),
836 CmpOrdering::Equal,
837 "Width mismatch for Katakana"
838 );
839
840 let text_kanji = "漢字";
841 let width_kanji = measure_text_width(text_kanji, FONT_SIZE, CHAR_WIDTH);
842 let expected_kanji = FONT_SIZE * 2.0;
843 assert_eq!(
844 compare_floats(width_kanji, expected_kanji),
845 CmpOrdering::Equal,
846 "Width mismatch for Kanji"
847 );
848 }
849
850 #[test]
851 fn test_set_font_size() {
852 let mut editor = CodeEditor::new("", "rs");
853
854 // Initial state (defaults)
855 assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
856 assert!((editor.line_height() - 20.0).abs() < f32::EPSILON);
857
858 // Test auto adjust = true
859 editor.set_font_size(28.0, true);
860 assert!((editor.font_size() - 28.0).abs() < f32::EPSILON);
861 // Line height should double: 20.0 * (28.0/14.0) = 40.0
862 assert_eq!(
863 compare_floats(editor.line_height(), 40.0),
864 CmpOrdering::Equal
865 );
866
867 // Test auto adjust = false
868 // First set line height to something custom
869 editor.set_line_height(50.0);
870 // Change font size but keep line height
871 editor.set_font_size(14.0, false);
872 assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
873 // Line height should stay 50.0
874 assert_eq!(
875 compare_floats(editor.line_height(), 50.0),
876 CmpOrdering::Equal
877 );
878 // Char width should have scaled back to roughly default (but depends on measurement)
879 // We check if it is close to the expected value, but since measurement can vary,
880 // we just ensure it is positive and close to what we expect (around 8.4)
881 assert!(editor.char_width > 0.0);
882 assert!((editor.char_width - CHAR_WIDTH).abs() < 0.5);
883 }
884
885 #[test]
886 fn test_measure_single_char_width() {
887 let editor = CodeEditor::new("", "rs");
888
889 // Measure 'a'
890 let width_a = editor.measure_single_char_width("a");
891 assert!(width_a > 0.0, "Width of 'a' should be positive");
892
893 // Measure Chinese char
894 let width_cjk = editor.measure_single_char_width("汉");
895 assert!(width_cjk > 0.0, "Width of '汉' should be positive");
896
897 assert!(
898 width_cjk > width_a,
899 "Width of '汉' should be greater than 'a'"
900 );
901
902 // Check that width_cjk is roughly double of width_a (common in terminal fonts)
903 // but we just check it is significantly larger
904 assert!(width_cjk >= width_a * 1.5);
905 }
906
907 #[test]
908 fn test_gutter_columns_default_to_numbers_then_markers() {
909 let editor = CodeEditor::new("fn a() {\n b\n}", "rs");
910 let columns = editor.gutter_columns();
911
912 assert_eq!(columns.line_numbers, 0.0..GUTTER_WIDTH);
913 assert_eq!(
914 columns.fold_markers,
915 GUTTER_WIDTH..GUTTER_WIDTH + FOLD_MARGIN_WIDTH
916 );
917 assert_eq!(
918 columns.fold_markers.end.to_bits(),
919 editor.gutter_width().to_bits()
920 );
921 }
922
923 #[test]
924 fn test_marker_position_only_swaps_the_gutter_columns() {
925 let mut editor = CodeEditor::new("fn a() {\n b\n}", "rs");
926 let width = editor.gutter_width();
927 editor.set_fold_marker_position(
928 crate::FoldMarkerPosition::BeforeLineNumbers,
929 );
930 let columns = editor.gutter_columns();
931
932 assert_eq!(columns.fold_markers, 0.0..FOLD_MARGIN_WIDTH);
933 assert_eq!(
934 columns.line_numbers,
935 FOLD_MARGIN_WIDTH..FOLD_MARGIN_WIDTH + GUTTER_WIDTH
936 );
937 assert_eq!(
938 editor.gutter_width().to_bits(),
939 width.to_bits(),
940 "the text must not move"
941 );
942 }
943
944 #[test]
945 fn test_never_markers_free_their_column_but_keep_fold_state() {
946 let mut editor = CodeEditor::new("fn a() {\n b\n}", "rs");
947 let _ = editor.update(&crate::Message::ToggleFold(0));
948 assert!(editor.is_folded(0));
949
950 editor.set_fold_markers(crate::FoldMarkers::Never);
951
952 assert!(editor.gutter_columns().fold_markers.is_empty());
953 assert_eq!(editor.gutter_width().to_bits(), GUTTER_WIDTH.to_bits());
954 assert!(editor.is_folded(0), "the fold state survives");
955 assert_eq!(
956 editor.visual_lines_cached(800.0).len(),
957 2,
958 "the folded block stays hidden"
959 );
960 }
961
962 #[test]
963 fn test_hover_markers_show_on_hover_and_on_collapsed_lines() {
964 let mut editor =
965 CodeEditor::new("fn a() {\n b\n}\nfn c() {\n d\n}", "rs");
966 editor.set_fold_markers(crate::FoldMarkers::OnGutterHover);
967 let marked = |editor: &CodeEditor| -> Vec<usize> {
968 editor
969 .visual_lines_cached(800.0)
970 .iter()
971 .filter(|line| editor.shows_fold_marker(line))
972 .map(|line| line.logical_line)
973 .collect()
974 };
975
976 assert!(marked(&editor).is_empty(), "hidden while not hovered");
977 let _ = editor.update(&crate::Message::ToggleFold(3));
978 assert_eq!(marked(&editor), vec![3], "a collapsed block stays marked");
979 editor.gutter_hovered.set(true);
980 assert_eq!(marked(&editor), vec![0, 3], "all shown on hover");
981 }
982
983 /// Wide measurements taken so far on this thread.
984 fn wide_measurements() -> usize {
985 WIDE_MEASUREMENTS.with(std::cell::Cell::get)
986 }
987
988 #[test]
989 fn test_wide_width_is_measured_once_per_font_and_size() {
990 // A font no other test uses, so the process-wide cache starts cold.
991 let font = iced::Font::with_name("Wide Width Count Test");
992 let mut first = CodeEditor::new("", "rs");
993 first.set_font(font);
994 let start = wide_measurements();
995
996 first.set_font_size(13.25, true);
997 assert_eq!(wide_measurements(), start + 1, "cold cache measures");
998
999 for _ in 0..5 {
1000 let mut editor = CodeEditor::new("", "rs");
1001 editor.set_font(font);
1002 editor.set_font_size(13.25, true);
1003 assert_eq!(
1004 editor.full_char_width.to_bits(),
1005 first.full_char_width.to_bits()
1006 );
1007 }
1008 assert_eq!(wide_measurements(), start + 1, "same font/size: cache hit");
1009
1010 first.set_font_size(16.75, true);
1011 assert_eq!(wide_measurements(), start + 2, "a new size measures once");
1012 }
1013
1014 #[test]
1015 fn test_cached_wide_width_matches_a_direct_measurement() {
1016 let mut editor = CodeEditor::new("", "rs");
1017 editor.set_font(iced::Font::with_name("Wide Width Match Test"));
1018 editor.set_font_size(15.5, false);
1019
1020 let direct = editor.measure_single_char_width(WIDE_REFERENCE_GLYPH);
1021 assert_eq!(editor.full_char_width.to_bits(), direct.to_bits());
1022 }
1023
1024 #[test]
1025 fn test_stale_wide_width_is_measured_again() {
1026 let font = iced::Font::with_name("Wide Width Stale Test");
1027 // Seed an entry whose narrow width no longer matches, as when the
1028 // font was still falling back to another face at first measurement.
1029 let _ = cached_wide_char_width(font, 12.0, 999.0, || 1.0);
1030
1031 let mut editor = CodeEditor::new("", "rs");
1032 editor.set_font(font);
1033 let start = wide_measurements();
1034 editor.set_font_size(12.0, false);
1035
1036 assert_eq!(wide_measurements(), start + 1, "stale entry re-measured");
1037 let direct = editor.measure_single_char_width(WIDE_REFERENCE_GLYPH);
1038 assert_eq!(editor.full_char_width.to_bits(), direct.to_bits());
1039 }
1040
1041 #[test]
1042 fn test_set_line_height() {
1043 let mut editor = CodeEditor::new("", "rs");
1044
1045 // Initial state
1046 assert!((editor.line_height() - LINE_HEIGHT).abs() < f32::EPSILON);
1047
1048 // Set custom line height
1049 editor.set_line_height(35.0);
1050 assert!((editor.line_height() - 35.0).abs() < f32::EPSILON);
1051
1052 // Font size should remain unchanged
1053 assert!((editor.font_size() - FONT_SIZE).abs() < f32::EPSILON);
1054 }
1055}