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_open_new_buffer);
158 client.add_model_request_handler(Self::handle_find_search_candidates);
159 client.add_model_request_handler(Self::handle_open_server_settings);
160
161 client.add_model_request_handler(BufferStore::handle_update_buffer);
162 client.add_model_message_handler(BufferStore::handle_close_buffer);
163
164 BufferStore::init(&client);
165 WorktreeStore::init(&client);
166 SettingsObserver::init(&client);
167 LspStore::init(&client);
168 TaskStore::init(Some(&client));
169
170 HeadlessProject {
171 session: client,
172 settings_observer,
173 fs,
174 worktree_store,
175 buffer_store,
176 lsp_store,
177 task_store,
178 next_entry_id: Default::default(),
179 languages,
180 }
181 }
182
183 fn on_buffer_event(
184 &mut self,
185 buffer: Model<Buffer>,
186 event: &BufferEvent,
187 cx: &mut ModelContext<Self>,
188 ) {
189 match event {
190 BufferEvent::Operation {
191 operation,
192 is_local: true,
193 } => cx
194 .background_executor()
195 .spawn(self.session.request(proto::UpdateBuffer {
196 project_id: SSH_PROJECT_ID,
197 buffer_id: buffer.read(cx).remote_id().to_proto(),
198 operations: vec![serialize_operation(operation)],
199 }))
200 .detach(),
201 _ => {}
202 }
203 }
204
205 fn on_lsp_store_event(
206 &mut self,
207 _lsp_store: Model<LspStore>,
208 event: &LspStoreEvent,
209 _cx: &mut ModelContext<Self>,
210 ) {
211 match event {
212 LspStoreEvent::LanguageServerUpdate {
213 language_server_id,
214 message,
215 } => {
216 self.session
217 .send(proto::UpdateLanguageServer {
218 project_id: SSH_PROJECT_ID,
219 language_server_id: language_server_id.to_proto(),
220 variant: Some(message.clone()),
221 })
222 .log_err();
223 }
224 LspStoreEvent::Notification(message) => {
225 self.session
226 .send(proto::Toast {
227 project_id: SSH_PROJECT_ID,
228 notification_id: "lsp".to_string(),
229 message: message.clone(),
230 })
231 .log_err();
232 }
233 LspStoreEvent::LanguageServerLog(language_server_id, log_type, message) => {
234 self.session
235 .send(proto::LanguageServerLog {
236 project_id: SSH_PROJECT_ID,
237 language_server_id: language_server_id.to_proto(),
238 message: message.clone(),
239 log_type: Some(log_type.to_proto()),
240 })
241 .log_err();
242 }
243 _ => {}
244 }
245 }
246
247 pub async fn handle_add_worktree(
248 this: Model<Self>,
249 message: TypedEnvelope<proto::AddWorktree>,
250 mut cx: AsyncAppContext,
251 ) -> Result<proto::AddWorktreeResponse> {
252 use client::ErrorCodeExt;
253 let path = shellexpand::tilde(&message.payload.path).to_string();
254
255 let fs = this.read_with(&mut cx, |this, _| this.fs.clone())?;
256 let path = PathBuf::from(path);
257
258 let canonicalized = match fs.canonicalize(&path).await {
259 Ok(path) => path,
260 Err(e) => {
261 let mut parent = path
262 .parent()
263 .ok_or(e)
264 .map_err(|_| anyhow!("{:?} does not exist", path))?;
265 if parent == Path::new("") {
266 parent = util::paths::home_dir();
267 }
268 let parent = fs.canonicalize(parent).await.map_err(|_| {
269 anyhow!(proto::ErrorCode::DevServerProjectPathDoesNotExist
270 .with_tag("path", &path.to_string_lossy().as_ref()))
271 })?;
272 parent.join(path.file_name().unwrap())
273 }
274 };
275
276 let worktree = this
277 .update(&mut cx.clone(), |this, _| {
278 Worktree::local(
279 Arc::from(canonicalized.as_path()),
280 message.payload.visible,
281 this.fs.clone(),
282 this.next_entry_id.clone(),
283 &mut cx,
284 )
285 })?
286 .await?;
287
288 let response = this.update(&mut cx, |_, cx| {
289 worktree.update(cx, |worktree, _| proto::AddWorktreeResponse {
290 worktree_id: worktree.id().to_proto(),
291 canonicalized_path: canonicalized.to_string_lossy().to_string(),
292 })
293 })?;
294
295 // We spawn this asynchronously, so that we can send the response back
296 // *before* `worktree_store.add()` can send out UpdateProject requests
297 // to the client about the new worktree.
298 //
299 // That lets the client manage the reference/handles of the newly-added
300 // worktree, before getting interrupted by an UpdateProject request.
301 //
302 // This fixes the problem of the client sending the AddWorktree request,
303 // headless project sending out a project update, client receiving it
304 // and immediately dropping the reference of the new client, causing it
305 // to be dropped on the headless project, and the client only then
306 // receiving a response to AddWorktree.
307 cx.spawn(|mut cx| async move {
308 this.update(&mut cx, |this, cx| {
309 this.worktree_store.update(cx, |worktree_store, cx| {
310 worktree_store.add(&worktree, cx);
311 });
312 })
313 .log_err();
314 })
315 .detach();
316
317 Ok(response)
318 }
319
320 pub async fn handle_remove_worktree(
321 this: Model<Self>,
322 envelope: TypedEnvelope<proto::RemoveWorktree>,
323 mut cx: AsyncAppContext,
324 ) -> Result<proto::Ack> {
325 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
326 this.update(&mut cx, |this, cx| {
327 this.worktree_store.update(cx, |worktree_store, cx| {
328 worktree_store.remove_worktree(worktree_id, cx);
329 });
330 })?;
331 Ok(proto::Ack {})
332 }
333
334 pub async fn handle_open_buffer_by_path(
335 this: Model<Self>,
336 message: TypedEnvelope<proto::OpenBufferByPath>,
337 mut cx: AsyncAppContext,
338 ) -> Result<proto::OpenBufferResponse> {
339 let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
340 let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
341 let buffer_store = this.buffer_store.clone();
342 let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
343 buffer_store.open_buffer(
344 ProjectPath {
345 worktree_id,
346 path: PathBuf::from(message.payload.path).into(),
347 },
348 cx,
349 )
350 });
351 anyhow::Ok((buffer_store, buffer))
352 })??;
353
354 let buffer = buffer.await?;
355 let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
356 buffer_store.update(&mut cx, |buffer_store, cx| {
357 buffer_store
358 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
359 .detach_and_log_err(cx);
360 })?;
361
362 Ok(proto::OpenBufferResponse {
363 buffer_id: buffer_id.to_proto(),
364 })
365 }
366
367 pub async fn handle_open_new_buffer(
368 this: Model<Self>,
369 _message: TypedEnvelope<proto::OpenNewBuffer>,
370 mut cx: AsyncAppContext,
371 ) -> Result<proto::OpenBufferResponse> {
372 let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
373 let buffer_store = this.buffer_store.clone();
374 let buffer = this
375 .buffer_store
376 .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx));
377 anyhow::Ok((buffer_store, buffer))
378 })??;
379
380 let buffer = buffer.await?;
381 let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
382 buffer_store.update(&mut cx, |buffer_store, cx| {
383 buffer_store
384 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
385 .detach_and_log_err(cx);
386 })?;
387
388 Ok(proto::OpenBufferResponse {
389 buffer_id: buffer_id.to_proto(),
390 })
391 }
392
393 pub async fn handle_open_server_settings(
394 this: Model<Self>,
395 _: TypedEnvelope<proto::OpenServerSettings>,
396 mut cx: AsyncAppContext,
397 ) -> Result<proto::OpenBufferResponse> {
398 let settings_path = paths::settings_file();
399 let (worktree, path) = this
400 .update(&mut cx, |this, cx| {
401 this.worktree_store.update(cx, |worktree_store, cx| {
402 worktree_store.find_or_create_worktree(settings_path, false, cx)
403 })
404 })?
405 .await?;
406
407 let (buffer, buffer_store) = this.update(&mut cx, |this, cx| {
408 let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
409 buffer_store.open_buffer(
410 ProjectPath {
411 worktree_id: worktree.read(cx).id(),
412 path: path.into(),
413 },
414 cx,
415 )
416 });
417
418 (buffer, this.buffer_store.clone())
419 })?;
420
421 let buffer = buffer.await?;
422
423 let buffer_id = cx.update(|cx| {
424 if buffer.read(cx).is_empty() {
425 buffer.update(cx, |buffer, cx| {
426 buffer.edit([(0..0, initial_server_settings_content())], None, cx)
427 });
428 }
429
430 let buffer_id = buffer.read_with(cx, |b, _| b.remote_id());
431
432 buffer_store.update(cx, |buffer_store, cx| {
433 buffer_store
434 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
435 .detach_and_log_err(cx);
436 });
437
438 buffer_id
439 })?;
440
441 Ok(proto::OpenBufferResponse {
442 buffer_id: buffer_id.to_proto(),
443 })
444 }
445
446 pub async fn handle_find_search_candidates(
447 this: Model<Self>,
448 envelope: TypedEnvelope<proto::FindSearchCandidates>,
449 mut cx: AsyncAppContext,
450 ) -> Result<proto::FindSearchCandidatesResponse> {
451 let message = envelope.payload;
452 let query = SearchQuery::from_proto(
453 message
454 .query
455 .ok_or_else(|| anyhow!("missing query field"))?,
456 )?;
457 let mut results = this.update(&mut cx, |this, cx| {
458 this.buffer_store.update(cx, |buffer_store, cx| {
459 buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
460 })
461 })?;
462
463 let mut response = proto::FindSearchCandidatesResponse {
464 buffer_ids: Vec::new(),
465 };
466
467 let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
468
469 while let Some(buffer) = results.next().await {
470 let buffer_id = buffer.update(&mut cx, |this, _| this.remote_id())?;
471 response.buffer_ids.push(buffer_id.to_proto());
472 buffer_store
473 .update(&mut cx, |buffer_store, cx| {
474 buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
475 })?
476 .await?;
477 }
478
479 Ok(response)
480 }
481
482 pub async fn handle_list_remote_directory(
483 this: Model<Self>,
484 envelope: TypedEnvelope<proto::ListRemoteDirectory>,
485 cx: AsyncAppContext,
486 ) -> Result<proto::ListRemoteDirectoryResponse> {
487 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
488 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
489
490 let mut entries = Vec::new();
491 let mut response = fs.read_dir(Path::new(&expanded)).await?;
492 while let Some(path) = response.next().await {
493 if let Some(file_name) = path?.file_name() {
494 entries.push(file_name.to_string_lossy().to_string());
495 }
496 }
497 Ok(proto::ListRemoteDirectoryResponse { entries })
498 }
499
500 pub async fn handle_check_file_exists(
501 this: Model<Self>,
502 envelope: TypedEnvelope<proto::CheckFileExists>,
503 cx: AsyncAppContext,
504 ) -> Result<proto::CheckFileExistsResponse> {
505 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
506 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
507
508 let exists = fs.is_file(&PathBuf::from(expanded.clone())).await;
509
510 Ok(proto::CheckFileExistsResponse {
511 exists,
512 path: expanded,
513 })
514 }
515
516 pub async fn handle_shutdown_remote_server(
517 _this: Model<Self>,
518 _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
519 cx: AsyncAppContext,
520 ) -> Result<proto::Ack> {
521 cx.spawn(|cx| async move {
522 cx.update(|cx| {
523 // TODO: This is a hack, because in a headless project, shutdown isn't executed
524 // when calling quit, but it should be.
525 cx.shutdown();
526 cx.quit();
527 })
528 })
529 .detach();
530
531 Ok(proto::Ack {})
532 }
533
534 pub async fn handle_ping(
535 _this: Model<Self>,
536 _envelope: TypedEnvelope<proto::Ping>,
537 _cx: AsyncAppContext,
538 ) -> Result<proto::Ack> {
539 log::debug!("Received ping from client");
540 Ok(proto::Ack {})
541 }
542}