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