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_model_request_handler(Self::handle_open_buffer_by_path);
139 client.add_model_request_handler(Self::handle_find_search_candidates);
140
141 client.add_model_request_handler(BufferStore::handle_update_buffer);
142 client.add_model_message_handler(BufferStore::handle_close_buffer);
143
144 BufferStore::init(&client);
145 WorktreeStore::init(&client);
146 SettingsObserver::init(&client);
147 LspStore::init(&client);
148 TaskStore::init(Some(&client));
149
150 HeadlessProject {
151 session: client,
152 settings_observer,
153 fs,
154 worktree_store,
155 buffer_store,
156 lsp_store,
157 task_store,
158 next_entry_id: Default::default(),
159 languages,
160 }
161 }
162
163 fn on_buffer_event(
164 &mut self,
165 buffer: Model<Buffer>,
166 event: &BufferEvent,
167 cx: &mut ModelContext<Self>,
168 ) {
169 match event {
170 BufferEvent::Operation {
171 operation,
172 is_local: true,
173 } => cx
174 .background_executor()
175 .spawn(self.session.request(proto::UpdateBuffer {
176 project_id: SSH_PROJECT_ID,
177 buffer_id: buffer.read(cx).remote_id().to_proto(),
178 operations: vec![serialize_operation(operation)],
179 }))
180 .detach(),
181 _ => {}
182 }
183 }
184
185 fn on_lsp_store_event(
186 &mut self,
187 _lsp_store: Model<LspStore>,
188 event: &LspStoreEvent,
189 _cx: &mut ModelContext<Self>,
190 ) {
191 match event {
192 LspStoreEvent::LanguageServerUpdate {
193 language_server_id,
194 message,
195 } => {
196 self.session
197 .send(proto::UpdateLanguageServer {
198 project_id: SSH_PROJECT_ID,
199 language_server_id: language_server_id.to_proto(),
200 variant: Some(message.clone()),
201 })
202 .log_err();
203 }
204 _ => {}
205 }
206 }
207
208 pub async fn handle_add_worktree(
209 this: Model<Self>,
210 message: TypedEnvelope<proto::AddWorktree>,
211 mut cx: AsyncAppContext,
212 ) -> Result<proto::AddWorktreeResponse> {
213 use client::ErrorCodeExt;
214 let path = shellexpand::tilde(&message.payload.path).to_string();
215
216 let fs = this.read_with(&mut cx, |this, _| this.fs.clone())?;
217 let path = PathBuf::from(path);
218
219 let canonicalized = match fs.canonicalize(&path).await {
220 Ok(path) => path,
221 Err(e) => {
222 let mut parent = path
223 .parent()
224 .ok_or(e)
225 .map_err(|_| anyhow!("{:?} does not exist", path))?;
226 if parent == Path::new("") {
227 parent = util::paths::home_dir();
228 }
229 let parent = fs.canonicalize(parent).await.map_err(|_| {
230 anyhow!(proto::ErrorCode::DevServerProjectPathDoesNotExist
231 .with_tag("path", &path.to_string_lossy().as_ref()))
232 })?;
233 parent.join(path.file_name().unwrap())
234 }
235 };
236
237 let worktree = this
238 .update(&mut cx.clone(), |this, _| {
239 Worktree::local(
240 Arc::from(canonicalized),
241 true,
242 this.fs.clone(),
243 this.next_entry_id.clone(),
244 &mut cx,
245 )
246 })?
247 .await?;
248
249 this.update(&mut cx, |this, cx| {
250 this.worktree_store.update(cx, |worktree_store, cx| {
251 worktree_store.add(&worktree, cx);
252 });
253 worktree.update(cx, |worktree, _| proto::AddWorktreeResponse {
254 worktree_id: worktree.id().to_proto(),
255 })
256 })
257 }
258
259 pub async fn handle_open_buffer_by_path(
260 this: Model<Self>,
261 message: TypedEnvelope<proto::OpenBufferByPath>,
262 mut cx: AsyncAppContext,
263 ) -> Result<proto::OpenBufferResponse> {
264 let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
265 let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
266 let buffer_store = this.buffer_store.clone();
267 let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
268 buffer_store.open_buffer(
269 ProjectPath {
270 worktree_id,
271 path: PathBuf::from(message.payload.path).into(),
272 },
273 cx,
274 )
275 });
276 anyhow::Ok((buffer_store, buffer))
277 })??;
278
279 let buffer = buffer.await?;
280 let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
281 buffer_store.update(&mut cx, |buffer_store, cx| {
282 buffer_store
283 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
284 .detach_and_log_err(cx);
285 })?;
286
287 Ok(proto::OpenBufferResponse {
288 buffer_id: buffer_id.to_proto(),
289 })
290 }
291
292 pub async fn handle_find_search_candidates(
293 this: Model<Self>,
294 envelope: TypedEnvelope<proto::FindSearchCandidates>,
295 mut cx: AsyncAppContext,
296 ) -> Result<proto::FindSearchCandidatesResponse> {
297 let message = envelope.payload;
298 let query = SearchQuery::from_proto(
299 message
300 .query
301 .ok_or_else(|| anyhow!("missing query field"))?,
302 )?;
303 let mut results = this.update(&mut cx, |this, cx| {
304 this.buffer_store.update(cx, |buffer_store, cx| {
305 buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
306 })
307 })?;
308
309 let mut response = proto::FindSearchCandidatesResponse {
310 buffer_ids: Vec::new(),
311 };
312
313 let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
314
315 while let Some(buffer) = results.next().await {
316 let buffer_id = buffer.update(&mut cx, |this, _| this.remote_id())?;
317 response.buffer_ids.push(buffer_id.to_proto());
318 buffer_store
319 .update(&mut cx, |buffer_store, cx| {
320 buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
321 })?
322 .await?;
323 }
324
325 Ok(response)
326 }
327
328 pub async fn handle_list_remote_directory(
329 this: Model<Self>,
330 envelope: TypedEnvelope<proto::ListRemoteDirectory>,
331 cx: AsyncAppContext,
332 ) -> Result<proto::ListRemoteDirectoryResponse> {
333 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
334 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
335
336 let mut entries = Vec::new();
337 let mut response = fs.read_dir(Path::new(&expanded)).await?;
338 while let Some(path) = response.next().await {
339 if let Some(file_name) = path?.file_name() {
340 entries.push(file_name.to_string_lossy().to_string());
341 }
342 }
343 Ok(proto::ListRemoteDirectoryResponse { entries })
344 }
345
346 pub async fn handle_check_file_exists(
347 this: Model<Self>,
348 envelope: TypedEnvelope<proto::CheckFileExists>,
349 cx: AsyncAppContext,
350 ) -> Result<proto::CheckFileExistsResponse> {
351 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
352 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
353
354 let exists = fs.is_file(&PathBuf::from(expanded.clone())).await;
355
356 Ok(proto::CheckFileExistsResponse {
357 exists,
358 path: expanded,
359 })
360 }
361
362 pub async fn handle_shutdown_remote_server(
363 _this: Model<Self>,
364 _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
365 cx: AsyncAppContext,
366 ) -> Result<proto::Ack> {
367 cx.spawn(|cx| async move {
368 cx.update(|cx| {
369 // TODO: This is a hack, because in a headless project, shutdown isn't executed
370 // when calling quit, but it should be.
371 cx.shutdown();
372 cx.quit();
373 })
374 })
375 .detach();
376
377 Ok(proto::Ack {})
378 }
379
380 pub async fn handle_ping(
381 _this: Model<Self>,
382 _envelope: TypedEnvelope<proto::Ping>,
383 _cx: AsyncAppContext,
384 ) -> Result<proto::Ack> {
385 log::debug!("Received ping from client");
386 Ok(proto::Ack {})
387 }
388}