1use 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#[derive(Clone, Copy, Debug, Default, PartialEq)]
51pub struct CharCellStyle {
52 pub foreground: Option<Color>,
54 pub background: Option<Color>,
56 pub bold: bool,
58 pub italic: bool,
60 pub underline: bool,
62 pub strikethrough: bool,
64 pub inverse: bool,
66}
67
68impl CharCellStyle {
69 pub fn foreground(mut self, color: Color) -> Self {
71 self.foreground = Some(color);
72 self
73 }
74
75 pub fn background(mut self, color: Color) -> Self {
77 self.background = Some(color);
78 self
79 }
80
81 pub fn bold(mut self, bold: bool) -> Self {
83 self.bold = bold;
84 self
85 }
86
87 pub fn italic(mut self, italic: bool) -> Self {
89 self.italic = italic;
90 self
91 }
92
93 pub fn underline(mut self, underline: bool) -> Self {
95 self.underline = underline;
96 self
97 }
98
99 pub fn strikethrough(mut self, strikethrough: bool) -> Self {
101 self.strikethrough = strikethrough;
102 self
103 }
104
105 pub fn inverse(mut self, inverse: bool) -> Self {
107 self.inverse = inverse;
108 self
109 }
110
111 const PLAIN: Self = Self { foreground: None, background: None, bold: false, italic: false, underline: false, strikethrough: false, inverse: false };
113}
114
115#[derive(Clone, Debug, PartialEq, Eq)]
117#[non_exhaustive]
118pub enum CharCellContent {
119 Char(char),
121 Cluster(Rc<str>),
123 WideTail,
125}
126
127impl 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#[derive(Clone, Debug, PartialEq)]
140pub struct CharCell {
141 pub content: CharCellContent,
143 pub style: CharCellStyle,
145}
146
147impl CharCell {
148 pub const BLANK: CharCell = CharCell { content: CharCellContent::Char(' '), style: CharCellStyle::PLAIN };
150}
151
152#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
154#[non_exhaustive]
155pub enum CaretShape {
156 #[default]
158 Block,
159 Bar,
161 Underline,
163}
164
165#[derive(Clone, Copy, Debug, PartialEq)]
167pub struct CharGridCaret {
168 pub row: usize,
170 pub column: usize,
172 pub shape: CaretShape,
174 pub blinking: bool,
176 pub hidden: bool,
178 pub color: Option<Color>,
180}
181
182impl CharGridCaret {
183 pub fn at(row: usize, column: usize) -> Self {
185 Self { row, column, shape: CaretShape::Block, blinking: true, hidden: false, color: None }
186 }
187
188 pub fn shape(mut self, shape: CaretShape) -> Self {
190 self.shape = shape;
191 self
192 }
193
194 pub fn blinking(mut self, blinking: bool) -> Self {
196 self.blinking = blinking;
197 self
198 }
199
200 pub fn color(mut self, color: Color) -> Self {
202 self.color = Some(color);
203 self
204 }
205}
206
207#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
209pub struct CharGridPosition {
210 pub row: usize,
212 pub column: usize,
214}
215
216impl CharGridPosition {
217 pub fn new(row: usize, column: usize) -> Self {
219 Self { row, column }
220 }
221}
222
223#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
225pub struct CharGridStats {
226 pub rows_built: u64,
228 pub shapes_built: u64,
230}
231
232#[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 #[inline]
252 fn char(self) -> Option<char> {
253 if self == Self::WIDE_TAIL { None } else { char::from_u32(self.0) }
254 }
255
256 #[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#[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
276struct Row {
278 cells: Vec<StoredCell>,
279 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 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 #[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 #[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 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 #[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 #[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 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 #[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 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 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 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 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 #[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 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 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 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 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 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 caret_moved: bool,
518 selection: Option<(CharGridPosition, CharGridPosition)>,
519 rows_built: u64,
520 shapes_built: u64,
521 notified: bool,
523 resized: bool,
525}
526
527#[derive(Clone)]
539pub struct CharGrid {
540 data: Rc<RefCell<GridData>>,
541 version: Signal<u64>,
543}
544
545impl CharGrid {
546 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 let version = detached(|| signal(0u64));
566 Self { data: Rc::new(RefCell::new(data)), version }
567 }
568
569 pub(crate) fn version_signal(&self) -> Signal<u64> {
571 self.version
572 }
573
574 pub fn size(&self) -> [usize; 2] {
576 let data = self.data.borrow();
577 [data.cols, data.rows.len()]
578 }
579
580 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 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 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 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 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 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 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 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 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 pub fn cell(&self, row: usize, col: usize) -> Option<CharCell> {
717 self.data.borrow().rows.get(row)?.cell(col)
718 }
719
720 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 pub fn caret(&self) -> CharGridCaret {
728 self.data.borrow().caret
729 }
730
731 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 pub fn selection(&self) -> Option<(CharGridPosition, CharGridPosition)> {
744 self.data.borrow().selection
745 }
746
747 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 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 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 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
794pub fn char_grid(grid: &CharGrid) -> Element {
802 Element::from_kind(CharGridBlock::new(grid.clone()))
803}
804
805struct RowQuads {
807 backgrounds: Vec<Quad>,
808 glyphs: Vec<Quad>,
809 background_inks: Vec<Tint>,
812 glyph_inks: Vec<Tint>,
813}
814
815#[derive(Clone, Copy, PartialEq)]
817enum Tint {
818 Fixed,
819 Text,
820 Backdrop,
821}
822
823#[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#[derive(Clone, Copy, PartialEq)]
843struct CacheKey {
844 style: TextStyle,
845 scale: f32,
846 atlas: u64,
848 ligated: bool,
849}
850
851pub(crate) struct CharGridBlock {
853 pub grid: CharGrid,
854 pub selection: Color,
856 style: TextStyle,
857 metrics: Option<(f32, CellMetrics)>,
858 key: Option<CacheKey>,
859 glyphs: HashMap<u32, Option<CellGlyph>, BuildHasherDefault<GlyphHasher>>,
861 pub ligated: bool,
863 shapes: [HashMap<Box<str>, Rc<CellShape>>; 4],
865 shape_glyphs: usize,
867 shapes_built: u64,
869 run_text: String,
871 run_cells: Vec<(u32, u32)>,
872 rows: HashMap<u64, RowQuads>,
874 blink_epoch: f64,
876 pub caret_on: bool,
877 unit: Option<(u32, CharGridPosition, CharGridPosition)>,
879 anchor: Option<CharGridPosition>,
880 pub text_input: bool,
882 pub preedit: Option<(String, Option<usize>)>,
884 pub inset: [f32; 2],
886}
887
888const BLINK: f64 = 0.5;
890const 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 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 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 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 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 pub fn take_resized(&mut self) -> bool {
975 std::mem::take(&mut self.grid.data.borrow_mut().resized)
976 }
977
978 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 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 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 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 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 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 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 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 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 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 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 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 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 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 let preedit = self.preedit.clone().filter(|_| caret.row < data.rows.len());
1185 let under = if preedit.is_some() { None } else { under };
1186 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 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 if self.rows.len() > order.len() {
1245 self.rows.retain(|v, _| order.contains(v));
1246 }
1247 }
1248
1249 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 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 #[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 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 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 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 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 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 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 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
1439const OVERFLOW: f32 = 1.25;
1441const MIDDLE_OF_TEXT: f32 = 0.35;
1443
1444#[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
1456fn 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
1466fn 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
1478fn 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
1496fn 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}