headless_project.rs

  1use anyhow::{anyhow, Result};
  2use fs::Fs;
  3use gpui::{AppContext, AsyncAppContext, Context, Model, ModelContext};
  4use http_client::HttpClient;
  5use language::{proto::serialize_operation, Buffer, BufferEvent, LanguageRegistry};
  6use node_runtime::NodeRuntime;
  7use project::{
  8    buffer_store::{BufferStore, BufferStoreEvent},
  9    project_settings::SettingsObserver,
 10    search::SearchQuery,
 11    task_store::TaskStore,
 12    worktree_store::WorktreeStore,
 13    LspStore, LspStoreEvent, PrettierStore, ProjectPath, WorktreeId,
 14};
 15use remote::ssh_session::ChannelClient;
 16use rpc::{
 17    proto::{self, SSH_PEER_ID, SSH_PROJECT_ID},
 18    AnyProtoClient, TypedEnvelope,
 19};
 20
 21use settings::initial_server_settings_content;
 22use smol::stream::StreamExt;
 23use std::{
 24    path::{Path, PathBuf},
 25    sync::{atomic::AtomicUsize, Arc},
 26};
 27use util::ResultExt;
 28use worktree::Worktree;
 29
 30pub struct HeadlessProject {
 31    pub fs: Arc<dyn Fs>,
 32    pub session: AnyProtoClient,
 33    pub worktree_store: Model<WorktreeStore>,
 34    pub buffer_store: Model<BufferStore>,
 35    pub lsp_store: Model<LspStore>,
 36    pub task_store: Model<TaskStore>,
 37    pub settings_observer: Model<SettingsObserver>,
 38    pub next_entry_id: Arc<AtomicUsize>,
 39    pub languages: Arc<LanguageRegistry>,
 40}
 41
 42pub struct HeadlessAppState {
 43    pub session: Arc<ChannelClient>,
 44    pub fs: Arc<dyn Fs>,
 45    pub http_client: Arc<dyn HttpClient>,
 46    pub node_runtime: NodeRuntime,
 47    pub languages: Arc<LanguageRegistry>,
 48}
 49
 50impl HeadlessProject {
 51    pub fn init(cx: &mut AppContext) {
 52        settings::init(cx);
 53        language::init(cx);
 54        project::Project::init_settings(cx);
 55    }
 56
 57    pub fn new(
 58        HeadlessAppState {
 59            session,
 60            fs,
 61            http_client,
 62            node_runtime,
 63            languages,
 64        }: HeadlessAppState,
 65        cx: &mut ModelContext<Self>,
 66    ) -> Self {
 67        languages::init(languages.clone(), node_runtime.clone(), cx);
 68
 69        let worktree_store = cx.new_model(|cx| {
 70            let mut store = WorktreeStore::local(true, fs.clone());
 71            store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
 72            store
 73        });
 74        let buffer_store = cx.new_model(|cx| {
 75            let mut buffer_store = BufferStore::local(worktree_store.clone(), cx);
 76            buffer_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
 77            buffer_store
 78        });
 79        let prettier_store = cx.new_model(|cx| {
 80            PrettierStore::new(
 81                node_runtime,
 82                fs.clone(),
 83                languages.clone(),
 84                worktree_store.clone(),
 85                cx,
 86            )
 87        });
 88
 89        let environment = project::ProjectEnvironment::new(&worktree_store, None, cx);
 90        let task_store = cx.new_model(|cx| {
 91            let mut task_store = TaskStore::local(
 92                fs.clone(),
 93                buffer_store.downgrade(),
 94                worktree_store.clone(),
 95                environment.clone(),
 96                cx,
 97            );
 98            task_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
 99            task_store
100        });
101        let settings_observer = cx.new_model(|cx| {
102            let mut observer = SettingsObserver::new_local(
103                fs.clone(),
104                worktree_store.clone(),
105                task_store.clone(),
106                cx,
107            );
108            observer.shared(SSH_PROJECT_ID, session.clone().into(), cx);
109            observer
110        });
111        let lsp_store = cx.new_model(|cx| {
112            let mut lsp_store = LspStore::new_local(
113                buffer_store.clone(),
114                worktree_store.clone(),
115                prettier_store.clone(),
116                environment,
117                languages.clone(),
118                http_client,
119                fs.clone(),
120                cx,
121            );
122            lsp_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
123            lsp_store
124        });
125
126        cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
127
128        cx.subscribe(
129            &buffer_store,
130            |_this, _buffer_store, event, cx| match event {
131                BufferStoreEvent::BufferAdded(buffer) => {
132                    cx.subscribe(buffer, Self::on_buffer_event).detach();
133                }
134                _ => {}
135            },
136        )
137        .detach();
138
139        let client: AnyProtoClient = session.clone().into();
140
141        session.subscribe_to_entity(SSH_PROJECT_ID, &worktree_store);
142        session.subscribe_to_entity(SSH_PROJECT_ID, &buffer_store);
143        session.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
144        session.subscribe_to_entity(SSH_PROJECT_ID, &lsp_store);
145        session.subscribe_to_entity(SSH_PROJECT_ID, &task_store);
146        session.subscribe_to_entity(SSH_PROJECT_ID, &settings_observer);
147
148        client.add_request_handler(cx.weak_model(), Self::handle_list_remote_directory);
149        client.add_request_handler(cx.weak_model(), Self::handle_check_file_exists);
150        client.add_request_handler(cx.weak_model(), Self::handle_shutdown_remote_server);
151        client.add_request_handler(cx.weak_model(), Self::handle_ping);
152
153        client.add_model_request_handler(Self::handle_add_worktree);
154        client.add_request_handler(cx.weak_model(), Self::handle_remove_worktree);
155
156        client.add_model_request_handler(Self::handle_open_buffer_by_path);
157        client.add_model_request_handler(Self::handle_find_search_candidates);
158        client.add_model_request_handler(Self::handle_open_server_settings);
159
160        client.add_model_request_handler(BufferStore::handle_update_buffer);
161        client.add_model_message_handler(BufferStore::handle_close_buffer);
162
163        BufferStore::init(&client);
164        WorktreeStore::init(&client);
165        SettingsObserver::init(&client);
166        LspStore::init(&client);
167        TaskStore::init(Some(&client));
168
169        HeadlessProject {
170            session: client,
171            settings_observer,
172            fs,
173            worktree_store,
174            buffer_store,
175            lsp_store,
176            task_store,
177            next_entry_id: Default::default(),
178            languages,
179        }
180    }
181
182    fn on_buffer_event(
183        &mut self,
184        buffer: Model<Buffer>,
185        event: &BufferEvent,
186        cx: &mut ModelContext<Self>,
187    ) {
188        match event {
189            BufferEvent::Operation {
190                operation,
191                is_local: true,
192            } => cx
193                .background_executor()
194                .spawn(self.session.request(proto::UpdateBuffer {
195                    project_id: SSH_PROJECT_ID,
196                    buffer_id: buffer.read(cx).remote_id().to_proto(),
197                    operations: vec![serialize_operation(operation)],
198                }))
199                .detach(),
200            _ => {}
201        }
202    }
203
204    fn on_lsp_store_event(
205        &mut self,
206        _lsp_store: Model<LspStore>,
207        event: &LspStoreEvent,
208        _cx: &mut ModelContext<Self>,
209    ) {
210        match event {
211            LspStoreEvent::LanguageServerUpdate {
212                language_server_id,
213                message,
214            } => {
215                self.session
216                    .send(proto::UpdateLanguageServer {
217                        project_id: SSH_PROJECT_ID,
218                        language_server_id: language_server_id.to_proto(),
219                        variant: Some(message.clone()),
220                    })
221                    .log_err();
222            }
223            LspStoreEvent::Notification(message) => {
224                self.session
225                    .send(proto::Toast {
226                        project_id: SSH_PROJECT_ID,
227                        notification_id: "lsp".to_string(),
228                        message: message.clone(),
229                    })
230                    .log_err();
231            }
232            LspStoreEvent::LanguageServerLog(language_server_id, log_type, message) => {
233                self.session
234                    .send(proto::LanguageServerLog {
235                        project_id: SSH_PROJECT_ID,
236                        language_server_id: language_server_id.to_proto(),
237                        message: message.clone(),
238                        log_type: Some(log_type.to_proto()),
239                    })
240                    .log_err();
241            }
242            _ => {}
243        }
244    }
245
246    pub async fn handle_add_worktree(
247        this: Model<Self>,
248        message: TypedEnvelope<proto::AddWorktree>,
249        mut cx: AsyncAppContext,
250    ) -> Result<proto::AddWorktreeResponse> {
251        use client::ErrorCodeExt;
252        let path = shellexpand::tilde(&message.payload.path).to_string();
253
254        let fs = this.read_with(&mut cx, |this, _| this.fs.clone())?;
255        let path = PathBuf::from(path);
256
257        let canonicalized = match fs.canonicalize(&path).await {
258            Ok(path) => path,
259            Err(e) => {
260                let mut parent = path
261                    .parent()
262                    .ok_or(e)
263                    .map_err(|_| anyhow!("{:?} does not exist", path))?;
264                if parent == Path::new("") {
265                    parent = util::paths::home_dir();
266                }
267                let parent = fs.canonicalize(parent).await.map_err(|_| {
268                    anyhow!(proto::ErrorCode::DevServerProjectPathDoesNotExist
269                        .with_tag("path", &path.to_string_lossy().as_ref()))
270                })?;
271                parent.join(path.file_name().unwrap())
272            }
273        };
274
275        let worktree = this
276            .update(&mut cx.clone(), |this, _| {
277                Worktree::local(
278                    Arc::from(canonicalized.as_path()),
279                    message.payload.visible,
280                    this.fs.clone(),
281                    this.next_entry_id.clone(),
282                    &mut cx,
283                )
284            })?
285            .await?;
286
287        let response = this.update(&mut cx, |_, cx| {
288            worktree.update(cx, |worktree, _| proto::AddWorktreeResponse {
289                worktree_id: worktree.id().to_proto(),
290                canonicalized_path: canonicalized.to_string_lossy().to_string(),
291            })
292        })?;
293
294        // We spawn this asynchronously, so that we can send the response back
295        // *before* `worktree_store.add()` can send out UpdateProject requests
296        // to the client about the new worktree.
297        //
298        // That lets the client manage the reference/handles of the newly-added
299        // worktree, before getting interrupted by an UpdateProject request.
300        //
301        // This fixes the problem of the client sending the AddWorktree request,
302        // headless project sending out a project update, client receiving it
303        // and immediately dropping the reference of the new client, causing it
304        // to be dropped on the headless project, and the client only then
305        // receiving a response to AddWorktree.
306        cx.spawn(|mut cx| async move {
307            this.update(&mut cx, |this, cx| {
308                this.worktree_store.update(cx, |worktree_store, cx| {
309                    worktree_store.add(&worktree, cx);
310                });
311            })
312            .log_err();
313        })
314        .detach();
315
316        Ok(response)
317    }
318
319    pub async fn handle_remove_worktree(
320        this: Model<Self>,
321        envelope: TypedEnvelope<proto::RemoveWorktree>,
322        mut cx: AsyncAppContext,
323    ) -> Result<proto::Ack> {
324        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
325        this.update(&mut cx, |this, cx| {
326            this.worktree_store.update(cx, |worktree_store, cx| {
327                worktree_store.remove_worktree(worktree_id, cx);
328            });
329        })?;
330        Ok(proto::Ack {})
331    }
332
333    pub async fn handle_open_buffer_by_path(
334        this: Model<Self>,
335        message: TypedEnvelope<proto::OpenBufferByPath>,
336        mut cx: AsyncAppContext,
337    ) -> Result<proto::OpenBufferResponse> {
338        let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
339        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
340            let buffer_store = this.buffer_store.clone();
341            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
342                buffer_store.open_buffer(
343                    ProjectPath {
344                        worktree_id,
345                        path: PathBuf::from(message.payload.path).into(),
346                    },
347                    cx,
348                )
349            });
350            anyhow::Ok((buffer_store, buffer))
351        })??;
352
353        let buffer = buffer.await?;
354        let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
355        buffer_store.update(&mut cx, |buffer_store, cx| {
356            buffer_store
357                .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
358                .detach_and_log_err(cx);
359        })?;
360
361        Ok(proto::OpenBufferResponse {
362            buffer_id: buffer_id.to_proto(),
363        })
364    }
365
366    pub async fn handle_open_server_settings(
367        this: Model<Self>,
368        _: TypedEnvelope<proto::OpenServerSettings>,
369        mut cx: AsyncAppContext,
370    ) -> Result<proto::OpenBufferResponse> {
371        let settings_path = paths::settings_file();
372        let (worktree, path) = this
373            .update(&mut cx, |this, cx| {
374                this.worktree_store.update(cx, |worktree_store, cx| {
375                    worktree_store.find_or_create_worktree(settings_path, false, cx)
376                })
377            })?
378            .await?;
379
380        let (buffer, buffer_store) = this.update(&mut cx, |this, cx| {
381            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
382                buffer_store.open_buffer(
383                    ProjectPath {
384                        worktree_id: worktree.read(cx).id(),
385                        path: path.into(),
386                    },
387                    cx,
388                )
389            });
390
391            (buffer, this.buffer_store.clone())
392        })?;
393
394        let buffer = buffer.await?;
395
396        let buffer_id = cx.update(|cx| {
397            if buffer.read(cx).is_empty() {
398                buffer.update(cx, |buffer, cx| {
399                    buffer.edit([(0..0, initial_server_settings_content())], None, cx)
400                });
401            }
402
403            let buffer_id = buffer.read_with(cx, |b, _| b.remote_id());
404
405            buffer_store.update(cx, |buffer_store, cx| {
406                buffer_store
407                    .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
408                    .detach_and_log_err(cx);
409            });
410
411            buffer_id
412        })?;
413
414        Ok(proto::OpenBufferResponse {
415            buffer_id: buffer_id.to_proto(),
416        })
417    }
418
419    pub async fn handle_find_search_candidates(
420        this: Model<Self>,
421        envelope: TypedEnvelope<proto::FindSearchCandidates>,
422        mut cx: AsyncAppContext,
423    ) -> Result<proto::FindSearchCandidatesResponse> {
424        let message = envelope.payload;
425        let query = SearchQuery::from_proto(
426            message
427                .query
428                .ok_or_else(|| anyhow!("missing query field"))?,
429        )?;
430        let mut results = this.update(&mut cx, |this, cx| {
431            this.buffer_store.update(cx, |buffer_store, cx| {
432                buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
433            })
434        })?;
435
436        let mut response = proto::FindSearchCandidatesResponse {
437            buffer_ids: Vec::new(),
438        };
439
440        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
441
442        while let Some(buffer) = results.next().await {
443            let buffer_id = buffer.update(&mut cx, |this, _| this.remote_id())?;
444            response.buffer_ids.push(buffer_id.to_proto());
445            buffer_store
446                .update(&mut cx, |buffer_store, cx| {
447                    buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
448                })?
449                .await?;
450        }
451
452        Ok(response)
453    }
454
455    pub async fn handle_list_remote_directory(
456        this: Model<Self>,
457        envelope: TypedEnvelope<proto::ListRemoteDirectory>,
458        cx: AsyncAppContext,
459    ) -> Result<proto::ListRemoteDirectoryResponse> {
460        let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
461        let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
462
463        let mut entries = Vec::new();
464        let mut response = fs.read_dir(Path::new(&expanded)).await?;
465        while let Some(path) = response.next().await {
466            if let Some(file_name) = path?.file_name() {
467                entries.push(file_name.to_string_lossy().to_string());
468            }
469        }
470        Ok(proto::ListRemoteDirectoryResponse { entries })
471    }
472
473    pub async fn handle_check_file_exists(
474        this: Model<Self>,
475        envelope: TypedEnvelope<proto::CheckFileExists>,
476        cx: AsyncAppContext,
477    ) -> Result<proto::CheckFileExistsResponse> {
478        let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
479        let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
480
481        let exists = fs.is_file(&PathBuf::from(expanded.clone())).await;
482
483        Ok(proto::CheckFileExistsResponse {
484            exists,
485            path: expanded,
486        })
487    }
488
489    pub async fn handle_shutdown_remote_server(
490        _this: Model<Self>,
491        _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
492        cx: AsyncAppContext,
493    ) -> Result<proto::Ack> {
494        cx.spawn(|cx| async move {
495            cx.update(|cx| {
496                // TODO: This is a hack, because in a headless project, shutdown isn't executed
497                // when calling quit, but it should be.
498                cx.shutdown();
499                cx.quit();
500            })
501        })
502        .detach();
503
504        Ok(proto::Ack {})
505    }
506
507    pub async fn handle_ping(
508        _this: Model<Self>,
509        _envelope: TypedEnvelope<proto::Ping>,
510        _cx: AsyncAppContext,
511    ) -> Result<proto::Ack> {
512        log::debug!("Received ping from client");
513        Ok(proto::Ack {})
514    }
515}