BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-component / src / root.rs

root.rs

root.rs 16.9 KiB Download Raw
1use crate::{
2 ActiveTheme, ElementExt, Placement,
3 dialog::{ANIMATION_DURATION, Dialog},
4 input::AnyInputState,
5 native_menu::FallbackMenuOverlay,
6 notification::{Notification, NotificationList},
7 sheet::Sheet,
8 tooltip::render_tooltip,
9 touch_selection::WindowTouchSelectionOverlay,
10 window_border,
11};
12use gpui::{
13 App, AppContext, Context, DefiniteLength, ElementId, Entity, FocusHandle, InteractiveElement,
14 IntoElement, ParentElement as _, Render, RenderOnce, Styled, WeakFocusHandle, Window, div,
15 prelude::FluentBuilder as _,
16};
17use gpui_base::{TextSelection, TextSelectionScopeId};
18use std::{any::TypeId, rc::Rc};
19
20pub(crate) fn init(cx: &mut App) {
21 gpui_base::Root::register_plugin::<WindowState>(cx, WindowState::new);
22}
23
24/// Component-owned window state and presentation; Base owns the actual root.
25pub(crate) struct WindowState {
26 pub(crate) active_sheet: Option<ActiveSheet>,
27 pub(crate) active_dialogs: Vec<ActiveDialog>,
28 pub(super) focused_input: Option<AnyInputState>,
29 pub notification: Entity<NotificationList>,
30 pub(crate) tooltip_overlay: Entity<gpui_base::TooltipOverlay>,
31 pub(crate) native_menu_overlay: Entity<FallbackMenuOverlay>,
32 touch_selection_overlay: Entity<WindowTouchSelectionOverlay>,
33 sheet_size: Option<DefiniteLength>,
34 pending_focus_restore: Option<WeakFocusHandle>,
35}
36
37#[derive(Clone)]
38pub(crate) struct ActiveSheet {
39 focus_handle: FocusHandle,
40 /// The previous focused handle before opening the Sheet.
41 previous_focused_handle: Option<WeakFocusHandle>,
42 placement: Placement,
43 selection_scope: TextSelectionScopeId,
44 builder: Rc<dyn Fn(Sheet, &mut Window, &mut App) -> Sheet + 'static>,
45}
46
47#[derive(Clone)]
48pub(crate) struct ActiveDialog {
49 focus_handle: FocusHandle,
50 /// The previous focused handle before opening the Dialog.
51 previous_focused_handle: Option<WeakFocusHandle>,
52 selection_scope: TextSelectionScopeId,
53 builder: Rc<dyn Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static>,
54}
55
56impl ActiveDialog {
57 pub(crate) fn new(
58 focus_handle: FocusHandle,
59 previous_focused_handle: Option<WeakFocusHandle>,
60 selection_scope: TextSelectionScopeId,
61 builder: impl Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
62 ) -> Self {
63 Self {
64 focus_handle,
65 previous_focused_handle,
66 selection_scope,
67 builder: Rc::new(builder),
68 }
69 }
70}
71
72impl WindowState {
73 fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
74 Self {
75 active_sheet: None,
76 active_dialogs: Vec::new(),
77 focused_input: None,
78 notification: cx.new(|cx| NotificationList::new(window, cx)),
79 tooltip_overlay: cx
80 .new(|_| gpui_base::TooltipOverlay::new().render_with(render_tooltip)),
81 native_menu_overlay: cx.new(|_| FallbackMenuOverlay::new()),
82 touch_selection_overlay: cx.new(|cx| WindowTouchSelectionOverlay::new(window, cx)),
83 sheet_size: None,
84 pending_focus_restore: None,
85 }
86 }
87
88 fn entity(window: &Window, cx: &App) -> Option<Entity<Self>> {
89 window.root::<gpui_base::Root>()??.read(cx).plugin::<Self>()
90 }
91
92 fn allocate_text_selection_scope(&mut self) -> TextSelectionScopeId {
93 TextSelectionScopeId::new()
94 }
95
96 pub(crate) fn active_text_selection_scope(&self) -> TextSelectionScopeId {
97 self.active_dialogs
98 .last()
99 .map(|dialog| dialog.selection_scope)
100 .or_else(|| {
101 self.active_sheet
102 .as_ref()
103 .map(|sheet| sheet.selection_scope)
104 })
105 .unwrap_or_default()
106 }
107
108 pub fn update<F, R>(window: &mut Window, cx: &mut App, f: F) -> R
109 where
110 F: FnOnce(&mut Self, &mut Window, &mut Context<Self>) -> R,
111 {
112 let root = Self::entity(window, cx).expect(ROOT_MISSING);
113
114 root.update(cx, |root, cx| f(root, window, cx))
115 }
116
117 pub(crate) fn try_update<F, R>(window: &mut Window, cx: &mut App, f: F) -> Option<R>
118 where
119 F: FnOnce(&mut Self, &mut Window, &mut Context<Self>) -> R,
120 {
121 let root = Self::entity(window, cx)?;
122 Some(root.update(cx, |root, cx| f(root, window, cx)))
123 }
124
125 pub fn read<'a>(window: &'a Window, cx: &'a App) -> &'a Self {
126 Self::entity(window, cx).expect(ROOT_MISSING).read(cx)
127 }
128
129 fn notification_layer(
130 root: &Entity<WindowState>,
131 cx: &App,
132 ) -> Option<impl IntoElement + use<>> {
133 let active_sheet_placement = root.read(cx).active_sheet.clone().map(|d| d.placement);
134
135 let sheet_size = root.read(cx).sheet_size;
136 let (mt, mr, mb, ml) = match active_sheet_placement {
137 Some(Placement::Top) => (sheet_size, None, None, None),
138 Some(Placement::Right) => (None, sheet_size, None, None),
139 Some(Placement::Bottom) => (None, None, sheet_size, None),
140 Some(Placement::Left) => (None, None, None, sheet_size),
141 _ => (None, None, None, None),
142 };
143
144 Some(
145 div()
146 .absolute()
147 .inset_0()
148 .when_some(mt, |this, offset| this.mt(offset))
149 .when_some(mr, |this, offset| this.mr(offset))
150 .when_some(mb, |this, offset| this.mb(offset))
151 .when_some(ml, |this, offset| this.ml(offset))
152 .child(root.read(cx).notification.clone()),
153 )
154 }
155
156 fn sheet_layer(
157 root: Entity<WindowState>,
158 window: &mut Window,
159 cx: &mut App,
160 ) -> Option<impl IntoElement + use<>> {
161 if let Some(active_sheet) = root.read(cx).active_sheet.clone() {
162 let mut sheet = Sheet::new(window, cx);
163 sheet = (active_sheet.builder)(sheet, window, cx);
164 sheet.focus_handle = active_sheet.focus_handle.clone();
165 sheet.placement = active_sheet.placement;
166 sheet.selection_scope = active_sheet.selection_scope;
167
168 let size = sheet.size;
169
170 return Some(
171 div()
172 .relative()
173 .child(sheet)
174 .on_prepaint(move |_, _, cx| root.update(cx, |r, _| r.sheet_size = Some(size))),
175 );
176 }
177
178 None
179 }
180
181 fn dialog_layer(
182 root: &Entity<WindowState>,
183 window: &mut Window,
184 cx: &mut App,
185 ) -> Option<impl IntoElement + use<>> {
186 let active_dialogs = root.read(cx).active_dialogs.clone();
187
188 if active_dialogs.is_empty() {
189 return None;
190 }
191
192 let mut show_overlay_ix = None;
193
194 let mut dialogs = active_dialogs
195 .iter()
196 .enumerate()
197 .map(|(i, active_dialog)| {
198 let mut dialog = Dialog::new(cx);
199
200 dialog = (active_dialog.builder)(dialog, window, cx);
201
202 // Give the dialog the focus handle, because `dialog` is a temporary value, is not possible to
203 // keep the focus handle in the dialog.
204 //
205 // So we keep the focus handle in the `active_dialog`, this is owned by the `WindowState`.
206 dialog.focus_handle = active_dialog.focus_handle.clone();
207 dialog.selection_scope = active_dialog.selection_scope;
208
209 dialog.layer_ix = i;
210 // Find the dialog which one needs to show overlay.
211 if dialog.has_overlay() {
212 show_overlay_ix = Some(i);
213 }
214
215 dialog
216 })
217 .collect::<Vec<_>>();
218
219 if let Some(ix) = show_overlay_ix {
220 if let Some(dialog) = dialogs.get_mut(ix) {
221 dialog.props.overlay_visible = true;
222 }
223 }
224
225 // Named so a test can assert the layer actually reached the screen. A
226 // dialog that opens into a root which never renders this layer looks
227 // exactly like one that does not open.
228 Some(
229 div()
230 .debug_selector(|| "dialog-layer".to_string())
231 .children(dialogs),
232 )
233 }
234
235 pub fn open_dialog<F>(
236 &mut self,
237 build: F,
238 window: &mut Window,
239 cx: &mut Context<'_, WindowState>,
240 ) where
241 F: Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
242 {
243 let mut previous_focused_handle = window.focused(cx).map(|h| h.downgrade());
244
245 // Use pending focus restore if available to maintain correct focus chain
246 // when a new dialog is opened immediately after closing another dialog.
247 if let Some(pending_handle) = self.pending_focus_restore.take() {
248 previous_focused_handle = Some(pending_handle);
249 }
250
251 let focus_handle = cx.focus_handle();
252 focus_handle.focus(window, cx);
253
254 let selection_scope = self.allocate_text_selection_scope();
255 self.active_dialogs.push(ActiveDialog::new(
256 focus_handle,
257 previous_focused_handle,
258 selection_scope,
259 build,
260 ));
261 // Opening a modal confines selection to it; drop any background
262 // selection so it cannot linger (or be copied) under the modal.
263 gpui_base::TextSelection::clear(window, cx);
264 cx.notify();
265 }
266
267 fn close_dialog_internal(&mut self) -> Option<FocusHandle> {
268 self.focused_input = None;
269 self.active_dialogs
270 .pop()
271 .and_then(|d| d.previous_focused_handle)
272 .and_then(|h| h.upgrade())
273 }
274
275 pub fn close_dialog(&mut self, window: &mut Window, cx: &mut Context<'_, WindowState>) {
276 if let Some(handle) = self.close_dialog_internal() {
277 window.focus(&handle, cx);
278 }
279 gpui_base::TextSelection::clear(window, cx);
280 cx.notify();
281 }
282
283 pub(crate) fn defer_close_dialog(
284 &mut self,
285 window: &mut Window,
286 cx: &mut Context<'_, WindowState>,
287 ) {
288 if let Some(handle) = self.close_dialog_internal() {
289 let dialogs_count = self.active_dialogs.len();
290
291 // Save for new dialogs opened during animation to maintain focus chain
292 self.pending_focus_restore = Some(handle.downgrade());
293
294 cx.spawn_in(window, async move |this, cx| {
295 cx.background_executor().timer(*ANIMATION_DURATION).await;
296 let _ = this.update_in(cx, |this, window, cx| {
297 let current_dialogs_count = this.active_dialogs.len();
298 // Only restore focus if no new dialogs were opened during animation
299 if current_dialogs_count == dialogs_count {
300 window.focus(&handle, cx);
301 }
302 this.pending_focus_restore = None;
303 });
304 })
305 .detach();
306 }
307 gpui_base::TextSelection::clear(window, cx);
308 cx.notify();
309 }
310
311 pub fn close_all_dialogs(&mut self, window: &mut Window, cx: &mut Context<'_, WindowState>) {
312 self.focused_input = None;
313 let previous_focused_handle = self
314 .active_dialogs
315 .first()
316 .and_then(|d| d.previous_focused_handle.clone());
317 self.active_dialogs.clear();
318 if let Some(handle) = previous_focused_handle.and_then(|h| h.upgrade()) {
319 window.focus(&handle, cx);
320 }
321 gpui_base::TextSelection::clear(window, cx);
322 cx.notify();
323 }
324
325 pub fn open_sheet_at<F>(
326 &mut self,
327 placement: Placement,
328 build: F,
329 window: &mut Window,
330 cx: &mut Context<'_, WindowState>,
331 ) where
332 F: Fn(Sheet, &mut Window, &mut App) -> Sheet + 'static,
333 {
334 let previous_focused_handle = self
335 .active_sheet
336 .take()
337 .and_then(|s| s.previous_focused_handle)
338 .or_else(|| window.focused(cx).map(|h| h.downgrade()));
339
340 let focus_handle = cx.focus_handle();
341 focus_handle.focus(window, cx);
342 let selection_scope = self.allocate_text_selection_scope();
343 self.active_sheet = Some(ActiveSheet {
344 focus_handle,
345 previous_focused_handle,
346 placement,
347 selection_scope,
348 builder: Rc::new(build),
349 });
350 // Opening a modal confines selection to it; drop any background
351 // selection so it cannot linger (or be copied) under the modal.
352 gpui_base::TextSelection::clear(window, cx);
353 cx.notify();
354 }
355
356 pub fn close_sheet(&mut self, window: &mut Window, cx: &mut Context<'_, WindowState>) {
357 self.focused_input = None;
358 if let Some(previous_handle) = self
359 .active_sheet
360 .as_ref()
361 .and_then(|s| s.previous_focused_handle.as_ref())
362 .and_then(|h| h.upgrade())
363 {
364 window.focus(&previous_handle, cx);
365 }
366 self.active_sheet = None;
367 gpui_base::TextSelection::clear(window, cx);
368 cx.notify();
369 }
370
371 pub fn push_notification(
372 &mut self,
373 note: impl Into<Notification>,
374 window: &mut Window,
375 cx: &mut Context<'_, WindowState>,
376 ) {
377 self.notification
378 .update(cx, |view, cx| view.push(note, window, cx));
379 cx.notify();
380 }
381
382 /// Removes all notifications whose id matches `T`, including ones registered with
383 /// either [`Notification::id`] or [`Notification::id1`] (any key).
384 pub fn remove_notification<T: Sized + 'static>(
385 &mut self,
386 window: &mut Window,
387 cx: &mut Context<'_, WindowState>,
388 ) {
389 self.notification.update(cx, |view, cx| {
390 view.close_by_type(TypeId::of::<T>(), window, cx);
391 });
392 cx.notify();
393 }
394
395 /// Removes the notification matching the given type and element id (paired with [`Notification::id1`]).
396 pub fn remove_notification1<T: Sized + 'static>(
397 &mut self,
398 key: impl Into<ElementId>,
399 window: &mut Window,
400 cx: &mut Context<'_, WindowState>,
401 ) {
402 let key = key.into();
403 self.notification.update(cx, |view, cx| {
404 view.close((TypeId::of::<T>(), key), window, cx);
405 });
406 cx.notify();
407 }
408
409 pub fn clear_notifications(&mut self, window: &mut Window, cx: &mut Context<'_, WindowState>) {
410 self.notification
411 .update(cx, |view, cx| view.clear(window, cx));
412 cx.notify();
413 }
414
415 /// Get the tooltip overlay entity for this window.
416 pub(crate) fn tooltip_overlay(
417 window: &Window,
418 cx: &App,
419 ) -> Option<Entity<gpui_base::TooltipOverlay>> {
420 let root = Self::entity(window, cx)?;
421 Some(root.read(cx).tooltip_overlay.clone())
422 }
423
424 /// Get the fallback native-menu overlay entity for this window.
425 pub(crate) fn native_menu_overlay(
426 window: &Window,
427 cx: &App,
428 ) -> Option<Entity<FallbackMenuOverlay>> {
429 let root = Self::entity(window, cx)?;
430 Some(root.read(cx).native_menu_overlay.clone())
431 }
432}
433
434impl gpui_base::RootPlugin for WindowState {
435 fn prepare(&mut self, window: &mut Window, cx: &mut Context<Self>) {
436 window.set_rem_size(cx.theme().font_size);
437 TextSelection::activate_scope(self.active_text_selection_scope(), window, cx);
438 }
439
440 fn style(&self, surface: &mut gpui::Stateful<gpui::Div>, _window: &mut Window, cx: &mut App) {
441 use gpui::Refineable as _;
442 surface.style().refine(
443 &gpui::StyleRefinement::default()
444 .font_family(cx.theme().font_family.clone())
445 .bg(cx.theme().tokens.background)
446 .text_color(cx.theme().foreground),
447 );
448 }
449
450 fn decorate(
451 &self,
452 surface: gpui::AnyElement,
453 _root: &gpui_base::Root,
454 _window: &mut Window,
455 _cx: &mut App,
456 ) -> impl IntoElement {
457 window_border().child(surface)
458 }
459}
460
461impl Render for WindowState {
462 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
463 div()
464 .absolute()
465 .inset_0()
466 .child(WindowStateLayers { root: cx.entity() })
467 .child(self.touch_selection_overlay.clone())
468 .child(self.tooltip_overlay.clone())
469 .child(self.native_menu_overlay.clone())
470 }
471}
472
473const ROOT_MISSING: &str =
474 "component window state is missing; call gpui_component::init before gpui_kit::open_window";
475
476/// Window-level layers, always mounted once after the application content.
477/// Child view caching does not affect their ownership or rendering.
478#[derive(IntoElement)]
479struct WindowStateLayers {
480 root: Entity<WindowState>,
481}
482
483impl RenderOnce for WindowStateLayers {
484 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
485 let root = self.root;
486 div()
487 .absolute()
488 .inset_0()
489 .debug_selector(|| "root-layers".to_string())
490 .children(WindowState::sheet_layer(root.clone(), window, cx))
491 .children(WindowState::dialog_layer(&root, window, cx))
492 .children(WindowState::notification_layer(&root, cx))
493 }
494}