Skip to main content

gpui_base/input/base/
inline_tokens.rs

1//! Document annotations for atomic inline objects. Coordinates are always source bytes.
2use std::ops::Range;
3
4use gpui::{Context, EntityInputHandler as _, SharedString, Window};
5use unicode_segmentation::UnicodeSegmentation as _;
6
7use super::{InputBaseState, InputModeKind, undo_manager::EditIntent};
8
9/// An application-defined reference rendered as one inline editing unit. The
10/// ID names the referenced resource; the same ID may occur more than once.
11#[derive(Clone, Debug, PartialEq, Eq, Hash)]
12pub struct InlineToken {
13    id: SharedString,
14    text: SharedString,
15    label: SharedString,
16}
17
18impl InlineToken {
19    pub fn new(id: impl Into<SharedString>, text: impl Into<SharedString>) -> Self {
20        let text = text.into();
21        Self {
22            id: id.into(),
23            label: text.clone(),
24            text,
25        }
26    }
27    pub fn with_label(mut self, label: impl Into<SharedString>) -> Self {
28        self.label = label.into();
29        self
30    }
31    pub fn id(&self) -> &SharedString {
32        &self.id
33    }
34    pub fn text(&self) -> &SharedString {
35        &self.text
36    }
37    pub fn label(&self) -> &SharedString {
38        &self.label
39    }
40
41    fn validate(&self) -> Result<(), InlineTokenError> {
42        if self.id.trim().is_empty()
43            || [&self.text, &self.label].iter().any(|s| {
44                s.is_empty()
45                    || s.chars()
46                        .any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}'))
47            })
48        {
49            return Err(InlineTokenError::InvalidToken);
50        }
51        Ok(())
52    }
53}
54
55/// A token and its current half-open UTF-8 byte range.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct InlineTokenSpan {
58    range: Range<usize>,
59    token: InlineToken,
60}
61impl InlineTokenSpan {
62    pub fn range(&self) -> Range<usize> {
63        self.range.clone()
64    }
65    pub fn token(&self) -> &InlineToken {
66        &self.token
67    }
68    fn shifted(&self, delta: isize) -> Self {
69        Self {
70            range: self
71                .range
72                .start
73                .checked_add_signed(delta)
74                .expect("valid token start")
75                ..self
76                    .range
77                    .end
78                    .checked_add_signed(delta)
79                    .expect("valid token end"),
80            token: self.token.clone(),
81        }
82    }
83}
84
85/// An owned, coherent text-and-token snapshot: what `content()` returns and
86/// what `set_value` accepts. Plain text converts into content without tokens,
87/// and every token is validated against the text as it is attached, so a
88/// content value is always consistent.
89#[derive(Clone, Debug, PartialEq, Eq)]
90pub struct InputContent {
91    text: SharedString,
92    tokens: Vec<InlineTokenSpan>,
93}
94impl InputContent {
95    pub fn new(text: impl Into<SharedString>) -> Self {
96        Self {
97            text: text.into(),
98            tokens: vec![],
99        }
100    }
101    /// Attach a token to a half-open UTF-8 byte range of the text. The range
102    /// must be nonempty, sit on grapheme boundaries, contain exactly the
103    /// token's text and not overlap another token.
104    pub fn with_token(
105        mut self,
106        range: Range<usize>,
107        token: InlineToken,
108    ) -> Result<Self, InlineTokenError> {
109        token.validate()?;
110        validate_range(&self.text, &range)?;
111        if range.is_empty() {
112            return Err(InlineTokenError::InvalidRange);
113        }
114        if &self.text[range.clone()] != token.text.as_ref() {
115            return Err(InlineTokenError::TextMismatch);
116        }
117        let ix = self
118            .tokens
119            .partition_point(|span| span.range.end <= range.start);
120        if self
121            .tokens
122            .get(ix)
123            .is_some_and(|span| span.range.start < range.end)
124        {
125            return Err(InlineTokenError::OverlappingTokens);
126        }
127        self.tokens.insert(ix, InlineTokenSpan { range, token });
128        Ok(self)
129    }
130    pub fn text(&self) -> &SharedString {
131        &self.text
132    }
133    pub fn tokens(&self) -> &[InlineTokenSpan] {
134        &self.tokens
135    }
136}
137
138macro_rules! content_from_text {
139    ($($text:ty),* $(,)?) => {
140        $(impl From<$text> for InputContent {
141            fn from(text: $text) -> Self {
142                Self::new(text)
143            }
144        })*
145    };
146}
147// Every text type `set_value` accepted before it took content.
148content_from_text!(
149    &str,
150    &mut str,
151    &String,
152    String,
153    char,
154    Box<str>,
155    std::sync::Arc<str>,
156    &std::sync::Arc<str>,
157    std::borrow::Cow<'_, str>,
158    &SharedString,
159    SharedString,
160);
161
162/// A rejected token operation never partially changes the document.
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164#[non_exhaustive]
165pub enum InlineTokenError {
166    InvalidRange,
167    InvalidBoundary,
168    InvalidToken,
169    OverlappingTokens,
170    TextMismatch,
171    UnsupportedMode,
172    ValidationRejected,
173    CompositionActive,
174    SplitsSelection,
175}
176
177impl std::error::Error for InlineTokenError {}
178impl std::fmt::Display for InlineTokenError {
179    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180        f.write_str(match self {
181            Self::InvalidRange => "token range is outside the document or empty",
182            Self::InvalidBoundary => "token range splits a Unicode grapheme",
183            Self::InvalidToken => {
184                "token requires a nonempty ID, text and label without control characters"
185            }
186            Self::OverlappingTokens => "token ranges overlap",
187            Self::TextMismatch => "token text does not match its range or input normalization",
188            Self::UnsupportedMode => "tokens are not supported by this input mode",
189            Self::ValidationRejected => "input validation rejected the content",
190            Self::CompositionActive => "finish the active IME composition before editing tokens",
191            Self::SplitsSelection => "token range splits a selection",
192        })
193    }
194}
195
196fn validate_range(text: &str, range: &Range<usize>) -> Result<(), InlineTokenError> {
197    if range.start > range.end || range.end > text.len() {
198        return Err(InlineTokenError::InvalidRange);
199    }
200    let boundary =
201        |offset| offset == text.len() || text.grapheme_indices(true).any(|(ix, _)| ix == offset);
202    if !boundary(range.start) || !boundary(range.end) {
203        return Err(InlineTokenError::InvalidBoundary);
204    }
205    Ok(())
206}
207
208#[derive(Default)]
209pub(super) struct InlineTokenStore {
210    spans: Vec<InlineTokenSpan>,
211}
212
213/// Only affected records are retained in history. Ranges are relative to the edit start.
214#[derive(Clone, Debug, PartialEq, Eq)]
215pub(super) struct TokenDelta {
216    removed: Vec<InlineTokenSpan>,
217    inserted: Vec<InlineTokenSpan>,
218}
219
220impl InlineTokenStore {
221    fn replace(
222        &mut self,
223        range: &Range<usize>,
224        new_len: usize,
225        inserted: &[InlineTokenSpan],
226    ) -> Option<Box<TokenDelta>> {
227        let mut removed = Vec::new();
228        let shift = new_len as isize - range.len() as isize;
229        self.spans.retain_mut(|span| {
230            if span.range.start < range.end && range.start < span.range.end {
231                // Replaying history can cut through a token set after the edit.
232                if range.start <= span.range.start && span.range.end <= range.end {
233                    removed.push(span.shifted(-(range.start as isize)));
234                }
235                false
236            } else {
237                if span.range.start >= range.end {
238                    *span = span.shifted(shift);
239                }
240                true
241            }
242        });
243        self.spans
244            .extend(inserted.iter().map(|s| s.shifted(range.start as isize)));
245        if !inserted.is_empty() {
246            self.spans.sort_by_key(|s| s.range.start);
247        }
248        (!removed.is_empty() || !inserted.is_empty()).then(|| {
249            Box::new(TokenDelta {
250                removed,
251                inserted: inserted.to_vec(),
252            })
253        })
254    }
255}
256
257impl<M: InputModeKind> InputBaseState<M> {
258    pub(super) fn token_spans(&self) -> &[InlineTokenSpan] {
259        self.inline_tokens
260            .as_ref()
261            .map_or(&[], |store| &store.spans)
262    }
263    pub(super) fn token_boundary(&self, offset: usize, bias: sum_tree::Bias) -> usize {
264        let spans = self.token_spans();
265        let ix = spans.partition_point(|s| s.range.end <= offset);
266        if let Some(span) = spans.get(ix).filter(|s| s.range.start < offset) {
267            if bias == sum_tree::Bias::Left {
268                span.range.start
269            } else {
270                span.range.end
271            }
272        } else {
273            offset
274        }
275    }
276    pub(super) fn normalize_token_range(&self, range: Range<usize>) -> Range<usize> {
277        if self.replaying_history {
278            return range;
279        }
280        if range.is_empty() {
281            let offset = self.token_boundary(range.start, sum_tree::Bias::Right);
282            offset..offset
283        } else {
284            self.token_boundary(range.start, sum_tree::Bias::Left)
285                ..self.token_boundary(range.end, sum_tree::Bias::Right)
286        }
287    }
288    pub(super) fn edit_tokens(
289        &mut self,
290        range: &Range<usize>,
291        new_len: usize,
292    ) -> Option<Box<TokenDelta>> {
293        if self.replaying_history {
294            return None;
295        }
296        let inserted = self.pending_token.take().map(|token| InlineTokenSpan {
297            range: 0..new_len,
298            token,
299        });
300        if inserted.is_some() && self.inline_tokens.is_none() {
301            self.inline_tokens = Some(Box::default());
302        }
303        self.inline_tokens
304            .as_mut()?
305            .replace(range, new_len, inserted.as_slice())
306    }
307    pub(super) fn replay_tokens(
308        &mut self,
309        range: &Range<usize>,
310        new_len: usize,
311        delta: Option<&TokenDelta>,
312        undo: bool,
313    ) {
314        let inserted = delta
315            .map(|d| {
316                if undo {
317                    &d.removed[..]
318                } else {
319                    &d.inserted[..]
320                }
321            })
322            .unwrap_or_default();
323        if !inserted.is_empty() && self.inline_tokens.is_none() {
324            self.inline_tokens = Some(Box::default());
325        }
326        if let Some(store) = self.inline_tokens.as_mut() {
327            store.replace(range, new_len, inserted);
328        }
329    }
330    fn check_token_mode(&self) -> Result<(), InlineTokenError> {
331        if self.ime_marked_range.is_some() {
332            return Err(InlineTokenError::CompositionActive);
333        }
334        if M::CODE_EDITOR || self.masked || self.token_is_secret() || !self.mask_pattern.is_none() {
335            return Err(InlineTokenError::UnsupportedMode);
336        }
337        Ok(())
338    }
339    fn replace_token(
340        &mut self,
341        range: Range<usize>,
342        token: InlineToken,
343        window: &mut Window,
344        cx: &mut Context<Self>,
345    ) -> Result<(), InlineTokenError> {
346        self.check_token_mode()?;
347        token.validate()?;
348        let text = self.text.to_string();
349        validate_range(&text, &range)?;
350        let range = self.normalize_token_range(range);
351        let mut next = text;
352        next.replace_range(range.clone(), &token.text);
353        validate_range(&next, &(range.start..range.start + token.text.len()))?;
354        if self.normalize_input(&next) != next {
355            return Err(InlineTokenError::TextMismatch);
356        }
357        if !self.is_valid_input(&next, cx) {
358            return Err(InlineTokenError::ValidationRejected);
359        }
360        if self
361            .token_spans()
362            .iter()
363            .any(|s| s.range == range && s.token == token)
364        {
365            return Ok(());
366        }
367        let new_text = token.text.clone();
368        self.pending_token = Some(token);
369        self.undo_manager.break_transaction_coalescing();
370        self.undo_manager.set_pending_intent(EditIntent::Atomic);
371        let range_utf16 = self.range_to_utf16(&range);
372        self.validated_token_edit = true;
373        self.with_edits_allowed(|state| {
374            state.replace_text_in_range(Some(range_utf16), &new_text, window, cx)
375        });
376        self.validated_token_edit = false;
377        self.pending_token = None;
378        Ok(())
379    }
380    /// Adopt the tokens of content whose text was just installed by
381    /// `set_value`. Tokens are dropped when this mode cannot show them or when
382    /// normalization changed the text, since their ranges would no longer
383    /// describe it.
384    pub(super) fn install_tokens(&mut self, content: InputContent) {
385        let supported = !M::CODE_EDITOR && self.mask_pattern.is_none();
386        let text_kept = self.text == content.text.as_ref();
387        self.inline_tokens = (supported && text_kept && !content.tokens.is_empty()).then(|| {
388            Box::new(InlineTokenStore {
389                spans: content.tokens,
390            })
391        });
392    }
393}
394
395macro_rules! token_api {
396    ($mode:ty) => {
397        impl InputBaseState<$mode> {
398            /// Replace the selection with an atomic token; no delimiter is added.
399            pub fn replace_with_token(
400                &mut self,
401                token: InlineToken,
402                window: &mut Window,
403                cx: &mut Context<Self>,
404            ) -> Result<(), InlineTokenError> {
405                self.replace_token(self.selected_range(), token, window, cx)
406            }
407            /// Replace a UTF-8 byte range, expanding overlaps to whole tokens.
408            pub fn replace_range_with_token(
409                &mut self,
410                range: Range<usize>,
411                token: InlineToken,
412                window: &mut Window,
413                cx: &mut Context<Self>,
414            ) -> Result<(), InlineTokenError> {
415                self.replace_token(range, token, window, cx)
416            }
417            pub fn tokens(&self) -> &[InlineTokenSpan] {
418                self.token_spans()
419            }
420            /// Replace the tokens and keep the text, the selections and the undo
421            /// history.
422            ///
423            /// Returns [`InlineTokenError::TextMismatch`] if `content` holds
424            /// different text, [`InlineTokenError::SplitsSelection`] if a token
425            /// cuts through any selection, [`InlineTokenError::CompositionActive`]
426            /// during IME composition and [`InlineTokenError::UnsupportedMode`]
427            /// for masked or password inputs.
428            ///
429            /// Undo and redo replay the text and the tokens recorded with it; a
430            /// token set here that an undone edit cuts through is dropped. Call
431            /// this again after every change to keep derived tokens current.
432            pub fn set_tokens(
433                &mut self,
434                content: InputContent,
435                cx: &mut Context<Self>,
436            ) -> Result<(), InlineTokenError> {
437                self.check_token_mode()?;
438                if self.text != content.text.as_ref() {
439                    return Err(InlineTokenError::TextMismatch);
440                }
441                let cuts = |at: usize| {
442                    content
443                        .tokens
444                        .iter()
445                        .any(|span| span.range.start < at && at < span.range.end)
446                };
447                if self
448                    .selections
449                    .iter()
450                    .any(|selection| cuts(selection.start) || cuts(selection.end))
451                {
452                    return Err(InlineTokenError::SplitsSelection);
453                }
454                if self.token_spans() == content.tokens.as_slice() {
455                    return Ok(());
456                }
457                self.document_revision = self.document_revision.wrapping_add(1);
458                self.inline_tokens = (!content.tokens.is_empty()).then(|| {
459                    Box::new(InlineTokenStore {
460                        spans: content.tokens,
461                    })
462                });
463                cx.notify();
464                Ok(())
465            }
466            /// The text with its tokens, as `set_value` accepts it.
467            pub fn content(&self) -> InputContent {
468                InputContent {
469                    text: self.value(),
470                    tokens: self.token_spans().to_vec(),
471                }
472            }
473        }
474    };
475}
476token_api!(super::InputMode);
477token_api!(super::TextareaMode);