BlueGit

ict rusty-teams

Files

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

inline_tokens.rs

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