Skip to main content

gpui_material_foundation/
interaction.rs

1use std::{cell::Cell, collections::HashMap};
2
3use gpui::{App, ElementId, Entity, EntityId, EventEmitter, WeakEntity, Window, WindowId};
4
5use crate::InteractionState;
6
7/// Observes the presentation state of controls with a shared GPUI entity.
8///
9/// A source can observe multiple controls. Give each control a distinct
10/// element ID within each window that uses the source.
11#[derive(Default)]
12pub struct InteractionSource {
13    windows: HashMap<WindowId, HashMap<ElementId, (EntityId, InteractionState)>>,
14}
15
16/// One deferred change from an observed control.
17///
18/// For a fast sequence, the event's snapshot can precede the latest state
19/// returned by [`InteractionSource::state`].
20#[derive(Clone, Debug, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct InteractionUpdate {
23    /// Window containing the observed control.
24    pub window: WindowId,
25    /// Element identifier of the observed control within [`Self::window`].
26    pub id: ElementId,
27    /// `None` means the control was detached from this source.
28    pub state: Option<InteractionState>,
29}
30
31impl EventEmitter<InteractionUpdate> for InteractionSource {}
32
33impl InteractionSource {
34    /// Creates an empty source for use in a caller-owned GPUI entity.
35    pub fn new() -> Self {
36        Self::default()
37    }
38
39    /// Reads the most recently delivered state for a control in a window.
40    pub fn state(&self, window: WindowId, id: &ElementId) -> Option<InteractionState> {
41        self.windows.get(&window)?.get(id).map(|(_, state)| *state)
42    }
43
44    /// Binds an observer to a control during its rendering.
45    ///
46    /// Record the control's initial state during rendering and later changes
47    /// from its existing input handlers. The tracker expires when the control
48    /// stops rendering with this source.
49    pub fn track(
50        source: &Entity<Self>,
51        id: &ElementId,
52        window: &mut Window,
53        cx: &mut App,
54    ) -> InteractionTracker {
55        let window_id = window.window_handle().window_id();
56        let source_id = source.entity_id();
57        let attachment = window.with_id((id.clone(), "material-interaction-source"), |window| {
58            window.use_keyed_state(("source", source_id), cx, |_, cx| {
59                cx.on_release(|this: &mut Attachment, cx| {
60                    let source = this.source.clone();
61                    let window = this.window;
62                    let id = this.id.clone();
63                    let owner = this.owner;
64                    cx.defer(move |cx| {
65                        source
66                            .update(cx, |source, cx| {
67                                if source.detach(window, &id, owner) {
68                                    cx.emit(InteractionUpdate {
69                                        window,
70                                        id,
71                                        state: None,
72                                    });
73                                    cx.notify();
74                                }
75                            })
76                            .ok();
77                    });
78                })
79                .detach();
80                Attachment {
81                    source: source.downgrade(),
82                    window: window_id,
83                    id: id.clone(),
84                    owner: cx.entity_id(),
85                    last: Cell::new(None),
86                }
87            })
88        });
89        InteractionTracker(attachment.downgrade())
90    }
91
92    fn detach(&mut self, window: WindowId, id: &ElementId, owner: EntityId) -> bool {
93        let Some(controls) = self.windows.get_mut(&window) else {
94            return false;
95        };
96        if controls
97            .get(id)
98            .is_none_or(|(current, _)| *current != owner)
99        {
100            return false;
101        }
102        controls.remove(id);
103        if controls.is_empty() {
104            self.windows.remove(&window);
105        }
106        true
107    }
108}
109
110struct Attachment {
111    source: WeakEntity<InteractionSource>,
112    window: WindowId,
113    id: ElementId,
114    owner: EntityId,
115    last: Cell<Option<InteractionState>>,
116}
117
118/// A control's binding to an interaction source.
119/// The tracker observes an existing input path and has no effect on activation.
120#[derive(Clone)]
121pub struct InteractionTracker(WeakEntity<Attachment>);
122
123impl InteractionTracker {
124    /// Records one changed snapshot. Events are delivered in recording order
125    /// after the current GPUI operation, even when several changes share a draw.
126    pub fn record(&self, state: InteractionState, cx: &mut App) {
127        let Some(attachment) = self.0.upgrade() else {
128            return;
129        };
130        if attachment.read(cx).last.replace(Some(state)) == Some(state) {
131            return;
132        }
133        let attachment = self.0.clone();
134        cx.defer(move |cx| {
135            let Some(attachment) = attachment.upgrade() else {
136                return;
137            };
138            let attachment = attachment.read(cx);
139            let source = attachment.source.clone();
140            let window = attachment.window;
141            let id = attachment.id.clone();
142            let owner = attachment.owner;
143            source
144                .update(cx, |source, cx| {
145                    source
146                        .windows
147                        .entry(window)
148                        .or_default()
149                        .insert(id.clone(), (owner, state));
150                    cx.emit(InteractionUpdate {
151                        window,
152                        id,
153                        state: Some(state),
154                    });
155                    cx.notify();
156                })
157                .ok();
158        });
159    }
160}