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