Skip to main content

aureole_core/
char_grid.rs

1//! 字符网格:终端、代码编辑器这类等宽字符的大网格。
2//!
3//! 每格(汉字、emoji 占两格)放一个字素簇:一个字,或者带变音符号的字、组合的 emoji(ZWJ、肤色、国旗、键帽、VS16);
4//! 还有前景色、背景色、粗体、斜体、下划线、删除线、反色;另外有插入点(方块、竖线、下划线,可以闪)和选区。
5//! 数据在 [`CharGrid`] 里,应用往里写,元素在下一帧把改过的行重新生成图元:
6//!
7//! - **一格 20 个字节,放得下一个字就放一个字**:放不下的簇(几个码点)存在这一行的簇表里,格子里放下标。没有簇的行、
8//!   没有簇的格子和只放字时一样大、一样快
9//! - **不走 parley 排版**:格子的位置是算出来的(列 × 格宽),每个字直接查字形图集。字第一次出现时用 parley 排一次
10//!   这一个字,取出字体和字形(顺便得到缺字回退、粗体斜体的字面或合成),之后按字查缓存。簇要真的整形:
11//!   第一次见到时整形,结果按簇和粗斜体缓存
12//! - **连字是开关**([`Element::ligated`],默认关):开着时同样式连续的格子一起整形(遇到空格分开),
13//!   字形仍然放在各自的格子上
14//! - **按行缓存图元**:每行改一次换一个新的版本号,元素按版本号缓存这一行的背景、字形、下划线、删除线图元(行内坐标);
15//!   改一行只重新生成这一行,滚动([`CharGrid::scroll_up`])只是挪行,行的缓存跟着走
16//! - 格子对齐物理像素(格宽、格高、基线都取整到物理像素),字形不用亚像素位置,背景色块之间没有缝
17//! - **制表符和方块自己画**(U+2500 ~ U+259F,见 `drawn`):铺满格子、连得上,和用哪个字体、行高多少无关
18//!
19//! ```
20//! # use aureole::prelude::*;
21//! let grid = CharGrid::new(80, 24);
22//! grid.write(0, 0, "$ cargo run", CharCellStyle::default());
23//! grid.write(1, 0, "   Compiling", CharCellStyle::default().foreground(Color::hex(0x3d9a5b)).bold(true));
24//! grid.write(1, 13, "终端里的汉字占两格", CharCellStyle::default());
25//! grid.set_caret(CharGridCaret::at(2, 0));
26//! char_grid(&grid).font_size(13).line_height(1.2);
27//! ```
28
29use std::cell::RefCell;
30use std::collections::HashMap;
31use std::hash::BuildHasherDefault;
32use std::rc::Rc;
33
34use reactive::{Signal, detached, signal};
35use scene::{Color, Quad};
36use unicode_width::UnicodeWidthChar;
37
38use crate::element::Element;
39use crate::geometry::{Affine, Rect};
40use crate::segmentation::graphemes;
41use crate::text::{CellGlyph, CellMetrics, CellShape, GlyphHasher, Ink, TextStyle, TextSystem};
42
43mod cluster;
44mod drawn;
45
46use cluster::{clamped, cluster_width, first_cluster_len, simple_width, simple_width_of_code};
47use drawn::is_drawn;
48
49/// 一格的样式:前景色、背景色(`None` 是元素的文字颜色、透明)、粗体、斜体、下划线、删除线、反色
50#[derive(Clone, Copy, Debug, Default, PartialEq)]
51pub struct CharCellStyle {
52    /// 字的颜色;`None` 用元素的文字颜色(继承)
53    pub foreground: Option<Color>,
54    /// 格子的底色;`None` 是透明(露出元素的背景)
55    pub background: Option<Color>,
56    /// 粗体(字体有粗体字面就用,没有时加粗画)
57    pub bold: bool,
58    /// 斜体(字体有斜体字面就用,没有时倾斜画)
59    pub italic: bool,
60    /// 下划线
61    pub underline: bool,
62    /// 删除线
63    pub strikethrough: bool,
64    /// 反色:前景色和底色对调
65    pub inverse: bool,
66}
67
68impl CharCellStyle {
69    /// 字的颜色
70    pub fn foreground(mut self, color: Color) -> Self {
71        self.foreground = Some(color);
72        self
73    }
74
75    /// 格子的底色
76    pub fn background(mut self, color: Color) -> Self {
77        self.background = Some(color);
78        self
79    }
80
81    /// 粗体
82    pub fn bold(mut self, bold: bool) -> Self {
83        self.bold = bold;
84        self
85    }
86
87    /// 斜体
88    pub fn italic(mut self, italic: bool) -> Self {
89        self.italic = italic;
90        self
91    }
92
93    /// 下划线
94    pub fn underline(mut self, underline: bool) -> Self {
95        self.underline = underline;
96        self
97    }
98
99    /// 删除线
100    pub fn strikethrough(mut self, strikethrough: bool) -> Self {
101        self.strikethrough = strikethrough;
102        self
103    }
104
105    /// 反色
106    pub fn inverse(mut self, inverse: bool) -> Self {
107        self.inverse = inverse;
108        self
109    }
110
111    /// 什么都没设的样式([`Default::default`] 在常量里用不了)
112    const PLAIN: Self = Self { foreground: None, background: None, bold: false, italic: false, underline: false, strikethrough: false, inverse: false };
113}
114
115/// 一格的内容([`CharGrid::cell`] 读到的)
116#[derive(Clone, Debug, PartialEq, Eq)]
117#[non_exhaustive]
118pub enum CharCellContent {
119    /// 一个字;空格是空的格子
120    Char(char),
121    /// 几个码点组成的一个字素簇:带变音符号的字、组合的 emoji
122    Cluster(Rc<str>),
123    /// 宽字(汉字、emoji)占的第二格
124    WideTail,
125}
126
127/// 写成文字:宽字的第二格是空的
128impl std::fmt::Display for CharCellContent {
129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130        match self {
131            Self::Char(ch) => write!(f, "{ch}"),
132            Self::Cluster(text) => f.write_str(text),
133            Self::WideTail => Ok(()),
134        }
135    }
136}
137
138/// 一格:内容和样式。宽字(汉字、emoji)占两格,第二格的内容是 [`CharCellContent::WideTail`]
139#[derive(Clone, Debug, PartialEq)]
140pub struct CharCell {
141    /// 这一格的内容
142    pub content: CharCellContent,
143    /// 样式
144    pub style: CharCellStyle,
145}
146
147impl CharCell {
148    /// 空的格子
149    pub const BLANK: CharCell = CharCell { content: CharCellContent::Char(' '), style: CharCellStyle::PLAIN };
150}
151
152/// 插入点的形状
153#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
154#[non_exhaustive]
155pub enum CaretShape {
156    /// 盖住整格的方块,里面的字反色;网格没有焦点时画成空心的框
157    #[default]
158    Block,
159    /// 格子左边的竖线
160    Bar,
161    /// 格子底下的横线
162    Underline,
163}
164
165/// 插入点:在第几行第几列、形状、闪不闪、颜色
166#[derive(Clone, Copy, Debug, PartialEq)]
167pub struct CharGridCaret {
168    /// 行
169    pub row: usize,
170    /// 列
171    pub column: usize,
172    /// 形状
173    pub shape: CaretShape,
174    /// 闪烁(亮 0.5 秒、灭 0.5 秒,移动之后先亮着)
175    pub blinking: bool,
176    /// 不显示
177    pub hidden: bool,
178    /// 颜色;`None` 用元素的文字颜色
179    pub color: Option<Color>,
180}
181
182impl CharGridCaret {
183    /// 第 `row` 行第 `col` 列的方块插入点,闪烁
184    pub fn at(row: usize, column: usize) -> Self {
185        Self { row, column, shape: CaretShape::Block, blinking: true, hidden: false, color: None }
186    }
187
188    /// 换形状
189    pub fn shape(mut self, shape: CaretShape) -> Self {
190        self.shape = shape;
191        self
192    }
193
194    /// 闪不闪
195    pub fn blinking(mut self, blinking: bool) -> Self {
196        self.blinking = blinking;
197        self
198    }
199
200    /// 颜色
201    pub fn color(mut self, color: Color) -> Self {
202        self.color = Some(color);
203        self
204    }
205}
206
207/// 网格里的位置:第几行、第几列(列是格子之间的边界,0 到列数)
208#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
209pub struct CharGridPosition {
210    /// 行
211    pub row: usize,
212    /// 列
213    pub column: usize,
214}
215
216impl CharGridPosition {
217    /// 第 `row` 行第 `col` 列
218    pub fn new(row: usize, column: usize) -> Self {
219        Self { row, column }
220    }
221}
222
223/// 统计:一共重新生成过多少行的图元、整形过多少段字(所有显示这个网格的元素加起来)
224#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
225pub struct CharGridStats {
226    /// 重新生成过的行数
227    pub rows_built: u64,
228    /// 整形过的段数:一个簇,或者连字开着时同样式连续的一串格子。缓存里有的不算
229    pub shapes_built: u64,
230}
231
232/// 一格存的内容,压成 4 个字节:一个字,或者这一行簇表的下标(最高位是 1,字最大才 21 位)。
233/// `0` 是宽字占的第二格
234#[derive(Clone, Copy, Debug, PartialEq, Eq)]
235struct Slot(u32);
236
237impl Slot {
238    const WIDE_TAIL: Self = Self(0);
239    const SPACE: Self = Self(' ' as u32);
240    const CLUSTER: u32 = 1 << 31;
241
242    fn from_char(ch: char) -> Self {
243        Self(ch as u32)
244    }
245
246    fn from_cluster(index: usize) -> Self {
247        Self(Self::CLUSTER | index as u32)
248    }
249
250    /// 放的是一个字(空格算,宽字的第二格和簇不算)
251    #[inline]
252    fn char(self) -> Option<char> {
253        if self == Self::WIDE_TAIL { None } else { char::from_u32(self.0) }
254    }
255
256    /// 放的是簇:在这一行簇表里的下标
257    #[inline]
258    fn cluster(self) -> Option<usize> {
259        (self.0 & Self::CLUSTER != 0).then_some((self.0 & !Self::CLUSTER) as usize)
260    }
261}
262
263/// 存在行里的一格,大小和只放一个字时一样
264#[derive(Clone, Copy)]
265struct StoredCell {
266    slot: Slot,
267    style: CharCellStyle,
268}
269
270const _: () = assert!(size_of::<StoredCell>() == 20, "格子变大会让大网格的内存跟着涨,改之前想清楚");
271
272impl StoredCell {
273    const BLANK: Self = Self { slot: Slot::SPACE, style: CharCellStyle::PLAIN };
274}
275
276/// 一行:格子、这一行的簇表、版本号(每改一次换一个新的,元素按它缓存这一行的图元)
277struct Row {
278    cells: Vec<StoredCell>,
279    /// 放不进一个字的簇。被覆盖的簇先留在这里,满了扫一遍([`Self::add_cluster`]);清空一行时一起清。
280    /// 跟着行走,滚屏不用动。空着时不占堆内存
281    clusters: Vec<Rc<str>>,
282    version: u64,
283}
284
285impl Row {
286    fn new(cols: usize, version: u64) -> Self {
287        Self { cells: vec![StoredCell::BLANK; cols], clusters: Vec::new(), version }
288    }
289
290    /// 整行填成空格(`style` 可以带底色)
291    fn clear(&mut self, style: CharCellStyle, version: u64) {
292        self.cells.fill(StoredCell { slot: Slot::SPACE, style });
293        self.clusters.clear();
294        self.version = version;
295    }
296
297    /// 第 `col` 格的簇占几格
298    #[inline]
299    fn span_at(&self, col: usize) -> usize {
300        if self.cells.get(col + 1).is_some_and(|c| c.slot == Slot::WIDE_TAIL) { 2 } else { 1 }
301    }
302
303    /// 第 `col` 格落在宽字的后一半时,退回前一半
304    #[inline]
305    fn head_of(&self, col: usize) -> usize {
306        if col > 0 && self.cells.get(col).is_some_and(|c| c.slot == Slot::WIDE_TAIL) { col - 1 } else { col }
307    }
308
309    /// 把一个簇放进簇表,返回放在格子里的内容。表里最多有列数个还在用的(每个至少占一格),满了扫一遍,至少又能放列数个:
310    /// 平摊下来每次放一个簇只多常数的工作
311    fn add_cluster(&mut self, text: &str) -> Slot {
312        if self.clusters.len() >= self.cells.len() * 2 + 8 {
313            let mut kept = Vec::with_capacity(self.cells.len().min(self.clusters.len()));
314            for cell in &mut self.cells {
315                if let Some(index) = cell.slot.cluster() {
316                    kept.push(self.clusters[index].clone());
317                    cell.slot = Slot::from_cluster(kept.len() - 1);
318                }
319            }
320            self.clusters = kept;
321        }
322        self.clusters.push(text.into());
323        Slot::from_cluster(self.clusters.len() - 1)
324    }
325
326    /// 把字或簇放在第 `col` 格(`col` 在行内),宽字占两格,最后一列放不下时写空格。被拆开的宽字,另一半变成空格。
327    /// 返回占了几格
328    #[inline]
329    fn place(&mut self, col: usize, slot: Slot, width: usize, style: CharCellStyle) -> usize {
330        let cells = &mut self.cells[..];
331        if col > 0 && cells[col].slot == Slot::WIDE_TAIL {
332            cells[col - 1].slot = Slot::SPACE;
333        }
334        let span = if width == 2 && col + 1 < cells.len() { 2 } else { 1 };
335        if let Some(next) = cells.get_mut(col + span)
336            && next.slot == Slot::WIDE_TAIL
337        {
338            next.slot = Slot::SPACE;
339        }
340        cells[col] = StoredCell { slot: if width == 2 && span == 1 { Slot::SPACE } else { slot }, style };
341        if span == 2 {
342            cells[col + 1] = StoredCell { slot: Slot::WIDE_TAIL, style };
343        }
344        span
345    }
346
347    /// 第 `col` 列前面的簇是简单的字(或者前面没有格子):简单的字接不上去,不用查规则
348    #[inline]
349    fn previous_is_simple(&self, col: usize) -> bool {
350        if col == 0 {
351            return true;
352        }
353        let previous = self.cells[col - 1].slot;
354        // 汉字占两格,前一格是它的第二格
355        let previous = if previous == Slot::WIDE_TAIL && col > 1 { self.cells[col - 2].slot } else { previous };
356        simple_width_of_code(previous.0).is_some()
357    }
358
359    /// 写一个字,返回写完后的列(`col` 不超过列数)。这个字和前一个簇都简单时直接放,不走切分
360    #[inline]
361    fn put_char(&mut self, col: usize, ch: char, style: CharCellStyle) -> usize {
362        if let Some(width) = simple_width(ch)
363            && col < self.cells.len()
364            && self.previous_is_simple(col)
365        {
366            return col + self.place(col, Slot::from_char(ch), width, style);
367        }
368        let mut buf = [0u8; 4];
369        self.write(col, ch.encode_utf8(&mut buf), style)
370    }
371
372    /// 从第 `col` 列开始写一串字(不换行,超出行尾的截掉),按字素簇切开,返回写完后的列
373    fn write(&mut self, col: usize, text: &str, style: CharCellStyle) -> usize {
374        let cols = self.cells.len();
375        let bytes = text.as_bytes();
376        let (mut col, mut at) = self.join_previous(col, text);
377        while at < bytes.len() && col < cols {
378            // 最常见的先判断:可打印的 ASCII 后面还是 ASCII,不用解码
379            let byte = bytes[at];
380            if (0x20..0x7f).contains(&byte) && bytes.get(at + 1).is_none_or(|next| *next < 0x80) {
381                col += self.place(col, Slot(byte as u32), 1, style);
382                at += 1;
383                continue;
384            }
385            // 接着是一串简单的字(汉字这些):一个字后面还是简单的字,它自己就是一个簇。每个字只解码、查表一次
386            let rest = &text[at..];
387            let used = self.write_simple(&mut col, rest, style);
388            if used > 0 {
389                at += used;
390                continue;
391            }
392            // 查规则:可能是一个组合的簇
393            let len = first_cluster_len(rest);
394            at += len;
395            let cluster = clamped(&rest[..len]);
396            let width = cluster_width(cluster);
397            if width == 0 {
398                continue;
399            }
400            let mut chars = cluster.chars();
401            let slot = match (chars.next(), chars.next()) {
402                (Some(only), None) => Slot::from_char(only),
403                _ => self.add_cluster(cluster),
404            };
405            col += self.place(col, slot, width, style);
406        }
407        col
408    }
409
410    /// 写 `text` 开头的一串简单的字,停在写满一行、不简单的字、或者后面跟着不简单的字的那个字上(它可能和后面的连成一个簇)。
411    /// 返回用掉的字节数
412    #[inline]
413    fn write_simple(&mut self, col: &mut usize, text: &str, style: CharCellStyle) -> usize {
414        let cols = self.cells.len();
415        let mut chars = text.chars();
416        let mut used = 0;
417        let Some(mut ch) = chars.next() else { return 0 };
418        let mut width = simple_width(ch);
419        while let Some(w) = width
420            && *col < cols
421        {
422            let next = chars.next();
423            let next_width = next.and_then(simple_width);
424            if next.is_some() && next_width.is_none() {
425                break;
426            }
427            *col += self.place(*col, Slot::from_char(ch), w, style);
428            used += ch.len_utf8();
429            let Some(next) = next else { break };
430            ch = next;
431            width = next_width;
432        }
433        used
434    }
435
436    /// 上一次写入可能停在组合序列中间(逐字符写的终端、分段到来的输出):`text` 开头能和第 `col` 列前面那个簇连成一个簇的话,
437    /// 接上去(保持那一格的样式;变宽时盖住后面一格,最后一列放不下时不接,丢掉这几个字)。返回接着写的列和 `text` 里用掉的字节数
438    fn join_previous(&mut self, col: usize, text: &str) -> (usize, usize) {
439        let unchanged = (col, 0);
440        let Some(first) = text.chars().next().filter(|_| col > 0 && col <= self.cells.len()) else { return unchanged };
441        // 两边都是简单的字(绝大多数时候):连不上,不用查规则
442        if simple_width(first).is_some() && self.previous_is_simple(col) {
443            return unchanged;
444        }
445        let head = self.head_of(col - 1);
446        let previous = self.cells[head].slot;
447        let mut joined = String::with_capacity(cluster::MAX_CLUSTER * 2);
448        match (previous.char(), previous.cluster()) {
449            (Some(ch), _) => joined.push(ch),
450            (_, Some(index)) => joined.push_str(&self.clusters[index]),
451            _ => return unchanged,
452        }
453        let before = joined.len();
454        joined.push_str(clamped(text));
455        let end = first_cluster_len(&joined);
456        if end <= before {
457            return unchanged;
458        }
459        let used = end - before;
460        let cluster = clamped(&joined[..end]);
461        // 这一格已经满了:多出来的组合字符丢掉
462        if cluster.len() <= before {
463            return (col, used);
464        }
465        let (old, new) = (self.span_at(head), cluster_width(cluster).max(1));
466        if new > old && head + new > self.cells.len() {
467            return (col, used);
468        }
469        let slot = self.add_cluster(cluster);
470        match new.cmp(&old) {
471            std::cmp::Ordering::Greater => {
472                let style = self.cells[head].style;
473                self.place(head, slot, new, style);
474            }
475            std::cmp::Ordering::Less => {
476                self.cells[head].slot = slot;
477                self.cells[head + 1].slot = Slot::SPACE;
478            }
479            std::cmp::Ordering::Equal => self.cells[head].slot = slot,
480        }
481        (head + new, used)
482    }
483
484    /// 读一格(公开的 [`CharCell`])
485    fn cell(&self, col: usize) -> Option<CharCell> {
486        let cell = self.cells.get(col)?;
487        let content = match (cell.slot.char(), cell.slot.cluster()) {
488            (Some(ch), _) => CharCellContent::Char(ch),
489            (_, Some(index)) => CharCellContent::Cluster(self.clusters[index].clone()),
490            _ => CharCellContent::WideTail,
491        };
492        Some(CharCell { content, style: cell.style })
493    }
494
495    /// `from..to` 列的文字:宽字的第二格跳过,去掉行尾的空格
496    fn text(&self, from: usize, to: usize) -> String {
497        let len = self.cells.len();
498        let mut text = String::new();
499        for cell in &self.cells[from.min(len)..to.min(len)] {
500            match (cell.slot.char(), cell.slot.cluster()) {
501                (Some(ch), _) => text.push(ch),
502                (_, Some(index)) => text.push_str(&self.clusters[index]),
503                _ => {}
504            }
505        }
506        text.truncate(text.trim_end().len());
507        text
508    }
509}
510
511struct GridData {
512    cols: usize,
513    rows: Vec<Row>,
514    next_version: u64,
515    caret: CharGridCaret,
516    /// 插入点最近一次动的时间(闪烁从这里算起,动过先亮着);由元素在下一帧填上
517    caret_moved: bool,
518    selection: Option<(CharGridPosition, CharGridPosition)>,
519    rows_built: u64,
520    shapes_built: u64,
521    /// 已经通知过元素这一帧要重画(一帧里写很多格只通知一次)
522    notified: bool,
523    /// 行数、列数变了:要重新布局
524    resized: bool,
525}
526
527/// 字符网格的数据:行 × 列的格子、插入点、选区。是一个句柄,`clone` 出来的是同一个网格;
528/// 用 [`char_grid`] 显示。写的时候记下哪几行变了,下一帧只重新生成这几行的图元。
529///
530/// 只能在主线程用(和信号一样)。
531///
532/// **一格放一个字素簇**:带变音符号的字、组合的 emoji(ZWJ、肤色、国旗、键帽、VS16)都在一格或两格里,不拆开。
533/// 占几格按 `unicode-width` 对整个簇的算法,最多两格:普通的字一格,汉字、emoji 两格,变音符号不加宽度。写到一半宽字上时,
534/// 被拆开的另一半变成空格;最后一列放不下两格的簇时写空格。
535///
536/// **组合字符接到前一格上**:[`Self::set`]、[`Self::write`] 写的开头如果和前一格的簇连得成一个簇(变音符号、`ZWJ` 和它后面的字、
537/// 第二个地区指示符),接上去,样式还是前一格的。所以逐字符写和一次写结果一样。接不上的零宽字符丢掉,控制字符也丢掉
538#[derive(Clone)]
539pub struct CharGrid {
540    data: Rc<RefCell<GridData>>,
541    /// 改了就加一:显示它的元素订阅这个信号,下一帧重画
542    version: Signal<u64>,
543}
544
545impl CharGrid {
546    /// `cols` 列、`rows` 行的空网格,插入点在左上角
547    pub fn new(cols: usize, rows: usize) -> Self {
548        let mut data = GridData {
549            cols,
550            rows: Vec::with_capacity(rows),
551            next_version: 1,
552            caret: CharGridCaret::at(0, 0),
553            caret_moved: true,
554            selection: None,
555            rows_built: 0,
556            shapes_built: 0,
557            notified: false,
558            resized: false,
559        };
560        for _ in 0..rows {
561            let version = data.bump();
562            data.rows.push(Row::new(cols, version));
563        }
564        // 网格可以比创建它的作用域活得久(放在应用状态里),信号不归任何作用域
565        let version = detached(|| signal(0u64));
566        Self { data: Rc::new(RefCell::new(data)), version }
567    }
568
569    /// 改了就加一的信号(元素订阅它)
570    pub(crate) fn version_signal(&self) -> Signal<u64> {
571        self.version
572    }
573
574    /// `[列数, 行数]`
575    pub fn size(&self) -> [usize; 2] {
576        let data = self.data.borrow();
577        [data.cols, data.rows.len()]
578    }
579
580    /// 改 `f` 里的数据,然后通知显示它的元素(一帧里第一次改时才通知)
581    fn update<R>(&self, f: impl FnOnce(&mut GridData) -> R) -> R {
582        let (result, notify) = {
583            let mut data = self.data.borrow_mut();
584            let result = f(&mut data);
585            (result, !std::mem::replace(&mut data.notified, true))
586        };
587        if notify {
588            self.version.update(|v| *v += 1);
589        }
590        result
591    }
592
593    /// 第 `row` 行第 `col` 列写一个字,返回写完后的列;宽字占这一格和下一格(最后一列放不下宽字时写空格)。越界的忽略。
594    /// 组合字符(变音符号、`ZWJ` 和它后面的字、肤色……)接到前一格的簇上,这时 `style` 不起作用:
595    ///
596    /// ```
597    /// # use aureole::prelude::*;
598    /// let grid = CharGrid::new(10, 1);
599    /// let mut col = 0;
600    /// for ch in "e\u{301}x".chars() {
601    ///     col = grid.set(0, col, ch, CharCellStyle::default()); // 终端逐字符写
602    /// }
603    /// assert_eq!(col, 2);
604    /// assert_eq!(grid.row_text(0), "e\u{301}x");
605    /// ```
606    pub fn set(&self, row: usize, col: usize, ch: char, style: CharCellStyle) -> usize {
607        self.update(|data| {
608            let version = data.bump();
609            match data.rows.get_mut(row) {
610                Some(r) if col <= r.cells.len() => {
611                    r.version = version;
612                    r.put_char(col, ch, style)
613                }
614                _ => col,
615            }
616        })
617    }
618
619    /// 从第 `row` 行第 `col` 列开始写一串字(不换行,超出行尾的截掉),按字素簇切开,返回写完后的列
620    pub fn write(&self, row: usize, col: usize, text: &str, style: CharCellStyle) -> usize {
621        self.update(|data| {
622            let version = data.bump();
623            match data.rows.get_mut(row) {
624                Some(r) if col <= r.cells.len() && !text.is_empty() => {
625                    r.version = version;
626                    r.write(col, text, style)
627                }
628                _ => col,
629            }
630        })
631    }
632
633    /// 把第 `row` 行从 `cols` 范围里的格子填成同一个字(`' '` 就是清掉)
634    pub fn set_cells(&self, row: usize, cols: std::ops::Range<usize>, ch: char, style: CharCellStyle) {
635        let width = ch.width().unwrap_or(0);
636        self.update(|data| {
637            let version = data.bump();
638            let columns = data.cols;
639            let Some(r) = data.rows.get_mut(row).filter(|_| width > 0 && cols.start < columns) else { return };
640            let mut col = cols.start;
641            while col < cols.end.min(columns) {
642                col += r.place(col, Slot::from_char(ch), width, style);
643            }
644            r.version = version;
645        });
646    }
647
648    /// 清空一行(空格,样式是 `style`:可以带底色)
649    pub fn clear_row(&self, row: usize, style: CharCellStyle) {
650        self.update(|data| {
651            let version = data.bump();
652            if let Some(r) = data.rows.get_mut(row) {
653                r.clear(style, version);
654            }
655        });
656    }
657
658    /// 清空整个网格
659    pub fn clear(&self) {
660        self.update(|data| {
661            for row in 0..data.rows.len() {
662                let version = data.bump();
663                data.rows[row].clear(CharCellStyle::PLAIN, version);
664            }
665            data.selection = None;
666        });
667    }
668
669    /// 整体上移 `n` 行(终端滚屏):顶上的 `n` 行移出去,底下补 `n` 行空行。只挪行,没变的行不用重新生成图元;
670    /// 选区跟着上移,移出去的部分去掉
671    pub fn scroll_up(&self, n: usize) {
672        self.update(|data| {
673            let n = n.min(data.rows.len());
674            data.rows.rotate_left(n);
675            let len = data.rows.len();
676            for row in len - n..len {
677                let version = data.bump();
678                data.rows[row].clear(CharCellStyle::PLAIN, version);
679            }
680            data.selection = data.selection.and_then(|(a, b)| {
681                (b.row >= n).then(|| {
682                    let a = if a.row >= n { CharGridPosition::new(a.row - n, a.column) } else { CharGridPosition::new(0, 0) };
683                    (a, CharGridPosition::new(b.row - n, b.column))
684                })
685            });
686        });
687    }
688
689    /// 改成 `cols` 列、`rows` 行:多出来的格子是空的,少了的截掉;元素下一帧重新布局
690    pub fn resize(&self, cols: usize, rows: usize) {
691        self.update(|data| {
692            if (data.cols, data.rows.len()) == (cols, rows) {
693                return;
694            }
695            data.cols = cols;
696            for row in &mut data.rows {
697                // 新的最后一列是宽字的前一半:另一半切掉了,变成空格
698                if cols > 0 && row.cells.get(cols).is_some_and(|c| c.slot == Slot::WIDE_TAIL) {
699                    row.cells[cols - 1].slot = Slot::SPACE;
700                }
701                row.cells.resize(cols, StoredCell::BLANK);
702            }
703            data.rows.truncate(rows);
704            while data.rows.len() < rows {
705                data.rows.push(Row::new(cols, 0));
706            }
707            for row in 0..rows {
708                let version = data.bump();
709                data.rows[row].version = version;
710            }
711            data.resized = true;
712        });
713    }
714
715    /// 一格的内容;越界时是 `None`
716    pub fn cell(&self, row: usize, col: usize) -> Option<CharCell> {
717        self.data.borrow().rows.get(row)?.cell(col)
718    }
719
720    /// 一行的文字(宽字只算一次,去掉行尾的空格)
721    pub fn row_text(&self, row: usize) -> String {
722        let data = self.data.borrow();
723        data.rows.get(row).map(|r| r.text(0, r.cells.len())).unwrap_or_default()
724    }
725
726    /// 插入点
727    pub fn caret(&self) -> CharGridCaret {
728        self.data.borrow().caret
729    }
730
731    /// 放插入点(闪烁的插入点移动之后先亮着)
732    pub fn set_caret(&self, caret: CharGridCaret) {
733        self.update(|data| {
734            if data.caret != caret {
735                data.caret = caret;
736                data.caret_moved = true;
737            }
738        });
739    }
740
741    /// 选区:从 `start` 到 `end`(按阅读顺序,`end` 不含)。也可以用指针在网格上拖出来,⌘C 复制。
742    /// 画和复制时都按整个簇:一端落在宽字中间时扩到整个字
743    pub fn selection(&self) -> Option<(CharGridPosition, CharGridPosition)> {
744        self.data.borrow().selection
745    }
746
747    /// 设置选区(`None` 清掉)
748    pub fn set_selection(&self, selection: Option<(CharGridPosition, CharGridPosition)>) {
749        self.update(|data| data.selection = selection.map(|(a, b)| if a <= b { (a, b) } else { (b, a) }));
750    }
751
752    /// 选中的文字:行与行之间换行,每行去掉行尾的空格
753    pub fn selected_text(&self) -> Option<String> {
754        let data = self.data.borrow();
755        let (start, end) = data.whole_clusters_selected().filter(|_| !data.rows.is_empty())?;
756        let mut lines = Vec::new();
757        for row in start.row..=end.row.min(data.rows.len().saturating_sub(1)) {
758            let r = &data.rows[row];
759            let from = if row == start.row { start.column } else { 0 };
760            let to = if row == end.row { end.column } else { r.cells.len() };
761            lines.push(r.text(from, to));
762        }
763        Some(lines.join("\n"))
764    }
765
766    /// 统计:一共重新生成过多少行的图元、整形过多少段字
767    pub fn stats(&self) -> CharGridStats {
768        let data = self.data.borrow();
769        CharGridStats { rows_built: data.rows_built, shapes_built: data.shapes_built }
770    }
771}
772
773impl GridData {
774    fn bump(&mut self) -> u64 {
775        self.next_version += 1;
776        self.next_version
777    }
778
779    /// 非空的选区,两端落在宽字中间时扩到整个簇
780    fn whole_clusters_selected(&self) -> Option<(CharGridPosition, CharGridPosition)> {
781        let (mut start, mut end) = self.selection.filter(|(a, b)| a != b)?;
782        if let Some(row) = self.rows.get(start.row) {
783            start.column = row.head_of(start.column);
784        }
785        if let Some(row) = self.rows.get(end.row)
786            && row.head_of(end.column) != end.column
787        {
788            end.column += 1;
789        }
790        Some((start, end))
791    }
792}
793
794/// 字符网格元素:显示一个 [`CharGrid`]。大小是列数 × 格宽、行数 × 格高(格宽是等宽字体的字宽,格高是字号 × 行高,
795/// 都对齐到物理像素),字号、行高、字体族、文字颜色可以设在元素上或者继承(字体族默认是系统的等宽字体;
796/// 终端一般用 `.line_height(1.2)`)。
797///
798/// 指针拖动选择格子(按整个字素簇选,双击选一串不是空格的字,三击选整行),⌘C 复制、⌘A 全选;点它获得键盘焦点,
799/// 按键用 [`Element::on_key_down`] 接(终端把按键交给自己的程序)。没有焦点时方块插入点画成空心的、选区画成不活跃的颜色。
800/// 读屏软件读到的是网格里的全部文字。要字体的连字(编程字体的 `->`)时设 [`Element::ligated`]
801pub fn char_grid(grid: &CharGrid) -> Element {
802    Element::from_kind(CharGridBlock::new(grid.clone()))
803}
804
805/// 一行生成好的图元(行内坐标:左上角是这一行的左上角)
806struct RowQuads {
807    backgrounds: Vec<Quad>,
808    glyphs: Vec<Quad>,
809    /// 每个图元的颜色从哪来(和上面两组一一对应):没设颜色的格子用元素的文字颜色、底下的颜色,
810    /// 画的时候才填上,文字颜色在过渡时不用重新生成
811    background_inks: Vec<Tint>,
812    glyph_inks: Vec<Tint>,
813}
814
815/// 图元的颜色:生成时定好的,或者画的时候填的文字颜色、底色
816#[derive(Clone, Copy, PartialEq)]
817enum Tint {
818    Fixed,
819    Text,
820    Backdrop,
821}
822
823/// 一格的字和底的颜色
824#[derive(Clone, Copy, PartialEq)]
825enum Paint {
826    Color(Color),
827    Text,
828    Backdrop,
829}
830
831impl Paint {
832    fn resolve(self) -> (Color, Tint) {
833        match self {
834            Self::Color(c) => (c, Tint::Fixed),
835            Self::Text => (Color::TRANSPARENT, Tint::Text),
836            Self::Backdrop => (Color::TRANSPARENT, Tint::Backdrop),
837        }
838    }
839}
840
841/// 缓存的图元在这些都没变时才能用
842#[derive(Clone, Copy, PartialEq)]
843struct CacheKey {
844    style: TextStyle,
845    scale: f32,
846    /// 字形图集扩大过就要重新取字形的位置
847    atlas: u64,
848    ligated: bool,
849}
850
851/// 字符网格元素的内容:数据的句柄、格子的尺寸、字形和每行图元的缓存
852pub(crate) struct CharGridBlock {
853    pub grid: CharGrid,
854    /// 继承来的选区颜色
855    pub selection: Color,
856    style: TextStyle,
857    metrics: Option<(f32, CellMetrics)>,
858    key: Option<CacheKey>,
859    /// 字(低 24 位)+ 粗斜体(高 8 位)→ 字形(`None` 是哪个字体里都没有)。生成一行时每格查一次,用快的哈希
860    glyphs: HashMap<u32, Option<CellGlyph>, BuildHasherDefault<GlyphHasher>>,
861    /// 同样式连续的格子一起整形([`Element::ligated`])
862    pub ligated: bool,
863    /// 整形过的字(簇,连字开着时是一串格子)→ 结果,按粗斜体分四张表
864    shapes: [HashMap<Box<str>, Rc<CellShape>>; 4],
865    /// 上面几张表一共存了多少字形,到 [`SHAPE_CACHE_GLYPHS`] 就全部丢掉
866    shape_glyphs: usize,
867    /// 这一帧整形过几段(记进网格的统计)
868    shapes_built: u64,
869    /// 连字开着时拼一串格子的文字、每格文字的起点(字节)和列;留着内存,不用每行都分配
870    run_text: String,
871    run_cells: Vec<(u32, u32)>,
872    /// 行的版本号 → 这一行的图元
873    rows: HashMap<u64, RowQuads>,
874    /// 插入点闪烁:从什么时候算起、现在亮不亮
875    blink_epoch: f64,
876    pub caret_on: bool,
877    /// 双击、三击之后拖动按词、按行扩展:一开始选中的范围
878    unit: Option<(u32, CharGridPosition, CharGridPosition)>,
879    anchor: Option<CharGridPosition>,
880    /// 接文字输入(有 [`crate::Element::on_text_insert`]):有焦点时开输入法,预编辑画在插入点处
881    pub text_input: bool,
882    /// 输入法的预编辑文字和其中的插入点(字节偏移);没在组字时是 `None`
883    pub preedit: Option<(String, Option<usize>)>,
884    /// 内容区左上角在元素里的位置(绘制时更新):插入点区域换算成元素坐标
885    pub inset: [f32; 2],
886}
887
888/// 插入点亮、灭各这么久
889const BLINK: f64 = 0.5;
890/// 整形缓存最多存这么多字形(一个字形 16 字节):连字开着时不停输出没见过的文字,缓存也不会一直涨
891const SHAPE_CACHE_GLYPHS: usize = 1 << 16;
892
893impl CharGridBlock {
894    pub fn new(grid: CharGrid) -> Self {
895        Self {
896            grid,
897            selection: Color::TRANSPARENT,
898            style: TextStyle::default(),
899            metrics: None,
900            key: None,
901            glyphs: HashMap::default(),
902            ligated: false,
903            shapes: Default::default(),
904            shape_glyphs: 0,
905            shapes_built: 0,
906            run_text: String::new(),
907            run_cells: Vec::new(),
908            rows: HashMap::new(),
909            blink_epoch: 0.0,
910            caret_on: true,
911            unit: None,
912            anchor: None,
913            text_input: false,
914            preedit: None,
915            inset: [0.0, 0.0],
916        }
917    }
918
919    /// 插入点所在的格子(组字时是预编辑文字占的那几格),相对内容区左上角;还没量过格子时按 0 大小
920    pub fn caret_rect(&self) -> Rect {
921        let m = self.metrics.map(|(_, m)| [m.width, m.height]).unwrap_or_default();
922        let caret = self.grid.caret();
923        let data = self.grid.data.borrow();
924        let row = data.rows.get(caret.row);
925        let column = row.map_or(caret.column, |r| r.head_of(caret.column));
926        let span = match &self.preedit {
927            Some((text, _)) => preedit_columns(text).max(1),
928            None => row.map_or(1, |r| r.span_at(column)),
929        };
930        Rect { x: column as f32 * m[0], y: caret.row as f32 * m[1], width: span as f32 * m[0], height: m[1] }
931    }
932
933    /// 继承来的文字样式变了,返回 true(要重新布局)
934    pub fn set_style(&mut self, style: TextStyle) -> bool {
935        if self.style == style {
936            return false;
937        }
938        self.style = style;
939        self.invalidate();
940        true
941    }
942
943    /// 丢掉格子尺寸、字形和图元的缓存(加载了新字体、换了样式)
944    pub fn invalidate(&mut self) {
945        self.metrics = None;
946        self.key = None;
947        self.glyphs.clear();
948        self.shapes = Default::default();
949        self.shape_glyphs = 0;
950        self.rows.clear();
951    }
952
953    fn metrics(&mut self, text: &mut TextSystem) -> CellMetrics {
954        let scale = text.scale();
955        match self.metrics {
956            Some((s, m)) if s == scale => m,
957            _ => {
958                let m = text.cell_metrics(&self.style);
959                self.metrics = Some((scale, m));
960                m
961            }
962        }
963    }
964
965    /// 大小:列数 × 格宽、行数 × 格高
966    pub fn measure(&mut self, text: &mut TextSystem) -> [f32; 2] {
967        let m = self.metrics(text);
968        let [cols, rows] = self.grid.size();
969        self.grid.data.borrow_mut().resized = false;
970        [cols as f32 * m.width, rows as f32 * m.height]
971    }
972
973    /// 行列数变了(要重新布局),顺便清掉"已通知"
974    pub fn take_resized(&mut self) -> bool {
975        std::mem::take(&mut self.grid.data.borrow_mut().resized)
976    }
977
978    /// 插入点下一次换亮灭的时刻(统一时钟的秒,`now` 之后):插入点不显示、不闪时是 `None`
979    pub fn next_blink(&self, now: f64) -> Option<f64> {
980        let caret = self.grid.data.borrow().caret;
981        (!caret.hidden && caret.blinking).then(|| crate::editor::next_toggle(self.blink_epoch, now, BLINK))
982    }
983
984    /// 推进插入点闪烁,返回亮灭是否变了
985    pub fn blink(&mut self, now: f64) -> bool {
986        let mut data = self.grid.data.borrow_mut();
987        if std::mem::take(&mut data.caret_moved) {
988            self.blink_epoch = now;
989        }
990        let on = !data.caret.blinking || (((now - self.blink_epoch).max(0.0) / BLINK) as u64).is_multiple_of(2);
991        std::mem::replace(&mut self.caret_on, on) != on
992    }
993
994    /// 内容区里的一点(相对网格左上角)在哪一行、靠近哪条格子边界
995    fn pos_at(&self, [x, y]: [f32; 2]) -> CharGridPosition {
996        let Some((_, m)) = self.metrics else { return CharGridPosition::default() };
997        let [cols, rows] = self.grid.size();
998        let row = ((y / m.height).floor().max(0.0) as usize).min(rows.saturating_sub(1));
999        let mut col = ((x / m.width).round().max(0.0) as usize).min(cols);
1000        // 落在宽字中间:去近的那一边,不把一个簇切开
1001        if let Some(r) = self.grid.data.borrow().rows.get(row)
1002            && r.head_of(col) != col
1003        {
1004            col = if x / m.width < col as f32 { col - 1 } else { col + 1 };
1005        }
1006        CharGridPosition::new(row, col)
1007    }
1008
1009    /// 双击:一串不是空格的字;三击:整行
1010    fn unit_at(&self, point: [f32; 2], clicks: u32) -> (CharGridPosition, CharGridPosition) {
1011        let Some((_, m)) = self.metrics else { return Default::default() };
1012        let [cols, _] = self.grid.size();
1013        if cols == 0 || self.grid.data.borrow().rows.is_empty() {
1014            return Default::default();
1015        }
1016        let row = self.pos_at(point).row;
1017        if clicks >= 3 {
1018            return (CharGridPosition::new(row, 0), CharGridPosition::new(row, cols));
1019        }
1020        let col = ((point[0] / m.width).floor().max(0.0) as usize).min(cols.saturating_sub(1));
1021        let data = self.grid.data.borrow();
1022        let cells = &data.rows[row].cells;
1023        let word = |c: &StoredCell| c.slot != Slot::SPACE;
1024        if !word(&cells[col]) {
1025            return (CharGridPosition::new(row, col), CharGridPosition::new(row, col + 1));
1026        }
1027        let start = (0..=col).rev().take_while(|&i| word(&cells[i])).last().unwrap_or(col);
1028        let end = (col..cols).take_while(|&i| word(&cells[i])).last().map_or(col + 1, |i| i + 1);
1029        (CharGridPosition::new(row, start), CharGridPosition::new(row, end))
1030    }
1031
1032    /// 指针按下(`point` 相对网格左上角):单击放下起点(Shift 扩展),双击选词,三击选整行
1033    pub fn press(&mut self, point: [f32; 2], clicks: u32, extend: bool) {
1034        let pos = self.pos_at(point);
1035        let selection = match clicks {
1036            1 if extend && self.anchor.is_some() => Some((self.anchor.unwrap_or(pos), pos)),
1037            1 => {
1038                self.anchor = Some(pos);
1039                self.unit = None;
1040                None
1041            }
1042            _ => {
1043                let (a, b) = self.unit_at(point, clicks);
1044                self.anchor = Some(a);
1045                self.unit = Some((clicks, a, b));
1046                Some((a, b))
1047            }
1048        };
1049        self.set_selection(selection);
1050    }
1051
1052    /// 拖动:扩展选区(双击、三击之后按词、按行)
1053    pub fn drag(&mut self, point: [f32; 2]) {
1054        let Some(anchor) = self.anchor else { return };
1055        let selection = match self.unit {
1056            Some((clicks, a, b)) => {
1057                let (c, d) = self.unit_at(point, clicks);
1058                (a.min(c), b.max(d))
1059            }
1060            None => (anchor, self.pos_at(point)),
1061        };
1062        self.set_selection(Some(selection));
1063    }
1064
1065    /// 全选
1066    pub fn select_all(&mut self) {
1067        let [cols, rows] = self.grid.size();
1068        self.anchor = Some(CharGridPosition::default());
1069        self.set_selection(Some((CharGridPosition::default(), CharGridPosition::new(rows.saturating_sub(1), cols))));
1070    }
1071
1072    /// 元素自己改选区(指针):直接写进数据,不再通知自己(调用的地方已经标记了重画)
1073    fn set_selection(&mut self, selection: Option<(CharGridPosition, CharGridPosition)>) {
1074        let selection = selection.filter(|(a, b)| a != b).map(|(a, b)| if a <= b { (a, b) } else { (b, a) });
1075        self.grid.data.borrow_mut().selection = selection;
1076    }
1077
1078    /// 生成图元。`origin` 是内容区左上角(布局坐标),`world` 是元素的累积变换;`focused` 时选区、插入点画成有焦点的样子
1079    pub fn paint(
1080        &mut self,
1081        text: &mut TextSystem,
1082        origin: [f32; 2],
1083        world: &Affine,
1084        ink: Ink,
1085        background: Color,
1086        selection: [Color; 2],
1087        focused: bool,
1088        quads: &mut Vec<Quad>,
1089    ) {
1090        let m = self.metrics(text);
1091        let scale = text.scale();
1092        let key = CacheKey { style: self.style, scale, atlas: text.atlas_generation(), ligated: self.ligated };
1093        if self.key != Some(key) {
1094            self.rows.clear();
1095            self.key = Some(key);
1096        }
1097        let data_ref = self.grid.data.clone();
1098        let mut data = data_ref.borrow_mut();
1099        data.notified = false;
1100        let cols = data.cols;
1101
1102        // 行的图元:版本号没变的直接用,变了的重新生成(缓存换成这一帧用到的行)
1103        let mut cached = std::mem::take(&mut self.rows);
1104        let mut order = Vec::with_capacity(data.rows.len());
1105        let mut built = 0;
1106        for row in &data.rows {
1107            if let std::collections::hash_map::Entry::Vacant(slot) = cached.entry(row.version) {
1108                slot.insert(self.build_row(text, row, &m));
1109                built += 1;
1110            }
1111            order.push(row.version);
1112        }
1113        data.rows_built += built;
1114        data.shapes_built += std::mem::take(&mut self.shapes_built);
1115        // 图集满了:有的行缺字。扩大图集后会重画,那时图集的代数变了,所有行都重新生成
1116
1117        // 对齐物理像素:没有缩放旋转时整个网格的左上角取整到物理像素,行内的图元已经是对齐的
1118        let snap = world.is_translation();
1119        let base = if snap {
1120            let [x, y] = world.apply(origin);
1121            [(x * scale).round() / scale, (y * scale).round() / scale]
1122        } else {
1123            origin
1124        };
1125        let backdrop = if background.is_transparent() { Color::WHITE } else { background };
1126        let tint = |quad: &Quad, tint: Tint| match tint {
1127            Tint::Fixed => *quad,
1128            Tint::Text => Quad { fill: ink.color, ..*quad },
1129            Tint::Backdrop => Quad { fill: backdrop, ..*quad },
1130        };
1131        let place = |quad: &Quad, dy: f32, opacity: f32| {
1132            let mut q = *quad;
1133            q.rect[0] += base[0];
1134            q.rect[1] += base[1] + dy;
1135            if !snap {
1136                let [w, h] = [q.rect[2], q.rect[3]];
1137                let [cx, cy] = world.apply([q.rect[0] + w * 0.5, q.rect[1] + h * 0.5]);
1138                q.rect[0] = cx - w * 0.5;
1139                q.rect[1] = cy - h * 0.5;
1140                q.transform = world.linear;
1141            }
1142            q.opacity *= opacity;
1143            q
1144        };
1145        let opacity = ink.opacity;
1146        // 先画所有行的底色,再画选区和方块插入点,最后画字(字在选区上面)
1147        for (i, version) in order.iter().enumerate() {
1148            let (dy, row) = (i as f32 * m.height, &cached[version]);
1149            quads.extend(row.backgrounds.iter().zip(&row.background_inks).map(|(q, t)| place(&tint(q, *t), dy, opacity)));
1150        }
1151        let rect = |col: usize, span: usize| Quad::new(col as f32 * m.width, 0.0, span as f32 * m.width, m.height);
1152        if let Some((start, end)) = data.whole_clusters_selected() {
1153            let fill = if focused { selection[0] } else { selection[1] };
1154            for row in start.row..=end.row.min(data.rows.len().saturating_sub(1)) {
1155                let from = if row == start.row { start.column } else { 0 };
1156                let to = if row == end.row { end.column } else { cols };
1157                if to > from {
1158                    quads.push(place(&rect(from, to - from).fill(fill), row as f32 * m.height, opacity));
1159                }
1160            }
1161        }
1162        let caret = data.caret;
1163        let show_caret = !caret.hidden && self.caret_on && caret.row < data.rows.len() && caret.column < cols;
1164        let caret_color = caret.color.unwrap_or(ink.color);
1165        // 插入点盖住的簇:第一格和占几格
1166        let under = show_caret.then(|| {
1167            let row = &data.rows[caret.row];
1168            let head = row.head_of(caret.column);
1169            (head, row.span_at(head))
1170        });
1171        let px = 1.0 / scale;
1172        let line = ((2.0 * scale).round().max(1.0)) / scale;
1173        let dy = caret.row as f32 * m.height;
1174        if let Some((head, span)) = under.filter(|_| caret.shape == CaretShape::Block && self.preedit.is_none()) {
1175            let block = rect(head, span);
1176            let block = if focused { block.fill(caret_color) } else { block.fill(Color::TRANSPARENT).border(px.max(1.0), caret_color) };
1177            quads.push(place(&block, dy, opacity));
1178        }
1179        for (i, version) in order.iter().enumerate() {
1180            let (dy, row) = (i as f32 * m.height, &cached[version]);
1181            quads.extend(row.glyphs.iter().zip(&row.glyph_inks).map(|(q, t)| place(&tint(q, *t), dy, opacity)));
1182        }
1183        // 输入法的预编辑画在插入点处:盖住底下的格子,加下划线,插入点画在预编辑里的位置
1184        let preedit = self.preedit.clone().filter(|_| caret.row < data.rows.len());
1185        let under = if preedit.is_some() { None } else { under };
1186        // 预编辑盖住的第一格:插入点落在宽字中间时从这个字开始
1187        let preedit_start = data.rows.get(caret.row).map_or(caret.column, |r| r.head_of(caret.column));
1188        if let Some((preedit, preedit_caret)) = &preedit {
1189            let mut col = preedit_start;
1190            let mut caret_col = None;
1191            let mut glyphs = Vec::new();
1192            let mut at = 0;
1193            for end in graphemes(preedit).skip(1) {
1194                let cluster = &preedit[at..end];
1195                if preedit_caret.is_some_and(|c| c <= at) && caret_col.is_none() {
1196                    caret_col = Some(col);
1197                }
1198                at = end;
1199                let width = cluster_width(cluster);
1200                if width == 0 || col + width > cols {
1201                    continue;
1202                }
1203                let mut chars = cluster.chars();
1204                match (chars.next(), chars.next()) {
1205                    (Some(ch), None) if is_drawn(ch) => drawn::draw(text, ch, col as f32 * m.width, &m, ink.color, &mut glyphs),
1206                    (Some(ch), None) => self.push_glyph(text, ch, 0, col, width, &m, ink.color, &mut glyphs),
1207                    _ => self.push_cluster(text, cluster, 0, col, width, &m, ink.color, &mut glyphs),
1208                }
1209                col += width;
1210            }
1211            let span = col.saturating_sub(preedit_start);
1212            quads.push(place(&rect(preedit_start, span.max(1)).fill(backdrop), dy, opacity));
1213            quads.extend(glyphs.iter().map(|q| place(q, dy, opacity)));
1214            quads.push(place(&Quad::new(preedit_start as f32 * m.width, m.height - line, span as f32 * m.width, line).fill(ink.color), dy, opacity));
1215            if focused && self.caret_on && preedit_caret.is_some() {
1216                let at = caret_col.unwrap_or(col);
1217                quads.push(place(&Quad::new(at as f32 * m.width, 0.0, line, m.height).fill(caret_color), dy, opacity));
1218            }
1219        }
1220        if let Some((head, span)) = under {
1221            let left = head as f32 * m.width;
1222            match caret.shape {
1223                // 实心方块里的字反色:这一行方块范围里的字形、线用底色再画一遍。连字可能只有一部分在方块里,按方块切开
1224                CaretShape::Block if focused => {
1225                    let right = left + span as f32 * m.width;
1226                    let row = &cached[&order[caret.row]];
1227                    for quad in row.glyphs.iter().filter(|q| q.kind != Quad::COLOR_GLYPH) {
1228                        if let Some(inside) = clipped_x(quad, left, right) {
1229                            quads.push(place(&inside.fill(backdrop), dy, opacity));
1230                        }
1231                    }
1232                }
1233                CaretShape::Block => {}
1234                CaretShape::Bar => quads.push(place(&Quad::new(left, 0.0, line, m.height).fill(caret_color), dy, opacity)),
1235                CaretShape::Underline => {
1236                    let bar = Quad::new(left, m.height - line, span as f32 * m.width, line).fill(caret_color);
1237                    quads.push(place(&bar, dy, opacity));
1238                }
1239            }
1240        }
1241        drop(data);
1242        self.rows = cached;
1243        // 这一帧没用到的行(被覆盖、移出去的)不留
1244        if self.rows.len() > order.len() {
1245            self.rows.retain(|v, _| order.contains(v));
1246        }
1247    }
1248
1249    /// 生成一行的图元:同样底色的相邻格子合成一块,每个字一个字形图元(方块、制表符自己画),簇和连字整形,
1250    /// 下划线、删除线一段一段地画
1251    fn build_row(&mut self, text: &mut TextSystem, source: &Row, m: &CellMetrics) -> RowQuads {
1252        let cells = &source.cells[..];
1253        let mut row = RowQuads {
1254            backgrounds: Vec::new(),
1255            glyphs: Vec::with_capacity(cells.len()),
1256            background_inks: Vec::new(),
1257            glyph_inks: Vec::with_capacity(cells.len()),
1258        };
1259        let colors = |cell: &StoredCell| {
1260            let f = cell.style.foreground.map_or(Paint::Text, Paint::Color);
1261            let b = cell.style.background.map(Paint::Color);
1262            match cell.style.inverse {
1263                true => (b.unwrap_or(Paint::Backdrop), Some(f)),
1264                false => (f, b),
1265            }
1266        };
1267        let mut col = 0;
1268        while col < cells.len() {
1269            let (_, b) = colors(&cells[col]);
1270            let start = col;
1271            col += 1;
1272            while col < cells.len() && colors(&cells[col]).1 == b {
1273                col += 1;
1274            }
1275            if let Some(b) = b.filter(|b| *b != Paint::Color(Color::TRANSPARENT)) {
1276                let (color, tint) = b.resolve();
1277                row.backgrounds.push(Quad::new(start as f32 * m.width, 0.0, (col - start) as f32 * m.width, m.height).fill(color));
1278                row.background_inks.push(tint);
1279            }
1280        }
1281        if self.ligated {
1282            let mut col = 0;
1283            while col < cells.len() {
1284                let (color, tint) = colors(&cells[col]).0.resolve();
1285                let before = row.glyphs.len();
1286                // 同样式连续的几格一起整形(一个簇的不用)
1287                let end = shaped_run_end(cells, col);
1288                if end > col + source.span_at(col) {
1289                    self.push_run(text, source, col, end, m, color, &mut row.glyphs);
1290                } else {
1291                    self.push_cell(text, source, col, m, color, &mut row.glyphs);
1292                }
1293                for (i, cell) in cells[col..end].iter().enumerate() {
1294                    push_lines(cell, col + i, m, color, &mut row.glyphs);
1295                }
1296                row.glyph_inks.resize(row.glyphs.len().max(before), tint);
1297                col = end;
1298            }
1299        } else {
1300            for (col, cell) in cells.iter().enumerate() {
1301                let (color, tint) = colors(cell).0.resolve();
1302                let before = row.glyphs.len();
1303                self.push_cell(text, source, col, m, color, &mut row.glyphs);
1304                push_lines(cell, col, m, color, &mut row.glyphs);
1305                row.glyph_inks.resize(row.glyphs.len().max(before), tint);
1306            }
1307        }
1308        row
1309    }
1310
1311    /// 一格的字形图元:方块、制表符自己画,一个字查字形,簇整形
1312    #[inline]
1313    fn push_cell(&mut self, text: &mut TextSystem, row: &Row, col: usize, m: &CellMetrics, color: Color, out: &mut Vec<Quad>) {
1314        let cell = &row.cells[col];
1315        if cell.slot == Slot::SPACE || cell.slot == Slot::WIDE_TAIL {
1316            return;
1317        }
1318        let flags = cell.style.bold as u8 | (cell.style.italic as u8) << 1;
1319        if let Some(index) = cell.slot.cluster() {
1320            self.push_cluster(text, &row.clusters[index], flags, col, row.span_at(col), m, color, out);
1321        } else if let Some(ch) = cell.slot.char() {
1322            if is_drawn(ch) {
1323                drawn::draw(text, ch, col as f32 * m.width, m, color, out);
1324            } else {
1325                self.push_glyph(text, ch, flags, col, row.span_at(col), m, color, out);
1326            }
1327        }
1328    }
1329
1330    /// 一个字的字形图元(行内坐标):主字体里的字从格子左边开始,回退来的字(宽度和格子不一样)放在占的格子正中,
1331    /// 比占的格子宽出很多时缩小到放得下,字的中间还在原来的高度上
1332    fn push_glyph(&mut self, text: &mut TextSystem, ch: char, flags: u8, col: usize, span: usize, m: &CellMetrics, color: Color, out: &mut Vec<Quad>) {
1333        let style = &self.style;
1334        let glyph = self.glyphs.entry(ch as u32 | (flags as u32) << 24).or_insert_with(|| text.cell_glyph(ch, &styled(style, flags)));
1335        let Some(glyph) = glyph else { return };
1336        let scale = text.scale();
1337        let room = span as f32 * m.width;
1338        let fit = if glyph.advance > room * OVERFLOW { room / glyph.advance } else { 1.0 };
1339        let advance = glyph.advance * fit;
1340        let left = if (advance - m.width).abs() < 0.5 / scale { 0.0 } else { ((room - advance) * 0.5 * scale).round() / scale };
1341        let x = (col as f32 * m.width + left) * scale;
1342        let baseline = m.baseline - (1.0 - fit) * self.style.size * MIDDLE_OF_TEXT;
1343        if let Some(quad) = text.cell_quad(&glyph.face, glyph.glyph, self.style.size * scale * fit, [x.round(), (baseline * scale).round()], color) {
1344            out.push(quad);
1345        }
1346    }
1347
1348    /// 一个簇的字形图元:放在占的格子里
1349    fn push_cluster(&mut self, text: &mut TextSystem, cluster: &str, flags: u8, col: usize, span: usize, m: &CellMetrics, color: Color, out: &mut Vec<Quad>) {
1350        let shape = self.shape(text, cluster, flags);
1351        self.push_shape(text, &shape, &[(0, col as u32)], col + span, m, color, out);
1352    }
1353
1354    /// 连字开着时同样式连续的 `start..end` 几格:拼成一段文字,整形(有缓存),字形放到各自的格子上
1355    fn push_run(&mut self, text: &mut TextSystem, row: &Row, start: usize, end: usize, m: &CellMetrics, color: Color, out: &mut Vec<Quad>) {
1356        let mut content = std::mem::take(&mut self.run_text);
1357        let mut cells = std::mem::take(&mut self.run_cells);
1358        content.clear();
1359        cells.clear();
1360        for col in start..end {
1361            let slot = row.cells[col].slot;
1362            if slot == Slot::WIDE_TAIL {
1363                continue;
1364            }
1365            cells.push((content.len() as u32, col as u32));
1366            match (slot.char(), slot.cluster()) {
1367                (Some(ch), _) => content.push(ch),
1368                (_, Some(index)) => content.push_str(&row.clusters[index]),
1369                _ => {}
1370            }
1371        }
1372        let style = row.cells[start].style;
1373        let shape = self.shape(text, &content, style.bold as u8 | (style.italic as u8) << 1);
1374        self.push_shape(text, &shape, &cells, end, m, color, out);
1375        self.run_text = content;
1376        self.run_cells = cells;
1377    }
1378
1379    /// 整形(有缓存)
1380    fn shape(&mut self, text: &mut TextSystem, content: &str, flags: u8) -> Rc<CellShape> {
1381        if let Some(shape) = self.shapes[flags as usize].get(content) {
1382            return shape.clone();
1383        }
1384        if self.shape_glyphs > SHAPE_CACHE_GLYPHS {
1385            self.shapes = Default::default();
1386            self.shape_glyphs = 0;
1387        }
1388        let shape = Rc::new(text.cell_shape(content, &styled(&self.style, flags)));
1389        self.shape_glyphs += shape.glyph_count() + 1;
1390        self.shapes_built += 1;
1391        self.shapes[flags as usize].insert(content.into(), shape.clone());
1392        shape
1393    }
1394
1395    /// 把整形结果放到格子上。`cells` 是文字里每一格的起点(字节)和列,`end` 是最后一格之后的列。
1396    /// 每组字形(一个簇或一个连字)放在它占的格子里:和格子一样宽时靠左,不一样宽时居中,比占的格子宽出很多时
1397    /// 缩小到放得下(字体里没有这个组合的 emoji,分开画成几个),字形的位置都取整到物理像素
1398    fn push_shape(&self, text: &mut TextSystem, shape: &CellShape, cells: &[(u32, u32)], end: usize, m: &CellMetrics, color: Color, out: &mut Vec<Quad>) {
1399        let scale = text.scale();
1400        let col_of = |byte: u32| cells[cells.partition_point(|c| c.0 <= byte).saturating_sub(1)].1 as usize;
1401        let end_of = |byte: u32| cells.get(cells.partition_point(|c| c.0 < byte)).map_or(end, |c| c.1 as usize);
1402        let units = &shape.units[..];
1403        let mut i = 0;
1404        while i < units.len() {
1405            let col = col_of(units[i].text.start);
1406            // parley 把一格的簇分成了几组(用了几个字体):合起来放
1407            let mut next = i + 1;
1408            let (mut advance, mut last) = (units[i].advance, units[i].text.end);
1409            while next < units.len() && col_of(units[next].text.start) == col {
1410                advance += units[next].advance;
1411                last = last.max(units[next].text.end);
1412                next += 1;
1413            }
1414            let room = (end_of(last).max(col + 1) - col) as f32 * m.width;
1415            let fit = if advance > room * OVERFLOW { room / advance } else { 1.0 };
1416            let left = if (advance * fit - room).abs() < 0.5 / scale { 0.0 } else { ((room - advance * fit) * 0.5 * scale).round() / scale };
1417            let mut pen = col as f32 * m.width + left;
1418            let size = self.style.size * scale * fit;
1419            for unit in &units[i..next] {
1420                for glyph in shape.glyphs(unit) {
1421                    let position = [((pen + glyph.x * fit) * scale).round(), ((m.baseline + glyph.y) * scale).round()];
1422                    if let Some(quad) = text.cell_quad(shape.face(unit), glyph.id, size, position, color) {
1423                        out.push(quad);
1424                    }
1425                }
1426                pen += unit.advance * fit;
1427            }
1428            i = next;
1429        }
1430    }
1431
1432    /// 读屏软件读到的文字:每行一段
1433    pub fn text(&self) -> String {
1434        let [_, rows] = self.grid.size();
1435        (0..rows).map(|r| self.grid.row_text(r)).collect::<Vec<_>>().join("\n")
1436    }
1437}
1438
1439/// 一组字形比占的格子宽这么多倍时缩小:一点点的出入(彩色表情比两格略宽)不值得换一个字号
1440const OVERFLOW: f32 = 1.25;
1441/// 字的中间在基线上面多少倍字号(和删除线一样):缩小的字绕着这里缩小
1442const MIDDLE_OF_TEXT: f32 = 0.35;
1443
1444/// 一格的下划线、删除线
1445#[inline]
1446fn push_lines(cell: &StoredCell, col: usize, m: &CellMetrics, color: Color, out: &mut Vec<Quad>) {
1447    let left = col as f32 * m.width;
1448    if cell.style.underline {
1449        out.push(Quad::new(left, m.baseline + m.underline_offset, m.width, m.underline_size).fill(color));
1450    }
1451    if cell.style.strikethrough {
1452        out.push(Quad::new(left, m.baseline - m.strikethrough_offset, m.width, m.strikethrough_size).fill(color));
1453    }
1454}
1455
1456/// 这一格是 `flags` 的粗斜体时用的文字样式
1457fn styled(style: &TextStyle, flags: u8) -> TextStyle {
1458    let mut style = *style;
1459    if flags & 1 != 0 {
1460        style.weight = 700.0;
1461    }
1462    style.italic |= flags & 2 != 0;
1463    style
1464}
1465
1466/// 连字开着时从第 `start` 格开始、一起整形的一串格子到哪一格为止:样式相同、不是空格、不是自己画的字。
1467/// 这一格本身不整形(空格、自己画的)时是 `start + 1`。遇到空格分开:没有字体的连字跨空格,分开之后同一个词能共用缓存
1468fn shaped_run_end(cells: &[StoredCell], start: usize) -> usize {
1469    let shaped = |cell: &StoredCell| cell.slot != Slot::SPACE && !cell.slot.char().is_some_and(is_drawn);
1470    if !shaped(&cells[start]) {
1471        return start + 1;
1472    }
1473    let style = &cells[start].style;
1474    let run = cells[start + 1..].iter().take_while(|cell| cell.style == *style && shaped(cell)).count();
1475    start + 1 + run
1476}
1477
1478/// 图元落在 `left..right` 里的部分(行内坐标):只有横向切开,字形的图集坐标按比例跟着切。完全在外面时是 `None`
1479fn clipped_x(quad: &Quad, left: f32, right: f32) -> Option<Quad> {
1480    let [x, _, width, _] = quad.rect;
1481    let (from, to) = (x.max(left), (x + width).min(right));
1482    if to <= from {
1483        return None;
1484    }
1485    let mut inside = *quad;
1486    inside.rect[0] = from;
1487    inside.rect[2] = to - from;
1488    if quad.kind != Quad::SHAPE {
1489        let [u0, _, u1, _] = quad.uv;
1490        inside.uv[0] = u0 + (u1 - u0) * (from - x) / width;
1491        inside.uv[2] = u0 + (u1 - u0) * (to - x) / width;
1492    }
1493    Some(inside)
1494}
1495
1496/// 预编辑文字占几列(按字素簇算)
1497fn preedit_columns(text: &str) -> usize {
1498    let mut at = 0;
1499    graphemes(text)
1500        .skip(1)
1501        .map(|end| {
1502            let width = cluster_width(&text[at..end]);
1503            at = end;
1504            width
1505        })
1506        .sum()
1507}