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