BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / input / base / inline_tokens.rs

inline_tokens.rs

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