BlueGit

ict rusty-teams

Files

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

token_presentation.rs

token_presentation.rs 12.8 KiB Download Raw
1//! Presentation callbacks and measured geometry. None of this enters document history.
2use super::{InlineToken, InlineTokenSpan, InputBaseState, InputModeKind, rope_ext::RopeExt as _};
3use gpui::{AnyElement, App, Bounds, ClickEvent, Font, IntoElement, Pixels, Size, Window};
4
5use crate::input::display_map::InlineMetric;
6use std::{collections::HashMap, ops::Range, rc::Rc};
7
8/// Read-only context for a single inline renderer. Width is the full available row.
9#[derive(Clone)]
10pub struct InlineTokenContext {
11 span: InlineTokenSpan,
12 selected: bool,
13 disabled: bool,
14 readonly: bool,
15 line_height: Pixels,
16 available_width: Pixels,
17}
18impl InlineTokenContext {
19 pub fn token(&self) -> &InlineToken {
20 self.span.token()
21 }
22 pub fn range(&self) -> Range<usize> {
23 self.span.range()
24 }
25 pub fn is_selected(&self) -> bool {
26 self.selected
27 }
28 pub fn is_disabled(&self) -> bool {
29 self.disabled
30 }
31 pub fn is_readonly(&self) -> bool {
32 self.readonly
33 }
34 pub fn is_block(&self) -> bool {
35 self.span.token().is_block()
36 }
37 pub fn line_height(&self) -> Pixels {
38 self.line_height
39 }
40 pub fn available_width(&self) -> Pixels {
41 self.available_width
42 }
43}
44
45/// Current token snapshot delivered after releasing the editor's update borrow.
46#[derive(Clone)]
47pub struct InlineTokenClickEvent {
48 span: InlineTokenSpan,
49 bounds: Bounds<Pixels>,
50 event: ClickEvent,
51}
52impl InlineTokenClickEvent {
53 pub fn token(&self) -> &InlineToken {
54 self.span.token()
55 }
56 pub fn range(&self) -> Range<usize> {
57 self.span.range()
58 }
59 pub fn bounds(&self) -> Bounds<Pixels> {
60 self.bounds
61 }
62 /// The click that opened the token; keyboard activation reports a
63 /// keyboard click.
64 pub fn click(&self) -> &ClickEvent {
65 &self.event
66 }
67}
68
69/// Hover snapshot for one atomic inline token. Hover never selects or edits;
70/// it reports pointer presence so the application can show a tooltip or run
71/// custom logic.
72#[derive(Clone)]
73pub struct InlineTokenHoverEvent {
74 span: InlineTokenSpan,
75 bounds: Bounds<Pixels>,
76 hovered: bool,
77 range_utf16: (usize, usize),
78}
79impl InlineTokenHoverEvent {
80 pub fn token(&self) -> &InlineToken {
81 self.span.token()
82 }
83 pub fn range(&self) -> Range<usize> {
84 self.span.range()
85 }
86 pub fn bounds(&self) -> Bounds<Pixels> {
87 self.bounds
88 }
89 /// Whether the pointer entered (`true`) or left (`false`) the token.
90 pub fn is_hovered(&self) -> bool {
91 self.hovered
92 }
93 /// The token range in UTF-16 code units, captured when the event was
94 /// built. Exits delivered after the text changed report these entry
95 /// coordinates, since the byte range can no longer be converted against
96 /// the current text.
97 pub fn range_utf16(&self) -> (usize, usize) {
98 self.range_utf16
99 }
100}
101
102/// The retained hover presence: the entered span, its placed bounds, and its
103/// UTF-16 range as of entry. JavaScript string offsets shift with later edits,
104/// so an exit delivered after a change cannot recompute them from the current
105/// text and reuses these instead.
106#[derive(Clone)]
107pub(super) struct HoverSnapshot {
108 pub(super) span: InlineTokenSpan,
109 pub(super) bounds: Bounds<Pixels>,
110 pub(super) range_utf16: (usize, usize),
111}
112
113/// A renderer installed by a styled control. Not part of the supported API.
114#[doc(hidden)]
115pub type InlineTokenRenderer = Rc<dyn Fn(&InlineTokenContext, &mut Window, &mut App) -> AnyElement>;
116/// A click listener installed by a styled control. Not part of the supported API.
117#[doc(hidden)]
118pub type InlineTokenClickListener = Rc<dyn Fn(&InlineTokenClickEvent, &mut Window, &mut App)>;
119/// A hover listener installed by a styled control. Not part of the supported API.
120#[doc(hidden)]
121pub type InlineTokenHoverListener = Rc<dyn Fn(&InlineTokenHoverEvent, &mut Window, &mut App)>;
122
123/// Presentation shared by Base and styled controls. It owns no content.
124#[derive(Clone, Default)]
125pub(crate) struct InlineTokenPresentation {
126 renderer: Option<InlineTokenRenderer>,
127 listener: Option<InlineTokenClickListener>,
128 hover_listener: Option<InlineTokenHoverListener>,
129 secret: bool,
130}
131impl InlineTokenPresentation {
132 pub(crate) fn token<R: IntoElement>(
133 mut self,
134 render: impl Fn(&InlineTokenContext, &mut Window, &mut App) -> R + 'static,
135 ) -> Self {
136 self.renderer = Some(Rc::new(move |token, window, cx| {
137 render(token, window, cx).into_any_element()
138 }));
139 self
140 }
141 pub(crate) fn on_token_click(
142 mut self,
143 listener: impl Fn(&InlineTokenClickEvent, &mut Window, &mut App) + 'static,
144 ) -> Self {
145 self.listener = Some(Rc::new(listener));
146 self
147 }
148 pub(crate) fn on_token_hover(
149 mut self,
150 listener: impl Fn(&InlineTokenHoverEvent, &mut Window, &mut App) + 'static,
151 ) -> Self {
152 self.hover_listener = Some(Rc::new(listener));
153 self
154 }
155 pub(super) fn has_hover_listener(&self) -> bool {
156 self.hover_listener.is_some()
157 }
158 pub(super) fn has_listener(&self) -> bool {
159 self.listener.is_some()
160 }
161 pub(super) fn render(
162 &self,
163 token: &InlineTokenContext,
164 window: &mut Window,
165 cx: &mut App,
166 ) -> AnyElement {
167 if let Some(render) = &self.renderer {
168 render(token, window, cx)
169 } else {
170 gpui::div()
171 .child(token.token().label().clone())
172 .into_any_element()
173 }
174 }
175}
176use gpui::ParentElement as _;
177
178#[derive(Default)]
179pub(super) struct TokenLayoutCache {
180 pub(super) key: Option<(Font, Pixels, Pixels, Pixels, bool)>,
181 pub(super) revision: u64,
182 pub(super) unwrapped_width: Pixels,
183 pub(super) metrics: Rc<[InlineMetric]>,
184 pub(super) sizes: HashMap<InlineToken, Size<Pixels>>,
185}
186
187impl<M: InputModeKind> InputBaseState<M> {
188 /// Inject presentation from a view without editing or notifying the document.
189 pub(crate) fn set_token_presentation(&mut self, presentation: InlineTokenPresentation) {
190 self.token_presentation = presentation;
191 }
192 /// Install a styled control's renderer, click listener and secrecy without
193 /// editing or notifying the document. Not part of the supported API.
194 #[doc(hidden)]
195 pub fn install_token_presentation(
196 &mut self,
197 renderer: Option<InlineTokenRenderer>,
198 listener: Option<InlineTokenClickListener>,
199 secret: bool,
200 ) {
201 self.token_presentation = InlineTokenPresentation {
202 renderer,
203 listener,
204 hover_listener: self.token_presentation.hover_listener.clone(),
205 secret,
206 };
207 }
208 /// Install a styled control's token hover listener without editing or
209 /// notifying the document. Kept separate so the original installer keeps
210 /// compiling for existing consumers. Not part of the supported API.
211 #[doc(hidden)]
212 pub fn install_token_hover_presentation(
213 &mut self,
214 hover_listener: Option<InlineTokenHoverListener>,
215 ) {
216 self.token_presentation.hover_listener = hover_listener;
217 }
218 pub(super) fn tokens_visible(&self) -> bool {
219 !self.masked
220 && !self.token_presentation.secret
221 && self.mask_pattern.is_none()
222 && !self.token_spans().is_empty()
223 }
224 pub(super) fn token_context(
225 &self,
226 span: &InlineTokenSpan,
227 line_height: Pixels,
228 width: Pixels,
229 ) -> InlineTokenContext {
230 let range = span.range();
231 let selection = self.selected_range();
232 InlineTokenContext {
233 span: span.clone(),
234 selected: selection.start < range.end && range.start < selection.end,
235 disabled: self.disabled,
236 readonly: self.readonly,
237 line_height,
238 // A header spans its row up to where block decorations end.
239 available_width: if span.token().is_header() {
240 width + super::element::RIGHT_MARGIN
241 } else {
242 width
243 },
244 }
245 }
246 /// The token starting at `start`, paired with the listener that opens it.
247 pub(super) fn token_activation(
248 &self,
249 start: usize,
250 bounds: Bounds<Pixels>,
251 event: ClickEvent,
252 ) -> Option<(InlineTokenClickListener, InlineTokenClickEvent)> {
253 if self.disabled || !self.tokens_visible() {
254 return None;
255 }
256 let span = self
257 .token_spans()
258 .iter()
259 .find(|span| span.range().start == start)?
260 .clone();
261 Some((
262 self.token_presentation.listener.clone()?,
263 InlineTokenClickEvent {
264 span,
265 bounds,
266 event,
267 },
268 ))
269 }
270 /// The token starting at `start`, paired with the hover listener.
271 /// Disabled tokens never enter; existing hover still receives its exit.
272 /// Readonly tokens report hover.
273 /// Records and clears the retained hover snapshot used for exit
274 /// reconciliation. An exit only clears the snapshot when it belongs to the
275 /// exiting token: GPUI dispatches a newly entered token before the exit of
276 /// the token the pointer left, so an older exit must not drop the newer
277 /// token's snapshot.
278 pub(super) fn token_hover(
279 &mut self,
280 start: usize,
281 bounds: Bounds<Pixels>,
282 hovered: bool,
283 expected_token: Option<&InlineToken>,
284 ) -> Option<(InlineTokenHoverListener, InlineTokenHoverEvent)> {
285 let listener = self.token_presentation.hover_listener.clone()?;
286 let matches = |snapshot: &HoverSnapshot| {
287 snapshot.span.range().start == start
288 && expected_token.is_none_or(|token| snapshot.span.token() == token)
289 };
290 let snapshot = if hovered {
291 if self.disabled || !self.tokens_visible() {
292 return None;
293 }
294 let span = self
295 .token_spans()
296 .iter()
297 .find(|span| {
298 span.range().start == start
299 && expected_token.is_none_or(|token| span.token() == token)
300 })?
301 .clone();
302 if self
303 .hovered_token
304 .as_ref()
305 .is_some_and(|snapshot| snapshot.span == span)
306 {
307 return None;
308 }
309 let range = span.range();
310 let snapshot = HoverSnapshot {
311 span,
312 bounds,
313 range_utf16: (
314 self.text.offset_to_offset_utf16(range.start),
315 self.text.offset_to_offset_utf16(range.end),
316 ),
317 };
318 if let Some(previous) = self.hovered_token.replace(snapshot.clone()) {
319 self.pending_token_hover_exits.push(previous);
320 }
321 snapshot
322 } else if self.hovered_token.as_ref().is_some_and(matches) {
323 self.hovered_token.take()?
324 } else {
325 let index = self.pending_token_hover_exits.iter().position(matches)?;
326 self.pending_token_hover_exits.remove(index)
327 };
328 Some((
329 listener,
330 InlineTokenHoverEvent {
331 span: snapshot.span,
332 bounds: snapshot.bounds,
333 hovered,
334 range_utf16: snapshot.range_utf16,
335 },
336 ))
337 }
338 /// Deliver exits from entry snapshots, even after edits or callback reentry
339 /// remove the token. Keep predecessors until their mouse exit is dispatched.
340 pub(super) fn reconcile_token_hover(
341 &mut self,
342 ) -> Option<(InlineTokenHoverListener, InlineTokenHoverEvent)> {
343 let is_placed = |snapshot: &HoverSnapshot| {
344 !self.disabled
345 && self.tokens_visible()
346 && self.token_presentation.has_hover_listener()
347 && self.token_bounds.contains_key(&snapshot.span.range().start)
348 && self.token_spans().contains(&snapshot.span)
349 };
350 let snapshot = if let Some(index) = self
351 .pending_token_hover_exits
352 .iter()
353 .position(|snapshot| !is_placed(snapshot))
354 {
355 self.pending_token_hover_exits.remove(index)
356 } else if self
357 .hovered_token
358 .as_ref()
359 .is_some_and(|snapshot| !is_placed(snapshot))
360 {
361 self.hovered_token.take()?
362 } else {
363 return None;
364 };
365 Some((
366 self.token_presentation.hover_listener.clone()?,
367 InlineTokenHoverEvent {
368 span: snapshot.span,
369 bounds: snapshot.bounds,
370 hovered: false,
371 range_utf16: snapshot.range_utf16,
372 },
373 ))
374 }
375 pub(super) fn token_is_secret(&self) -> bool {
376 self.token_presentation.secret
377 }
378}