use iced::advanced::text::{
Alignment, Paragraph, Renderer as TextRenderer, Text,
};
use std::cmp::Ordering as CmpOrdering;
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use unicode_width::UnicodeWidthChar;
use crate::canvas_editor::CodeEditor;
pub(crate) const FONT_SIZE: f32 = 14.0;
pub(crate) const LINE_HEIGHT: f32 = 20.0;
pub(crate) const CHAR_WIDTH: f32 = 8.4; pub(crate) const TAB_WIDTH: usize = 4;
pub(crate) const GUTTER_WIDTH: f32 = 45.0;
pub(crate) const FOLD_MARGIN_WIDTH: f32 = 14.0;
pub(crate) const CURSOR_BLINK_INTERVAL: std::time::Duration =
std::time::Duration::from_millis(530);
const WIDE_REFERENCE_GLYPH: &str = "汉";
const NARROW_WIDTH_TOLERANCE: f32 = 0.01;
type WideWidthCache = HashMap<(iced::Font, u32), (f32, f32)>;
static WIDE_WIDTHS: OnceLock<Mutex<WideWidthCache>> = OnceLock::new();
#[cfg(test)]
thread_local! {
static WIDE_MEASUREMENTS: std::cell::Cell<usize> =
const { std::cell::Cell::new(0) };
}
fn cached_wide_char_width(
font: iced::Font,
size: f32,
narrow_width: f32,
measure: impl FnOnce() -> f32,
) -> f32 {
let key = (font, size.to_bits());
let cache = WIDE_WIDTHS.get_or_init(Mutex::default);
let cached = cache
.lock()
.unwrap_or_else(|error| error.into_inner())
.get(&key)
.copied();
if let Some((narrow, wide)) = cached
&& (narrow - narrow_width).abs() <= NARROW_WIDTH_TOLERANCE
{
return wide;
}
#[cfg(test)]
WIDE_MEASUREMENTS.with(|count| count.set(count.get() + 1));
let wide = measure();
cache
.lock()
.unwrap_or_else(|error| error.into_inner())
.insert(key, (narrow_width, wide));
wide
}
pub(crate) fn measure_char_width(
c: char,
full_char_width: f32,
char_width: f32,
) -> f32 {
if c == '\t' {
return char_width * TAB_WIDTH as f32;
}
match c.width() {
Some(w) if w > 1 => full_char_width,
Some(_) => char_width,
None => 0.0,
}
}
pub(crate) fn indent_width(line: &str) -> Option<usize> {
let mut width = 0;
for c in line.chars() {
match c {
'\t' => width += TAB_WIDTH,
' ' => width += 1,
_ if c.is_whitespace() => width += 1,
_ => return Some(width),
}
}
None
}
pub(crate) fn measure_text_width(
text: &str,
full_char_width: f32,
char_width: f32,
) -> f32 {
let width: f32 = text
.chars()
.map(|c| measure_char_width(c, full_char_width, char_width))
.sum();
if width.is_sign_negative() { width.abs() } else { width }
}
pub(crate) const EPSILON: f32 = 0.001;
pub(crate) const CACHE_WINDOW_MARGIN_MULTIPLIER: usize = 2;
pub(crate) const HIGHLIGHT_LINES_PER_FRAME: usize = 2_000;
pub(crate) const HIGHLIGHT_TIME_PER_FRAME: std::time::Duration =
std::time::Duration::from_millis(8);
pub(crate) const HIGHLIGHT_CLOCK_CHECK_INTERVAL: usize = 64;
pub(crate) fn compare_floats(a: f32, b: f32) -> CmpOrdering {
if (a - b).abs() < EPSILON {
CmpOrdering::Equal
} else if a > b {
CmpOrdering::Greater
} else {
CmpOrdering::Less
}
}
impl CodeEditor {
pub fn set_font(&mut self, font: iced::Font) {
self.font = font;
self.recalculate_char_dimensions(false);
}
pub fn set_font_size(&mut self, size: f32, auto_adjust_line_height: bool) {
self.font_size = size;
self.recalculate_char_dimensions(auto_adjust_line_height);
}
pub(crate) fn recalculate_char_dimensions(
&mut self,
auto_adjust_line_height: bool,
) {
self.char_width = self.measure_single_char_width("a");
self.full_char_width = cached_wide_char_width(
self.font,
self.font_size,
self.char_width,
|| self.measure_single_char_width(WIDE_REFERENCE_GLYPH),
);
if self.char_width.is_infinite() {
self.char_width = self.font_size / 2.0; }
if self.full_char_width.is_infinite() {
self.full_char_width = self.font_size;
}
if auto_adjust_line_height {
let line_height_ratio = LINE_HEIGHT / FONT_SIZE;
self.line_height = self.font_size * line_height_ratio;
}
self.content_cache.clear();
self.overlay_cache.clear();
*self.max_content_width_cache.borrow_mut() = None;
}
fn measure_single_char_width(&self, content: &str) -> f32 {
let text = Text {
content,
font: self.font,
size: iced::Pixels(self.font_size),
line_height: iced::advanced::text::LineHeight::default(),
bounds: iced::Size::new(f32::INFINITY, f32::INFINITY),
align_x: Alignment::Left,
align_y: iced::alignment::Vertical::Top,
shaping: iced::advanced::text::Shaping::Advanced,
wrapping: iced::advanced::text::Wrapping::default(),
};
let p = <iced::Renderer as TextRenderer>::Paragraph::with_text(text);
p.min_width()
}
pub fn font_size(&self) -> f32 {
self.font_size
}
pub fn char_width(&self) -> f32 {
self.char_width
}
pub fn full_char_width(&self) -> f32 {
self.full_char_width
}
pub fn measure_text_width(&self, text: &str) -> f32 {
measure_text_width(text, self.full_char_width, self.char_width)
}
pub fn set_line_height(&mut self, height: f32) {
self.line_height = height;
self.content_cache.clear();
self.overlay_cache.clear();
}
pub fn line_height(&self) -> f32 {
self.line_height
}
pub fn viewport_height(&self) -> f32 {
self.viewport_height
}
pub fn viewport_width(&self) -> f32 {
self.viewport_width
}
pub fn viewport_scroll(&self) -> f32 {
self.viewport_scroll
}
#[must_use]
pub fn with_viewport_height(mut self, height: f32) -> Self {
self.viewport_height = height;
self
}
pub(crate) fn gutter_width(&self) -> f32 {
self.line_number_gutter_width() + self.fold_margin_width()
}
pub(crate) fn line_number_gutter_width(&self) -> f32 {
if self.line_numbers_enabled { GUTTER_WIDTH } else { 0.0 }
}
pub(crate) fn fold_margin_width(&self) -> f32 {
if self.folding_enabled
&& self.fold_markers != crate::FoldMarkers::Never
{
FOLD_MARGIN_WIDTH
} else {
0.0
}
}
pub(crate) fn gutter_columns(&self) -> GutterColumns {
let numbers = self.line_number_gutter_width();
let markers = self.fold_margin_width();
match self.fold_marker_position {
crate::FoldMarkerPosition::AfterLineNumbers => GutterColumns {
line_numbers: 0.0..numbers,
fold_markers: numbers..numbers + markers,
},
crate::FoldMarkerPosition::BeforeLineNumbers => GutterColumns {
fold_markers: 0.0..markers,
line_numbers: markers..markers + numbers,
},
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct GutterColumns {
pub(crate) line_numbers: std::ops::Range<f32>,
pub(crate) fold_markers: std::ops::Range<f32>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_indent_width_blank_lines() {
assert_eq!(indent_width(""), None);
assert_eq!(indent_width(" "), None);
assert_eq!(indent_width("\t"), None);
}
#[test]
fn test_indent_width_expands_tabs() {
assert_eq!(indent_width("code"), Some(0));
assert_eq!(indent_width(" code"), Some(2));
assert_eq!(indent_width("\tcode"), Some(TAB_WIDTH));
assert_eq!(indent_width("\t code"), Some(TAB_WIDTH + 2));
}
#[test]
fn test_compare_floats() {
assert_eq!(
compare_floats(1.0, 1.0),
CmpOrdering::Equal,
"Exact equality"
);
assert_eq!(
compare_floats(1.0, 1.0 + 0.0001),
CmpOrdering::Equal,
"Within epsilon (positive)"
);
assert_eq!(
compare_floats(1.0, 1.0 - 0.0001),
CmpOrdering::Equal,
"Within epsilon (negative)"
);
assert_eq!(
compare_floats(1.0 + 0.002, 1.0),
CmpOrdering::Greater,
"Definitely greater"
);
assert_eq!(
compare_floats(1.0011, 1.0),
CmpOrdering::Greater,
"Just above epsilon"
);
assert_eq!(
compare_floats(1.0, 1.0 + 0.002),
CmpOrdering::Less,
"Definitely less"
);
assert_eq!(
compare_floats(1.0, 1.0011),
CmpOrdering::Less,
"Just below negative epsilon"
);
}
#[test]
fn test_measure_text_width_ascii() {
let text = "abc";
let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
let expected = CHAR_WIDTH * 3.0;
assert_eq!(
compare_floats(width, expected),
CmpOrdering::Equal,
"Width mismatch for ASCII"
);
}
#[test]
fn test_measure_text_width_cjk() {
let text = "你好";
let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
let expected = FONT_SIZE * 2.0;
assert_eq!(
compare_floats(width, expected),
CmpOrdering::Equal,
"Width mismatch for CJK"
);
}
#[test]
fn test_measure_text_width_mixed() {
let text = "Hi你好";
let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
let expected = CHAR_WIDTH * 2.0 + FONT_SIZE * 2.0;
assert_eq!(
compare_floats(width, expected),
CmpOrdering::Equal,
"Width mismatch for mixed content"
);
}
#[test]
fn test_measure_text_width_control_chars() {
let text = "\t\n";
let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
let expected = CHAR_WIDTH * TAB_WIDTH as f32;
assert_eq!(
compare_floats(width, expected),
CmpOrdering::Equal,
"Width mismatch for control chars"
);
}
#[test]
fn test_measure_text_width_empty() {
let text = "";
let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
assert!(
(width - 0.0).abs() < f32::EPSILON,
"Width should be 0 for empty string"
);
assert!(
!width.is_sign_negative(),
"an empty line's width must be positive zero, not -0.0"
);
}
#[test]
fn test_measure_text_width_emoji() {
let text = "👋";
let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
let expected = FONT_SIZE;
assert_eq!(
compare_floats(width, expected),
CmpOrdering::Equal,
"Width mismatch for emoji"
);
}
#[test]
fn test_measure_text_width_korean() {
let text = "안녕하세요";
let width = measure_text_width(text, FONT_SIZE, CHAR_WIDTH);
let expected = FONT_SIZE * 5.0;
assert_eq!(
compare_floats(width, expected),
CmpOrdering::Equal,
"Width mismatch for Korean"
);
}
#[test]
fn test_measure_text_width_japanese() {
let text_hiragana = "こんにちは";
let width_hiragana =
measure_text_width(text_hiragana, FONT_SIZE, CHAR_WIDTH);
let expected_hiragana = FONT_SIZE * 5.0;
assert_eq!(
compare_floats(width_hiragana, expected_hiragana),
CmpOrdering::Equal,
"Width mismatch for Hiragana"
);
let text_katakana = "カタカナ";
let width_katakana =
measure_text_width(text_katakana, FONT_SIZE, CHAR_WIDTH);
let expected_katakana = FONT_SIZE * 4.0;
assert_eq!(
compare_floats(width_katakana, expected_katakana),
CmpOrdering::Equal,
"Width mismatch for Katakana"
);
let text_kanji = "漢字";
let width_kanji = measure_text_width(text_kanji, FONT_SIZE, CHAR_WIDTH);
let expected_kanji = FONT_SIZE * 2.0;
assert_eq!(
compare_floats(width_kanji, expected_kanji),
CmpOrdering::Equal,
"Width mismatch for Kanji"
);
}
#[test]
fn test_set_font_size() {
let mut editor = CodeEditor::new("", "rs");
assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
assert!((editor.line_height() - 20.0).abs() < f32::EPSILON);
editor.set_font_size(28.0, true);
assert!((editor.font_size() - 28.0).abs() < f32::EPSILON);
assert_eq!(
compare_floats(editor.line_height(), 40.0),
CmpOrdering::Equal
);
editor.set_line_height(50.0);
editor.set_font_size(14.0, false);
assert!((editor.font_size() - 14.0).abs() < f32::EPSILON);
assert_eq!(
compare_floats(editor.line_height(), 50.0),
CmpOrdering::Equal
);
assert!(editor.char_width > 0.0);
assert!((editor.char_width - CHAR_WIDTH).abs() < 0.5);
}
#[test]
fn test_measure_single_char_width() {
let editor = CodeEditor::new("", "rs");
let width_a = editor.measure_single_char_width("a");
assert!(width_a > 0.0, "Width of 'a' should be positive");
let width_cjk = editor.measure_single_char_width("汉");
assert!(width_cjk > 0.0, "Width of '汉' should be positive");
assert!(
width_cjk > width_a,
"Width of '汉' should be greater than 'a'"
);
assert!(width_cjk >= width_a * 1.5);
}
#[test]
fn test_gutter_columns_default_to_numbers_then_markers() {
let editor = CodeEditor::new("fn a() {\n b\n}", "rs");
let columns = editor.gutter_columns();
assert_eq!(columns.line_numbers, 0.0..GUTTER_WIDTH);
assert_eq!(
columns.fold_markers,
GUTTER_WIDTH..GUTTER_WIDTH + FOLD_MARGIN_WIDTH
);
assert_eq!(
columns.fold_markers.end.to_bits(),
editor.gutter_width().to_bits()
);
}
#[test]
fn test_marker_position_only_swaps_the_gutter_columns() {
let mut editor = CodeEditor::new("fn a() {\n b\n}", "rs");
let width = editor.gutter_width();
editor.set_fold_marker_position(
crate::FoldMarkerPosition::BeforeLineNumbers,
);
let columns = editor.gutter_columns();
assert_eq!(columns.fold_markers, 0.0..FOLD_MARGIN_WIDTH);
assert_eq!(
columns.line_numbers,
FOLD_MARGIN_WIDTH..FOLD_MARGIN_WIDTH + GUTTER_WIDTH
);
assert_eq!(
editor.gutter_width().to_bits(),
width.to_bits(),
"the text must not move"
);
}
#[test]
fn test_never_markers_free_their_column_but_keep_fold_state() {
let mut editor = CodeEditor::new("fn a() {\n b\n}", "rs");
let _ = editor.update(&crate::Message::ToggleFold(0));
assert!(editor.is_folded(0));
editor.set_fold_markers(crate::FoldMarkers::Never);
assert!(editor.gutter_columns().fold_markers.is_empty());
assert_eq!(editor.gutter_width().to_bits(), GUTTER_WIDTH.to_bits());
assert!(editor.is_folded(0), "the fold state survives");
assert_eq!(
editor.visual_lines_cached(800.0).len(),
2,
"the folded block stays hidden"
);
}
#[test]
fn test_hover_markers_show_on_hover_and_on_collapsed_lines() {
let mut editor =
CodeEditor::new("fn a() {\n b\n}\nfn c() {\n d\n}", "rs");
editor.set_fold_markers(crate::FoldMarkers::OnGutterHover);
let marked = |editor: &CodeEditor| -> Vec<usize> {
editor
.visual_lines_cached(800.0)
.iter()
.filter(|line| editor.shows_fold_marker(line))
.map(|line| line.logical_line)
.collect()
};
assert!(marked(&editor).is_empty(), "hidden while not hovered");
let _ = editor.update(&crate::Message::ToggleFold(3));
assert_eq!(marked(&editor), vec![3], "a collapsed block stays marked");
editor.gutter_hovered.set(true);
assert_eq!(marked(&editor), vec![0, 3], "all shown on hover");
}
fn wide_measurements() -> usize {
WIDE_MEASUREMENTS.with(std::cell::Cell::get)
}
#[test]
fn test_wide_width_is_measured_once_per_font_and_size() {
let font = iced::Font::with_name("Wide Width Count Test");
let mut first = CodeEditor::new("", "rs");
first.set_font(font);
let start = wide_measurements();
first.set_font_size(13.25, true);
assert_eq!(wide_measurements(), start + 1, "cold cache measures");
for _ in 0..5 {
let mut editor = CodeEditor::new("", "rs");
editor.set_font(font);
editor.set_font_size(13.25, true);
assert_eq!(
editor.full_char_width.to_bits(),
first.full_char_width.to_bits()
);
}
assert_eq!(wide_measurements(), start + 1, "same font/size: cache hit");
first.set_font_size(16.75, true);
assert_eq!(wide_measurements(), start + 2, "a new size measures once");
}
#[test]
fn test_cached_wide_width_matches_a_direct_measurement() {
let mut editor = CodeEditor::new("", "rs");
editor.set_font(iced::Font::with_name("Wide Width Match Test"));
editor.set_font_size(15.5, false);
let direct = editor.measure_single_char_width(WIDE_REFERENCE_GLYPH);
assert_eq!(editor.full_char_width.to_bits(), direct.to_bits());
}
#[test]
fn test_stale_wide_width_is_measured_again() {
let font = iced::Font::with_name("Wide Width Stale Test");
let _ = cached_wide_char_width(font, 12.0, 999.0, || 1.0);
let mut editor = CodeEditor::new("", "rs");
editor.set_font(font);
let start = wide_measurements();
editor.set_font_size(12.0, false);
assert_eq!(wide_measurements(), start + 1, "stale entry re-measured");
let direct = editor.measure_single_char_width(WIDE_REFERENCE_GLYPH);
assert_eq!(editor.full_char_width.to_bits(), direct.to_bits());
}
#[test]
fn test_set_line_height() {
let mut editor = CodeEditor::new("", "rs");
assert!((editor.line_height() - LINE_HEIGHT).abs() < f32::EPSILON);
editor.set_line_height(35.0);
assert!((editor.line_height() - 35.0).abs() < f32::EPSILON);
assert!((editor.font_size() - FONT_SIZE).abs() < f32::EPSILON);
}
}