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 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(|cx| {
48 let mut store = WorktreeStore::local(true, fs.clone());
49 store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
50 store
51 });
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 NodeRuntime::unavailable(),
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 client.add_request_handler(cx.weak_model(), Self::handle_check_file_exists);
112
113 client.add_model_request_handler(Self::handle_add_worktree);
114 client.add_model_request_handler(Self::handle_open_buffer_by_path);
115 client.add_model_request_handler(Self::handle_find_search_candidates);
116
117 client.add_model_request_handler(BufferStore::handle_update_buffer);
118 client.add_model_message_handler(BufferStore::handle_close_buffer);
119
120 client.add_model_request_handler(LspStore::handle_create_language_server);
121 client.add_model_request_handler(LspStore::handle_which_command);
122 client.add_model_request_handler(LspStore::handle_shell_env);
123 client.add_model_request_handler(LspStore::handle_try_exec);
124 client.add_model_request_handler(LspStore::handle_read_text_file);
125
126 BufferStore::init(&client);
127 WorktreeStore::init(&client);
128 SettingsObserver::init(&client);
129 LspStore::init(&client);
130
131 HeadlessProject {
132 session: client,
133 settings_observer,
134 fs,
135 worktree_store,
136 buffer_store,
137 lsp_store,
138 next_entry_id: Default::default(),
139 languages,
140 }
141 }
142
143 fn on_buffer_event(
144 &mut self,
145 buffer: Model<Buffer>,
146 event: &BufferEvent,
147 cx: &mut ModelContext<Self>,
148 ) {
149 match event {
150 BufferEvent::Operation {
151 operation,
152 is_local: true,
153 } => cx
154 .background_executor()
155 .spawn(self.session.request(proto::UpdateBuffer {
156 project_id: SSH_PROJECT_ID,
157 buffer_id: buffer.read(cx).remote_id().to_proto(),
158 operations: vec![serialize_operation(operation)],
159 }))
160 .detach(),
161 _ => {}
162 }
163 }
164
165 fn on_lsp_store_event(
166 &mut self,
167 _lsp_store: Model<LspStore>,
168 event: &LspStoreEvent,
169 _cx: &mut ModelContext<Self>,
170 ) {
171 match event {
172 LspStoreEvent::LanguageServerUpdate {
173 language_server_id,
174 message,
175 } => {
176 self.session
177 .send(proto::UpdateLanguageServer {
178 project_id: SSH_PROJECT_ID,
179 language_server_id: language_server_id.to_proto(),
180 variant: Some(message.clone()),
181 })
182 .log_err();
183 }
184 _ => {}
185 }
186 }
187
188 pub async fn handle_add_worktree(
189 this: Model<Self>,
190 message: TypedEnvelope<proto::AddWorktree>,
191 mut cx: AsyncAppContext,
192 ) -> Result<proto::AddWorktreeResponse> {
193 let path = shellexpand::tilde(&message.payload.path).to_string();
194 let worktree = this
195 .update(&mut cx.clone(), |this, _| {
196 Worktree::local(
197 Path::new(&path),
198 true,
199 this.fs.clone(),
200 this.next_entry_id.clone(),
201 &mut cx,
202 )
203 })?
204 .await?;
205
206 this.update(&mut cx, |this, cx| {
207 this.worktree_store.update(cx, |worktree_store, cx| {
208 worktree_store.add(&worktree, cx);
209 });
210 worktree.update(cx, |worktree, _| proto::AddWorktreeResponse {
211 worktree_id: worktree.id().to_proto(),
212 })
213 })
214 }
215
216 pub async fn handle_open_buffer_by_path(
217 this: Model<Self>,
218 message: TypedEnvelope<proto::OpenBufferByPath>,
219 mut cx: AsyncAppContext,
220 ) -> Result<proto::OpenBufferResponse> {
221 let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
222 let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
223 let buffer_store = this.buffer_store.clone();
224 let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
225 buffer_store.open_buffer(
226 ProjectPath {
227 worktree_id,
228 path: PathBuf::from(message.payload.path).into(),
229 },
230 cx,
231 )
232 });
233 anyhow::Ok((buffer_store, buffer))
234 })??;
235
236 let buffer = buffer.await?;
237 let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
238 buffer_store.update(&mut cx, |buffer_store, cx| {
239 buffer_store
240 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
241 .detach_and_log_err(cx);
242 })?;
243
244 Ok(proto::OpenBufferResponse {
245 buffer_id: buffer_id.to_proto(),
246 })
247 }
248
249 pub async fn handle_find_search_candidates(
250 this: Model<Self>,
251 envelope: TypedEnvelope<proto::FindSearchCandidates>,
252 mut cx: AsyncAppContext,
253 ) -> Result<proto::FindSearchCandidatesResponse> {
254 let message = envelope.payload;
255 let query = SearchQuery::from_proto(
256 message
257 .query
258 .ok_or_else(|| anyhow!("missing query field"))?,
259 )?;
260 let mut results = this.update(&mut cx, |this, cx| {
261 this.buffer_store.update(cx, |buffer_store, cx| {
262 buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
263 })
264 })?;
265
266 let mut response = proto::FindSearchCandidatesResponse {
267 buffer_ids: Vec::new(),
268 };
269
270 let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
271
272 while let Some(buffer) = results.next().await {
273 let buffer_id = buffer.update(&mut cx, |this, _| this.remote_id())?;
274 response.buffer_ids.push(buffer_id.to_proto());
275 buffer_store
276 .update(&mut cx, |buffer_store, cx| {
277 buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
278 })?
279 .await?;
280 }
281
282 Ok(response)
283 }
284
285 pub async fn handle_list_remote_directory(
286 this: Model<Self>,
287 envelope: TypedEnvelope<proto::ListRemoteDirectory>,
288 cx: AsyncAppContext,
289 ) -> Result<proto::ListRemoteDirectoryResponse> {
290 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
291 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
292
293 let mut entries = Vec::new();
294 let mut response = fs.read_dir(Path::new(&expanded)).await?;
295 while let Some(path) = response.next().await {
296 if let Some(file_name) = path?.file_name() {
297 entries.push(file_name.to_string_lossy().to_string());
298 }
299 }
300 Ok(proto::ListRemoteDirectoryResponse { entries })
301 }
302
303 pub async fn handle_check_file_exists(
304 this: Model<Self>,
305 envelope: TypedEnvelope<proto::CheckFileExists>,
306 cx: AsyncAppContext,
307 ) -> Result<proto::CheckFileExistsResponse> {
308 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
309 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
310
311 let exists = fs.is_file(&PathBuf::from(expanded.clone())).await;
312
313 Ok(proto::CheckFileExistsResponse {
314 exists,
315 path: expanded,
316 })
317 }
318}