Debian Codegraph @

helix-core/src/text_annotations.rs

raw symbols SCIP
1 use std::cell::Cell;
2 use std::cmp::Ordering;
3 use std::fmt::Debug;
4 use std::ops::Range;
5 use std::ptr::NonNull;
6
7 use crate::doc_formatter::FormattedGrapheme;
8 use crate::syntax::{Highlight, OverlayHighlights};
9 use crate::{Position, Tendril};
10
11 /// An inline annotation is continuous text shown
12 /// on the screen before the grapheme that starts at
13 /// `char_idx`
14 #[derive(Debug, Clone)]
15 pub struct InlineAnnotation {
16 pub text: Tendril,
17 pub char_idx: usize,
18 }
19
20 impl InlineAnnotation {
21 pub fn new(char_idx: usize, text: impl Into<Tendril>) -> Self {
22 Self {
23 char_idx,
24 text: text.into(),
25 }
26 }
27 }
28
29 /// Represents a **single Grapheme** that is part of the document
30 /// that start at `char_idx` that will be replaced with
31 /// a different `grapheme`.
32 /// If `grapheme` contains multiple graphemes the text
33 /// will render incorrectly.
34 /// If you want to overlay multiple graphemes simply
35 /// use multiple `Overlays`.
36 ///
37 /// # Examples
38 ///
39 /// The following examples are valid overlays for the following text:
40 ///
41 /// `aX͎̊͢͜͝͡bc`
42 ///
43 /// ```
44 /// use helix_core::text_annotations::Overlay;
45 ///
46 /// // replaces a
47 /// Overlay::new(0, "X");
48 ///
49 /// // replaces X͎̊͢͜͝͡
50 /// Overlay::new(1, "\t");
51 ///
52 /// // replaces b
53 /// Overlay::new(6, "X̢̢̟͖̲͌̋̇͑͝");
54 /// ```
55 ///
56 /// The following examples are invalid uses
57 ///
58 /// ```
59 /// use helix_core::text_annotations::Overlay;
60 ///
61 /// // overlay is not aligned at grapheme boundary
62 /// Overlay::new(3, "x");
63 ///
64 /// // overlay contains multiple graphemes
65 /// Overlay::new(0, "xy");
66 /// ```
67 #[derive(Debug, Clone)]
68 pub struct Overlay {
69 pub char_idx: usize,
70 pub grapheme: Tendril,
71 }
72
73 impl Overlay {
74 pub fn new(char_idx: usize, grapheme: impl Into<Tendril>) -> Self {
75 Self {
76 char_idx,
77 grapheme: grapheme.into(),
78 }
79 }
80 }
81
82 /// Line annotations allow inserting virtual text lines between normal text
83 /// lines. These lines can be filled with text in the rendering code as their
84 /// contents have no effect beyond visual appearance.
85 ///
86 /// The height of virtual text is usually not known ahead of time as virtual
87 /// text often requires softwrapping. Furthermore the height of some virtual
88 /// text like side-by-side diffs depends on the height of the text (again
89 /// influenced by softwrap) and other virtual text. Therefore line annotations
90 /// are computed on the fly instead of ahead of time like other annotations.
91 ///
92 /// The core of this trait `insert_virtual_lines` function. It is called at the
93 /// end of every visual line and allows the `LineAnnotation` to insert empty
94 /// virtual lines. Apart from that the `LineAnnotation` trait has multiple
95 /// methods that allow it to track anchors in the document.
96 ///
97 /// When a new traversal of a document starts `reset_pos` is called. Afterwards
98 /// the other functions are called with indices that are larger then the
99 /// one passed to `reset_pos`. This allows performing a binary search (use
100 /// `partition_point`) in `reset_pos` once and then to only look at the next
101 /// anchor during each method call.
102 ///
103 /// The `reset_pos`, `skip_conceal` and `process_anchor` functions all return a
104 /// `char_idx` anchor. This anchor is stored when transversing the document and
105 /// when the grapheme at the anchor is traversed the `process_anchor` function
106 /// is called.
107 ///
108 /// # Note
109 ///
110 /// All functions only receive immutable references to `self`.
111 /// `LineAnnotation`s that want to store an internal position or
112 /// state of some kind should use `Cell`. Using interior mutability for
113 /// caches is preferable as otherwise a lot of lifetimes become invariant
114 /// which complicates APIs a lot.
115 pub trait LineAnnotation {
116 /// Resets the internal position to `char_idx`. This function is called
117 /// when a new traversal of a document starts.
118 ///
119 /// All `char_idx` passed to `insert_virtual_lines` are strictly monotonically increasing
120 /// with the first `char_idx` greater or equal to the `char_idx`
121 /// passed to this function.
122 ///
123 /// # Returns
124 ///
125 /// The `char_idx` of the next anchor this `LineAnnotation` is interested in,
126 /// replaces the currently registered anchor. Return `usize::MAX` to ignore
127 fn reset_pos(&mut self, _char_idx: usize) -> usize {
128 usize::MAX
129 }
130
131 /// Called when a text is concealed that contains an anchor registered by this `LineAnnotation`.
132 /// In this case the line decorations **must** ensure that virtual text anchored within that
133 /// char range is skipped.
134 ///
135 /// # Returns
136 ///
137 /// The `char_idx` of the next anchor this `LineAnnotation` is interested in,
138 /// **after the end of conceal_end_char_idx**
139 /// replaces the currently registered anchor. Return `usize::MAX` to ignore
140 fn skip_concealed_anchors(&mut self, conceal_end_char_idx: usize) -> usize {
141 self.reset_pos(conceal_end_char_idx)
142 }
143
144 /// Process an anchor (horizontal position is provided) and returns the next anchor.
145 ///
146 /// # Returns
147 ///
148 /// The `char_idx` of the next anchor this `LineAnnotation` is interested in,
149 /// replaces the currently registered anchor. Return `usize::MAX` to ignore
150 fn process_anchor(&mut self, _grapheme: &FormattedGrapheme) -> usize {
151 usize::MAX
152 }
153
154 /// This function is called at the end of a visual line to insert virtual text
155 ///
156 /// # Returns
157 ///
158 /// The number of additional virtual lines to reserve
159 ///
160 /// # Note
161 ///
162 /// The `line_end_visual_pos` parameter indicates the visual vertical distance
163 /// from the start of block where the traversal starts. This includes the offset
164 /// from other `LineAnnotations`. This allows inline annotations to consider
165 /// the height of the text and "align" two different documents (like for side
166 /// by side diffs). These annotations that want to "align" two documents should
167 /// therefore be added last so that other virtual text is also considered while aligning
168 fn insert_virtual_lines(
169 &mut self,
170 line_end_char_idx: usize,
171 line_end_visual_pos: Position,
172 doc_line: usize,
173 ) -> Position;
174 }
175
176 #[derive(Debug)]
177 struct Layer<'a, A, M> {
178 annotations: &'a [A],
179 current_index: Cell<usize>,
180 metadata: M,
181 }
182
183 impl<A, M: Clone> Clone for Layer<'_, A, M> {
184 fn clone(&self) -> Self {
185 Layer {
186 annotations: self.annotations,
187 current_index: self.current_index.clone(),
188 metadata: self.metadata.clone(),
189 }
190 }
191 }
192
193 impl<A, M> Layer<'_, A, M> {
194 pub fn reset_pos(&self, char_idx: usize, get_char_idx: impl Fn(&A) -> usize) {
195 let new_index = self
196 .annotations
197 .partition_point(|annot| get_char_idx(annot) < char_idx);
198 self.current_index.set(new_index);
199 }
200
201 pub fn consume(&self, char_idx: usize, get_char_idx: impl Fn(&A) -> usize) -> Option<&A> {
202 let annot = self.annotations.get(self.current_index.get())?;
203 debug_assert!(get_char_idx(annot) >= char_idx);
204 if get_char_idx(annot) == char_idx {
205 self.current_index.set(self.current_index.get() + 1);
206 Some(annot)
207 } else {
208 None
209 }
210 }
211 }
212
213 impl<'a, A, M> From<(&'a [A], M)> for Layer<'a, A, M> {
214 fn from((annotations, metadata): (&'a [A], M)) -> Layer<'a, A, M> {
215 Layer {
216 annotations,
217 current_index: Cell::new(0),
218 metadata,
219 }
220 }
221 }
222
223 fn reset_pos<A, M>(layers: &[Layer<A, M>], pos: usize, get_pos: impl Fn(&A) -> usize) {
224 for layer in layers {
225 layer.reset_pos(pos, &get_pos)
226 }
227 }
228
229 /// Safety: We store LineAnnotation in a NonNull pointer. This is necessary to work
230 /// around an unfortunate inconsistency in rusts variance system that unnnecesarily
231 /// makes the lifetime invariant if implemented with safe code. This makes the
232 /// DocFormatter API very cumbersome/basically impossible to work with.
233 ///
234 /// Normally object types `dyn Foo + 'a` are covariant so if we used `Box<dyn LineAnnotation + 'a>` below
235 /// everything would be alright. However we want to use `Cell<Box<dyn LineAnnotation + 'a>>`
236 /// to be able to call the mutable function on `LineAnnotation`. The problem is that
237 /// some types like `Cell` make all their arguments invariant. This is important for soundness
238 /// normally for the same reasons that `&'a mut T` is invariant over `T`
239 /// (see <https://doc.rust-lang.org/nomicon/subtyping.html>). However for `&'a mut` (`dyn Foo + 'b`)
240 /// there is a specical rule in the language to make `'b` covariant (otherwise trait objects would be
241 /// super annoying to use). See <https://users.rust-lang.org/t/solved-variance-of-dyn-trait-a> for
242 /// why this is sound. Sadly that rule doesn't apply to `Cell<Box<(dyn Foo + 'a)>`
243 /// (or other invariant types like `UnsafeCell` or `*mut (dyn Foo + 'a)`).
244 ///
245 /// We sidestep the problem by using `NonNull` which is covariant. In the
246 /// special case of trait objects this is sound (easily checked by adding a
247 /// `PhantomData<&'a mut Foo + 'a)>` field). We don't need an explicit `Cell`
248 /// type here because we never hand out any refereces to the trait objects. That
249 /// means any reference to the pointer can create a valid multable reference
250 /// that is covariant over `'a` (or in other words it's a raw pointer, as long as
251 /// we don't hand out references we are free to do whatever we want).
252 struct RawBox<T: ?Sized>(NonNull<T>);
253
254 impl<T: ?Sized> RawBox<T> {
255 /// Safety: Only a single mutable reference
256 /// created by this function may exist at a given time.
257 #[allow(clippy::mut_from_ref)]
258 unsafe fn get(&self) -> &mut T {
259 &mut *self.0.as_ptr()
260 }
261 }
262 impl<T: ?Sized> From<Box<T>> for RawBox<T> {
263 fn from(box_: Box<T>) -> Self {
264 // obviously safe because Box::into_raw never returns null
265 unsafe { Self(NonNull::new_unchecked(Box::into_raw(box_))) }
266 }
267 }
268
269 impl<T: ?Sized> Drop for RawBox<T> {
270 fn drop(&mut self) {
271 unsafe { drop(Box::from_raw(self.0.as_ptr())) }
272 }
273 }
274
275 /// Annotations that change that is displayed when the document is render.
276 /// Also commonly called virtual text.
277 #[derive(Default)]
278 pub struct TextAnnotations<'a> {
279 inline_annotations: Vec<Layer<'a, InlineAnnotation, Option<Highlight>>>,
280 overlays: Vec<Layer<'a, Overlay, Option<Highlight>>>,
281 line_annotations: Vec<(Cell<usize>, RawBox<dyn LineAnnotation + 'a>)>,
282 }
283
284 impl Debug for TextAnnotations<'_> {
285 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
286 f.debug_struct("TextAnnotations")
287 .field("inline_annotations", &self.inline_annotations)
288 .field("overlays", &self.overlays)
289 .finish_non_exhaustive()
290 }
291 }
292
293 impl<'a> TextAnnotations<'a> {
294 /// Prepare the TextAnnotations for iteration starting at char_idx
295 pub fn reset_pos(&self, char_idx: usize) {
296 reset_pos(&self.inline_annotations, char_idx, |annot| annot.char_idx);
297 reset_pos(&self.overlays, char_idx, |annot| annot.char_idx);
298 for (next_anchor, layer) in &self.line_annotations {
299 next_anchor.set(unsafe { layer.get().reset_pos(char_idx) });
300 }
301 }
302
303 pub fn collect_overlay_highlights(&self, char_range: Range<usize>) -> OverlayHighlights {
304 let mut highlights = Vec::new();
305 self.reset_pos(char_range.start);
306 for char_idx in char_range {
307 if let Some((_, Some(highlight))) = self.overlay_at(char_idx) {
308 // we don't know the number of chars the original grapheme takes
309 // however it doesn't matter as highlight boundaries are automatically
310 // aligned to grapheme boundaries in the rendering code
311 highlights.push((highlight, char_idx..char_idx + 1));
312 }
313 }
314
315 OverlayHighlights::Heterogenous { highlights }
316 }
317
318 /// Add new inline annotations.
319 ///
320 /// The annotations grapheme will be rendered with `highlight`
321 /// patched on top of `ui.text`.
322 ///
323 /// The annotations **must be sorted** by their `char_idx`.
324 /// Multiple annotations with the same `char_idx` are allowed,
325 /// they will be display in the order that they are present in the layer.
326 ///
327 /// If multiple layers contain annotations at the same position
328 /// the annotations that belong to the layers added first will be shown first.
329 pub fn add_inline_annotations(
330 &mut self,
331 layer: &'a [InlineAnnotation],
332 highlight: Option<Highlight>,
333 ) -> &mut Self {
334 if !layer.is_empty() {
335 self.inline_annotations.push((layer, highlight).into());
336 }
337 self
338 }
339
340 /// Add new grapheme overlays.
341 ///
342 /// The overlaid grapheme will be rendered with `highlight`
343 /// patched on top of `ui.text`.
344 ///
345 /// The overlays **must be sorted** by their `char_idx`.
346 /// Multiple overlays with the same `char_idx` **are allowed**.
347 ///
348 /// If multiple layers contain overlay at the same position
349 /// the overlay from the layer added last will be show.
350 pub fn add_overlay(&mut self, layer: &'a [Overlay], highlight: Option<Highlight>) -> &mut Self {
351 if !layer.is_empty() {
352 self.overlays.push((layer, highlight).into());
353 }
354 self
355 }
356
357 /// Add new annotation lines.
358 ///
359 /// The line annotations **must be sorted** by their `char_idx`.
360 /// Multiple line annotations with the same `char_idx` **are not allowed**.
361 pub fn add_line_annotation(&mut self, layer: Box<dyn LineAnnotation + 'a>) -> &mut Self {
362 self.line_annotations
363 .push((Cell::new(usize::MAX), layer.into()));
364 self
365 }
366
367 /// Removes all line annotations, useful for vertical motions
368 /// so that virtual text lines are automatically skipped.
369 pub fn clear_line_annotations(&mut self) {
370 self.line_annotations.clear();
371 }
372
373 pub(crate) fn next_inline_annotation_at(
374 &self,
375 char_idx: usize,
376 ) -> Option<(&InlineAnnotation, Option<Highlight>)> {
377 self.inline_annotations.iter().find_map(|layer| {
378 let annotation = layer.consume(char_idx, |annot| annot.char_idx)?;
379 Some((annotation, layer.metadata))
380 })
381 }
382
383 pub(crate) fn overlay_at(&self, char_idx: usize) -> Option<(&Overlay, Option<Highlight>)> {
384 let mut overlay = None;
385 for layer in &self.overlays {
386 while let Some(new_overlay) = layer.consume(char_idx, |annot| annot.char_idx) {
387 overlay = Some((new_overlay, layer.metadata));
388 }
389 }
390 overlay
391 }
392
393 pub(crate) fn process_virtual_text_anchors(&self, grapheme: &FormattedGrapheme) {
394 for (next_anchor, layer) in &self.line_annotations {
395 loop {
396 match next_anchor.get().cmp(&grapheme.char_idx) {
397 Ordering::Less => next_anchor
398 .set(unsafe { layer.get().skip_concealed_anchors(grapheme.char_idx) }),
399 Ordering::Equal => {
400 next_anchor.set(unsafe { layer.get().process_anchor(grapheme) })
401 }
402 Ordering::Greater => break,
403 };
404 }
405 }
406 }
407
408 pub(crate) fn virtual_lines_at(
409 &self,
410 char_idx: usize,
411 line_end_visual_pos: Position,
412 doc_line: usize,
413 ) -> usize {
414 let mut virt_off = Position::new(0, 0);
415 for (_, layer) in &self.line_annotations {
416 virt_off += unsafe {
417 layer
418 .get()
419 .insert_virtual_lines(char_idx, line_end_visual_pos + virt_off, doc_line)
420 };
421 }
422 virt_off.row
423 }
424 }