1#[cfg(not(feature = "std"))]
4use alloc::{string::String, vec::Vec};
5
6use core::{cmp, fmt};
7
8#[cfg(not(feature = "std"))]
9use core_maths::CoreFloat;
10use unicode_segmentation::UnicodeSegmentation;
11
12#[cfg(feature = "swash")]
13use crate::Color;
14
15use crate::{
16 Affinity, Align, Attrs, AttrsList, BidiParagraphs, BorrowedWithFontSystem, BufferLine, Cursor,
17 FontSystem, LayoutCursor, LayoutGlyph, LayoutLine, LineEnding, LineIter, Motion, Scroll,
18 ShapeLine, Shaping, Wrap,
19};
20
21#[derive(Debug)]
23pub struct LayoutRun<'a> {
24 pub line_i: usize,
26 pub text: &'a str,
28 pub rtl: bool,
30 pub glyphs: &'a [LayoutGlyph],
32 pub line_y: f32,
34 pub line_top: f32,
36 pub line_height: f32,
38 pub line_w: f32,
40}
41
42impl LayoutRun<'_> {
43 #[allow(clippy::missing_panics_doc)]
48 pub fn highlight(&self, cursor_start: Cursor, cursor_end: Cursor) -> Option<(f32, f32)> {
49 let mut x_start = None;
50 let mut x_end = None;
51 let rtl_factor = if self.rtl { 1. } else { 0. };
52 let ltr_factor = 1. - rtl_factor;
53 for glyph in self.glyphs {
54 let cursor = self.cursor_from_glyph_left(glyph);
55 if cursor >= cursor_start && cursor <= cursor_end {
56 if x_start.is_none() {
57 x_start = Some(glyph.x + glyph.w.mul_add(rtl_factor, 0.0));
58 }
59 x_end = Some(glyph.x + glyph.w.mul_add(rtl_factor, 0.0));
60 }
61 let cursor = self.cursor_from_glyph_right(glyph);
62 if cursor >= cursor_start && cursor <= cursor_end {
63 if x_start.is_none() {
64 x_start = Some(glyph.x + glyph.w.mul_add(ltr_factor, 0.0));
65 }
66 x_end = Some(glyph.x + glyph.w.mul_add(ltr_factor, 0.0));
67 }
68 }
69 x_start.map(|x_start| {
70 let x_end = x_end.expect("end of cursor not found");
71 let (x_start, x_end) = if x_start < x_end {
72 (x_start, x_end)
73 } else {
74 (x_end, x_start)
75 };
76 (x_start, x_end - x_start)
77 })
78 }
79
80 const fn cursor_from_glyph_left(&self, glyph: &LayoutGlyph) -> Cursor {
81 if self.rtl {
82 Cursor::new_with_affinity(self.line_i, glyph.end, Affinity::Before)
83 } else {
84 Cursor::new_with_affinity(self.line_i, glyph.start, Affinity::After)
85 }
86 }
87
88 const fn cursor_from_glyph_right(&self, glyph: &LayoutGlyph) -> Cursor {
89 if self.rtl {
90 Cursor::new_with_affinity(self.line_i, glyph.start, Affinity::After)
91 } else {
92 Cursor::new_with_affinity(self.line_i, glyph.end, Affinity::Before)
93 }
94 }
95}
96
97#[derive(Debug)]
99pub struct LayoutRunIter<'b> {
100 buffer: &'b Buffer,
101 line_i: usize,
102 layout_i: usize,
103 total_height: f32,
104 line_top: f32,
105}
106
107impl<'b> LayoutRunIter<'b> {
108 pub const fn new(buffer: &'b Buffer) -> Self {
109 Self {
110 buffer,
111 line_i: buffer.scroll.line,
112 layout_i: 0,
113 total_height: 0.0,
114 line_top: 0.0,
115 }
116 }
117}
118
119impl<'b> Iterator for LayoutRunIter<'b> {
120 type Item = LayoutRun<'b>;
121
122 fn next(&mut self) -> Option<Self::Item> {
123 while let Some(line) = self.buffer.lines.get(self.line_i) {
124 let shape = line.shape_opt()?;
125 let layout = line.layout_opt()?;
126 while let Some(layout_line) = layout.get(self.layout_i) {
127 self.layout_i += 1;
128
129 let line_height = layout_line
130 .line_height_opt
131 .unwrap_or(self.buffer.metrics.line_height);
132 self.total_height += line_height;
133
134 let line_top = self.line_top - self.buffer.scroll.vertical;
135 let glyph_height = layout_line.max_ascent + layout_line.max_descent;
136 let centering_offset = (line_height - glyph_height) / 2.0;
137 let line_y = line_top + centering_offset + layout_line.max_ascent;
138 if let Some(height) = self.buffer.height_opt {
139 if line_y - layout_line.max_ascent > height {
140 return None;
141 }
142 }
143 self.line_top += line_height;
144 if line_y + layout_line.max_descent < 0.0 {
145 continue;
146 }
147
148 return Some(LayoutRun {
149 line_i: self.line_i,
150 text: line.text(),
151 rtl: shape.rtl,
152 glyphs: &layout_line.glyphs,
153 line_y,
154 line_top,
155 line_height,
156 line_w: layout_line.w,
157 });
158 }
159 self.line_i += 1;
160 self.layout_i = 0;
161 }
162
163 None
164 }
165}
166
167#[derive(Clone, Copy, Debug, Default, PartialEq)]
169pub struct Metrics {
170 pub font_size: f32,
172 pub line_height: f32,
174}
175
176impl Metrics {
177 pub const fn new(font_size: f32, line_height: f32) -> Self {
179 Self {
180 font_size,
181 line_height,
182 }
183 }
184
185 pub fn relative(font_size: f32, line_height_scale: f32) -> Self {
187 Self {
188 font_size,
189 line_height: font_size * line_height_scale,
190 }
191 }
192
193 pub fn scale(self, scale: f32) -> Self {
195 Self {
196 font_size: self.font_size * scale,
197 line_height: self.line_height * scale,
198 }
199 }
200}
201
202impl fmt::Display for Metrics {
203 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
204 write!(f, "{}px / {}px", self.font_size, self.line_height)
205 }
206}
207
208#[derive(Debug)]
210pub struct Buffer {
211 pub lines: Vec<BufferLine>,
213 metrics: Metrics,
214 width_opt: Option<f32>,
215 height_opt: Option<f32>,
216 scroll: Scroll,
217 redraw: bool,
219 wrap: Wrap,
220 monospace_width: Option<f32>,
221 tab_width: u16,
222}
223
224impl Clone for Buffer {
225 fn clone(&self) -> Self {
226 Self {
227 lines: self.lines.clone(),
228 metrics: self.metrics,
229 width_opt: self.width_opt,
230 height_opt: self.height_opt,
231 scroll: self.scroll,
232 redraw: self.redraw,
233 wrap: self.wrap,
234 monospace_width: self.monospace_width,
235 tab_width: self.tab_width,
236 }
237 }
238}
239
240impl Buffer {
241 pub fn new_empty(metrics: Metrics) -> Self {
253 assert_ne!(metrics.line_height, 0.0, "line height cannot be 0");
254 Self {
255 lines: Vec::new(),
256 metrics,
257 width_opt: None,
258 height_opt: None,
259 scroll: Scroll::default(),
260 redraw: false,
261 wrap: Wrap::WordOrGlyph,
262 monospace_width: None,
263 tab_width: 8,
264 }
265 }
266
267 pub fn new(font_system: &mut FontSystem, metrics: Metrics) -> Self {
273 let mut buffer = Self::new_empty(metrics);
274 buffer.set_text(font_system, "", &Attrs::new(), Shaping::Advanced);
275 buffer
276 }
277
278 pub fn borrow_with<'a>(
280 &'a mut self,
281 font_system: &'a mut FontSystem,
282 ) -> BorrowedWithFontSystem<'a, Self> {
283 BorrowedWithFontSystem {
284 inner: self,
285 font_system,
286 }
287 }
288
289 fn relayout(&mut self, font_system: &mut FontSystem) {
290 #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
291 let instant = std::time::Instant::now();
292
293 for line in &mut self.lines {
294 if line.shape_opt().is_some() {
295 line.reset_layout();
296 line.layout(
297 font_system,
298 self.metrics.font_size,
299 self.width_opt,
300 self.wrap,
301 self.monospace_width,
302 self.tab_width,
303 );
304 }
305 }
306
307 self.redraw = true;
308
309 #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
310 log::debug!("relayout: {:?}", instant.elapsed());
311 }
312
313 #[allow(clippy::missing_panics_doc)]
315 pub fn shape_until_cursor(
316 &mut self,
317 font_system: &mut FontSystem,
318 cursor: Cursor,
319 prune: bool,
320 ) {
321 let metrics = self.metrics;
322 let old_scroll = self.scroll;
323
324 let layout_cursor = self
325 .layout_cursor(font_system, cursor)
326 .expect("shape_until_cursor invalid cursor");
327
328 let mut layout_y = 0.0;
329 let mut total_height = {
330 let layout = self
331 .line_layout(font_system, layout_cursor.line)
332 .expect("shape_until_cursor failed to scroll forwards");
333 (0..layout_cursor.layout).for_each(|layout_i| {
334 layout_y += layout[layout_i]
335 .line_height_opt
336 .unwrap_or(metrics.line_height);
337 });
338 layout_y
339 + layout[layout_cursor.layout]
340 .line_height_opt
341 .unwrap_or(metrics.line_height)
342 };
343
344 if self.scroll.line > layout_cursor.line
345 || (self.scroll.line == layout_cursor.line && self.scroll.vertical > layout_y)
346 {
347 self.scroll.line = layout_cursor.line;
349 self.scroll.vertical = layout_y;
350 } else if let Some(height) = self.height_opt {
351 let mut line_i = layout_cursor.line;
353 if line_i <= self.scroll.line {
354 if total_height > height + self.scroll.vertical {
356 self.scroll.vertical = total_height - height;
357 }
358 } else {
359 while line_i > self.scroll.line {
360 line_i -= 1;
361 let layout = self
362 .line_layout(font_system, line_i)
363 .expect("shape_until_cursor failed to scroll forwards");
364 for layout_line in layout {
365 total_height += layout_line.line_height_opt.unwrap_or(metrics.line_height);
366 }
367 if total_height > height + self.scroll.vertical {
368 self.scroll.line = line_i;
369 self.scroll.vertical = total_height - height;
370 }
371 }
372 }
373 }
374
375 if old_scroll != self.scroll {
376 self.redraw = true;
377 }
378
379 self.shape_until_scroll(font_system, prune);
380
381 if let Some(layout_cursor) = self.layout_cursor(font_system, cursor) {
383 if let Some(layout_lines) = self.line_layout(font_system, layout_cursor.line) {
384 if let Some(layout_line) = layout_lines.get(layout_cursor.layout) {
385 let (x_min, x_max) = layout_line
386 .glyphs
387 .get(layout_cursor.glyph)
388 .or_else(|| layout_line.glyphs.last())
389 .map_or((0.0, 0.0), |glyph| {
390 let x_a = glyph.x;
392 let x_b = glyph.x + glyph.w;
393 (x_a.min(x_b), x_a.max(x_b))
394 });
395 if x_min < self.scroll.horizontal {
396 self.scroll.horizontal = x_min;
397 self.redraw = true;
398 }
399 if let Some(width) = self.width_opt {
400 if x_max > self.scroll.horizontal + width {
401 self.scroll.horizontal = x_max - width;
402 self.redraw = true;
403 }
404 }
405 }
406 }
407 }
408 }
409
410 #[allow(clippy::missing_panics_doc)]
412 pub fn shape_until_scroll(&mut self, font_system: &mut FontSystem, prune: bool) {
413 let metrics = self.metrics;
414 let old_scroll = self.scroll;
415
416 loop {
417 while self.scroll.vertical < 0.0 {
419 if self.scroll.line > 0 {
420 let line_i = self.scroll.line - 1;
421 if let Some(layout) = self.line_layout(font_system, line_i) {
422 let mut layout_height = 0.0;
423 for layout_line in layout {
424 layout_height +=
425 layout_line.line_height_opt.unwrap_or(metrics.line_height);
426 }
427 self.scroll.line = line_i;
428 self.scroll.vertical += layout_height;
429 } else {
430 self.scroll.line = line_i;
432 self.scroll.vertical += metrics.line_height;
433 }
434 } else {
435 self.scroll.vertical = 0.0;
436 break;
437 }
438 }
439
440 let scroll_start = self.scroll.vertical;
441 let scroll_end = scroll_start + self.height_opt.unwrap_or(f32::INFINITY);
442
443 let mut total_height = 0.0;
444 for line_i in 0..self.lines.len() {
445 if line_i < self.scroll.line {
446 if prune {
447 self.lines[line_i].reset_shaping();
448 }
449 continue;
450 }
451 if total_height > scroll_end {
452 if prune {
453 self.lines[line_i].reset_shaping();
454 continue;
455 }
456 break;
457 }
458
459 let mut layout_height = 0.0;
460 let layout = self
461 .line_layout(font_system, line_i)
462 .expect("shape_until_scroll invalid line");
463 for layout_line in layout {
464 let line_height = layout_line.line_height_opt.unwrap_or(metrics.line_height);
465 layout_height += line_height;
466 total_height += line_height;
467 }
468
469 if line_i == self.scroll.line && layout_height <= self.scroll.vertical {
471 self.scroll.line += 1;
472 self.scroll.vertical -= layout_height;
473 }
474 }
475
476 if total_height < scroll_end && self.scroll.line > 0 {
477 self.scroll.vertical -= scroll_end - total_height;
479 } else {
480 break;
482 }
483 }
484
485 if old_scroll != self.scroll {
486 self.redraw = true;
487 }
488 }
489
490 pub fn layout_cursor(
492 &mut self,
493 font_system: &mut FontSystem,
494 cursor: Cursor,
495 ) -> Option<LayoutCursor> {
496 let layout = self.line_layout(font_system, cursor.line)?;
497 for (layout_i, layout_line) in layout.iter().enumerate() {
498 for (glyph_i, glyph) in layout_line.glyphs.iter().enumerate() {
499 let cursor_end =
500 Cursor::new_with_affinity(cursor.line, glyph.end, Affinity::Before);
501 let cursor_start =
502 Cursor::new_with_affinity(cursor.line, glyph.start, Affinity::After);
503 let (cursor_left, cursor_right) = if glyph.level.is_ltr() {
504 (cursor_start, cursor_end)
505 } else {
506 (cursor_end, cursor_start)
507 };
508 if cursor == cursor_left {
509 return Some(LayoutCursor::new(cursor.line, layout_i, glyph_i));
510 }
511 if cursor == cursor_right {
512 return Some(LayoutCursor::new(cursor.line, layout_i, glyph_i + 1));
513 }
514 }
515 }
516
517 Some(LayoutCursor::new(cursor.line, 0, 0))
520 }
521
522 pub fn line_shape(
524 &mut self,
525 font_system: &mut FontSystem,
526 line_i: usize,
527 ) -> Option<&ShapeLine> {
528 let line = self.lines.get_mut(line_i)?;
529 Some(line.shape(font_system, self.tab_width))
530 }
531
532 pub fn line_layout(
534 &mut self,
535 font_system: &mut FontSystem,
536 line_i: usize,
537 ) -> Option<&[LayoutLine]> {
538 let line = self.lines.get_mut(line_i)?;
539 Some(line.layout(
540 font_system,
541 self.metrics.font_size,
542 self.width_opt,
543 self.wrap,
544 self.monospace_width,
545 self.tab_width,
546 ))
547 }
548
549 pub const fn metrics(&self) -> Metrics {
551 self.metrics
552 }
553
554 pub fn set_metrics(&mut self, font_system: &mut FontSystem, metrics: Metrics) {
560 self.set_metrics_and_size(font_system, metrics, self.width_opt, self.height_opt);
561 }
562
563 pub const fn wrap(&self) -> Wrap {
565 self.wrap
566 }
567
568 pub fn set_wrap(&mut self, font_system: &mut FontSystem, wrap: Wrap) {
570 if wrap != self.wrap {
571 self.wrap = wrap;
572 self.relayout(font_system);
573 self.shape_until_scroll(font_system, false);
574 }
575 }
576
577 pub const fn monospace_width(&self) -> Option<f32> {
579 self.monospace_width
580 }
581
582 pub fn set_monospace_width(
584 &mut self,
585 font_system: &mut FontSystem,
586 monospace_width: Option<f32>,
587 ) {
588 if monospace_width != self.monospace_width {
589 self.monospace_width = monospace_width;
590 self.relayout(font_system);
591 self.shape_until_scroll(font_system, false);
592 }
593 }
594
595 pub const fn tab_width(&self) -> u16 {
597 self.tab_width
598 }
599
600 pub fn set_tab_width(&mut self, font_system: &mut FontSystem, tab_width: u16) {
602 if tab_width == 0 {
604 return;
605 }
606 if tab_width != self.tab_width {
607 self.tab_width = tab_width;
608 for line in &mut self.lines {
610 if line.shape_opt().is_some() && line.text().contains('\t') {
611 line.reset_shaping();
612 }
613 }
614 self.redraw = true;
615 self.shape_until_scroll(font_system, false);
616 }
617 }
618
619 pub const fn size(&self) -> (Option<f32>, Option<f32>) {
621 (self.width_opt, self.height_opt)
622 }
623
624 pub fn set_size(
626 &mut self,
627 font_system: &mut FontSystem,
628 width_opt: Option<f32>,
629 height_opt: Option<f32>,
630 ) {
631 self.set_metrics_and_size(font_system, self.metrics, width_opt, height_opt);
632 }
633
634 pub fn set_metrics_and_size(
640 &mut self,
641 font_system: &mut FontSystem,
642 metrics: Metrics,
643 width_opt: Option<f32>,
644 height_opt: Option<f32>,
645 ) {
646 let clamped_width_opt = width_opt.map(|width| width.max(0.0));
647 let clamped_height_opt = height_opt.map(|height| height.max(0.0));
648
649 if metrics != self.metrics
650 || clamped_width_opt != self.width_opt
651 || clamped_height_opt != self.height_opt
652 {
653 assert_ne!(metrics.font_size, 0.0, "font size cannot be 0");
654 self.metrics = metrics;
655 self.width_opt = clamped_width_opt;
656 self.height_opt = clamped_height_opt;
657 self.relayout(font_system);
658 self.shape_until_scroll(font_system, false);
659 }
660 }
661
662 pub const fn scroll(&self) -> Scroll {
664 self.scroll
665 }
666
667 pub fn set_scroll(&mut self, scroll: Scroll) {
669 if scroll != self.scroll {
670 self.scroll = scroll;
671 self.redraw = true;
672 }
673 }
674
675 pub fn set_text(
677 &mut self,
678 font_system: &mut FontSystem,
679 text: &str,
680 attrs: &Attrs,
681 shaping: Shaping,
682 ) {
683 self.lines.clear();
684 for (range, ending) in LineIter::new(text) {
685 self.lines.push(BufferLine::new(
686 &text[range],
687 ending,
688 AttrsList::new(attrs),
689 shaping,
690 ));
691 }
692 if self.lines.is_empty() {
693 self.lines.push(BufferLine::new(
694 "",
695 LineEnding::default(),
696 AttrsList::new(attrs),
697 shaping,
698 ));
699 }
700 self.scroll = Scroll::default();
701 self.shape_until_scroll(font_system, false);
702 }
703
704 pub fn set_rich_text<'r, 's, I>(
723 &mut self,
724 font_system: &mut FontSystem,
725 spans: I,
726 default_attrs: &Attrs,
727 shaping: Shaping,
728 alignment: Option<Align>,
729 ) where
730 I: IntoIterator<Item = (&'s str, Attrs<'r>)>,
731 {
732 let mut end = 0;
733 let (string, spans_data): (String, Vec<_>) = spans
735 .into_iter()
736 .map(|(s, attrs)| {
737 let start = end;
738 end += s.len();
739 (s, (attrs, start..end))
740 })
741 .unzip();
742
743 let mut spans_iter = spans_data.into_iter();
744 let mut maybe_span = spans_iter.next();
745
746 let string_start = string.as_ptr() as usize;
748 let mut lines_iter = BidiParagraphs::new(&string).map(|line: &str| {
749 let start = line.as_ptr() as usize - string_start;
750 let end = start + line.len();
751 start..end
752 });
753 let mut maybe_line = lines_iter.next();
754 let line_ending = LineEnding::default();
756
757 let mut line_count = 0;
758 let mut attrs_list = self
759 .lines
760 .get_mut(line_count)
761 .map_or_else(|| AttrsList::new(&Attrs::new()), BufferLine::reclaim_attrs)
762 .reset(default_attrs);
763 let mut line_string = self
764 .lines
765 .get_mut(line_count)
766 .map(BufferLine::reclaim_text)
767 .unwrap_or_default();
768
769 loop {
770 let (Some(line_range), Some((attrs, span_range))) = (&maybe_line, &maybe_span) else {
771 if self.lines.len() == line_count {
773 self.lines.push(BufferLine::empty());
774 }
775 self.lines[line_count].reset_new(
776 String::new(),
777 line_ending,
778 AttrsList::new(default_attrs),
779 shaping,
780 );
781 line_count += 1;
782 break;
783 };
784
785 let start = line_range.start.max(span_range.start);
787 let end = line_range.end.min(span_range.end);
788 if start < end {
789 let text = &string[start..end];
790 let text_start = line_string.len();
791 line_string.push_str(text);
792 let text_end = line_string.len();
793 if *attrs != attrs_list.defaults() {
795 attrs_list.add_span(text_start..text_end, attrs);
796 }
797 }
798
799 if span_range.end < line_range.end {
805 maybe_span = spans_iter.next();
806 } else {
807 maybe_line = lines_iter.next();
808 if maybe_line.is_some() {
809 let next_attrs_list = self
811 .lines
812 .get_mut(line_count + 1)
813 .map_or_else(|| AttrsList::new(&Attrs::new()), BufferLine::reclaim_attrs)
814 .reset(default_attrs);
815 let next_line_string = self
816 .lines
817 .get_mut(line_count + 1)
818 .map(BufferLine::reclaim_text)
819 .unwrap_or_default();
820 let prev_attrs_list = core::mem::replace(&mut attrs_list, next_attrs_list);
821 let prev_line_string = core::mem::replace(&mut line_string, next_line_string);
822 if self.lines.len() == line_count {
823 self.lines.push(BufferLine::empty());
824 }
825 self.lines[line_count].reset_new(
826 prev_line_string,
827 line_ending,
828 prev_attrs_list,
829 shaping,
830 );
831 line_count += 1;
832 } else {
833 if self.lines.len() == line_count {
835 self.lines.push(BufferLine::empty());
836 }
837 self.lines[line_count].reset_new(line_string, line_ending, attrs_list, shaping);
838 line_count += 1;
839 break;
840 }
841 }
842 }
843
844 self.lines.truncate(line_count);
846
847 self.lines.iter_mut().for_each(|line| {
848 line.set_align(alignment);
849 });
850
851 self.scroll = Scroll::default();
852
853 self.shape_until_scroll(font_system, false);
854 }
855
856 pub const fn redraw(&self) -> bool {
858 self.redraw
859 }
860
861 pub fn set_redraw(&mut self, redraw: bool) {
863 self.redraw = redraw;
864 }
865
866 pub fn layout_runs(&self) -> LayoutRunIter<'_> {
868 LayoutRunIter::new(self)
869 }
870
871 pub fn hit(&self, x: f32, y: f32) -> Option<Cursor> {
873 #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
874 let instant = std::time::Instant::now();
875
876 let mut new_cursor_opt = None;
877
878 let mut runs = self.layout_runs().peekable();
879 let mut first_run = true;
880 while let Some(run) = runs.next() {
881 let line_top = run.line_top;
882 let line_height = run.line_height;
883
884 if first_run && y < line_top {
885 first_run = false;
886 let new_cursor = Cursor::new(run.line_i, 0);
887 new_cursor_opt = Some(new_cursor);
888 } else if y >= line_top && y < line_top + line_height {
889 let mut new_cursor_glyph = run.glyphs.len();
890 let mut new_cursor_char = 0;
891 let mut new_cursor_affinity = Affinity::After;
892
893 let mut first_glyph = true;
894
895 'hit: for (glyph_i, glyph) in run.glyphs.iter().enumerate() {
896 if first_glyph {
897 first_glyph = false;
898 if (run.rtl && x > glyph.x) || (!run.rtl && x < 0.0) {
899 new_cursor_glyph = 0;
900 new_cursor_char = 0;
901 }
902 }
903 if x >= glyph.x && x <= glyph.x + glyph.w {
904 new_cursor_glyph = glyph_i;
905
906 let cluster = &run.text[glyph.start..glyph.end];
907 let total = cluster.grapheme_indices(true).count();
908 let mut egc_x = glyph.x;
909 let egc_w = glyph.w / (total as f32);
910 for (egc_i, egc) in cluster.grapheme_indices(true) {
911 if x >= egc_x && x <= egc_x + egc_w {
912 new_cursor_char = egc_i;
913
914 let right_half = x >= egc_x + egc_w / 2.0;
915 if right_half != glyph.level.is_rtl() {
916 new_cursor_char += egc.len();
918 new_cursor_affinity = Affinity::Before;
919 }
920 break 'hit;
921 }
922 egc_x += egc_w;
923 }
924
925 let right_half = x >= glyph.x + glyph.w / 2.0;
926 if right_half != glyph.level.is_rtl() {
927 new_cursor_char = cluster.len();
929 new_cursor_affinity = Affinity::Before;
930 }
931 break 'hit;
932 }
933 }
934
935 let mut new_cursor = Cursor::new(run.line_i, 0);
936
937 match run.glyphs.get(new_cursor_glyph) {
938 Some(glyph) => {
939 new_cursor.index = glyph.start + new_cursor_char;
941 new_cursor.affinity = new_cursor_affinity;
942 }
943 None => {
944 if let Some(glyph) = run.glyphs.last() {
945 new_cursor.index = glyph.end;
947 new_cursor.affinity = Affinity::Before;
948 }
949 }
950 }
951
952 new_cursor_opt = Some(new_cursor);
953
954 break;
955 } else if runs.peek().is_none() && y > run.line_y {
956 let mut new_cursor = Cursor::new(run.line_i, 0);
957 if let Some(glyph) = run.glyphs.last() {
958 new_cursor = run.cursor_from_glyph_right(glyph);
959 }
960 new_cursor_opt = Some(new_cursor);
961 }
962 }
963
964 #[cfg(all(feature = "std", not(target_arch = "wasm32")))]
965 log::trace!("click({}, {}): {:?}", x, y, instant.elapsed());
966
967 new_cursor_opt
968 }
969
970 pub fn cursor_motion(
972 &mut self,
973 font_system: &mut FontSystem,
974 mut cursor: Cursor,
975 mut cursor_x_opt: Option<i32>,
976 motion: Motion,
977 ) -> Option<(Cursor, Option<i32>)> {
978 match motion {
979 Motion::LayoutCursor(layout_cursor) => {
980 let layout = self.line_layout(font_system, layout_cursor.line)?;
981
982 let layout_line = match layout.get(layout_cursor.layout) {
983 Some(some) => some,
984 None => match layout.last() {
985 Some(some) => some,
986 None => {
987 return None;
988 }
989 },
990 };
991
992 let (new_index, new_affinity) =
993 layout_line.glyphs.get(layout_cursor.glyph).map_or_else(
994 || {
995 layout_line
996 .glyphs
997 .last()
998 .map_or((0, Affinity::After), |glyph| (glyph.end, Affinity::Before))
999 },
1000 |glyph| (glyph.start, Affinity::After),
1001 );
1002
1003 if cursor.line != layout_cursor.line
1004 || cursor.index != new_index
1005 || cursor.affinity != new_affinity
1006 {
1007 cursor.line = layout_cursor.line;
1008 cursor.index = new_index;
1009 cursor.affinity = new_affinity;
1010 }
1011 }
1012 Motion::Previous => {
1013 let line = self.lines.get(cursor.line)?;
1014 if cursor.index > 0 {
1015 let mut prev_index = 0;
1017 for (i, _) in line.text().grapheme_indices(true) {
1018 if i < cursor.index {
1019 prev_index = i;
1020 } else {
1021 break;
1022 }
1023 }
1024
1025 cursor.index = prev_index;
1026 cursor.affinity = Affinity::After;
1027 } else if cursor.line > 0 {
1028 cursor.line -= 1;
1029 cursor.index = self.lines.get(cursor.line)?.text().len();
1030 cursor.affinity = Affinity::After;
1031 }
1032 cursor_x_opt = None;
1033 }
1034 Motion::Next => {
1035 let line = self.lines.get(cursor.line)?;
1036 if cursor.index < line.text().len() {
1037 for (i, c) in line.text().grapheme_indices(true) {
1038 if i == cursor.index {
1039 cursor.index += c.len();
1040 cursor.affinity = Affinity::Before;
1041 break;
1042 }
1043 }
1044 } else if cursor.line + 1 < self.lines.len() {
1045 cursor.line += 1;
1046 cursor.index = 0;
1047 cursor.affinity = Affinity::Before;
1048 }
1049 cursor_x_opt = None;
1050 }
1051 Motion::Left => {
1052 let rtl_opt = self
1053 .line_shape(font_system, cursor.line)
1054 .map(|shape| shape.rtl);
1055 if let Some(rtl) = rtl_opt {
1056 if rtl {
1057 (cursor, cursor_x_opt) =
1058 self.cursor_motion(font_system, cursor, cursor_x_opt, Motion::Next)?;
1059 } else {
1060 (cursor, cursor_x_opt) = self.cursor_motion(
1061 font_system,
1062 cursor,
1063 cursor_x_opt,
1064 Motion::Previous,
1065 )?;
1066 }
1067 }
1068 }
1069 Motion::Right => {
1070 let rtl_opt = self
1071 .line_shape(font_system, cursor.line)
1072 .map(|shape| shape.rtl);
1073 if let Some(rtl) = rtl_opt {
1074 if rtl {
1075 (cursor, cursor_x_opt) = self.cursor_motion(
1076 font_system,
1077 cursor,
1078 cursor_x_opt,
1079 Motion::Previous,
1080 )?;
1081 } else {
1082 (cursor, cursor_x_opt) =
1083 self.cursor_motion(font_system, cursor, cursor_x_opt, Motion::Next)?;
1084 }
1085 }
1086 }
1087 Motion::Up => {
1088 let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1089
1090 if cursor_x_opt.is_none() {
1091 cursor_x_opt = Some(
1092 layout_cursor.glyph as i32, );
1094 }
1095
1096 if layout_cursor.layout > 0 {
1097 layout_cursor.layout -= 1;
1098 } else if layout_cursor.line > 0 {
1099 layout_cursor.line -= 1;
1100 layout_cursor.layout = usize::MAX;
1101 }
1102
1103 if let Some(cursor_x) = cursor_x_opt {
1104 layout_cursor.glyph = cursor_x as usize; }
1106
1107 (cursor, cursor_x_opt) = self.cursor_motion(
1108 font_system,
1109 cursor,
1110 cursor_x_opt,
1111 Motion::LayoutCursor(layout_cursor),
1112 )?;
1113 }
1114 Motion::Down => {
1115 let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1116
1117 let layout_len = self.line_layout(font_system, layout_cursor.line)?.len();
1118
1119 if cursor_x_opt.is_none() {
1120 cursor_x_opt = Some(
1121 layout_cursor.glyph as i32, );
1123 }
1124
1125 if layout_cursor.layout + 1 < layout_len {
1126 layout_cursor.layout += 1;
1127 } else if layout_cursor.line + 1 < self.lines.len() {
1128 layout_cursor.line += 1;
1129 layout_cursor.layout = 0;
1130 }
1131
1132 if let Some(cursor_x) = cursor_x_opt {
1133 layout_cursor.glyph = cursor_x as usize; }
1135
1136 (cursor, cursor_x_opt) = self.cursor_motion(
1137 font_system,
1138 cursor,
1139 cursor_x_opt,
1140 Motion::LayoutCursor(layout_cursor),
1141 )?;
1142 }
1143 Motion::Home => {
1144 let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1145 layout_cursor.glyph = 0;
1146 #[allow(unused_assignments)]
1147 {
1148 (cursor, cursor_x_opt) = self.cursor_motion(
1149 font_system,
1150 cursor,
1151 cursor_x_opt,
1152 Motion::LayoutCursor(layout_cursor),
1153 )?;
1154 }
1155 cursor_x_opt = None;
1156 }
1157 Motion::SoftHome => {
1158 let line = self.lines.get(cursor.line)?;
1159 cursor.index = line
1160 .text()
1161 .char_indices()
1162 .find_map(|(i, c)| if c.is_whitespace() { None } else { Some(i) })
1163 .unwrap_or(0);
1164 cursor_x_opt = None;
1165 }
1166 Motion::End => {
1167 let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1168 layout_cursor.glyph = usize::MAX;
1169 #[allow(unused_assignments)]
1170 {
1171 (cursor, cursor_x_opt) = self.cursor_motion(
1172 font_system,
1173 cursor,
1174 cursor_x_opt,
1175 Motion::LayoutCursor(layout_cursor),
1176 )?;
1177 }
1178 cursor_x_opt = None;
1179 }
1180 Motion::ParagraphStart => {
1181 cursor.index = 0;
1182 cursor_x_opt = None;
1183 }
1184 Motion::ParagraphEnd => {
1185 cursor.index = self.lines.get(cursor.line)?.text().len();
1186 cursor_x_opt = None;
1187 }
1188 Motion::PageUp => {
1189 if let Some(height) = self.height_opt {
1190 (cursor, cursor_x_opt) = self.cursor_motion(
1191 font_system,
1192 cursor,
1193 cursor_x_opt,
1194 Motion::Vertical(-height as i32),
1195 )?;
1196 }
1197 }
1198 Motion::PageDown => {
1199 if let Some(height) = self.height_opt {
1200 (cursor, cursor_x_opt) = self.cursor_motion(
1201 font_system,
1202 cursor,
1203 cursor_x_opt,
1204 Motion::Vertical(height as i32),
1205 )?;
1206 }
1207 }
1208 Motion::Vertical(px) => {
1209 let lines = px / self.metrics().line_height as i32;
1211 match lines.cmp(&0) {
1212 cmp::Ordering::Less => {
1213 for _ in 0..-lines {
1214 (cursor, cursor_x_opt) =
1215 self.cursor_motion(font_system, cursor, cursor_x_opt, Motion::Up)?;
1216 }
1217 }
1218 cmp::Ordering::Greater => {
1219 for _ in 0..lines {
1220 (cursor, cursor_x_opt) = self.cursor_motion(
1221 font_system,
1222 cursor,
1223 cursor_x_opt,
1224 Motion::Down,
1225 )?;
1226 }
1227 }
1228 cmp::Ordering::Equal => {}
1229 }
1230 }
1231 Motion::PreviousWord => {
1232 let line = self.lines.get(cursor.line)?;
1233 if cursor.index > 0 {
1234 cursor.index = line
1235 .text()
1236 .unicode_word_indices()
1237 .rev()
1238 .map(|(i, _)| i)
1239 .find(|&i| i < cursor.index)
1240 .unwrap_or(0);
1241 } else if cursor.line > 0 {
1242 cursor.line -= 1;
1243 cursor.index = self.lines.get(cursor.line)?.text().len();
1244 }
1245 cursor_x_opt = None;
1246 }
1247 Motion::NextWord => {
1248 let line = self.lines.get(cursor.line)?;
1249 if cursor.index < line.text().len() {
1250 cursor.index = line
1251 .text()
1252 .unicode_word_indices()
1253 .map(|(i, word)| i + word.len())
1254 .find(|&i| i > cursor.index)
1255 .unwrap_or_else(|| line.text().len());
1256 } else if cursor.line + 1 < self.lines.len() {
1257 cursor.line += 1;
1258 cursor.index = 0;
1259 }
1260 cursor_x_opt = None;
1261 }
1262 Motion::LeftWord => {
1263 let rtl_opt = self
1264 .line_shape(font_system, cursor.line)
1265 .map(|shape| shape.rtl);
1266 if let Some(rtl) = rtl_opt {
1267 if rtl {
1268 (cursor, cursor_x_opt) = self.cursor_motion(
1269 font_system,
1270 cursor,
1271 cursor_x_opt,
1272 Motion::NextWord,
1273 )?;
1274 } else {
1275 (cursor, cursor_x_opt) = self.cursor_motion(
1276 font_system,
1277 cursor,
1278 cursor_x_opt,
1279 Motion::PreviousWord,
1280 )?;
1281 }
1282 }
1283 }
1284 Motion::RightWord => {
1285 let rtl_opt = self
1286 .line_shape(font_system, cursor.line)
1287 .map(|shape| shape.rtl);
1288 if let Some(rtl) = rtl_opt {
1289 if rtl {
1290 (cursor, cursor_x_opt) = self.cursor_motion(
1291 font_system,
1292 cursor,
1293 cursor_x_opt,
1294 Motion::PreviousWord,
1295 )?;
1296 } else {
1297 (cursor, cursor_x_opt) = self.cursor_motion(
1298 font_system,
1299 cursor,
1300 cursor_x_opt,
1301 Motion::NextWord,
1302 )?;
1303 }
1304 }
1305 }
1306 Motion::BufferStart => {
1307 cursor.line = 0;
1308 cursor.index = 0;
1309 cursor_x_opt = None;
1310 }
1311 Motion::BufferEnd => {
1312 cursor.line = self.lines.len().saturating_sub(1);
1313 cursor.index = self.lines.get(cursor.line)?.text().len();
1314 cursor_x_opt = None;
1315 }
1316 Motion::GotoLine(line) => {
1317 let mut layout_cursor = self.layout_cursor(font_system, cursor)?;
1318 layout_cursor.line = line;
1319 (cursor, cursor_x_opt) = self.cursor_motion(
1320 font_system,
1321 cursor,
1322 cursor_x_opt,
1323 Motion::LayoutCursor(layout_cursor),
1324 )?;
1325 }
1326 }
1327 Some((cursor, cursor_x_opt))
1328 }
1329
1330 #[cfg(feature = "swash")]
1332 pub fn draw<F>(
1333 &self,
1334 font_system: &mut FontSystem,
1335 cache: &mut crate::SwashCache,
1336 color: Color,
1337 mut f: F,
1338 ) where
1339 F: FnMut(i32, i32, u32, u32, Color),
1340 {
1341 for run in self.layout_runs() {
1342 for glyph in run.glyphs {
1343 let physical_glyph = glyph.physical((0., 0.), 1.0);
1344 let glyph_color = glyph.color_opt.map_or(color, |some| some);
1345
1346 cache.with_pixels(
1347 font_system,
1348 physical_glyph.cache_key,
1349 glyph_color,
1350 |x, y, color| {
1351 f(
1352 physical_glyph.x + x,
1353 run.line_y as i32 + physical_glyph.y + y,
1354 1,
1355 1,
1356 color,
1357 );
1358 },
1359 );
1360 }
1361 }
1362 }
1363}
1364
1365impl BorrowedWithFontSystem<'_, Buffer> {
1366 pub fn shape_until_cursor(&mut self, cursor: Cursor, prune: bool) {
1368 self.inner
1369 .shape_until_cursor(self.font_system, cursor, prune);
1370 }
1371
1372 pub fn shape_until_scroll(&mut self, prune: bool) {
1374 self.inner.shape_until_scroll(self.font_system, prune);
1375 }
1376
1377 pub fn line_shape(&mut self, line_i: usize) -> Option<&ShapeLine> {
1379 self.inner.line_shape(self.font_system, line_i)
1380 }
1381
1382 pub fn line_layout(&mut self, line_i: usize) -> Option<&[LayoutLine]> {
1384 self.inner.line_layout(self.font_system, line_i)
1385 }
1386
1387 pub fn set_metrics(&mut self, metrics: Metrics) {
1393 self.inner.set_metrics(self.font_system, metrics);
1394 }
1395
1396 pub fn set_wrap(&mut self, wrap: Wrap) {
1398 self.inner.set_wrap(self.font_system, wrap);
1399 }
1400
1401 pub fn set_size(&mut self, width_opt: Option<f32>, height_opt: Option<f32>) {
1403 self.inner.set_size(self.font_system, width_opt, height_opt);
1404 }
1405
1406 pub fn set_metrics_and_size(
1412 &mut self,
1413 metrics: Metrics,
1414 width_opt: Option<f32>,
1415 height_opt: Option<f32>,
1416 ) {
1417 self.inner
1418 .set_metrics_and_size(self.font_system, metrics, width_opt, height_opt);
1419 }
1420
1421 pub fn set_tab_width(&mut self, tab_width: u16) {
1423 self.inner.set_tab_width(self.font_system, tab_width);
1424 }
1425
1426 pub fn set_text(&mut self, text: &str, attrs: &Attrs, shaping: Shaping) {
1428 self.inner.set_text(self.font_system, text, attrs, shaping);
1429 }
1430
1431 pub fn set_rich_text<'r, 's, I>(
1450 &mut self,
1451 spans: I,
1452 default_attrs: &Attrs,
1453 shaping: Shaping,
1454 alignment: Option<Align>,
1455 ) where
1456 I: IntoIterator<Item = (&'s str, Attrs<'r>)>,
1457 {
1458 self.inner
1459 .set_rich_text(self.font_system, spans, default_attrs, shaping, alignment);
1460 }
1461
1462 pub fn cursor_motion(
1464 &mut self,
1465 cursor: Cursor,
1466 cursor_x_opt: Option<i32>,
1467 motion: Motion,
1468 ) -> Option<(Cursor, Option<i32>)> {
1469 self.inner
1470 .cursor_motion(self.font_system, cursor, cursor_x_opt, motion)
1471 }
1472
1473 #[cfg(feature = "swash")]
1475 pub fn draw<F>(&mut self, cache: &mut crate::SwashCache, color: Color, f: F)
1476 where
1477 F: FnMut(i32, i32, u32, u32, Color),
1478 {
1479 self.inner.draw(self.font_system, cache, color, f);
1480 }
1481}