1use crate::{Channel, ChannelId, ChannelStore};
2use anyhow::Result;
3use client::{Client, Collaborator, UserStore, ZED_ALWAYS_ACTIVE};
4use collections::HashMap;
5use gpui::{AppContext, AsyncAppContext, Context, EventEmitter, Model, ModelContext, Task};
6use language::proto::serialize_version;
7use rpc::{
8 proto::{self, PeerId},
9 TypedEnvelope,
10};
11use std::{sync::Arc, time::Duration};
12use util::ResultExt;
13
14pub const ACKNOWLEDGE_DEBOUNCE_INTERVAL: Duration = Duration::from_millis(250);
15
16pub(crate) fn init(client: &Arc<Client>) {
17 client.add_model_message_handler(ChannelBuffer::handle_update_channel_buffer);
18 client.add_model_message_handler(ChannelBuffer::handle_update_channel_buffer_collaborators);
19}
20
21pub struct ChannelBuffer {
22 pub channel_id: ChannelId,
23 connected: bool,
24 collaborators: HashMap<PeerId, Collaborator>,
25 user_store: Model<UserStore>,
26 channel_store: Model<ChannelStore>,
27 buffer: Model<language::Buffer>,
28 buffer_epoch: u64,
29 client: Arc<Client>,
30 subscription: Option<client::Subscription>,
31 acknowledge_task: Option<Task<Result<()>>>,
32}
33
34pub enum ChannelBufferEvent {
35 CollaboratorsChanged,
36 Disconnected,
37 BufferEdited,
38 ChannelChanged,
39}
40
41impl EventEmitter<ChannelBufferEvent> for ChannelBuffer {}
42
43impl ChannelBuffer {
44 pub(crate) async fn new(
45 channel: Arc<Channel>,
46 client: Arc<Client>,
47 user_store: Model<UserStore>,
48 channel_store: Model<ChannelStore>,
49 mut cx: AsyncAppContext,
50 ) -> Result<Model<Self>> {
51 let response = client
52 .request(proto::JoinChannelBuffer {
53 channel_id: channel.id,
54 })
55 .await?;
56
57 let base_text = response.base_text;
58 let operations = response
59 .operations
60 .into_iter()
61 .map(language::proto::deserialize_operation)
62 .collect::<Result<Vec<_>, _>>()?;
63
64 let buffer = cx.new_model(|_| {
65 language::Buffer::remote(
66 response.buffer_id,
67 response.replica_id as u16,
68 channel.channel_buffer_capability(),
69 base_text,
70 )
71 })?;
72 buffer.update(&mut cx, |buffer, cx| buffer.apply_ops(operations, cx))??;
73
74 let subscription = client.subscribe_to_entity(channel.id)?;
75
76 anyhow::Ok(cx.new_model(|cx| {
77 cx.subscribe(&buffer, Self::on_buffer_update).detach();
78 cx.on_release(Self::release).detach();
79 let mut this = Self {
80 buffer,
81 buffer_epoch: response.epoch,
82 client,
83 connected: true,
84 collaborators: Default::default(),
85 acknowledge_task: None,
86 channel_id: channel.id,
87 subscription: Some(subscription.set_model(&cx.handle(), &mut cx.to_async())),
88 user_store,
89 channel_store,
90 };
91 this.replace_collaborators(response.collaborators, cx);
92 this
93 })?)
94 }
95
96 fn release(&mut self, _: &mut AppContext) {
97 if self.connected {
98 if let Some(task) = self.acknowledge_task.take() {
99 task.detach();
100 }
101 self.client
102 .send(proto::LeaveChannelBuffer {
103 channel_id: self.channel_id,
104 })
105 .log_err();
106 }
107 }
108
109 pub fn remote_id(&self, cx: &AppContext) -> u64 {
110 self.buffer.read(cx).remote_id()
111 }
112
113 pub fn user_store(&self) -> &Model<UserStore> {
114 &self.user_store
115 }
116
117 pub(crate) fn replace_collaborators(
118 &mut self,
119 collaborators: Vec<proto::Collaborator>,
120 cx: &mut ModelContext<Self>,
121 ) {
122 let mut new_collaborators = HashMap::default();
123 for collaborator in collaborators {
124 if let Ok(collaborator) = Collaborator::from_proto(collaborator) {
125 new_collaborators.insert(collaborator.peer_id, collaborator);
126 }
127 }
128
129 for (_, old_collaborator) in &self.collaborators {
130 if !new_collaborators.contains_key(&old_collaborator.peer_id) {
131 self.buffer.update(cx, |buffer, cx| {
132 buffer.remove_peer(old_collaborator.replica_id as u16, cx)
133 });
134 }
135 }
136 self.collaborators = new_collaborators;
137 cx.emit(ChannelBufferEvent::CollaboratorsChanged);
138 cx.notify();
139 }
140
141 async fn handle_update_channel_buffer(
142 this: Model<Self>,
143 update_channel_buffer: TypedEnvelope<proto::UpdateChannelBuffer>,
144 _: Arc<Client>,
145 mut cx: AsyncAppContext,
146 ) -> Result<()> {
147 let ops = update_channel_buffer
148 .payload
149 .operations
150 .into_iter()
151 .map(language::proto::deserialize_operation)
152 .collect::<Result<Vec<_>, _>>()?;
153
154 this.update(&mut cx, |this, cx| {
155 cx.notify();
156 this.buffer
157 .update(cx, |buffer, cx| buffer.apply_ops(ops, cx))
158 })??;
159
160 Ok(())
161 }
162
163 async fn handle_update_channel_buffer_collaborators(
164 this: Model<Self>,
165 message: TypedEnvelope<proto::UpdateChannelBufferCollaborators>,
166 _: Arc<Client>,
167 mut cx: AsyncAppContext,
168 ) -> Result<()> {
169 this.update(&mut cx, |this, cx| {
170 this.replace_collaborators(message.payload.collaborators, cx);
171 cx.emit(ChannelBufferEvent::CollaboratorsChanged);
172 cx.notify();
173 })
174 }
175
176 fn on_buffer_update(
177 &mut self,
178 _: Model<language::Buffer>,
179 event: &language::Event,
180 cx: &mut ModelContext<Self>,
181 ) {
182 match event {
183 language::Event::Operation(operation) => {
184 if *ZED_ALWAYS_ACTIVE {
185 match operation {
186 language::Operation::UpdateSelections { selections, .. } => {
187 if selections.is_empty() {
188 return;
189 }
190 }
191 _ => {}
192 }
193 }
194 let operation = language::proto::serialize_operation(operation);
195 self.client
196 .send(proto::UpdateChannelBuffer {
197 channel_id: self.channel_id,
198 operations: vec![operation],
199 })
200 .log_err();
201 }
202 language::Event::Edited => {
203 cx.emit(ChannelBufferEvent::BufferEdited);
204 }
205 _ => {}
206 }
207 }
208
209 pub fn acknowledge_buffer_version(&mut self, cx: &mut ModelContext<'_, ChannelBuffer>) {
210 let buffer = self.buffer.read(cx);
211 let version = buffer.version();
212 let buffer_id = buffer.remote_id();
213 let client = self.client.clone();
214 let epoch = self.epoch();
215
216 self.acknowledge_task = Some(cx.spawn(move |_, cx| async move {
217 cx.background_executor()
218 .timer(ACKNOWLEDGE_DEBOUNCE_INTERVAL)
219 .await;
220 client
221 .send(proto::AckBufferOperation {
222 buffer_id,
223 epoch,
224 version: serialize_version(&version),
225 })
226 .ok();
227 Ok(())
228 }));
229 }
230
231 pub fn epoch(&self) -> u64 {
232 self.buffer_epoch
233 }
234
235 pub fn buffer(&self) -> Model<language::Buffer> {
236 self.buffer.clone()
237 }
238
239 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
240 &self.collaborators
241 }
242
243 pub fn channel(&self, cx: &AppContext) -> Option<Arc<Channel>> {
244 self.channel_store
245 .read(cx)
246 .channel_for_id(self.channel_id)
247 .cloned()
248 }
249
250 pub(crate) fn disconnect(&mut self, cx: &mut ModelContext<Self>) {
251 log::info!("channel buffer {} disconnected", self.channel_id);
252 if self.connected {
253 self.connected = false;
254 self.subscription.take();
255 cx.emit(ChannelBufferEvent::Disconnected);
256 cx.notify()
257 }
258 }
259
260 pub(crate) fn channel_changed(&mut self, cx: &mut ModelContext<Self>) {
261 cx.emit(ChannelBufferEvent::ChannelChanged);
262 cx.notify()
263 }
264
265 pub fn is_connected(&self) -> bool {
266 self.connected
267 }
268
269 pub fn replica_id(&self, cx: &AppContext) -> u16 {
270 self.buffer.read(cx).replica_id()
271 }
272}