mgui-core 0.7.0

mgui 框架核心:Element/RenderObject/Widget 三树、布局与绘制协议、帧管线与响应式原语
Documentation
//! 共用文本编辑契约 —— buffer / selection / preedit 的单一语义来源。
//!
//! `TextField` 与 `CodeEditor` 的字段布局不同(前者是单行字节偏移 + 可选区间,
//! 后者是 `Pos { line, col }` + anchor/cursor),但以下语义必须完全一致:
//!
//! - 左右移动、退格、前删以 **grapheme cluster** 为边界;
//! - 选区由 anchor/focus 定义,`range()` 负责归一化;
//! - preedit 不写入 buffer,commit 落地一次,失焦/取消只丢弃组合态。
//!
//! 这里只定义契约与算法,不绑定任何控件或渲染层。buffer 由各 crate 实现
//! [`TextBuffer`]:`String` 的实现在 core 内,行式文档在 `mgui-editor` 内。

use crate::grapheme::{floor_grapheme_boundary, next_grapheme_boundary, prev_grapheme_boundary};

/// 一次替换操作的结果。与 undo 栈条目解耦:buffer 自行决定是否记录 undo。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextEdit<P> {
    pub start: P,
    pub end: P,
    pub removed: String,
    pub inserted: String,
    pub new_end: P,
}

/// 文本缓冲区契约。
///
/// `Pos` 可以是字节偏移(`String`)或 `{ line, col }`(行式文档)。
/// 所有位置参数在算法内都先经 `clamp_pos`,实现方必须保证返回值落在合法边界上。
pub trait TextBuffer {
    type Pos: Clone + Ord;

    fn start_pos(&self) -> Self::Pos;
    fn end_pos(&self) -> Self::Pos;
    fn clamp_pos(&self, pos: Self::Pos) -> Self::Pos;
    fn prev_boundary(&self, pos: Self::Pos) -> Self::Pos;
    fn next_boundary(&self, pos: Self::Pos) -> Self::Pos;
    fn text_between(&self, start: Self::Pos, end: Self::Pos) -> String;
    fn replace(&mut self, start: Self::Pos, end: Self::Pos, text: &str) -> TextEdit<Self::Pos>;
}

impl TextBuffer for String {
    type Pos = usize;

    fn start_pos(&self) -> usize {
        0
    }

    fn end_pos(&self) -> usize {
        self.len()
    }

    fn clamp_pos(&self, pos: usize) -> usize {
        floor_grapheme_boundary(self, pos)
    }

    fn prev_boundary(&self, pos: usize) -> usize {
        prev_grapheme_boundary(self, pos)
    }

    fn next_boundary(&self, pos: usize) -> usize {
        next_grapheme_boundary(self, pos)
    }

    fn text_between(&self, start: usize, end: usize) -> String {
        let len = self.len();
        let a = start.min(end).min(len);
        let b = start.max(end).min(len);
        self[a..b].to_string()
    }

    fn replace(&mut self, start: usize, end: usize, text: &str) -> TextEdit<usize> {
        let start = self.clamp_pos(start);
        let end = self.clamp_pos(end);
        let (start, end) = if start <= end { (start, end) } else { (end, start) };
        let removed = self[start..end].to_string();
        self.replace_range(start..end, text);
        TextEdit { start, end, removed, inserted: text.to_string(), new_end: start + text.len() }
    }
}

/// anchor/focus 选区。`anchor` 不随扩展方向变化,`focus` 即光标。
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TextSelection<P> {
    anchor: P,
    focus: P,
}

impl<P: Clone + Ord> TextSelection<P> {
    pub fn new(anchor: P, focus: P) -> Self {
        Self { anchor, focus }
    }

    pub fn collapsed(pos: P) -> Self {
        Self::new(pos.clone(), pos)
    }

    /// 从归一化区间构造:anchor = start,focus = end(光标在 focus 端)。
    pub fn from_range(a: P, b: P) -> Self {
        let (start, end) = if a <= b { (a, b) } else { (b, a) };
        Self::new(start, end)
    }

    pub fn anchor(&self) -> &P {
        &self.anchor
    }

    pub fn focus(&self) -> &P {
        &self.focus
    }

    pub fn is_empty(&self) -> bool {
        self.anchor == self.focus
    }

    pub fn range(&self) -> (P, P) {
        if self.anchor <= self.focus {
            (self.anchor.clone(), self.focus.clone())
        } else {
            (self.focus.clone(), self.anchor.clone())
        }
    }

    pub fn set_anchor(&mut self, pos: P) {
        self.anchor = pos;
    }

    pub fn collapse_to(&mut self, pos: P) {
        self.anchor = pos.clone();
        self.focus = pos;
    }

    pub fn set_focus(&mut self, pos: P) {
        self.focus = pos;
    }
}

/// 光标移动方向(均以 grapheme cluster 为步长,可跨硬行/软换行由 buffer 决定)。
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TextMove {
    Left,
    Right,
}

/// 共用移动算法:`extend = false` 折叠选区,`true` 保持 anchor 只改 focus。
pub fn move_selection<B: TextBuffer>(buf: &B, sel: &mut TextSelection<B::Pos>, dir: TextMove, extend: bool) {
    let focus = sel.focus().clone();
    let next = match dir {
        TextMove::Left => buf.prev_boundary(focus),
        TextMove::Right => buf.next_boundary(focus),
    };
    if extend {
        sel.set_focus(next);
    } else {
        sel.collapse_to(next);
    }
}

/// 用 `text` 替换当前选区(含空选区插入)。无实际变化时返回 `None`。
pub fn replace_selection<B: TextBuffer>(
    buf: &mut B,
    sel: &mut TextSelection<B::Pos>,
    text: &str,
) -> Option<TextEdit<B::Pos>> {
    if sel.is_empty() && text.is_empty() {
        return None;
    }
    let (start, end) = sel.range();
    let edit = buf.replace(start, end, text);
    sel.collapse_to(edit.new_end.clone());
    Some(edit)
}

/// 删除选区;无选区返回 `None`。
pub fn delete_selection<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
    if sel.is_empty() {
        return None;
    }
    replace_selection(buf, sel, "")
}

/// Backspace:有选区删选区,否则删光标前一个 grapheme。
pub fn delete_before<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
    if !sel.is_empty() {
        return delete_selection(buf, sel);
    }
    let focus = sel.focus().clone();
    let start = buf.prev_boundary(focus.clone());
    if start == focus {
        return None;
    }
    let edit = buf.replace(start, focus, "");
    sel.collapse_to(edit.new_end.clone());
    Some(edit)
}

/// Delete:有选区删选区,否则删光标后一个 grapheme。
pub fn delete_after<B: TextBuffer>(buf: &mut B, sel: &mut TextSelection<B::Pos>) -> Option<TextEdit<B::Pos>> {
    if !sel.is_empty() {
        return delete_selection(buf, sel);
    }
    let focus = sel.focus().clone();
    let end = buf.next_boundary(focus.clone());
    if end == focus {
        return None;
    }
    let edit = buf.replace(focus, end, "");
    sel.collapse_to(edit.new_end.clone());
    Some(edit)
}

/// IME 组合态。`text = None` 表示无组合;`cursor` 是组合串内的字节区间。
///
/// 组合期间不触碰 buffer;`commit()` 是唯一落地入口,`cancel()` 只丢弃组合态。
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PreeditState {
    text: Option<String>,
    cursor: Option<(usize, usize)>,
}

impl PreeditState {
    pub fn is_active(&self) -> bool {
        self.text.is_some()
    }

    pub fn text(&self) -> Option<&str> {
        self.text.as_deref()
    }

    pub fn cursor(&self) -> Option<(usize, usize)> {
        self.cursor
    }

    /// 更新组合串;空串等价于取消。光标区间夹紧并排序,越界不 panic。
    pub fn update(&mut self, text: &str, cursor: Option<(usize, usize)>) {
        if text.is_empty() {
            self.cancel();
            return;
        }
        let len = text.len();
        self.cursor = cursor.map(|(a, b)| {
            let a = a.min(len);
            let b = b.min(len);
            (a.min(b), a.max(b))
        });
        self.text = Some(text.to_string());
    }

    /// 提交组合串:返回最终文本并清空组合态。
    pub fn commit(&mut self) -> Option<String> {
        let text = self.text.take();
        self.cursor = None;
        text
    }

    pub fn cancel(&mut self) {
        self.text = None;
        self.cursor = None;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn selection_normalizes_anchor_and_focus() {
        let sel = TextSelection::from_range(9usize, 3);
        assert_eq!(sel.range(), (3, 9));
        assert_eq!(sel.anchor(), &3);
        assert_eq!(sel.focus(), &9);
        assert!(!sel.is_empty());

        let mut sel = TextSelection::collapsed(4usize);
        assert!(sel.is_empty());
        sel.set_anchor(1);
        assert_eq!(sel.range(), (1, 4));
    }

    #[test]
    fn movement_and_delete_keep_emoji_zwj_intact() {
        let family = "👨‍👩‍👧‍👦";
        let mut buf = format!("A{family}B");
        let mut sel = TextSelection::collapsed(1 + family.len());
        move_selection(&buf, &mut sel, TextMove::Left, false);
        assert_eq!(*sel.focus(), 1, "左移跳过整个 ZWJ 簇");

        sel.collapse_to(1 + family.len());
        let edit = delete_before(&mut buf, &mut sel).expect("应删除一个簇");
        assert_eq!(edit.removed, family);
        assert_eq!(buf, "AB");
        assert_eq!(*sel.focus(), 1);
    }

    #[test]
    fn replace_selection_collapses_focus_after_insert() {
        let mut buf = String::from("hello");
        let mut sel = TextSelection::from_range(1usize, 4);
        let edit = replace_selection(&mut buf, &mut sel, "i").expect("替换选区");
        assert_eq!(edit.removed, "ell");
        assert_eq!(buf, "hio");
        assert_eq!(*sel.focus(), 2);
        assert!(sel.is_empty());
    }

    #[test]
    fn preedit_lifecycle_never_touches_buffer() {
        let buf = String::from("ab");
        let mut preedit = PreeditState::default();
        preedit.update("中", Some((9, 0)));
        assert!(preedit.is_active());
        assert_eq!(preedit.text(), Some("中"));
        assert_eq!(preedit.cursor(), Some((0, 3)), "光标区间夹紧并排序");
        assert_eq!(buf, "ab");

        assert_eq!(preedit.commit().as_deref(), Some("中"));
        assert!(!preedit.is_active());
        assert_eq!(buf, "ab", "commit 由调用方决定如何写入 buffer");

        preedit.update("x", None);
        preedit.cancel();
        assert_eq!(preedit.text(), None);
    }
}