1use collections::{BTreeMap, BTreeSet};
2use parking_lot::Mutex;
3use std::{cell::Cell, fmt::Debug, mem, rc::Rc, sync::Arc};
4use util::post_inc;
5
6pub(crate) struct SubscriberSet<EmitterKey, Callback>(
7 Arc<Mutex<SubscriberSetState<EmitterKey, Callback>>>,
8);
9
10impl<EmitterKey, Callback> Clone for SubscriberSet<EmitterKey, Callback> {
11 fn clone(&self) -> Self {
12 SubscriberSet(self.0.clone())
13 }
14}
15
16struct SubscriberSetState<EmitterKey, Callback> {
17 subscribers: BTreeMap<EmitterKey, Option<BTreeMap<usize, Subscriber<Callback>>>>,
18 dropped_subscribers: BTreeSet<(EmitterKey, usize)>,
19 next_subscriber_id: usize,
20}
21
22struct Subscriber<Callback> {
23 active: Rc<Cell<bool>>,
24 callback: Callback,
25}
26
27impl<EmitterKey, Callback> SubscriberSet<EmitterKey, Callback>
28where
29 EmitterKey: 'static + Ord + Clone + Debug,
30 Callback: 'static,
31{
32 pub fn new() -> Self {
33 Self(Arc::new(Mutex::new(SubscriberSetState {
34 subscribers: Default::default(),
35 dropped_subscribers: Default::default(),
36 next_subscriber_id: 0,
37 })))
38 }
39
40 /// Inserts a new [`Subscription`] for the given `emitter_key`. By default, subscriptions
41 /// are inert, meaning that they won't be listed when calling `[SubscriberSet::remove]` or `[SubscriberSet::retain]`.
42 /// This method returns a tuple of a [`Subscription`] and an `impl FnOnce`, and you can use the latter
43 /// to activate the [`Subscription`].
44 pub fn insert(
45 &self,
46 emitter_key: EmitterKey,
47 callback: Callback,
48 ) -> (Subscription, impl FnOnce()) {
49 let active = Rc::new(Cell::new(false));
50 let mut lock = self.0.lock();
51 let subscriber_id = post_inc(&mut lock.next_subscriber_id);
52 lock.subscribers
53 .entry(emitter_key.clone())
54 .or_default()
55 .get_or_insert_with(Default::default)
56 .insert(
57 subscriber_id,
58 Subscriber {
59 active: active.clone(),
60 callback,
61 },
62 );
63 let this = self.0.clone();
64
65 let subscription = Subscription {
66 unsubscribe: Some(Box::new(move || {
67 let mut lock = this.lock();
68 let Some(subscribers) = lock.subscribers.get_mut(&emitter_key) else {
69 // remove was called with this emitter_key
70 return;
71 };
72
73 if let Some(subscribers) = subscribers {
74 subscribers.remove(&subscriber_id);
75 if subscribers.is_empty() {
76 lock.subscribers.remove(&emitter_key);
77 }
78 return;
79 }
80
81 // We didn't manage to remove the subscription, which means it was dropped
82 // while invoking the callback. Mark it as dropped so that we can remove it
83 // later.
84 lock.dropped_subscribers
85 .insert((emitter_key, subscriber_id));
86 })),
87 };
88 (subscription, move || active.set(true))
89 }
90
91 pub fn remove(&self, emitter: &EmitterKey) -> impl IntoIterator<Item = Callback> {
92 let subscribers = self.0.lock().subscribers.remove(emitter);
93 subscribers
94 .unwrap_or_default()
95 .map(|s| s.into_values())
96 .into_iter()
97 .flatten()
98 .filter_map(|subscriber| {
99 if subscriber.active.get() {
100 Some(subscriber.callback)
101 } else {
102 None
103 }
104 })
105 }
106
107 /// Call the given callback for each subscriber to the given emitter.
108 /// If the callback returns false, the subscriber is removed.
109 pub fn retain<F>(&self, emitter: &EmitterKey, mut f: F)
110 where
111 F: FnMut(&mut Callback) -> bool,
112 {
113 let Some(mut subscribers) = self
114 .0
115 .lock()
116 .subscribers
117 .get_mut(emitter)
118 .and_then(|s| s.take())
119 else {
120 return;
121 };
122
123 subscribers.retain(|_, subscriber| {
124 if subscriber.active.get() {
125 f(&mut subscriber.callback)
126 } else {
127 true
128 }
129 });
130 let mut lock = self.0.lock();
131
132 // Add any new subscribers that were added while invoking the callback.
133 if let Some(Some(new_subscribers)) = lock.subscribers.remove(emitter) {
134 subscribers.extend(new_subscribers);
135 }
136
137 // Remove any dropped subscriptions that were dropped while invoking the callback.
138 for (dropped_emitter, dropped_subscription_id) in mem::take(&mut lock.dropped_subscribers) {
139 debug_assert_eq!(*emitter, dropped_emitter);
140 subscribers.remove(&dropped_subscription_id);
141 }
142
143 if !subscribers.is_empty() {
144 lock.subscribers.insert(emitter.clone(), Some(subscribers));
145 }
146 }
147}
148
149/// A handle to a subscription created by GPUI. When dropped, the subscription
150/// is cancelled and the callback will no longer be invoked.
151#[must_use]
152pub struct Subscription {
153 unsubscribe: Option<Box<dyn FnOnce() + 'static>>,
154}
155
156impl Subscription {
157 /// Creates a new subscription with a callback that gets invoked when
158 /// this subscription is dropped.
159 pub fn new(unsubscribe: impl 'static + FnOnce()) -> Self {
160 Self {
161 unsubscribe: Some(Box::new(unsubscribe)),
162 }
163 }
164
165 /// Detaches the subscription from this handle. The callback will
166 /// continue to be invoked until the entities it has been
167 /// subscribed to are dropped
168 pub fn detach(mut self) {
169 self.unsubscribe.take();
170 }
171
172 /// Joins two subscriptions into a single subscription. Detach will
173 /// detach both interior subscriptions.
174 pub fn join(mut subscription_a: Self, mut subscription_b: Self) -> Self {
175 let a_unsubscribe = subscription_a.unsubscribe.take();
176 let b_unsubscribe = subscription_b.unsubscribe.take();
177 Self {
178 unsubscribe: Some(Box::new(move || {
179 if let Some(self_unsubscribe) = a_unsubscribe {
180 self_unsubscribe();
181 }
182 if let Some(other_unsubscribe) = b_unsubscribe {
183 other_unsubscribe();
184 }
185 })),
186 }
187 }
188}
189
190impl Drop for Subscription {
191 fn drop(&mut self) {
192 if let Some(unsubscribe) = self.unsubscribe.take() {
193 unsubscribe();
194 }
195 }
196}