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 = BufferStore::local(worktree_store.clone(), cx);
54 buffer_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
55 buffer_store
56 });
57 let prettier_store = cx.new_model(|cx| {
58 PrettierStore::new(
59 NodeRuntime::unavailable(),
60 fs.clone(),
61 languages.clone(),
62 worktree_store.clone(),
63 cx,
64 )
65 });
66
67 let settings_observer = cx.new_model(|cx| {
68 let mut observer = SettingsObserver::new_local(fs.clone(), worktree_store.clone(), cx);
69 observer.shared(SSH_PROJECT_ID, session.clone().into(), cx);
70 observer
71 });
72 let environment = project::ProjectEnvironment::new(&worktree_store, None, cx);
73 let lsp_store = cx.new_model(|cx| {
74 let mut lsp_store = LspStore::new_local(
75 buffer_store.clone(),
76 worktree_store.clone(),
77 prettier_store.clone(),
78 environment,
79 languages.clone(),
80 None,
81 fs.clone(),
82 cx,
83 );
84 lsp_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
85 lsp_store
86 });
87
88 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
89
90 cx.subscribe(
91 &buffer_store,
92 |_this, _buffer_store, event, cx| match event {
93 BufferStoreEvent::BufferAdded(buffer) => {
94 cx.subscribe(buffer, Self::on_buffer_event).detach();
95 }
96 _ => {}
97 },
98 )
99 .detach();
100
101 let client: AnyProtoClient = session.clone().into();
102
103 session.subscribe_to_entity(SSH_PROJECT_ID, &worktree_store);
104 session.subscribe_to_entity(SSH_PROJECT_ID, &buffer_store);
105 session.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
106 session.subscribe_to_entity(SSH_PROJECT_ID, &lsp_store);
107 session.subscribe_to_entity(SSH_PROJECT_ID, &settings_observer);
108
109 client.add_request_handler(cx.weak_model(), Self::handle_list_remote_directory);
110 client.add_request_handler(cx.weak_model(), Self::handle_check_file_exists);
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 {
150 operation,
151 is_local: true,
152 } => cx
153 .background_executor()
154 .spawn(self.session.request(proto::UpdateBuffer {
155 project_id: SSH_PROJECT_ID,
156 buffer_id: buffer.read(cx).remote_id().to_proto(),
157 operations: vec![serialize_operation(operation)],
158 }))
159 .detach(),
160 _ => {}
161 }
162 }
163
164 fn on_lsp_store_event(
165 &mut self,
166 _lsp_store: Model<LspStore>,
167 event: &LspStoreEvent,
168 _cx: &mut ModelContext<Self>,
169 ) {
170 match event {
171 LspStoreEvent::LanguageServerUpdate {
172 language_server_id,
173 message,
174 } => {
175 self.session
176 .send(proto::UpdateLanguageServer {
177 project_id: SSH_PROJECT_ID,
178 language_server_id: language_server_id.to_proto(),
179 variant: Some(message.clone()),
180 })
181 .log_err();
182 }
183 _ => {}
184 }
185 }
186
187 pub async fn handle_add_worktree(
188 this: Model<Self>,
189 message: TypedEnvelope<proto::AddWorktree>,
190 mut cx: AsyncAppContext,
191 ) -> Result<proto::AddWorktreeResponse> {
192 let path = shellexpand::tilde(&message.payload.path).to_string();
193 let worktree = this
194 .update(&mut cx.clone(), |this, _| {
195 Worktree::local(
196 Path::new(&path),
197 true,
198 this.fs.clone(),
199 this.next_entry_id.clone(),
200 &mut cx,
201 )
202 })?
203 .await?;
204
205 this.update(&mut cx, |this, cx| {
206 this.worktree_store.update(cx, |worktree_store, cx| {
207 worktree_store.add(&worktree, cx);
208 });
209 worktree.update(cx, |worktree, _| proto::AddWorktreeResponse {
210 worktree_id: worktree.id().to_proto(),
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
302 pub async fn handle_check_file_exists(
303 this: Model<Self>,
304 envelope: TypedEnvelope<proto::CheckFileExists>,
305 cx: AsyncAppContext,
306 ) -> Result<proto::CheckFileExistsResponse> {
307 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
308 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
309
310 let exists = fs.is_file(&PathBuf::from(expanded.clone())).await;
311
312 Ok(proto::CheckFileExistsResponse {
313 exists,
314 path: expanded,
315 })
316 }
317}