BlueGit

ict rusty-teams

Files

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

root.rs

root.rs 17.0 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 crate::elevation::set_framework_modal_layers(window, active_dialogs.len(), cx);
188
189 if active_dialogs.is_empty() {
190 return None;
191 }
192
193 let mut show_overlay_ix = None;
194
195 let mut dialogs = active_dialogs
196 .iter()
197 .enumerate()
198 .map(|(i, active_dialog)| {
199 let mut dialog = Dialog::new(cx);
200
201 dialog = (active_dialog.builder)(dialog, window, cx);
202
203 // Give the dialog the focus handle, because `dialog` is a temporary value, is not possible to
204 // keep the focus handle in the dialog.
205 //
206 // So we keep the focus handle in the `active_dialog`, this is owned by the `WindowState`.
207 dialog.focus_handle = active_dialog.focus_handle.clone();
208 dialog.selection_scope = active_dialog.selection_scope;
209
210 dialog.layer_ix = i;
211 // Find the dialog which one needs to show overlay.
212 if dialog.has_overlay() {
213 show_overlay_ix = Some(i);
214 }
215
216 dialog
217 })
218 .collect::<Vec<_>>();
219
220 if let Some(ix) = show_overlay_ix {
221 if let Some(dialog) = dialogs.get_mut(ix) {
222 dialog.props.overlay_visible = true;
223 }
224 }
225
226 // Named so a test can assert the layer actually reached the screen. A
227 // dialog that opens into a root which never renders this layer looks
228 // exactly like one that does not open.
229 Some(
230 div()
231 .debug_selector(|| "dialog-layer".to_string())
232 .children(dialogs),
233 )
234 }
235
236 pub fn open_dialog<F>(
237 &mut self,
238 build: F,
239 window: &mut Window,
240 cx: &mut Context<'_, WindowState>,
241 ) where
242 F: Fn(Dialog, &mut Window, &mut App) -> Dialog + 'static,
243 {
244 let mut previous_focused_handle = window.focused(cx).map(|h| h.downgrade());
245
246 // Use pending focus restore if available to maintain correct focus chain
247 // when a new dialog is opened immediately after closing another dialog.
248 if let Some(pending_handle) = self.pending_focus_restore.take() {
249 previous_focused_handle = Some(pending_handle);
250 }
251
252 let focus_handle = cx.focus_handle();
253 focus_handle.focus(window, cx);
254
255 let selection_scope = self.allocate_text_selection_scope();
256 self.active_dialogs.push(ActiveDialog::new(
257 focus_handle,
258 previous_focused_handle,
259 selection_scope,
260 build,
261 ));
262 // Opening a modal confines selection to it; drop any background
263 // selection so it cannot linger (or be copied) under the modal.
264 gpui_base::TextSelection::clear(window, cx);
265 cx.notify();
266 }
267
268 fn close_dialog_internal(&mut self) -> Option<FocusHandle> {
269 self.focused_input = None;
270 self.active_dialogs
271 .pop()
272 .and_then(|d| d.previous_focused_handle)
273 .and_then(|h| h.upgrade())
274 }
275
276 pub fn close_dialog(&mut self, window: &mut Window, cx: &mut Context<'_, WindowState>) {
277 if let Some(handle) = self.close_dialog_internal() {
278 window.focus(&handle, cx);
279 }
280 gpui_base::TextSelection::clear(window, cx);
281 cx.notify();
282 }
283
284 pub(crate) fn defer_close_dialog(
285 &mut self,
286 window: &mut Window,
287 cx: &mut Context<'_, WindowState>,
288 ) {
289 if let Some(handle) = self.close_dialog_internal() {
290 let dialogs_count = self.active_dialogs.len();
291
292 // Save for new dialogs opened during animation to maintain focus chain
293 self.pending_focus_restore = Some(handle.downgrade());
294
295 cx.spawn_in(window, async move |this, cx| {
296 cx.background_executor().timer(*ANIMATION_DURATION).await;
297 let _ = this.update_in(cx, |this, window, cx| {
298 let current_dialogs_count = this.active_dialogs.len();
299 // Only restore focus if no new dialogs were opened during animation
300 if current_dialogs_count == dialogs_count {
301 window.focus(&handle, cx);
302 }
303 this.pending_focus_restore = None;
304 });
305 })
306 .detach();
307 }
308 gpui_base::TextSelection::clear(window, cx);
309 cx.notify();
310 }
311
312 pub fn close_all_dialogs(&mut self, window: &mut Window, cx: &mut Context<'_, WindowState>) {
313 self.focused_input = None;
314 let previous_focused_handle = self
315 .active_dialogs
316 .first()
317 .and_then(|d| d.previous_focused_handle.clone());
318 self.active_dialogs.clear();
319 if let Some(handle) = previous_focused_handle.and_then(|h| h.upgrade()) {
320 window.focus(&handle, cx);
321 }
322 gpui_base::TextSelection::clear(window, cx);
323 cx.notify();
324 }
325
326 pub fn open_sheet_at<F>(
327 &mut self,
328 placement: Placement,
329 build: F,
330 window: &mut Window,
331 cx: &mut Context<'_, WindowState>,
332 ) where
333 F: Fn(Sheet, &mut Window, &mut App) -> Sheet + 'static,
334 {
335 let previous_focused_handle = self
336 .active_sheet
337 .take()
338 .and_then(|s| s.previous_focused_handle)
339 .or_else(|| window.focused(cx).map(|h| h.downgrade()));
340
341 let focus_handle = cx.focus_handle();
342 focus_handle.focus(window, cx);
343 let selection_scope = self.allocate_text_selection_scope();
344 self.active_sheet = Some(ActiveSheet {
345 focus_handle,
346 previous_focused_handle,
347 placement,
348 selection_scope,
349 builder: Rc::new(build),
350 });
351 // Opening a modal confines selection to it; drop any background
352 // selection so it cannot linger (or be copied) under the modal.
353 gpui_base::TextSelection::clear(window, cx);
354 cx.notify();
355 }
356
357 pub fn close_sheet(&mut self, window: &mut Window, cx: &mut Context<'_, WindowState>) {
358 self.focused_input = None;
359 if let Some(previous_handle) = self
360 .active_sheet
361 .as_ref()
362 .and_then(|s| s.previous_focused_handle.as_ref())
363 .and_then(|h| h.upgrade())
364 {
365 window.focus(&previous_handle, cx);
366 }
367 self.active_sheet = None;
368 gpui_base::TextSelection::clear(window, cx);
369 cx.notify();
370 }
371
372 pub fn push_notification(
373 &mut self,
374 note: impl Into<Notification>,
375 window: &mut Window,
376 cx: &mut Context<'_, WindowState>,
377 ) {
378 self.notification
379 .update(cx, |view, cx| view.push(note, window, cx));
380 cx.notify();
381 }
382
383 /// Removes all notifications whose id matches `T`, including ones registered with
384 /// either [`Notification::id`] or [`Notification::id1`] (any key).
385 pub fn remove_notification<T: Sized + 'static>(
386 &mut self,
387 window: &mut Window,
388 cx: &mut Context<'_, WindowState>,
389 ) {
390 self.notification.update(cx, |view, cx| {
391 view.close_by_type(TypeId::of::<T>(), window, cx);
392 });
393 cx.notify();
394 }
395
396 /// Removes the notification matching the given type and element id (paired with [`Notification::id1`]).
397 pub fn remove_notification1<T: Sized + 'static>(
398 &mut self,
399 key: impl Into<ElementId>,
400 window: &mut Window,
401 cx: &mut Context<'_, WindowState>,
402 ) {
403 let key = key.into();
404 self.notification.update(cx, |view, cx| {
405 view.close((TypeId::of::<T>(), key), window, cx);
406 });
407 cx.notify();
408 }
409
410 pub fn clear_notifications(&mut self, window: &mut Window, cx: &mut Context<'_, WindowState>) {
411 self.notification
412 .update(cx, |view, cx| view.clear(window, cx));
413 cx.notify();
414 }
415
416 /// Get the tooltip overlay entity for this window.
417 pub(crate) fn tooltip_overlay(
418 window: &Window,
419 cx: &App,
420 ) -> Option<Entity<gpui_base::TooltipOverlay>> {
421 let root = Self::entity(window, cx)?;
422 Some(root.read(cx).tooltip_overlay.clone())
423 }
424
425 /// Get the fallback native-menu overlay entity for this window.
426 pub(crate) fn native_menu_overlay(
427 window: &Window,
428 cx: &App,
429 ) -> Option<Entity<FallbackMenuOverlay>> {
430 let root = Self::entity(window, cx)?;
431 Some(root.read(cx).native_menu_overlay.clone())
432 }
433}
434
435impl gpui_base::RootPlugin for WindowState {
436 fn prepare(&mut self, window: &mut Window, cx: &mut Context<Self>) {
437 window.set_rem_size(cx.theme().font_size);
438 TextSelection::activate_scope(self.active_text_selection_scope(), window, cx);
439 }
440
441 fn style(&self, surface: &mut gpui::Stateful<gpui::Div>, _window: &mut Window, cx: &mut App) {
442 use gpui::Refineable as _;
443 surface.style().refine(
444 &gpui::StyleRefinement::default()
445 .font_family(cx.theme().font_family.clone())
446 .bg(cx.theme().tokens.background)
447 .text_color(cx.theme().foreground),
448 );
449 }
450
451 fn decorate(
452 &self,
453 surface: gpui::AnyElement,
454 _root: &gpui_base::Root,
455 _window: &mut Window,
456 _cx: &mut App,
457 ) -> impl IntoElement {
458 window_border().child(surface)
459 }
460}
461
462impl Render for WindowState {
463 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
464 div()
465 .absolute()
466 .inset_0()
467 .child(WindowStateLayers { root: cx.entity() })
468 .child(self.touch_selection_overlay.clone())
469 .child(self.tooltip_overlay.clone())
470 .child(self.native_menu_overlay.clone())
471 }
472}
473
474const ROOT_MISSING: &str =
475 "component window state is missing; call gpui_component::init before gpui_kit::open_window";
476
477/// Window-level layers, always mounted once after the application content.
478/// Child view caching does not affect their ownership or rendering.
479#[derive(IntoElement)]
480struct WindowStateLayers {
481 root: Entity<WindowState>,
482}
483
484impl RenderOnce for WindowStateLayers {
485 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
486 let root = self.root;
487 div()
488 .absolute()
489 .inset_0()
490 .debug_selector(|| "root-layers".to_string())
491 .children(WindowState::sheet_layer(root.clone(), window, cx))
492 .children(WindowState::dialog_layer(&root, window, cx))
493 .children(WindowState::notification_layer(&root, cx))
494 }
495}