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