use mgui_core::{
BoxConstraints, Color, ElementId, LayoutContext, PaintCommand, PaintList, Point, Rect, RenderObject, Size,
StateApply,
};
use std::any::Any;
use crate::text::{
is_rtl_text, measure_caret_positions, measure_text_width, nearest_caret_index, paint_text_line, text_visual_height,
wrapped_line_ranges, DEFAULT_FONT_STACK,
};
pub fn text_layout_metrics(height: f32, value: &str, font_size: f32) -> (f32, f32) {
let first_line = value.split('\n').next().unwrap_or("");
let line_h = text_visual_height(first_line, font_size, None);
let total_lines = value.split('\n').count().max(1);
let top_pad = if total_lines == 1 { (height - line_h).max(0.0) * 0.5 } else { RING_T + 2.0 };
(line_h, top_pad)
}
const PAD_X: f32 = 10.0;
pub const TEXT_PAD_X: f32 = PAD_X;
const CURSOR_W: f32 = 1.5;
const RING_T: f32 = 2.0;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TextFieldLine {
pub hard_line: usize,
pub start: usize,
pub end: usize,
}
#[derive(Clone, Debug)]
pub struct TextFieldLayout {
pub lines: Vec<TextFieldLine>,
pub line_h: f32,
pub top_pad: f32,
pub text_width: f32,
pub content_height: f32,
pub viewport_height: f32,
pub max_scroll: f32,
pub scroll_y: f32,
}
impl TextFieldLayout {
pub fn cursor_line(&self, cursor: usize) -> usize {
self.lines.iter().rposition(|line| line.start <= cursor).unwrap_or(0)
}
pub fn line_text<'a>(&self, value: &'a str, index: usize) -> &'a str {
self.lines.get(index).map(|line| &value[line.start.min(value.len())..line.end.min(value.len())]).unwrap_or("")
}
pub fn x_at_in_line(&self, value: &str, line_index: usize, byte: usize, font_size: f32) -> f32 {
let Some(line) = self.lines.get(line_index) else {
return 0.0;
};
let end = byte.clamp(line.start, line.end).min(value.len());
let line_text = &value[line.start.min(value.len())..line.end.min(value.len())];
let char_index = value[line.start..end].chars().count();
measure_caret_positions(line_text, font_size, DEFAULT_FONT_STACK).get(char_index).copied().unwrap_or(0.0)
}
pub fn single_line_char_positions(&self, value: &str, font_size: f32) -> Option<(Vec<f32>, Vec<f32>)> {
if self.lines.len() != 1 {
return None;
}
let line = self.lines[0];
let text = &value[line.start.min(value.len())..line.end.min(value.len())];
if text.contains('\n') || is_rtl_text(text) {
return None;
}
let carets = measure_caret_positions(text, font_size, DEFAULT_FONT_STACK);
let chars = text.chars().count();
if carets.len() < chars + 1 {
return None;
}
let mut positions = Vec::with_capacity(chars);
let mut widths = Vec::with_capacity(chars);
for i in 0..chars {
positions.push(carets[i]);
widths.push((carets[i + 1] - carets[i]).max(0.0));
}
Some((positions, widths))
}
pub fn cursor_x(&self, value: &str, cursor: usize, font_size: f32) -> f32 {
self.x_at_in_line(value, self.cursor_line(cursor), cursor, font_size)
}
pub fn cursor_y(&self, cursor: usize) -> f32 {
self.top_pad + self.cursor_line(cursor) as f32 * self.line_h - self.scroll_y
}
pub fn offset_at(&self, value: &str, x: f32, y: f32, font_size: f32) -> usize {
if self.lines.is_empty() {
return 0;
}
let text_y = y - self.top_pad + self.scroll_y;
let index =
((text_y / self.line_h.max(0.001)).floor() as isize).clamp(0, (self.lines.len() - 1) as isize) as usize;
let line = self.lines[index];
let line_text = &value[line.start..line.end];
let carets = measure_caret_positions(line_text, font_size, DEFAULT_FONT_STACK);
let local_x = (x - PAD_X).max(0.0);
let char_col = nearest_caret_index(&carets, local_x).min(line_text.chars().count());
let byte_in_line = line_text.char_indices().nth(char_col).map(|(b, _)| b).unwrap_or(line_text.len());
(line.start + byte_in_line).min(value.len())
}
pub fn scroll_to_show(&self, cursor: usize) -> f32 {
let index = self.cursor_line(cursor);
let top = index as f32 * self.line_h;
let bottom = top + self.line_h;
let scroll = if top < self.scroll_y {
top
} else if bottom > self.scroll_y + self.viewport_height {
bottom - self.viewport_height
} else {
self.scroll_y
};
scroll.clamp(0.0, self.max_scroll)
}
}
pub fn text_field_layout(
value: &str,
width: f32,
height: f32,
font_size: f32,
soft_wrap: bool,
scroll_y: f32,
) -> TextFieldLayout {
let text_width = (width - PAD_X * 2.0).max(1.0);
let first_line = value.split('\n').next().unwrap_or("");
let line_h = text_visual_height(first_line, font_size, None).max(1.0);
let mut lines = Vec::new();
let mut hard_start = 0usize;
for (hard_line, hard_text) in value.split('\n').enumerate() {
let mut ranges =
if soft_wrap { wrapped_line_ranges(hard_text, font_size, text_width) } else { vec![(0, hard_text.len())] };
if ranges.is_empty() {
ranges.push((0, hard_text.len()));
}
if let Some(first) = ranges.first_mut() {
first.0 = 0;
}
if let Some(last) = ranges.last_mut() {
last.1 = hard_text.len().max(last.0);
}
for (start, end) in ranges {
lines.push(TextFieldLine { hard_line, start: hard_start + start, end: hard_start + end });
}
hard_start += hard_text.len() + 1;
}
if lines.is_empty() {
lines.push(TextFieldLine { hard_line: 0, start: 0, end: 0 });
}
let top_pad = if lines.len() == 1 { ((height - line_h) * 0.5).max(0.0) } else { RING_T + 2.0 };
let viewport_height = (height - top_pad * 2.0).max(line_h);
let content_height = lines.len() as f32 * line_h;
let max_scroll = (content_height - viewport_height).max(0.0);
let scroll_y = scroll_y.clamp(0.0, max_scroll);
TextFieldLayout { lines, line_h, top_pad, text_width, content_height, viewport_height, max_scroll, scroll_y }
}
pub struct TextFieldRenderObject {
pub width: f32,
pub height: f32,
pub font_size: f32,
pub placeholder: String,
pub value: String,
pub cursor: usize,
pub preedit: Option<String>,
pub preedit_cursor: Option<(usize, usize)>,
pub focused: bool,
pub cursor_visible: bool,
pub bg_color: Color,
pub bg_focused_color: Color,
pub focus_ring_color: Color,
pub text_color: Color,
pub placeholder_color: Color,
pub cursor_color: Color,
pub selection: Option<(usize, usize)>,
pub soft_wrap: bool,
pub scroll_y: f32,
pub element_id: Option<ElementId>,
}
#[derive(Clone, Debug)]
pub struct TextFieldApply {
pub width: f32,
pub height: f32,
pub font_size: f32,
pub placeholder: String,
pub value: String,
pub cursor: usize,
pub preedit: Option<String>,
pub preedit_cursor: Option<(usize, usize)>,
pub focused: bool,
pub cursor_visible: bool,
pub bg_color: Color,
pub bg_focused_color: Color,
pub focus_ring_color: Color,
pub text_color: Color,
pub placeholder_color: Color,
pub cursor_color: Color,
pub selection: Option<(usize, usize)>,
pub soft_wrap: bool,
pub scroll_y: f32,
}
impl From<TextFieldApply> for TextFieldRenderObject {
fn from(a: TextFieldApply) -> Self {
Self {
width: a.width,
height: a.height,
font_size: a.font_size,
placeholder: a.placeholder,
value: a.value,
cursor: a.cursor,
preedit: a.preedit,
preedit_cursor: a.preedit_cursor,
focused: a.focused,
cursor_visible: a.cursor_visible,
bg_color: a.bg_color,
bg_focused_color: a.bg_focused_color,
focus_ring_color: a.focus_ring_color,
text_color: a.text_color,
placeholder_color: a.placeholder_color,
cursor_color: a.cursor_color,
selection: a.selection,
soft_wrap: a.soft_wrap,
scroll_y: a.scroll_y,
element_id: None,
}
}
}
impl RenderObject for TextFieldRenderObject {
fn layout(&mut self, constraints: BoxConstraints, _ctx: &mut LayoutContext) -> Size {
let s = Size::new(self.width, self.height);
self.width = constraints.constrain(s).width;
self.height = constraints.constrain(s).height;
Size::new(self.width, self.height)
}
fn paint(&self, offset: Point, list: &mut PaintList) {
let rect = Rect::new(offset.x, offset.y, self.width, self.height);
let radius = 6.0;
if self.focused {
list.push(PaintCommand::Rect { rect, color: self.focus_ring_color, radius });
let inner =
Rect::new(offset.x + RING_T, offset.y + RING_T, self.width - RING_T * 2.0, self.height - RING_T * 2.0);
list.push(PaintCommand::Rect {
rect: inner,
color: self.bg_focused_color,
radius: (radius - RING_T).max(0.0),
});
} else {
list.push(PaintCommand::Rect { rect, color: self.bg_color, radius });
}
let layout =
text_field_layout(&self.value, self.width, self.height, self.font_size, self.soft_wrap, self.scroll_y);
let text_x = offset.x + PAD_X;
let clip = Rect::new(
offset.x + PAD_X,
offset.y + RING_T,
(self.width - PAD_X * 2.0).max(1.0),
(self.height - RING_T * 2.0).max(1.0),
);
list.push(PaintCommand::PushClip(clip));
let has_preedit = self.preedit.as_ref().map(|p| !p.is_empty()).unwrap_or(false);
if self.value.is_empty() && !has_preedit && !self.placeholder.is_empty() {
let ph_line_h = text_visual_height(&self.placeholder, self.font_size, None);
let ph_total_h = text_visual_height(&self.placeholder, self.font_size, Some(layout.text_width));
let ph_top = offset.y + ((self.height - ph_total_h) * 0.5).max(0.0);
paint_text_line(
&self.placeholder,
self.font_size,
self.placeholder_color,
Point::new(text_x, ph_top),
list,
Some(layout.text_width),
);
if self.focused {
self.paint_cursor(list, text_x, ph_top, ph_line_h);
}
list.pop_clip();
return;
}
if let Some((sel_start, sel_end)) = self.selection {
let sel_color = Color::rgba(0.24, 0.47, 0.95, 0.35);
for (index, line) in layout.lines.iter().enumerate() {
let start = sel_start.max(line.start);
let end = sel_end.min(line.end);
if start >= end {
continue;
}
let y = offset.y + layout.top_pad + index as f32 * layout.line_h - layout.scroll_y;
if y + layout.line_h < offset.y || y > offset.y + self.height {
continue;
}
let prefix_w = layout.x_at_in_line(&self.value, index, start, self.font_size);
let end_w = layout.x_at_in_line(&self.value, index, end, self.font_size);
let left = prefix_w.min(end_w);
list.push(PaintCommand::Rect {
rect: Rect::new(text_x + left, y, (prefix_w - end_w).abs(), layout.line_h),
color: sel_color,
radius: 0.0,
});
}
}
for (index, line) in layout.lines.iter().enumerate() {
let y = offset.y + layout.top_pad + index as f32 * layout.line_h - layout.scroll_y;
if y + layout.line_h < offset.y || y > offset.y + self.height {
continue;
}
let text = &self.value[line.start..line.end];
paint_text_line(text, self.font_size, self.text_color, Point::new(text_x, y), list, None);
}
let cursor_index = layout.cursor_line(self.cursor);
let cursor_y = offset.y + layout.cursor_y(self.cursor);
if has_preedit {
let preedit = self.preedit.as_deref().unwrap_or("");
let line =
layout.lines.get(cursor_index).copied().unwrap_or(TextFieldLine { hard_line: 0, start: 0, end: 0 });
let prefix = &self.value[line.start.min(self.cursor)..self.cursor.min(line.end)];
let preedit_x = text_x + measure_text_width(prefix, self.font_size);
let cursor_in_preedit = self.preedit_cursor.map(|(s, _)| s.min(preedit.len())).unwrap_or(preedit.len());
let preedit_cursor_x = text_x
+ measure_text_width(prefix, self.font_size)
+ measure_text_width(&preedit[..cursor_in_preedit], self.font_size);
if !preedit.is_empty() {
paint_text_line(
preedit,
self.font_size,
self.text_color,
Point::new(preedit_x, cursor_y),
list,
Some((layout.text_width - (preedit_x - text_x)).max(1.0)),
);
let w_preedit = measure_text_width(preedit, self.font_size);
list.push(PaintCommand::Rect {
rect: Rect::new(preedit_x, cursor_y + layout.line_h - 2.0, w_preedit, 1.5),
color: self.text_color,
radius: 0.0,
});
}
if self.focused && self.cursor_visible {
self.paint_cursor(list, preedit_cursor_x, cursor_y, layout.line_h);
}
} else {
let cursor_x = text_x + layout.cursor_x(&self.value, self.cursor, self.font_size);
if self.focused && self.cursor_visible {
self.paint_cursor(list, cursor_x, cursor_y, layout.line_h);
}
}
list.pop_clip();
}
fn hit_test(&self, position: Point, offset: Point) -> Option<ElementId> {
let rect = Rect::new(offset.x, offset.y, self.width, self.height);
if rect.contains(position) {
self.element_id
} else {
None
}
}
fn set_element_id(&mut self, id: ElementId) {
self.element_id = Some(id);
}
fn element_id(&self) -> Option<ElementId> {
self.element_id
}
fn content_size(&self) -> Size {
Size::new(self.width, self.height)
}
fn apply_state(&mut self, state: &mut dyn Any) -> StateApply {
let Some(a) = state.downcast_mut::<TextFieldApply>() else {
return StateApply::Unsupported;
};
if self.width == a.width
&& self.height == a.height
&& self.font_size == a.font_size
&& self.placeholder == a.placeholder
&& self.value == a.value
&& self.cursor == a.cursor
&& self.preedit == a.preedit
&& self.preedit_cursor == a.preedit_cursor
&& self.focused == a.focused
&& self.cursor_visible == a.cursor_visible
&& self.bg_color == a.bg_color
&& self.bg_focused_color == a.bg_focused_color
&& self.focus_ring_color == a.focus_ring_color
&& self.text_color == a.text_color
&& self.placeholder_color == a.placeholder_color
&& self.cursor_color == a.cursor_color
&& self.selection == a.selection
&& self.soft_wrap == a.soft_wrap
&& self.scroll_y == a.scroll_y
{
return StateApply::Unchanged;
}
self.width = a.width;
self.height = a.height;
self.font_size = a.font_size;
self.placeholder = std::mem::take(&mut a.placeholder);
self.value = std::mem::take(&mut a.value);
self.cursor = a.cursor;
self.preedit = a.preedit.take();
self.preedit_cursor = a.preedit_cursor;
self.focused = a.focused;
self.cursor_visible = a.cursor_visible;
self.bg_color = a.bg_color;
self.bg_focused_color = a.bg_focused_color;
self.focus_ring_color = a.focus_ring_color;
self.text_color = a.text_color;
self.placeholder_color = a.placeholder_color;
self.cursor_color = a.cursor_color;
self.selection = a.selection;
self.soft_wrap = a.soft_wrap;
self.scroll_y = a.scroll_y;
StateApply::Updated
}
}
impl TextFieldRenderObject {
fn paint_cursor(&self, list: &mut PaintList, x: f32, text_y: f32, line_h: f32) {
list.push(PaintCommand::Rect {
rect: Rect::new(x, text_y + 1.0, CURSOR_W, (line_h - 2.0).max(1.0)),
color: self.cursor_color,
radius: 0.0,
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn render_object_paints_bg_and_cursor() {
let mut ro = TextFieldRenderObject {
width: 200.0,
height: 40.0,
font_size: 16.0,
placeholder: String::new(),
value: String::new(),
cursor: 0,
preedit: None,
preedit_cursor: None,
focused: false,
cursor_visible: true,
bg_color: Color::BLACK,
bg_focused_color: Color::BLACK,
focus_ring_color: Color::WHITE,
text_color: Color::WHITE,
placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
cursor_color: Color::WHITE,
selection: None,
soft_wrap: false,
scroll_y: 0.0,
element_id: None,
};
ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
let mut list = PaintList::new();
ro.paint(Point::ZERO, &mut list);
let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
assert_eq!(rects, 1, "未聚焦空值:仅背景");
let mut focused_ro = TextFieldRenderObject { focused: true, value: "hi".to_string(), cursor: 2, ..ro };
focused_ro.set_element_id(ElementId::default());
assert!(focused_ro.element_id().is_some());
let mut list = PaintList::new();
focused_ro.paint(Point::ZERO, &mut list);
let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
let texts = list.commands.iter().filter(|c| matches!(c, PaintCommand::TexturedRect { .. })).count();
assert_eq!(rects, 3, "ring + bg + cursor");
assert!(texts >= 1, "文字至少 1 个 glyph rect");
}
#[test]
fn preedit_paints_underline() {
let mut ro = TextFieldRenderObject {
width: 200.0,
height: 40.0,
font_size: 16.0,
placeholder: String::new(),
value: "a".to_string(),
cursor: 1,
preedit: Some("中".to_string()),
preedit_cursor: None,
focused: true,
cursor_visible: true,
bg_color: Color::BLACK,
bg_focused_color: Color::BLACK,
focus_ring_color: Color::WHITE,
text_color: Color::WHITE,
placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
cursor_color: Color::WHITE,
selection: None,
soft_wrap: false,
scroll_y: 0.0,
element_id: None,
};
ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
let mut list = PaintList::new();
ro.paint(Point::ZERO, &mut list);
let rects = list.commands.iter().filter(|c| matches!(c, PaintCommand::Rect { .. })).count();
assert_eq!(rects, 4, "ring + bg + preedit 下划线 + 光标");
}
#[test]
fn placeholder_uses_own_glyph_metrics_for_vertical_centering() {
fn glyph_bounds(list: &PaintList) -> (f32, f32) {
let mut min = f32::INFINITY;
let mut max = f32::NEG_INFINITY;
for c in &list.commands {
if let PaintCommand::TexturedRect { rect, .. } = c {
min = min.min(rect.y);
max = max.max(rect.y + rect.height);
}
}
(min, max)
}
fn paint(value: &str, placeholder: &str) -> PaintList {
let mut ro = TextFieldRenderObject {
width: 240.0,
height: 48.0,
font_size: 16.0,
placeholder: placeholder.to_string(),
value: value.to_string(),
cursor: value.len(),
preedit: None,
preedit_cursor: None,
focused: false,
cursor_visible: true,
bg_color: Color::BLACK,
bg_focused_color: Color::BLACK,
focus_ring_color: Color::WHITE,
text_color: Color::WHITE,
placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
cursor_color: Color::WHITE,
selection: None,
soft_wrap: false,
scroll_y: 0.0,
element_id: None,
};
ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
let mut list = PaintList::new();
ro.paint(Point::ZERO, &mut list);
list
}
let ph = paint("", "Ag你好");
let value = paint("Ag你好", "");
let (ph_min, ph_max) = glyph_bounds(&ph);
let (v_min, v_max) = glyph_bounds(&value);
assert!((ph_min - v_min).abs() < 0.01, "placeholder 顶边应等于同文本 value 顶边");
assert!((ph_max - v_max).abs() < 0.01, "placeholder 底边应等于同文本 value 底边");
}
#[test]
fn soft_wrap_splits_long_line() {
let layout = text_field_layout("hello world hello world", 100.0, 80.0, 16.0, true, 0.0);
assert!(layout.lines.len() > 1, "长行应拆成多条视觉行");
assert_eq!(layout.lines[0].hard_line, 0);
assert!(layout.lines.iter().all(|line| line.start <= line.end));
assert_eq!(layout.lines.first().unwrap().start, 0);
assert_eq!(layout.lines.last().unwrap().end, "hello world hello world".len());
}
#[test]
fn hard_newlines_preserve_empty_lines() {
let value = "a\n\nb";
let layout = text_field_layout(value, 200.0, 100.0, 16.0, false, 0.0);
assert_eq!(layout.lines.len(), 3);
assert_eq!(layout.lines[1].start, 2);
assert_eq!(layout.lines[1].end, 2);
assert_eq!(layout.lines[2].start, 3);
}
#[test]
fn cursor_and_hit_test_follow_visual_lines() {
let value = "hello world hello world";
let layout = text_field_layout(value, 100.0, 80.0, 16.0, true, 0.0);
let second = layout.lines[1];
assert!(second.start > 0);
assert_eq!(layout.cursor_line(second.start), 1);
assert!(layout.cursor_x(value, second.start, 16.0).abs() < 0.01);
let y = layout.top_pad + layout.line_h * 1.5;
assert_eq!(layout.offset_at(value, PAD_X + 1.0, y, 16.0), second.start);
}
#[test]
fn soft_wrap_paints_multiple_visual_rows() {
let mut ro = TextFieldRenderObject {
width: 100.0,
height: 120.0,
font_size: 16.0,
placeholder: String::new(),
value: "hello world hello world".to_string(),
cursor: 0,
preedit: None,
preedit_cursor: None,
focused: false,
cursor_visible: true,
bg_color: Color::BLACK,
bg_focused_color: Color::BLACK,
focus_ring_color: Color::WHITE,
text_color: Color::WHITE,
placeholder_color: Color::rgba(0.5, 0.5, 0.5, 1.0),
cursor_color: Color::WHITE,
selection: None,
soft_wrap: true,
scroll_y: 0.0,
element_id: None,
};
ro.layout(BoxConstraints::UNBOUNDED, &mut LayoutContext);
let mut list = PaintList::new();
ro.paint(Point::ZERO, &mut list);
let mut rows: Vec<i32> = list
.commands
.iter()
.filter_map(|cmd| match cmd {
PaintCommand::TexturedRect { rect, .. } => Some(rect.y as i32),
_ => None,
})
.collect();
rows.sort_unstable();
rows.dedup();
assert!(rows.len() > 1, "soft wrap 应绘制多条视觉行(rows={rows:?})");
}
#[test]
fn scroll_to_show_last_line() {
let value = "one\ntwo\nthree\nfour\nfive";
let mut layout = text_field_layout(value, 200.0, 40.0, 16.0, false, 0.0);
assert!(layout.max_scroll > 0.0);
let cursor = value.rfind("five").unwrap();
layout.scroll_y = layout.scroll_to_show(cursor);
assert!(layout.scroll_y > 0.0, "光标在末尾时应向下滚动");
assert!(layout.scroll_y <= layout.max_scroll);
}
}
#[cfg(test)]
mod apply_state_tests {
use super::*;
fn payload(value: &str, cursor: usize) -> TextFieldApply {
TextFieldApply {
width: 200.0,
height: 40.0,
font_size: 16.0,
placeholder: String::new(),
value: value.into(),
cursor,
preedit: None,
preedit_cursor: None,
focused: true,
cursor_visible: true,
bg_color: Color::BLACK,
bg_focused_color: Color::BLACK,
focus_ring_color: Color::WHITE,
text_color: Color::WHITE,
placeholder_color: Color::WHITE,
cursor_color: Color::WHITE,
selection: None,
soft_wrap: false,
scroll_y: 0.0,
}
}
#[test]
fn payload_apply_updates_text_field_in_place() {
let mut ro = TextFieldRenderObject::from(payload("a", 1));
let mut next = payload("ab", 2);
assert_eq!(ro.apply_state(&mut next), StateApply::Updated);
assert_eq!(ro.value, "ab");
assert_eq!(ro.cursor, 2);
let mut same = payload("ab", 2);
assert_eq!(ro.apply_state(&mut same), StateApply::Unchanged);
}
}