headless_project.rs

  1use anyhow::{anyhow, Result};
  2use fs::Fs;
  3use gpui::{AppContext, AsyncAppContext, Context, Model, ModelContext};
  4use language::{proto::serialize_operation, Buffer, BufferEvent, LanguageRegistry};
  5use node_runtime::DummyNodeRuntime;
  6use project::{
  7    buffer_store::{BufferStore, BufferStoreEvent},
  8    project_settings::SettingsObserver,
  9    search::SearchQuery,
 10    worktree_store::WorktreeStore,
 11    LspStore, LspStoreEvent, PrettierStore, ProjectPath, WorktreeId,
 12};
 13use remote::SshSession;
 14use rpc::{
 15    proto::{self, SSH_PEER_ID, SSH_PROJECT_ID},
 16    AnyProtoClient, TypedEnvelope,
 17};
 18use smol::stream::StreamExt;
 19use std::{
 20    path::{Path, PathBuf},
 21    sync::{atomic::AtomicUsize, Arc},
 22};
 23use util::ResultExt;
 24use worktree::Worktree;
 25
 26pub struct HeadlessProject {
 27    pub fs: Arc<dyn Fs>,
 28    pub session: AnyProtoClient,
 29    pub worktree_store: Model<WorktreeStore>,
 30    pub buffer_store: Model<BufferStore>,
 31    pub lsp_store: Model<LspStore>,
 32    pub settings_observer: Model<SettingsObserver>,
 33    pub next_entry_id: Arc<AtomicUsize>,
 34    pub languages: Arc<LanguageRegistry>,
 35}
 36
 37impl HeadlessProject {
 38    pub fn init(cx: &mut AppContext) {
 39        settings::init(cx);
 40        language::init(cx);
 41        project::Project::init_settings(cx);
 42    }
 43
 44    pub fn new(session: Arc<SshSession>, fs: Arc<dyn Fs>, cx: &mut ModelContext<Self>) -> Self {
 45        let mut languages = LanguageRegistry::new(cx.background_executor().clone());
 46        languages
 47            .set_language_server_download_dir(PathBuf::from("/Users/conrad/what-could-go-wrong"));
 48
 49        let languages = Arc::new(languages);
 50
 51        let worktree_store = cx.new_model(|_| WorktreeStore::new(true, fs.clone()));
 52        let buffer_store = cx.new_model(|cx| {
 53            let mut buffer_store =
 54                BufferStore::new(worktree_store.clone(), Some(SSH_PROJECT_ID), cx);
 55            buffer_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
 56            buffer_store
 57        });
 58        let prettier_store = cx.new_model(|cx| {
 59            PrettierStore::new(
 60                DummyNodeRuntime::new(),
 61                fs.clone(),
 62                languages.clone(),
 63                worktree_store.clone(),
 64                cx,
 65            )
 66        });
 67
 68        let settings_observer = cx.new_model(|cx| {
 69            let mut observer = SettingsObserver::new_local(fs.clone(), worktree_store.clone(), cx);
 70            observer.shared(SSH_PROJECT_ID, session.clone().into(), cx);
 71            observer
 72        });
 73        let environment = project::ProjectEnvironment::new(&worktree_store, None, cx);
 74        let lsp_store = cx.new_model(|cx| {
 75            let mut lsp_store = LspStore::new_local(
 76                buffer_store.clone(),
 77                worktree_store.clone(),
 78                prettier_store.clone(),
 79                environment,
 80                languages.clone(),
 81                None,
 82                fs.clone(),
 83                cx,
 84            );
 85            lsp_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
 86            lsp_store
 87        });
 88
 89        cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 90
 91        cx.subscribe(
 92            &buffer_store,
 93            |_this, _buffer_store, event, cx| match event {
 94                BufferStoreEvent::BufferAdded(buffer) => {
 95                    cx.subscribe(buffer, Self::on_buffer_event).detach();
 96                }
 97                _ => {}
 98            },
 99        )
100        .detach();
101
102        let client: AnyProtoClient = session.clone().into();
103
104        session.subscribe_to_entity(SSH_PROJECT_ID, &worktree_store);
105        session.subscribe_to_entity(SSH_PROJECT_ID, &buffer_store);
106        session.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
107        session.subscribe_to_entity(SSH_PROJECT_ID, &lsp_store);
108        session.subscribe_to_entity(SSH_PROJECT_ID, &settings_observer);
109
110        client.add_request_handler(cx.weak_model(), Self::handle_list_remote_directory);
111
112        client.add_model_request_handler(Self::handle_add_worktree);
113        client.add_model_request_handler(Self::handle_open_buffer_by_path);
114        client.add_model_request_handler(Self::handle_find_search_candidates);
115
116        client.add_model_request_handler(BufferStore::handle_update_buffer);
117        client.add_model_message_handler(BufferStore::handle_close_buffer);
118
119        client.add_model_request_handler(LspStore::handle_create_language_server);
120        client.add_model_request_handler(LspStore::handle_which_command);
121        client.add_model_request_handler(LspStore::handle_shell_env);
122        client.add_model_request_handler(LspStore::handle_try_exec);
123        client.add_model_request_handler(LspStore::handle_read_text_file);
124
125        BufferStore::init(&client);
126        WorktreeStore::init(&client);
127        SettingsObserver::init(&client);
128        LspStore::init(&client);
129
130        HeadlessProject {
131            session: client,
132            settings_observer,
133            fs,
134            worktree_store,
135            buffer_store,
136            lsp_store,
137            next_entry_id: Default::default(),
138            languages,
139        }
140    }
141
142    fn on_buffer_event(
143        &mut self,
144        buffer: Model<Buffer>,
145        event: &BufferEvent,
146        cx: &mut ModelContext<Self>,
147    ) {
148        match event {
149            BufferEvent::Operation(op) => cx
150                .background_executor()
151                .spawn(self.session.request(proto::UpdateBuffer {
152                    project_id: SSH_PROJECT_ID,
153                    buffer_id: buffer.read(cx).remote_id().to_proto(),
154                    operations: vec![serialize_operation(op)],
155                }))
156                .detach(),
157            _ => {}
158        }
159    }
160
161    fn on_lsp_store_event(
162        &mut self,
163        _lsp_store: Model<LspStore>,
164        event: &LspStoreEvent,
165        _cx: &mut ModelContext<Self>,
166    ) {
167        match event {
168            LspStoreEvent::LanguageServerUpdate {
169                language_server_id,
170                message,
171            } => {
172                self.session
173                    .send(proto::UpdateLanguageServer {
174                        project_id: SSH_PROJECT_ID,
175                        language_server_id: language_server_id.to_proto(),
176                        variant: Some(message.clone()),
177                    })
178                    .log_err();
179            }
180            _ => {}
181        }
182    }
183
184    pub async fn handle_add_worktree(
185        this: Model<Self>,
186        message: TypedEnvelope<proto::AddWorktree>,
187        mut cx: AsyncAppContext,
188    ) -> Result<proto::AddWorktreeResponse> {
189        let path = shellexpand::tilde(&message.payload.path).to_string();
190        let worktree = this
191            .update(&mut cx.clone(), |this, _| {
192                Worktree::local(
193                    Path::new(&path),
194                    true,
195                    this.fs.clone(),
196                    this.next_entry_id.clone(),
197                    &mut cx,
198                )
199            })?
200            .await?;
201
202        this.update(&mut cx, |this, cx| {
203            let session = this.session.clone();
204            this.worktree_store.update(cx, |worktree_store, cx| {
205                worktree_store.add(&worktree, cx);
206            });
207            worktree.update(cx, |worktree, cx| {
208                worktree.observe_updates(0, cx, move |update| {
209                    session.send(update).ok();
210                    futures::future::ready(true)
211                });
212                proto::AddWorktreeResponse {
213                    worktree_id: worktree.id().to_proto(),
214                }
215            })
216        })
217    }
218
219    pub async fn handle_open_buffer_by_path(
220        this: Model<Self>,
221        message: TypedEnvelope<proto::OpenBufferByPath>,
222        mut cx: AsyncAppContext,
223    ) -> Result<proto::OpenBufferResponse> {
224        let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
225        let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
226            let buffer_store = this.buffer_store.clone();
227            let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
228                buffer_store.open_buffer(
229                    ProjectPath {
230                        worktree_id,
231                        path: PathBuf::from(message.payload.path).into(),
232                    },
233                    cx,
234                )
235            });
236            anyhow::Ok((buffer_store, buffer))
237        })??;
238
239        let buffer = buffer.await?;
240        let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
241        buffer_store.update(&mut cx, |buffer_store, cx| {
242            buffer_store
243                .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
244                .detach_and_log_err(cx);
245        })?;
246
247        Ok(proto::OpenBufferResponse {
248            buffer_id: buffer_id.to_proto(),
249        })
250    }
251
252    pub async fn handle_find_search_candidates(
253        this: Model<Self>,
254        envelope: TypedEnvelope<proto::FindSearchCandidates>,
255        mut cx: AsyncAppContext,
256    ) -> Result<proto::FindSearchCandidatesResponse> {
257        let message = envelope.payload;
258        let query = SearchQuery::from_proto(
259            message
260                .query
261                .ok_or_else(|| anyhow!("missing query field"))?,
262        )?;
263        let mut results = this.update(&mut cx, |this, cx| {
264            this.buffer_store.update(cx, |buffer_store, cx| {
265                buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
266            })
267        })?;
268
269        let mut response = proto::FindSearchCandidatesResponse {
270            buffer_ids: Vec::new(),
271        };
272
273        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
274
275        while let Some(buffer) = results.next().await {
276            let buffer_id = buffer.update(&mut cx, |this, _| this.remote_id())?;
277            response.buffer_ids.push(buffer_id.to_proto());
278            buffer_store
279                .update(&mut cx, |buffer_store, cx| {
280                    buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
281                })?
282                .await?;
283        }
284
285        Ok(response)
286    }
287
288    pub async fn handle_list_remote_directory(
289        this: Model<Self>,
290        envelope: TypedEnvelope<proto::ListRemoteDirectory>,
291        cx: AsyncAppContext,
292    ) -> Result<proto::ListRemoteDirectoryResponse> {
293        let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
294        let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
295
296        let mut entries = Vec::new();
297        let mut response = fs.read_dir(Path::new(&expanded)).await?;
298        while let Some(path) = response.next().await {
299            if let Some(file_name) = path?.file_name() {
300                entries.push(file_name.to_string_lossy().to_string());
301            }
302        }
303        Ok(proto::ListRemoteDirectoryResponse { entries })
304    }
305}