1mod db;
2pub mod fs;
3mod ignore;
4mod lsp_command;
5pub mod search;
6pub mod worktree;
7
8#[cfg(test)]
9mod project_tests;
10
11use anyhow::{anyhow, Context, Result};
12use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
13use clock::ReplicaId;
14use collections::{hash_map, BTreeMap, HashMap, HashSet};
15use futures::{future::Shared, AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt};
16use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
17use gpui::{
18 AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
19 MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
20};
21use language::{
22 point_to_lsp,
23 proto::{
24 deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
25 serialize_version,
26 },
27 range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CharKind, CodeAction, CodeLabel,
28 Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _,
29 Language, LanguageRegistry, LanguageServerName, LineEnding, LocalFile, LspAdapter,
30 OffsetRangeExt, Operation, Patch, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16,
31 Transaction,
32};
33use lsp::{
34 DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer, LanguageString,
35 MarkedString,
36};
37use lsp_command::*;
38use parking_lot::Mutex;
39use postage::stream::Stream;
40use postage::watch;
41use rand::prelude::*;
42use search::SearchQuery;
43use serde::Serialize;
44use settings::Settings;
45use sha2::{Digest, Sha256};
46use similar::{ChangeTag, TextDiff};
47use std::{
48 cell::RefCell,
49 cmp::{self, Ordering},
50 convert::TryInto,
51 ffi::OsString,
52 hash::Hash,
53 mem,
54 num::NonZeroU32,
55 ops::Range,
56 os::unix::{ffi::OsStrExt, prelude::OsStringExt},
57 path::{Component, Path, PathBuf},
58 rc::Rc,
59 str,
60 sync::{
61 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
62 Arc,
63 },
64 time::Instant,
65};
66use thiserror::Error;
67use util::{post_inc, ResultExt, TryFutureExt as _};
68
69pub use db::Db;
70pub use fs::*;
71pub use worktree::*;
72
73pub trait Item: Entity {
74 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
75}
76
77pub struct ProjectStore {
78 db: Arc<Db>,
79 projects: Vec<WeakModelHandle<Project>>,
80}
81
82// Language server state is stored across 3 collections:
83// language_servers =>
84// a mapping from unique server id to LanguageServerState which can either be a task for a
85// server in the process of starting, or a running server with adapter and language server arcs
86// language_server_ids => a mapping from worktreeId and server name to the unique server id
87// language_server_statuses => a mapping from unique server id to the current server status
88//
89// Multiple worktrees can map to the same language server for example when you jump to the definition
90// of a file in the standard library. So language_server_ids is used to look up which server is active
91// for a given worktree and language server name
92//
93// When starting a language server, first the id map is checked to make sure a server isn't already available
94// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
95// the Starting variant of LanguageServerState is stored in the language_servers map.
96pub struct Project {
97 worktrees: Vec<WorktreeHandle>,
98 active_entry: Option<ProjectEntryId>,
99 languages: Arc<LanguageRegistry>,
100 language_servers: HashMap<usize, LanguageServerState>,
101 language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
102 language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
103 language_server_settings: Arc<Mutex<serde_json::Value>>,
104 last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
105 next_language_server_id: usize,
106 client: Arc<client::Client>,
107 next_entry_id: Arc<AtomicUsize>,
108 next_diagnostic_group_id: usize,
109 user_store: ModelHandle<UserStore>,
110 project_store: ModelHandle<ProjectStore>,
111 fs: Arc<dyn Fs>,
112 client_state: ProjectClientState,
113 collaborators: HashMap<PeerId, Collaborator>,
114 client_subscriptions: Vec<client::Subscription>,
115 _subscriptions: Vec<gpui::Subscription>,
116 opened_buffer: (Rc<RefCell<watch::Sender<()>>>, watch::Receiver<()>),
117 shared_buffers: HashMap<PeerId, HashSet<u64>>,
118 loading_buffers: HashMap<
119 ProjectPath,
120 postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
121 >,
122 loading_local_worktrees:
123 HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
124 opened_buffers: HashMap<u64, OpenBuffer>,
125 buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
126 nonce: u128,
127 initialized_persistent_state: bool,
128 _maintain_buffer_languages: Task<()>,
129}
130
131#[derive(Error, Debug)]
132pub enum JoinProjectError {
133 #[error("host declined join request")]
134 HostDeclined,
135 #[error("host closed the project")]
136 HostClosedProject,
137 #[error("host went offline")]
138 HostWentOffline,
139 #[error("{0}")]
140 Other(#[from] anyhow::Error),
141}
142
143enum OpenBuffer {
144 Strong(ModelHandle<Buffer>),
145 Weak(WeakModelHandle<Buffer>),
146 Loading(Vec<Operation>),
147}
148
149enum WorktreeHandle {
150 Strong(ModelHandle<Worktree>),
151 Weak(WeakModelHandle<Worktree>),
152}
153
154enum ProjectClientState {
155 Local {
156 is_shared: bool,
157 remote_id_tx: watch::Sender<Option<u64>>,
158 remote_id_rx: watch::Receiver<Option<u64>>,
159 online_tx: watch::Sender<bool>,
160 online_rx: watch::Receiver<bool>,
161 _maintain_remote_id: Task<Option<()>>,
162 _maintain_online_status: Task<Option<()>>,
163 },
164 Remote {
165 sharing_has_stopped: bool,
166 remote_id: u64,
167 replica_id: ReplicaId,
168 _detect_unshare: Task<Option<()>>,
169 },
170}
171
172#[derive(Clone, Debug)]
173pub struct Collaborator {
174 pub user: Arc<User>,
175 pub peer_id: PeerId,
176 pub replica_id: ReplicaId,
177}
178
179#[derive(Clone, Debug, PartialEq, Eq)]
180pub enum Event {
181 ActiveEntryChanged(Option<ProjectEntryId>),
182 WorktreeAdded,
183 WorktreeRemoved(WorktreeId),
184 DiskBasedDiagnosticsStarted {
185 language_server_id: usize,
186 },
187 DiskBasedDiagnosticsFinished {
188 language_server_id: usize,
189 },
190 DiagnosticsUpdated {
191 path: ProjectPath,
192 language_server_id: usize,
193 },
194 RemoteIdChanged(Option<u64>),
195 CollaboratorLeft(PeerId),
196 ContactRequestedJoin(Arc<User>),
197 ContactCancelledJoinRequest(Arc<User>),
198}
199
200pub enum LanguageServerState {
201 Starting(Task<Option<Arc<LanguageServer>>>),
202 Running {
203 adapter: Arc<LspAdapter>,
204 server: Arc<LanguageServer>,
205 },
206}
207
208#[derive(Serialize)]
209pub struct LanguageServerStatus {
210 pub name: String,
211 pub pending_work: BTreeMap<String, LanguageServerProgress>,
212 pub has_pending_diagnostic_updates: bool,
213 progress_tokens: HashSet<String>,
214}
215
216#[derive(Clone, Debug, Serialize)]
217pub struct LanguageServerProgress {
218 pub message: Option<String>,
219 pub percentage: Option<usize>,
220 #[serde(skip_serializing)]
221 pub last_update_at: Instant,
222}
223
224#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
225pub struct ProjectPath {
226 pub worktree_id: WorktreeId,
227 pub path: Arc<Path>,
228}
229
230#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
231pub struct DiagnosticSummary {
232 pub language_server_id: usize,
233 pub error_count: usize,
234 pub warning_count: usize,
235}
236
237#[derive(Debug, Clone)]
238pub struct Location {
239 pub buffer: ModelHandle<Buffer>,
240 pub range: Range<language::Anchor>,
241}
242
243#[derive(Debug, Clone)]
244pub struct LocationLink {
245 pub origin: Option<Location>,
246 pub target: Location,
247}
248
249#[derive(Debug)]
250pub struct DocumentHighlight {
251 pub range: Range<language::Anchor>,
252 pub kind: DocumentHighlightKind,
253}
254
255#[derive(Clone, Debug)]
256pub struct Symbol {
257 pub source_worktree_id: WorktreeId,
258 pub worktree_id: WorktreeId,
259 pub language_server_name: LanguageServerName,
260 pub path: PathBuf,
261 pub label: CodeLabel,
262 pub name: String,
263 pub kind: lsp::SymbolKind,
264 pub range: Range<PointUtf16>,
265 pub signature: [u8; 32],
266}
267
268#[derive(Clone, Debug, PartialEq)]
269pub struct HoverBlock {
270 pub text: String,
271 pub language: Option<String>,
272}
273
274impl HoverBlock {
275 fn try_new(marked_string: MarkedString) -> Option<Self> {
276 let result = match marked_string {
277 MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
278 text: value,
279 language: Some(language),
280 },
281 MarkedString::String(text) => HoverBlock {
282 text,
283 language: None,
284 },
285 };
286 if result.text.is_empty() {
287 None
288 } else {
289 Some(result)
290 }
291 }
292}
293
294#[derive(Debug)]
295pub struct Hover {
296 pub contents: Vec<HoverBlock>,
297 pub range: Option<Range<language::Anchor>>,
298}
299
300#[derive(Default)]
301pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
302
303impl DiagnosticSummary {
304 fn new<'a, T: 'a>(
305 language_server_id: usize,
306 diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
307 ) -> Self {
308 let mut this = Self {
309 language_server_id,
310 error_count: 0,
311 warning_count: 0,
312 };
313
314 for entry in diagnostics {
315 if entry.diagnostic.is_primary {
316 match entry.diagnostic.severity {
317 DiagnosticSeverity::ERROR => this.error_count += 1,
318 DiagnosticSeverity::WARNING => this.warning_count += 1,
319 _ => {}
320 }
321 }
322 }
323
324 this
325 }
326
327 pub fn is_empty(&self) -> bool {
328 self.error_count == 0 && self.warning_count == 0
329 }
330
331 pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
332 proto::DiagnosticSummary {
333 path: path.to_string_lossy().to_string(),
334 language_server_id: self.language_server_id as u64,
335 error_count: self.error_count as u32,
336 warning_count: self.warning_count as u32,
337 }
338 }
339}
340
341#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
342pub struct ProjectEntryId(usize);
343
344impl ProjectEntryId {
345 pub const MAX: Self = Self(usize::MAX);
346
347 pub fn new(counter: &AtomicUsize) -> Self {
348 Self(counter.fetch_add(1, SeqCst))
349 }
350
351 pub fn from_proto(id: u64) -> Self {
352 Self(id as usize)
353 }
354
355 pub fn to_proto(&self) -> u64 {
356 self.0 as u64
357 }
358
359 pub fn to_usize(&self) -> usize {
360 self.0
361 }
362}
363
364impl Project {
365 pub fn init(client: &Arc<Client>) {
366 client.add_model_message_handler(Self::handle_request_join_project);
367 client.add_model_message_handler(Self::handle_add_collaborator);
368 client.add_model_message_handler(Self::handle_buffer_reloaded);
369 client.add_model_message_handler(Self::handle_buffer_saved);
370 client.add_model_message_handler(Self::handle_start_language_server);
371 client.add_model_message_handler(Self::handle_update_language_server);
372 client.add_model_message_handler(Self::handle_remove_collaborator);
373 client.add_model_message_handler(Self::handle_join_project_request_cancelled);
374 client.add_model_message_handler(Self::handle_update_project);
375 client.add_model_message_handler(Self::handle_unregister_project);
376 client.add_model_message_handler(Self::handle_project_unshared);
377 client.add_model_message_handler(Self::handle_update_buffer_file);
378 client.add_model_message_handler(Self::handle_update_buffer);
379 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
380 client.add_model_message_handler(Self::handle_update_worktree);
381 client.add_model_request_handler(Self::handle_create_project_entry);
382 client.add_model_request_handler(Self::handle_rename_project_entry);
383 client.add_model_request_handler(Self::handle_copy_project_entry);
384 client.add_model_request_handler(Self::handle_delete_project_entry);
385 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
386 client.add_model_request_handler(Self::handle_apply_code_action);
387 client.add_model_request_handler(Self::handle_reload_buffers);
388 client.add_model_request_handler(Self::handle_format_buffers);
389 client.add_model_request_handler(Self::handle_get_code_actions);
390 client.add_model_request_handler(Self::handle_get_completions);
391 client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
392 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
393 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
394 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
395 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
396 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
397 client.add_model_request_handler(Self::handle_search_project);
398 client.add_model_request_handler(Self::handle_get_project_symbols);
399 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
400 client.add_model_request_handler(Self::handle_open_buffer_by_id);
401 client.add_model_request_handler(Self::handle_open_buffer_by_path);
402 client.add_model_request_handler(Self::handle_save_buffer);
403 }
404
405 pub fn local(
406 online: bool,
407 client: Arc<Client>,
408 user_store: ModelHandle<UserStore>,
409 project_store: ModelHandle<ProjectStore>,
410 languages: Arc<LanguageRegistry>,
411 fs: Arc<dyn Fs>,
412 cx: &mut MutableAppContext,
413 ) -> ModelHandle<Self> {
414 cx.add_model(|cx: &mut ModelContext<Self>| {
415 let (remote_id_tx, remote_id_rx) = watch::channel();
416 let _maintain_remote_id = cx.spawn_weak({
417 let mut status_rx = client.clone().status();
418 move |this, mut cx| async move {
419 while let Some(status) = status_rx.recv().await {
420 let this = this.upgrade(&cx)?;
421 if status.is_connected() {
422 this.update(&mut cx, |this, cx| this.register(cx))
423 .await
424 .log_err()?;
425 } else {
426 this.update(&mut cx, |this, cx| this.unregister(cx))
427 .await
428 .log_err();
429 }
430 }
431 None
432 }
433 });
434
435 let (online_tx, online_rx) = watch::channel_with(online);
436 let _maintain_online_status = cx.spawn_weak({
437 let mut online_rx = online_rx.clone();
438 move |this, mut cx| async move {
439 while let Some(online) = online_rx.recv().await {
440 let this = this.upgrade(&cx)?;
441 this.update(&mut cx, |this, cx| {
442 if !online {
443 this.unshared(cx);
444 }
445 this.metadata_changed(false, cx)
446 });
447 }
448 None
449 }
450 });
451
452 let handle = cx.weak_handle();
453 project_store.update(cx, |store, cx| store.add_project(handle, cx));
454
455 let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
456 Self {
457 worktrees: Default::default(),
458 collaborators: Default::default(),
459 opened_buffers: Default::default(),
460 shared_buffers: Default::default(),
461 loading_buffers: Default::default(),
462 loading_local_worktrees: Default::default(),
463 buffer_snapshots: Default::default(),
464 client_state: ProjectClientState::Local {
465 is_shared: false,
466 remote_id_tx,
467 remote_id_rx,
468 online_tx,
469 online_rx,
470 _maintain_remote_id,
471 _maintain_online_status,
472 },
473 opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
474 client_subscriptions: Vec::new(),
475 _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
476 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
477 active_entry: None,
478 languages,
479 client,
480 user_store,
481 project_store,
482 fs,
483 next_entry_id: Default::default(),
484 next_diagnostic_group_id: Default::default(),
485 language_servers: Default::default(),
486 language_server_ids: Default::default(),
487 language_server_statuses: Default::default(),
488 last_workspace_edits_by_language_server: Default::default(),
489 language_server_settings: Default::default(),
490 next_language_server_id: 0,
491 nonce: StdRng::from_entropy().gen(),
492 initialized_persistent_state: false,
493 }
494 })
495 }
496
497 pub async fn remote(
498 remote_id: u64,
499 client: Arc<Client>,
500 user_store: ModelHandle<UserStore>,
501 project_store: ModelHandle<ProjectStore>,
502 languages: Arc<LanguageRegistry>,
503 fs: Arc<dyn Fs>,
504 mut cx: AsyncAppContext,
505 ) -> Result<ModelHandle<Self>, JoinProjectError> {
506 client.authenticate_and_connect(true, &cx).await?;
507
508 let response = client
509 .request(proto::JoinProject {
510 project_id: remote_id,
511 })
512 .await?;
513
514 let response = match response.variant.ok_or_else(|| anyhow!("missing variant"))? {
515 proto::join_project_response::Variant::Accept(response) => response,
516 proto::join_project_response::Variant::Decline(decline) => {
517 match proto::join_project_response::decline::Reason::from_i32(decline.reason) {
518 Some(proto::join_project_response::decline::Reason::Declined) => {
519 Err(JoinProjectError::HostDeclined)?
520 }
521 Some(proto::join_project_response::decline::Reason::Closed) => {
522 Err(JoinProjectError::HostClosedProject)?
523 }
524 Some(proto::join_project_response::decline::Reason::WentOffline) => {
525 Err(JoinProjectError::HostWentOffline)?
526 }
527 None => Err(anyhow!("missing decline reason"))?,
528 }
529 }
530 };
531
532 let replica_id = response.replica_id as ReplicaId;
533
534 let mut worktrees = Vec::new();
535 for worktree in response.worktrees {
536 let worktree = cx
537 .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
538 worktrees.push(worktree);
539 }
540
541 let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
542 let this = cx.add_model(|cx: &mut ModelContext<Self>| {
543 let handle = cx.weak_handle();
544 project_store.update(cx, |store, cx| store.add_project(handle, cx));
545
546 let mut this = Self {
547 worktrees: Vec::new(),
548 loading_buffers: Default::default(),
549 opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
550 shared_buffers: Default::default(),
551 loading_local_worktrees: Default::default(),
552 active_entry: None,
553 collaborators: Default::default(),
554 _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
555 languages,
556 user_store: user_store.clone(),
557 project_store,
558 fs,
559 next_entry_id: Default::default(),
560 next_diagnostic_group_id: Default::default(),
561 client_subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
562 _subscriptions: Default::default(),
563 client: client.clone(),
564 client_state: ProjectClientState::Remote {
565 sharing_has_stopped: false,
566 remote_id,
567 replica_id,
568 _detect_unshare: cx.spawn_weak(move |this, mut cx| {
569 async move {
570 let mut status = client.status();
571 let is_connected =
572 status.next().await.map_or(false, |s| s.is_connected());
573 // Even if we're initially connected, any future change of the status means we momentarily disconnected.
574 if !is_connected || status.next().await.is_some() {
575 if let Some(this) = this.upgrade(&cx) {
576 this.update(&mut cx, |this, cx| this.removed_from_project(cx))
577 }
578 }
579 Ok(())
580 }
581 .log_err()
582 }),
583 },
584 language_servers: Default::default(),
585 language_server_ids: Default::default(),
586 language_server_settings: Default::default(),
587 language_server_statuses: response
588 .language_servers
589 .into_iter()
590 .map(|server| {
591 (
592 server.id as usize,
593 LanguageServerStatus {
594 name: server.name,
595 pending_work: Default::default(),
596 has_pending_diagnostic_updates: false,
597 progress_tokens: Default::default(),
598 },
599 )
600 })
601 .collect(),
602 last_workspace_edits_by_language_server: Default::default(),
603 next_language_server_id: 0,
604 opened_buffers: Default::default(),
605 buffer_snapshots: Default::default(),
606 nonce: StdRng::from_entropy().gen(),
607 initialized_persistent_state: false,
608 };
609 for worktree in worktrees {
610 this.add_worktree(&worktree, cx);
611 }
612 this
613 });
614
615 let user_ids = response
616 .collaborators
617 .iter()
618 .map(|peer| peer.user_id)
619 .collect();
620 user_store
621 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
622 .await?;
623 let mut collaborators = HashMap::default();
624 for message in response.collaborators {
625 let collaborator = Collaborator::from_proto(message, &user_store, &mut cx).await?;
626 collaborators.insert(collaborator.peer_id, collaborator);
627 }
628
629 this.update(&mut cx, |this, _| {
630 this.collaborators = collaborators;
631 });
632
633 Ok(this)
634 }
635
636 #[cfg(any(test, feature = "test-support"))]
637 pub async fn test(
638 fs: Arc<dyn Fs>,
639 root_paths: impl IntoIterator<Item = &Path>,
640 cx: &mut gpui::TestAppContext,
641 ) -> ModelHandle<Project> {
642 if !cx.read(|cx| cx.has_global::<Settings>()) {
643 cx.update(|cx| cx.set_global(Settings::test(cx)));
644 }
645
646 let languages = Arc::new(LanguageRegistry::test());
647 let http_client = client::test::FakeHttpClient::with_404_response();
648 let client = client::Client::new(http_client.clone());
649 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
650 let project_store = cx.add_model(|_| ProjectStore::new(Db::open_fake()));
651 let project = cx.update(|cx| {
652 Project::local(true, client, user_store, project_store, languages, fs, cx)
653 });
654 for path in root_paths {
655 let (tree, _) = project
656 .update(cx, |project, cx| {
657 project.find_or_create_local_worktree(path, true, cx)
658 })
659 .await
660 .unwrap();
661 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
662 .await;
663 }
664 project
665 }
666
667 pub fn restore_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
668 if self.is_remote() {
669 return Task::ready(Ok(()));
670 }
671
672 let db = self.project_store.read(cx).db.clone();
673 let keys = self.db_keys_for_online_state(cx);
674 let online_by_default = cx.global::<Settings>().projects_online_by_default;
675 let read_online = cx.background().spawn(async move {
676 let values = db.read(keys)?;
677 anyhow::Ok(
678 values
679 .into_iter()
680 .all(|e| e.map_or(online_by_default, |e| e == [true as u8])),
681 )
682 });
683 cx.spawn(|this, mut cx| async move {
684 let online = read_online.await.log_err().unwrap_or(false);
685 this.update(&mut cx, |this, cx| {
686 this.initialized_persistent_state = true;
687 if let ProjectClientState::Local { online_tx, .. } = &mut this.client_state {
688 let mut online_tx = online_tx.borrow_mut();
689 if *online_tx != online {
690 *online_tx = online;
691 drop(online_tx);
692 this.metadata_changed(false, cx);
693 }
694 }
695 });
696 Ok(())
697 })
698 }
699
700 fn persist_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
701 if self.is_remote() || !self.initialized_persistent_state {
702 return Task::ready(Ok(()));
703 }
704
705 let db = self.project_store.read(cx).db.clone();
706 let keys = self.db_keys_for_online_state(cx);
707 let is_online = self.is_online();
708 cx.background().spawn(async move {
709 let value = &[is_online as u8];
710 db.write(keys.into_iter().map(|key| (key, value)))
711 })
712 }
713
714 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
715 let settings = cx.global::<Settings>();
716
717 let mut language_servers_to_start = Vec::new();
718 for buffer in self.opened_buffers.values() {
719 if let Some(buffer) = buffer.upgrade(cx) {
720 let buffer = buffer.read(cx);
721 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
722 {
723 if settings.enable_language_server(Some(&language.name())) {
724 let worktree = file.worktree.read(cx);
725 language_servers_to_start.push((
726 worktree.id(),
727 worktree.as_local().unwrap().abs_path().clone(),
728 language.clone(),
729 ));
730 }
731 }
732 }
733 }
734
735 let mut language_servers_to_stop = Vec::new();
736 for language in self.languages.to_vec() {
737 if let Some(lsp_adapter) = language.lsp_adapter() {
738 if !settings.enable_language_server(Some(&language.name())) {
739 let lsp_name = &lsp_adapter.name;
740 for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
741 if lsp_name == started_lsp_name {
742 language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
743 }
744 }
745 }
746 }
747 }
748
749 // Stop all newly-disabled language servers.
750 for (worktree_id, adapter_name) in language_servers_to_stop {
751 self.stop_language_server(worktree_id, adapter_name, cx)
752 .detach();
753 }
754
755 // Start all the newly-enabled language servers.
756 for (worktree_id, worktree_path, language) in language_servers_to_start {
757 self.start_language_server(worktree_id, worktree_path, language, cx);
758 }
759
760 cx.notify();
761 }
762
763 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
764 self.opened_buffers
765 .get(&remote_id)
766 .and_then(|buffer| buffer.upgrade(cx))
767 }
768
769 pub fn languages(&self) -> &Arc<LanguageRegistry> {
770 &self.languages
771 }
772
773 pub fn client(&self) -> Arc<Client> {
774 self.client.clone()
775 }
776
777 pub fn user_store(&self) -> ModelHandle<UserStore> {
778 self.user_store.clone()
779 }
780
781 pub fn project_store(&self) -> ModelHandle<ProjectStore> {
782 self.project_store.clone()
783 }
784
785 #[cfg(any(test, feature = "test-support"))]
786 pub fn check_invariants(&self, cx: &AppContext) {
787 if self.is_local() {
788 let mut worktree_root_paths = HashMap::default();
789 for worktree in self.worktrees(cx) {
790 let worktree = worktree.read(cx);
791 let abs_path = worktree.as_local().unwrap().abs_path().clone();
792 let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
793 assert_eq!(
794 prev_worktree_id,
795 None,
796 "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
797 abs_path,
798 worktree.id(),
799 prev_worktree_id
800 )
801 }
802 } else {
803 let replica_id = self.replica_id();
804 for buffer in self.opened_buffers.values() {
805 if let Some(buffer) = buffer.upgrade(cx) {
806 let buffer = buffer.read(cx);
807 assert_eq!(
808 buffer.deferred_ops_len(),
809 0,
810 "replica {}, buffer {} has deferred operations",
811 replica_id,
812 buffer.remote_id()
813 );
814 }
815 }
816 }
817 }
818
819 #[cfg(any(test, feature = "test-support"))]
820 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
821 let path = path.into();
822 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
823 self.opened_buffers.iter().any(|(_, buffer)| {
824 if let Some(buffer) = buffer.upgrade(cx) {
825 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
826 if file.worktree == worktree && file.path() == &path.path {
827 return true;
828 }
829 }
830 }
831 false
832 })
833 } else {
834 false
835 }
836 }
837
838 pub fn fs(&self) -> &Arc<dyn Fs> {
839 &self.fs
840 }
841
842 pub fn set_online(&mut self, online: bool, _: &mut ModelContext<Self>) {
843 if let ProjectClientState::Local { online_tx, .. } = &mut self.client_state {
844 let mut online_tx = online_tx.borrow_mut();
845 if *online_tx != online {
846 *online_tx = online;
847 }
848 }
849 }
850
851 pub fn is_online(&self) -> bool {
852 match &self.client_state {
853 ProjectClientState::Local { online_rx, .. } => *online_rx.borrow(),
854 ProjectClientState::Remote { .. } => true,
855 }
856 }
857
858 fn unregister(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
859 self.unshared(cx);
860 if let ProjectClientState::Local { remote_id_rx, .. } = &mut self.client_state {
861 if let Some(remote_id) = *remote_id_rx.borrow() {
862 let request = self.client.request(proto::UnregisterProject {
863 project_id: remote_id,
864 });
865 return cx.spawn(|this, mut cx| async move {
866 let response = request.await;
867
868 // Unregistering the project causes the server to send out a
869 // contact update removing this project from the host's list
870 // of online projects. Wait until this contact update has been
871 // processed before clearing out this project's remote id, so
872 // that there is no moment where this project appears in the
873 // contact metadata and *also* has no remote id.
874 this.update(&mut cx, |this, cx| {
875 this.user_store()
876 .update(cx, |store, _| store.contact_updates_done())
877 })
878 .await;
879
880 this.update(&mut cx, |this, cx| {
881 if let ProjectClientState::Local { remote_id_tx, .. } =
882 &mut this.client_state
883 {
884 *remote_id_tx.borrow_mut() = None;
885 }
886 this.client_subscriptions.clear();
887 this.metadata_changed(false, cx);
888 });
889 response.map(drop)
890 });
891 }
892 }
893 Task::ready(Ok(()))
894 }
895
896 fn register(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
897 if let ProjectClientState::Local {
898 remote_id_rx,
899 online_rx,
900 ..
901 } = &self.client_state
902 {
903 if remote_id_rx.borrow().is_some() {
904 return Task::ready(Ok(()));
905 }
906
907 let response = self.client.request(proto::RegisterProject {
908 online: *online_rx.borrow(),
909 });
910 cx.spawn(|this, mut cx| async move {
911 let remote_id = response.await?.project_id;
912 this.update(&mut cx, |this, cx| {
913 if let ProjectClientState::Local { remote_id_tx, .. } = &mut this.client_state {
914 *remote_id_tx.borrow_mut() = Some(remote_id);
915 }
916
917 this.metadata_changed(false, cx);
918 cx.emit(Event::RemoteIdChanged(Some(remote_id)));
919 this.client_subscriptions
920 .push(this.client.add_model_for_remote_entity(remote_id, cx));
921 Ok(())
922 })
923 })
924 } else {
925 Task::ready(Err(anyhow!("can't register a remote project")))
926 }
927 }
928
929 pub fn remote_id(&self) -> Option<u64> {
930 match &self.client_state {
931 ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
932 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
933 }
934 }
935
936 pub fn next_remote_id(&self) -> impl Future<Output = u64> {
937 let mut id = None;
938 let mut watch = None;
939 match &self.client_state {
940 ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
941 ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
942 }
943
944 async move {
945 if let Some(id) = id {
946 return id;
947 }
948 let mut watch = watch.unwrap();
949 loop {
950 let id = *watch.borrow();
951 if let Some(id) = id {
952 return id;
953 }
954 watch.next().await;
955 }
956 }
957 }
958
959 pub fn shared_remote_id(&self) -> Option<u64> {
960 match &self.client_state {
961 ProjectClientState::Local {
962 remote_id_rx,
963 is_shared,
964 ..
965 } => {
966 if *is_shared {
967 *remote_id_rx.borrow()
968 } else {
969 None
970 }
971 }
972 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
973 }
974 }
975
976 pub fn replica_id(&self) -> ReplicaId {
977 match &self.client_state {
978 ProjectClientState::Local { .. } => 0,
979 ProjectClientState::Remote { replica_id, .. } => *replica_id,
980 }
981 }
982
983 fn metadata_changed(&mut self, persist: bool, cx: &mut ModelContext<Self>) {
984 if let ProjectClientState::Local {
985 remote_id_rx,
986 online_rx,
987 ..
988 } = &self.client_state
989 {
990 // Broadcast worktrees only if the project is online.
991 let worktrees = if *online_rx.borrow() {
992 self.worktrees
993 .iter()
994 .filter_map(|worktree| {
995 worktree
996 .upgrade(&cx)
997 .map(|worktree| worktree.read(cx).as_local().unwrap().metadata_proto())
998 })
999 .collect()
1000 } else {
1001 Default::default()
1002 };
1003 if let Some(project_id) = *remote_id_rx.borrow() {
1004 let online = *online_rx.borrow();
1005 self.client
1006 .send(proto::UpdateProject {
1007 project_id,
1008 worktrees,
1009 online,
1010 })
1011 .log_err();
1012
1013 if online {
1014 let worktrees = self.visible_worktrees(cx).collect::<Vec<_>>();
1015 let scans_complete =
1016 futures::future::join_all(worktrees.iter().filter_map(|worktree| {
1017 Some(worktree.read(cx).as_local()?.scan_complete())
1018 }));
1019
1020 let worktrees = worktrees.into_iter().map(|handle| handle.downgrade());
1021 cx.spawn_weak(move |_, cx| async move {
1022 scans_complete.await;
1023 cx.read(|cx| {
1024 for worktree in worktrees {
1025 if let Some(worktree) = worktree
1026 .upgrade(cx)
1027 .and_then(|worktree| worktree.read(cx).as_local())
1028 {
1029 worktree.send_extension_counts(project_id);
1030 }
1031 }
1032 })
1033 })
1034 .detach();
1035 }
1036 }
1037
1038 self.project_store.update(cx, |_, cx| cx.notify());
1039 if persist {
1040 self.persist_state(cx).detach_and_log_err(cx);
1041 }
1042 cx.notify();
1043 }
1044 }
1045
1046 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
1047 &self.collaborators
1048 }
1049
1050 pub fn worktrees<'a>(
1051 &'a self,
1052 cx: &'a AppContext,
1053 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1054 self.worktrees
1055 .iter()
1056 .filter_map(move |worktree| worktree.upgrade(cx))
1057 }
1058
1059 pub fn visible_worktrees<'a>(
1060 &'a self,
1061 cx: &'a AppContext,
1062 ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1063 self.worktrees.iter().filter_map(|worktree| {
1064 worktree.upgrade(cx).and_then(|worktree| {
1065 if worktree.read(cx).is_visible() {
1066 Some(worktree)
1067 } else {
1068 None
1069 }
1070 })
1071 })
1072 }
1073
1074 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1075 self.visible_worktrees(cx)
1076 .map(|tree| tree.read(cx).root_name())
1077 }
1078
1079 fn db_keys_for_online_state(&self, cx: &AppContext) -> Vec<String> {
1080 self.worktrees
1081 .iter()
1082 .filter_map(|worktree| {
1083 let worktree = worktree.upgrade(&cx)?.read(cx);
1084 if worktree.is_visible() {
1085 Some(format!(
1086 "project-path-online:{}",
1087 worktree.as_local().unwrap().abs_path().to_string_lossy()
1088 ))
1089 } else {
1090 None
1091 }
1092 })
1093 .collect::<Vec<_>>()
1094 }
1095
1096 pub fn worktree_for_id(
1097 &self,
1098 id: WorktreeId,
1099 cx: &AppContext,
1100 ) -> Option<ModelHandle<Worktree>> {
1101 self.worktrees(cx)
1102 .find(|worktree| worktree.read(cx).id() == id)
1103 }
1104
1105 pub fn worktree_for_entry(
1106 &self,
1107 entry_id: ProjectEntryId,
1108 cx: &AppContext,
1109 ) -> Option<ModelHandle<Worktree>> {
1110 self.worktrees(cx)
1111 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1112 }
1113
1114 pub fn worktree_id_for_entry(
1115 &self,
1116 entry_id: ProjectEntryId,
1117 cx: &AppContext,
1118 ) -> Option<WorktreeId> {
1119 self.worktree_for_entry(entry_id, cx)
1120 .map(|worktree| worktree.read(cx).id())
1121 }
1122
1123 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1124 paths.iter().all(|path| self.contains_path(&path, cx))
1125 }
1126
1127 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1128 for worktree in self.worktrees(cx) {
1129 let worktree = worktree.read(cx).as_local();
1130 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1131 return true;
1132 }
1133 }
1134 false
1135 }
1136
1137 pub fn create_entry(
1138 &mut self,
1139 project_path: impl Into<ProjectPath>,
1140 is_directory: bool,
1141 cx: &mut ModelContext<Self>,
1142 ) -> Option<Task<Result<Entry>>> {
1143 let project_path = project_path.into();
1144 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1145 if self.is_local() {
1146 Some(worktree.update(cx, |worktree, cx| {
1147 worktree
1148 .as_local_mut()
1149 .unwrap()
1150 .create_entry(project_path.path, is_directory, cx)
1151 }))
1152 } else {
1153 let client = self.client.clone();
1154 let project_id = self.remote_id().unwrap();
1155 Some(cx.spawn_weak(|_, mut cx| async move {
1156 let response = client
1157 .request(proto::CreateProjectEntry {
1158 worktree_id: project_path.worktree_id.to_proto(),
1159 project_id,
1160 path: project_path.path.as_os_str().as_bytes().to_vec(),
1161 is_directory,
1162 })
1163 .await?;
1164 let entry = response
1165 .entry
1166 .ok_or_else(|| anyhow!("missing entry in response"))?;
1167 worktree
1168 .update(&mut cx, |worktree, cx| {
1169 worktree.as_remote_mut().unwrap().insert_entry(
1170 entry,
1171 response.worktree_scan_id as usize,
1172 cx,
1173 )
1174 })
1175 .await
1176 }))
1177 }
1178 }
1179
1180 pub fn copy_entry(
1181 &mut self,
1182 entry_id: ProjectEntryId,
1183 new_path: impl Into<Arc<Path>>,
1184 cx: &mut ModelContext<Self>,
1185 ) -> Option<Task<Result<Entry>>> {
1186 let worktree = self.worktree_for_entry(entry_id, cx)?;
1187 let new_path = new_path.into();
1188 if self.is_local() {
1189 worktree.update(cx, |worktree, cx| {
1190 worktree
1191 .as_local_mut()
1192 .unwrap()
1193 .copy_entry(entry_id, new_path, cx)
1194 })
1195 } else {
1196 let client = self.client.clone();
1197 let project_id = self.remote_id().unwrap();
1198
1199 Some(cx.spawn_weak(|_, mut cx| async move {
1200 let response = client
1201 .request(proto::CopyProjectEntry {
1202 project_id,
1203 entry_id: entry_id.to_proto(),
1204 new_path: new_path.as_os_str().as_bytes().to_vec(),
1205 })
1206 .await?;
1207 let entry = response
1208 .entry
1209 .ok_or_else(|| anyhow!("missing entry in response"))?;
1210 worktree
1211 .update(&mut cx, |worktree, cx| {
1212 worktree.as_remote_mut().unwrap().insert_entry(
1213 entry,
1214 response.worktree_scan_id as usize,
1215 cx,
1216 )
1217 })
1218 .await
1219 }))
1220 }
1221 }
1222
1223 pub fn rename_entry(
1224 &mut self,
1225 entry_id: ProjectEntryId,
1226 new_path: impl Into<Arc<Path>>,
1227 cx: &mut ModelContext<Self>,
1228 ) -> Option<Task<Result<Entry>>> {
1229 let worktree = self.worktree_for_entry(entry_id, cx)?;
1230 let new_path = new_path.into();
1231 if self.is_local() {
1232 worktree.update(cx, |worktree, cx| {
1233 worktree
1234 .as_local_mut()
1235 .unwrap()
1236 .rename_entry(entry_id, new_path, cx)
1237 })
1238 } else {
1239 let client = self.client.clone();
1240 let project_id = self.remote_id().unwrap();
1241
1242 Some(cx.spawn_weak(|_, mut cx| async move {
1243 let response = client
1244 .request(proto::RenameProjectEntry {
1245 project_id,
1246 entry_id: entry_id.to_proto(),
1247 new_path: new_path.as_os_str().as_bytes().to_vec(),
1248 })
1249 .await?;
1250 let entry = response
1251 .entry
1252 .ok_or_else(|| anyhow!("missing entry in response"))?;
1253 worktree
1254 .update(&mut cx, |worktree, cx| {
1255 worktree.as_remote_mut().unwrap().insert_entry(
1256 entry,
1257 response.worktree_scan_id as usize,
1258 cx,
1259 )
1260 })
1261 .await
1262 }))
1263 }
1264 }
1265
1266 pub fn delete_entry(
1267 &mut self,
1268 entry_id: ProjectEntryId,
1269 cx: &mut ModelContext<Self>,
1270 ) -> Option<Task<Result<()>>> {
1271 let worktree = self.worktree_for_entry(entry_id, cx)?;
1272 if self.is_local() {
1273 worktree.update(cx, |worktree, cx| {
1274 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1275 })
1276 } else {
1277 let client = self.client.clone();
1278 let project_id = self.remote_id().unwrap();
1279 Some(cx.spawn_weak(|_, mut cx| async move {
1280 let response = client
1281 .request(proto::DeleteProjectEntry {
1282 project_id,
1283 entry_id: entry_id.to_proto(),
1284 })
1285 .await?;
1286 worktree
1287 .update(&mut cx, move |worktree, cx| {
1288 worktree.as_remote_mut().unwrap().delete_entry(
1289 entry_id,
1290 response.worktree_scan_id as usize,
1291 cx,
1292 )
1293 })
1294 .await
1295 }))
1296 }
1297 }
1298
1299 fn share(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
1300 if !self.is_online() {
1301 return Task::ready(Err(anyhow!("can't share an offline project")));
1302 }
1303
1304 let project_id;
1305 if let ProjectClientState::Local {
1306 remote_id_rx,
1307 is_shared,
1308 ..
1309 } = &mut self.client_state
1310 {
1311 if *is_shared {
1312 return Task::ready(Ok(()));
1313 }
1314 *is_shared = true;
1315 if let Some(id) = *remote_id_rx.borrow() {
1316 project_id = id;
1317 } else {
1318 return Task::ready(Err(anyhow!("project hasn't been registered")));
1319 }
1320 } else {
1321 return Task::ready(Err(anyhow!("can't share a remote project")));
1322 };
1323
1324 for open_buffer in self.opened_buffers.values_mut() {
1325 match open_buffer {
1326 OpenBuffer::Strong(_) => {}
1327 OpenBuffer::Weak(buffer) => {
1328 if let Some(buffer) = buffer.upgrade(cx) {
1329 *open_buffer = OpenBuffer::Strong(buffer);
1330 }
1331 }
1332 OpenBuffer::Loading(_) => unreachable!(),
1333 }
1334 }
1335
1336 for worktree_handle in self.worktrees.iter_mut() {
1337 match worktree_handle {
1338 WorktreeHandle::Strong(_) => {}
1339 WorktreeHandle::Weak(worktree) => {
1340 if let Some(worktree) = worktree.upgrade(cx) {
1341 *worktree_handle = WorktreeHandle::Strong(worktree);
1342 }
1343 }
1344 }
1345 }
1346
1347 let mut tasks = Vec::new();
1348 for worktree in self.worktrees(cx).collect::<Vec<_>>() {
1349 worktree.update(cx, |worktree, cx| {
1350 let worktree = worktree.as_local_mut().unwrap();
1351 tasks.push(worktree.share(project_id, cx));
1352 });
1353 }
1354
1355 for (server_id, status) in &self.language_server_statuses {
1356 self.client
1357 .send(proto::StartLanguageServer {
1358 project_id,
1359 server: Some(proto::LanguageServer {
1360 id: *server_id as u64,
1361 name: status.name.clone(),
1362 }),
1363 })
1364 .log_err();
1365 }
1366
1367 cx.spawn(|this, mut cx| async move {
1368 for task in tasks {
1369 task.await?;
1370 }
1371 this.update(&mut cx, |_, cx| cx.notify());
1372 Ok(())
1373 })
1374 }
1375
1376 fn unshared(&mut self, cx: &mut ModelContext<Self>) {
1377 if let ProjectClientState::Local { is_shared, .. } = &mut self.client_state {
1378 if !*is_shared {
1379 return;
1380 }
1381
1382 *is_shared = false;
1383 self.collaborators.clear();
1384 self.shared_buffers.clear();
1385 for worktree_handle in self.worktrees.iter_mut() {
1386 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1387 let is_visible = worktree.update(cx, |worktree, _| {
1388 worktree.as_local_mut().unwrap().unshare();
1389 worktree.is_visible()
1390 });
1391 if !is_visible {
1392 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1393 }
1394 }
1395 }
1396
1397 for open_buffer in self.opened_buffers.values_mut() {
1398 match open_buffer {
1399 OpenBuffer::Strong(buffer) => {
1400 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1401 }
1402 _ => {}
1403 }
1404 }
1405
1406 cx.notify();
1407 } else {
1408 log::error!("attempted to unshare a remote project");
1409 }
1410 }
1411
1412 pub fn respond_to_join_request(
1413 &mut self,
1414 requester_id: u64,
1415 allow: bool,
1416 cx: &mut ModelContext<Self>,
1417 ) {
1418 if let Some(project_id) = self.remote_id() {
1419 let share = if self.is_online() && allow {
1420 Some(self.share(cx))
1421 } else {
1422 None
1423 };
1424 let client = self.client.clone();
1425 cx.foreground()
1426 .spawn(async move {
1427 client.send(proto::RespondToJoinProjectRequest {
1428 requester_id,
1429 project_id,
1430 allow,
1431 })?;
1432 if let Some(share) = share {
1433 share.await?;
1434 }
1435 anyhow::Ok(())
1436 })
1437 .detach_and_log_err(cx);
1438 }
1439 }
1440
1441 fn removed_from_project(&mut self, cx: &mut ModelContext<Self>) {
1442 if let ProjectClientState::Remote {
1443 sharing_has_stopped,
1444 ..
1445 } = &mut self.client_state
1446 {
1447 *sharing_has_stopped = true;
1448 self.collaborators.clear();
1449 for worktree in &self.worktrees {
1450 if let Some(worktree) = worktree.upgrade(cx) {
1451 worktree.update(cx, |worktree, _| {
1452 if let Some(worktree) = worktree.as_remote_mut() {
1453 worktree.disconnected_from_host();
1454 }
1455 });
1456 }
1457 }
1458 cx.notify();
1459 }
1460 }
1461
1462 pub fn is_read_only(&self) -> bool {
1463 match &self.client_state {
1464 ProjectClientState::Local { .. } => false,
1465 ProjectClientState::Remote {
1466 sharing_has_stopped,
1467 ..
1468 } => *sharing_has_stopped,
1469 }
1470 }
1471
1472 pub fn is_local(&self) -> bool {
1473 match &self.client_state {
1474 ProjectClientState::Local { .. } => true,
1475 ProjectClientState::Remote { .. } => false,
1476 }
1477 }
1478
1479 pub fn is_remote(&self) -> bool {
1480 !self.is_local()
1481 }
1482
1483 pub fn create_buffer(
1484 &mut self,
1485 text: &str,
1486 language: Option<Arc<Language>>,
1487 cx: &mut ModelContext<Self>,
1488 ) -> Result<ModelHandle<Buffer>> {
1489 if self.is_remote() {
1490 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1491 }
1492
1493 let buffer = cx.add_model(|cx| {
1494 Buffer::new(self.replica_id(), text, cx)
1495 .with_language(language.unwrap_or(language::PLAIN_TEXT.clone()), cx)
1496 });
1497 self.register_buffer(&buffer, cx)?;
1498 Ok(buffer)
1499 }
1500
1501 pub fn open_path(
1502 &mut self,
1503 path: impl Into<ProjectPath>,
1504 cx: &mut ModelContext<Self>,
1505 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1506 let task = self.open_buffer(path, cx);
1507 cx.spawn_weak(|_, cx| async move {
1508 let buffer = task.await?;
1509 let project_entry_id = buffer
1510 .read_with(&cx, |buffer, cx| {
1511 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1512 })
1513 .ok_or_else(|| anyhow!("no project entry"))?;
1514 Ok((project_entry_id, buffer.into()))
1515 })
1516 }
1517
1518 pub fn open_local_buffer(
1519 &mut self,
1520 abs_path: impl AsRef<Path>,
1521 cx: &mut ModelContext<Self>,
1522 ) -> Task<Result<ModelHandle<Buffer>>> {
1523 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1524 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1525 } else {
1526 Task::ready(Err(anyhow!("no such path")))
1527 }
1528 }
1529
1530 pub fn open_buffer(
1531 &mut self,
1532 path: impl Into<ProjectPath>,
1533 cx: &mut ModelContext<Self>,
1534 ) -> Task<Result<ModelHandle<Buffer>>> {
1535 let project_path = path.into();
1536 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1537 worktree
1538 } else {
1539 return Task::ready(Err(anyhow!("no such worktree")));
1540 };
1541
1542 // If there is already a buffer for the given path, then return it.
1543 let existing_buffer = self.get_open_buffer(&project_path, cx);
1544 if let Some(existing_buffer) = existing_buffer {
1545 return Task::ready(Ok(existing_buffer));
1546 }
1547
1548 let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1549 // If the given path is already being loaded, then wait for that existing
1550 // task to complete and return the same buffer.
1551 hash_map::Entry::Occupied(e) => e.get().clone(),
1552
1553 // Otherwise, record the fact that this path is now being loaded.
1554 hash_map::Entry::Vacant(entry) => {
1555 let (mut tx, rx) = postage::watch::channel();
1556 entry.insert(rx.clone());
1557
1558 let load_buffer = if worktree.read(cx).is_local() {
1559 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1560 } else {
1561 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1562 };
1563
1564 cx.spawn(move |this, mut cx| async move {
1565 let load_result = load_buffer.await;
1566 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1567 // Record the fact that the buffer is no longer loading.
1568 this.loading_buffers.remove(&project_path);
1569 let buffer = load_result.map_err(Arc::new)?;
1570 Ok(buffer)
1571 }));
1572 })
1573 .detach();
1574 rx
1575 }
1576 };
1577
1578 cx.foreground().spawn(async move {
1579 loop {
1580 if let Some(result) = loading_watch.borrow().as_ref() {
1581 match result {
1582 Ok(buffer) => return Ok(buffer.clone()),
1583 Err(error) => return Err(anyhow!("{}", error)),
1584 }
1585 }
1586 loading_watch.next().await;
1587 }
1588 })
1589 }
1590
1591 fn open_local_buffer_internal(
1592 &mut self,
1593 path: &Arc<Path>,
1594 worktree: &ModelHandle<Worktree>,
1595 cx: &mut ModelContext<Self>,
1596 ) -> Task<Result<ModelHandle<Buffer>>> {
1597 let load_buffer = worktree.update(cx, |worktree, cx| {
1598 let worktree = worktree.as_local_mut().unwrap();
1599 worktree.load_buffer(path, cx)
1600 });
1601 cx.spawn(|this, mut cx| async move {
1602 let buffer = load_buffer.await?;
1603 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1604 Ok(buffer)
1605 })
1606 }
1607
1608 fn open_remote_buffer_internal(
1609 &mut self,
1610 path: &Arc<Path>,
1611 worktree: &ModelHandle<Worktree>,
1612 cx: &mut ModelContext<Self>,
1613 ) -> Task<Result<ModelHandle<Buffer>>> {
1614 let rpc = self.client.clone();
1615 let project_id = self.remote_id().unwrap();
1616 let remote_worktree_id = worktree.read(cx).id();
1617 let path = path.clone();
1618 let path_string = path.to_string_lossy().to_string();
1619 cx.spawn(|this, mut cx| async move {
1620 let response = rpc
1621 .request(proto::OpenBufferByPath {
1622 project_id,
1623 worktree_id: remote_worktree_id.to_proto(),
1624 path: path_string,
1625 })
1626 .await?;
1627 let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
1628 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1629 .await
1630 })
1631 }
1632
1633 /// LanguageServerName is owned, because it is inserted into a map
1634 fn open_local_buffer_via_lsp(
1635 &mut self,
1636 abs_path: lsp::Url,
1637 language_server_id: usize,
1638 language_server_name: LanguageServerName,
1639 cx: &mut ModelContext<Self>,
1640 ) -> Task<Result<ModelHandle<Buffer>>> {
1641 cx.spawn(|this, mut cx| async move {
1642 let abs_path = abs_path
1643 .to_file_path()
1644 .map_err(|_| anyhow!("can't convert URI to path"))?;
1645 let (worktree, relative_path) = if let Some(result) =
1646 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1647 {
1648 result
1649 } else {
1650 let worktree = this
1651 .update(&mut cx, |this, cx| {
1652 this.create_local_worktree(&abs_path, false, cx)
1653 })
1654 .await?;
1655 this.update(&mut cx, |this, cx| {
1656 this.language_server_ids.insert(
1657 (worktree.read(cx).id(), language_server_name),
1658 language_server_id,
1659 );
1660 });
1661 (worktree, PathBuf::new())
1662 };
1663
1664 let project_path = ProjectPath {
1665 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1666 path: relative_path.into(),
1667 };
1668 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1669 .await
1670 })
1671 }
1672
1673 pub fn open_buffer_by_id(
1674 &mut self,
1675 id: u64,
1676 cx: &mut ModelContext<Self>,
1677 ) -> Task<Result<ModelHandle<Buffer>>> {
1678 if let Some(buffer) = self.buffer_for_id(id, cx) {
1679 Task::ready(Ok(buffer))
1680 } else if self.is_local() {
1681 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1682 } else if let Some(project_id) = self.remote_id() {
1683 let request = self
1684 .client
1685 .request(proto::OpenBufferById { project_id, id });
1686 cx.spawn(|this, mut cx| async move {
1687 let buffer = request
1688 .await?
1689 .buffer
1690 .ok_or_else(|| anyhow!("invalid buffer"))?;
1691 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1692 .await
1693 })
1694 } else {
1695 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1696 }
1697 }
1698
1699 pub fn save_buffer_as(
1700 &mut self,
1701 buffer: ModelHandle<Buffer>,
1702 abs_path: PathBuf,
1703 cx: &mut ModelContext<Project>,
1704 ) -> Task<Result<()>> {
1705 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1706 let old_path =
1707 File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1708 cx.spawn(|this, mut cx| async move {
1709 if let Some(old_path) = old_path {
1710 this.update(&mut cx, |this, cx| {
1711 this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1712 });
1713 }
1714 let (worktree, path) = worktree_task.await?;
1715 worktree
1716 .update(&mut cx, |worktree, cx| {
1717 worktree
1718 .as_local_mut()
1719 .unwrap()
1720 .save_buffer_as(buffer.clone(), path, cx)
1721 })
1722 .await?;
1723 this.update(&mut cx, |this, cx| {
1724 this.assign_language_to_buffer(&buffer, cx);
1725 this.register_buffer_with_language_server(&buffer, cx);
1726 });
1727 Ok(())
1728 })
1729 }
1730
1731 pub fn get_open_buffer(
1732 &mut self,
1733 path: &ProjectPath,
1734 cx: &mut ModelContext<Self>,
1735 ) -> Option<ModelHandle<Buffer>> {
1736 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1737 self.opened_buffers.values().find_map(|buffer| {
1738 let buffer = buffer.upgrade(cx)?;
1739 let file = File::from_dyn(buffer.read(cx).file())?;
1740 if file.worktree == worktree && file.path() == &path.path {
1741 Some(buffer)
1742 } else {
1743 None
1744 }
1745 })
1746 }
1747
1748 fn register_buffer(
1749 &mut self,
1750 buffer: &ModelHandle<Buffer>,
1751 cx: &mut ModelContext<Self>,
1752 ) -> Result<()> {
1753 let remote_id = buffer.read(cx).remote_id();
1754 let open_buffer = if self.is_remote() || self.is_shared() {
1755 OpenBuffer::Strong(buffer.clone())
1756 } else {
1757 OpenBuffer::Weak(buffer.downgrade())
1758 };
1759
1760 match self.opened_buffers.insert(remote_id, open_buffer) {
1761 None => {}
1762 Some(OpenBuffer::Loading(operations)) => {
1763 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1764 }
1765 Some(OpenBuffer::Weak(existing_handle)) => {
1766 if existing_handle.upgrade(cx).is_some() {
1767 Err(anyhow!(
1768 "already registered buffer with remote id {}",
1769 remote_id
1770 ))?
1771 }
1772 }
1773 Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1774 "already registered buffer with remote id {}",
1775 remote_id
1776 ))?,
1777 }
1778 cx.subscribe(buffer, |this, buffer, event, cx| {
1779 this.on_buffer_event(buffer, event, cx);
1780 })
1781 .detach();
1782
1783 self.assign_language_to_buffer(buffer, cx);
1784 self.register_buffer_with_language_server(buffer, cx);
1785 cx.observe_release(buffer, |this, buffer, cx| {
1786 if let Some(file) = File::from_dyn(buffer.file()) {
1787 if file.is_local() {
1788 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1789 if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1790 server
1791 .notify::<lsp::notification::DidCloseTextDocument>(
1792 lsp::DidCloseTextDocumentParams {
1793 text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1794 },
1795 )
1796 .log_err();
1797 }
1798 }
1799 }
1800 })
1801 .detach();
1802
1803 Ok(())
1804 }
1805
1806 fn register_buffer_with_language_server(
1807 &mut self,
1808 buffer_handle: &ModelHandle<Buffer>,
1809 cx: &mut ModelContext<'_, Self>,
1810 ) {
1811 let buffer = buffer_handle.read(cx);
1812 let buffer_id = buffer.remote_id();
1813 if let Some(file) = File::from_dyn(buffer.file()) {
1814 if file.is_local() {
1815 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1816 let initial_snapshot = buffer.text_snapshot();
1817
1818 let mut language_server = None;
1819 let mut language_id = None;
1820 if let Some(language) = buffer.language() {
1821 let worktree_id = file.worktree_id(cx);
1822 if let Some(adapter) = language.lsp_adapter() {
1823 language_id = adapter.id_for_language.clone();
1824 language_server = self
1825 .language_server_ids
1826 .get(&(worktree_id, adapter.name.clone()))
1827 .and_then(|id| self.language_servers.get(&id))
1828 .and_then(|server_state| {
1829 if let LanguageServerState::Running { server, .. } = server_state {
1830 Some(server.clone())
1831 } else {
1832 None
1833 }
1834 });
1835 }
1836 }
1837
1838 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1839 if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1840 self.update_buffer_diagnostics(&buffer_handle, diagnostics, None, cx)
1841 .log_err();
1842 }
1843 }
1844
1845 if let Some(server) = language_server {
1846 server
1847 .notify::<lsp::notification::DidOpenTextDocument>(
1848 lsp::DidOpenTextDocumentParams {
1849 text_document: lsp::TextDocumentItem::new(
1850 uri,
1851 language_id.unwrap_or_default(),
1852 0,
1853 initial_snapshot.text(),
1854 ),
1855 }
1856 .clone(),
1857 )
1858 .log_err();
1859 buffer_handle.update(cx, |buffer, cx| {
1860 buffer.set_completion_triggers(
1861 server
1862 .capabilities()
1863 .completion_provider
1864 .as_ref()
1865 .and_then(|provider| provider.trigger_characters.clone())
1866 .unwrap_or(Vec::new()),
1867 cx,
1868 )
1869 });
1870 self.buffer_snapshots
1871 .insert(buffer_id, vec![(0, initial_snapshot)]);
1872 }
1873 }
1874 }
1875 }
1876
1877 fn unregister_buffer_from_language_server(
1878 &mut self,
1879 buffer: &ModelHandle<Buffer>,
1880 old_path: PathBuf,
1881 cx: &mut ModelContext<Self>,
1882 ) {
1883 buffer.update(cx, |buffer, cx| {
1884 buffer.update_diagnostics(Default::default(), cx);
1885 self.buffer_snapshots.remove(&buffer.remote_id());
1886 if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1887 language_server
1888 .notify::<lsp::notification::DidCloseTextDocument>(
1889 lsp::DidCloseTextDocumentParams {
1890 text_document: lsp::TextDocumentIdentifier::new(
1891 lsp::Url::from_file_path(old_path).unwrap(),
1892 ),
1893 },
1894 )
1895 .log_err();
1896 }
1897 });
1898 }
1899
1900 fn on_buffer_event(
1901 &mut self,
1902 buffer: ModelHandle<Buffer>,
1903 event: &BufferEvent,
1904 cx: &mut ModelContext<'_, Self>,
1905 ) -> Option<()> {
1906 match event {
1907 BufferEvent::Operation(operation) => {
1908 if let Some(project_id) = self.shared_remote_id() {
1909 let request = self.client.request(proto::UpdateBuffer {
1910 project_id,
1911 buffer_id: buffer.read(cx).remote_id(),
1912 operations: vec![language::proto::serialize_operation(&operation)],
1913 });
1914 cx.background().spawn(request).detach_and_log_err(cx);
1915 } else if let Some(project_id) = self.remote_id() {
1916 let _ = self
1917 .client
1918 .send(proto::RegisterProjectActivity { project_id });
1919 }
1920 }
1921 BufferEvent::Edited { .. } => {
1922 let language_server = self
1923 .language_server_for_buffer(buffer.read(cx), cx)
1924 .map(|(_, server)| server.clone())?;
1925 let buffer = buffer.read(cx);
1926 let file = File::from_dyn(buffer.file())?;
1927 let abs_path = file.as_local()?.abs_path(cx);
1928 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1929 let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1930 let (version, prev_snapshot) = buffer_snapshots.last()?;
1931 let next_snapshot = buffer.text_snapshot();
1932 let next_version = version + 1;
1933
1934 let content_changes = buffer
1935 .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1936 .map(|edit| {
1937 let edit_start = edit.new.start.0;
1938 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1939 let new_text = next_snapshot
1940 .text_for_range(edit.new.start.1..edit.new.end.1)
1941 .collect();
1942 lsp::TextDocumentContentChangeEvent {
1943 range: Some(lsp::Range::new(
1944 point_to_lsp(edit_start),
1945 point_to_lsp(edit_end),
1946 )),
1947 range_length: None,
1948 text: new_text,
1949 }
1950 })
1951 .collect();
1952
1953 buffer_snapshots.push((next_version, next_snapshot));
1954
1955 language_server
1956 .notify::<lsp::notification::DidChangeTextDocument>(
1957 lsp::DidChangeTextDocumentParams {
1958 text_document: lsp::VersionedTextDocumentIdentifier::new(
1959 uri,
1960 next_version,
1961 ),
1962 content_changes,
1963 },
1964 )
1965 .log_err();
1966 }
1967 BufferEvent::Saved => {
1968 let file = File::from_dyn(buffer.read(cx).file())?;
1969 let worktree_id = file.worktree_id(cx);
1970 let abs_path = file.as_local()?.abs_path(cx);
1971 let text_document = lsp::TextDocumentIdentifier {
1972 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1973 };
1974
1975 for (_, server) in self.language_servers_for_worktree(worktree_id) {
1976 server
1977 .notify::<lsp::notification::DidSaveTextDocument>(
1978 lsp::DidSaveTextDocumentParams {
1979 text_document: text_document.clone(),
1980 text: None,
1981 },
1982 )
1983 .log_err();
1984 }
1985
1986 // After saving a buffer, simulate disk-based diagnostics being finished for languages
1987 // that don't support a disk-based progress token.
1988 let (lsp_adapter, language_server) =
1989 self.language_server_for_buffer(buffer.read(cx), cx)?;
1990 if lsp_adapter.disk_based_diagnostics_progress_token.is_none() {
1991 let server_id = language_server.server_id();
1992 self.disk_based_diagnostics_finished(server_id, cx);
1993 self.broadcast_language_server_update(
1994 server_id,
1995 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1996 proto::LspDiskBasedDiagnosticsUpdated {},
1997 ),
1998 );
1999 }
2000 }
2001 _ => {}
2002 }
2003
2004 None
2005 }
2006
2007 fn language_servers_for_worktree(
2008 &self,
2009 worktree_id: WorktreeId,
2010 ) -> impl Iterator<Item = (&Arc<LspAdapter>, &Arc<LanguageServer>)> {
2011 self.language_server_ids
2012 .iter()
2013 .filter_map(move |((language_server_worktree_id, _), id)| {
2014 if *language_server_worktree_id == worktree_id {
2015 if let Some(LanguageServerState::Running { adapter, server }) =
2016 self.language_servers.get(&id)
2017 {
2018 return Some((adapter, server));
2019 }
2020 }
2021 None
2022 })
2023 }
2024
2025 fn maintain_buffer_languages(
2026 languages: &LanguageRegistry,
2027 cx: &mut ModelContext<Project>,
2028 ) -> Task<()> {
2029 let mut subscription = languages.subscribe();
2030 cx.spawn_weak(|project, mut cx| async move {
2031 while let Some(()) = subscription.next().await {
2032 if let Some(project) = project.upgrade(&cx) {
2033 project.update(&mut cx, |project, cx| {
2034 let mut buffers_without_language = Vec::new();
2035 for buffer in project.opened_buffers.values() {
2036 if let Some(buffer) = buffer.upgrade(cx) {
2037 if buffer.read(cx).language().is_none() {
2038 buffers_without_language.push(buffer);
2039 }
2040 }
2041 }
2042
2043 for buffer in buffers_without_language {
2044 project.assign_language_to_buffer(&buffer, cx);
2045 project.register_buffer_with_language_server(&buffer, cx);
2046 }
2047 });
2048 }
2049 }
2050 })
2051 }
2052
2053 fn assign_language_to_buffer(
2054 &mut self,
2055 buffer: &ModelHandle<Buffer>,
2056 cx: &mut ModelContext<Self>,
2057 ) -> Option<()> {
2058 // If the buffer has a language, set it and start the language server if we haven't already.
2059 let full_path = buffer.read(cx).file()?.full_path(cx);
2060 let language = self.languages.select_language(&full_path)?;
2061 buffer.update(cx, |buffer, cx| {
2062 buffer.set_language(Some(language.clone()), cx);
2063 });
2064
2065 let file = File::from_dyn(buffer.read(cx).file())?;
2066 let worktree = file.worktree.read(cx).as_local()?;
2067 let worktree_id = worktree.id();
2068 let worktree_abs_path = worktree.abs_path().clone();
2069 self.start_language_server(worktree_id, worktree_abs_path, language, cx);
2070
2071 None
2072 }
2073
2074 fn start_language_server(
2075 &mut self,
2076 worktree_id: WorktreeId,
2077 worktree_path: Arc<Path>,
2078 language: Arc<Language>,
2079 cx: &mut ModelContext<Self>,
2080 ) {
2081 if !cx
2082 .global::<Settings>()
2083 .enable_language_server(Some(&language.name()))
2084 {
2085 return;
2086 }
2087
2088 let adapter = if let Some(adapter) = language.lsp_adapter() {
2089 adapter
2090 } else {
2091 return;
2092 };
2093 let key = (worktree_id, adapter.name.clone());
2094
2095 self.language_server_ids
2096 .entry(key.clone())
2097 .or_insert_with(|| {
2098 let server_id = post_inc(&mut self.next_language_server_id);
2099 let language_server = self.languages.start_language_server(
2100 server_id,
2101 language.clone(),
2102 worktree_path,
2103 self.client.http_client(),
2104 cx,
2105 );
2106 self.language_servers.insert(
2107 server_id,
2108 LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2109 let language_server = language_server?.await.log_err()?;
2110 let language_server = language_server
2111 .initialize(adapter.initialization_options.clone())
2112 .await
2113 .log_err()?;
2114 let this = this.upgrade(&cx)?;
2115
2116 language_server
2117 .on_notification::<lsp::notification::PublishDiagnostics, _>({
2118 let this = this.downgrade();
2119 let adapter = adapter.clone();
2120 move |mut params, cx| {
2121 let this = this.clone();
2122 let adapter = adapter.clone();
2123 cx.spawn(|mut cx| async move {
2124 adapter.process_diagnostics(&mut params).await;
2125 if let Some(this) = this.upgrade(&cx) {
2126 this.update(&mut cx, |this, cx| {
2127 this.update_diagnostics(
2128 server_id,
2129 params,
2130 &adapter.disk_based_diagnostic_sources,
2131 cx,
2132 )
2133 .log_err();
2134 });
2135 }
2136 })
2137 .detach();
2138 }
2139 })
2140 .detach();
2141
2142 language_server
2143 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2144 let settings = this.read_with(&cx, |this, _| {
2145 this.language_server_settings.clone()
2146 });
2147 move |params, _| {
2148 let settings = settings.lock().clone();
2149 async move {
2150 Ok(params
2151 .items
2152 .into_iter()
2153 .map(|item| {
2154 if let Some(section) = &item.section {
2155 settings
2156 .get(section)
2157 .cloned()
2158 .unwrap_or(serde_json::Value::Null)
2159 } else {
2160 settings.clone()
2161 }
2162 })
2163 .collect())
2164 }
2165 }
2166 })
2167 .detach();
2168
2169 // Even though we don't have handling for these requests, respond to them to
2170 // avoid stalling any language server like `gopls` which waits for a response
2171 // to these requests when initializing.
2172 language_server
2173 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2174 let this = this.downgrade();
2175 move |params, mut cx| async move {
2176 if let Some(this) = this.upgrade(&cx) {
2177 this.update(&mut cx, |this, _| {
2178 if let Some(status) =
2179 this.language_server_statuses.get_mut(&server_id)
2180 {
2181 if let lsp::NumberOrString::String(token) =
2182 params.token
2183 {
2184 status.progress_tokens.insert(token);
2185 }
2186 }
2187 });
2188 }
2189 Ok(())
2190 }
2191 })
2192 .detach();
2193 language_server
2194 .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
2195 Ok(())
2196 })
2197 .detach();
2198
2199 language_server
2200 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2201 let this = this.downgrade();
2202 let adapter = adapter.clone();
2203 let language_server = language_server.clone();
2204 move |params, cx| {
2205 Self::on_lsp_workspace_edit(
2206 this,
2207 params,
2208 server_id,
2209 adapter.clone(),
2210 language_server.clone(),
2211 cx,
2212 )
2213 }
2214 })
2215 .detach();
2216
2217 let disk_based_diagnostics_progress_token =
2218 adapter.disk_based_diagnostics_progress_token.clone();
2219
2220 language_server
2221 .on_notification::<lsp::notification::Progress, _>({
2222 let this = this.downgrade();
2223 move |params, mut cx| {
2224 if let Some(this) = this.upgrade(&cx) {
2225 this.update(&mut cx, |this, cx| {
2226 this.on_lsp_progress(
2227 params,
2228 server_id,
2229 disk_based_diagnostics_progress_token.clone(),
2230 cx,
2231 );
2232 });
2233 }
2234 }
2235 })
2236 .detach();
2237
2238 this.update(&mut cx, |this, cx| {
2239 // If the language server for this key doesn't match the server id, don't store the
2240 // server. Which will cause it to be dropped, killing the process
2241 if this
2242 .language_server_ids
2243 .get(&key)
2244 .map(|id| id != &server_id)
2245 .unwrap_or(false)
2246 {
2247 return None;
2248 }
2249
2250 // Update language_servers collection with Running variant of LanguageServerState
2251 // indicating that the server is up and running and ready
2252 this.language_servers.insert(
2253 server_id,
2254 LanguageServerState::Running {
2255 adapter: adapter.clone(),
2256 server: language_server.clone(),
2257 },
2258 );
2259 this.language_server_statuses.insert(
2260 server_id,
2261 LanguageServerStatus {
2262 name: language_server.name().to_string(),
2263 pending_work: Default::default(),
2264 has_pending_diagnostic_updates: false,
2265 progress_tokens: Default::default(),
2266 },
2267 );
2268 language_server
2269 .notify::<lsp::notification::DidChangeConfiguration>(
2270 lsp::DidChangeConfigurationParams {
2271 settings: this.language_server_settings.lock().clone(),
2272 },
2273 )
2274 .ok();
2275
2276 if let Some(project_id) = this.shared_remote_id() {
2277 this.client
2278 .send(proto::StartLanguageServer {
2279 project_id,
2280 server: Some(proto::LanguageServer {
2281 id: server_id as u64,
2282 name: language_server.name().to_string(),
2283 }),
2284 })
2285 .log_err();
2286 }
2287
2288 // Tell the language server about every open buffer in the worktree that matches the language.
2289 for buffer in this.opened_buffers.values() {
2290 if let Some(buffer_handle) = buffer.upgrade(cx) {
2291 let buffer = buffer_handle.read(cx);
2292 let file = if let Some(file) = File::from_dyn(buffer.file()) {
2293 file
2294 } else {
2295 continue;
2296 };
2297 let language = if let Some(language) = buffer.language() {
2298 language
2299 } else {
2300 continue;
2301 };
2302 if file.worktree.read(cx).id() != key.0
2303 || language.lsp_adapter().map(|a| a.name.clone())
2304 != Some(key.1.clone())
2305 {
2306 continue;
2307 }
2308
2309 let file = file.as_local()?;
2310 let versions = this
2311 .buffer_snapshots
2312 .entry(buffer.remote_id())
2313 .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2314 let (version, initial_snapshot) = versions.last().unwrap();
2315 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2316 language_server
2317 .notify::<lsp::notification::DidOpenTextDocument>(
2318 lsp::DidOpenTextDocumentParams {
2319 text_document: lsp::TextDocumentItem::new(
2320 uri,
2321 adapter
2322 .id_for_language
2323 .clone()
2324 .unwrap_or_default(),
2325 *version,
2326 initial_snapshot.text(),
2327 ),
2328 },
2329 )
2330 .log_err()?;
2331 buffer_handle.update(cx, |buffer, cx| {
2332 buffer.set_completion_triggers(
2333 language_server
2334 .capabilities()
2335 .completion_provider
2336 .as_ref()
2337 .and_then(|provider| {
2338 provider.trigger_characters.clone()
2339 })
2340 .unwrap_or(Vec::new()),
2341 cx,
2342 )
2343 });
2344 }
2345 }
2346
2347 cx.notify();
2348 Some(language_server)
2349 })
2350 })),
2351 );
2352
2353 server_id
2354 });
2355 }
2356
2357 // Returns a list of all of the worktrees which no longer have a language server and the root path
2358 // for the stopped server
2359 fn stop_language_server(
2360 &mut self,
2361 worktree_id: WorktreeId,
2362 adapter_name: LanguageServerName,
2363 cx: &mut ModelContext<Self>,
2364 ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2365 let key = (worktree_id, adapter_name);
2366 if let Some(server_id) = self.language_server_ids.remove(&key) {
2367 // Remove other entries for this language server as well
2368 let mut orphaned_worktrees = vec![worktree_id];
2369 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2370 for other_key in other_keys {
2371 if self.language_server_ids.get(&other_key) == Some(&server_id) {
2372 self.language_server_ids.remove(&other_key);
2373 orphaned_worktrees.push(other_key.0);
2374 }
2375 }
2376
2377 self.language_server_statuses.remove(&server_id);
2378 cx.notify();
2379
2380 let server_state = self.language_servers.remove(&server_id);
2381 cx.spawn_weak(|this, mut cx| async move {
2382 let mut root_path = None;
2383
2384 let server = match server_state {
2385 Some(LanguageServerState::Starting(started_language_server)) => {
2386 started_language_server.await
2387 }
2388 Some(LanguageServerState::Running { server, .. }) => Some(server),
2389 None => None,
2390 };
2391
2392 if let Some(server) = server {
2393 root_path = Some(server.root_path().clone());
2394 if let Some(shutdown) = server.shutdown() {
2395 shutdown.await;
2396 }
2397 }
2398
2399 if let Some(this) = this.upgrade(&cx) {
2400 this.update(&mut cx, |this, cx| {
2401 this.language_server_statuses.remove(&server_id);
2402 cx.notify();
2403 });
2404 }
2405
2406 (root_path, orphaned_worktrees)
2407 })
2408 } else {
2409 Task::ready((None, Vec::new()))
2410 }
2411 }
2412
2413 pub fn restart_language_servers_for_buffers(
2414 &mut self,
2415 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2416 cx: &mut ModelContext<Self>,
2417 ) -> Option<()> {
2418 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2419 .into_iter()
2420 .filter_map(|buffer| {
2421 let file = File::from_dyn(buffer.read(cx).file())?;
2422 let worktree = file.worktree.read(cx).as_local()?;
2423 let worktree_id = worktree.id();
2424 let worktree_abs_path = worktree.abs_path().clone();
2425 let full_path = file.full_path(cx);
2426 Some((worktree_id, worktree_abs_path, full_path))
2427 })
2428 .collect();
2429 for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2430 let language = self.languages.select_language(&full_path)?;
2431 self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2432 }
2433
2434 None
2435 }
2436
2437 fn restart_language_server(
2438 &mut self,
2439 worktree_id: WorktreeId,
2440 fallback_path: Arc<Path>,
2441 language: Arc<Language>,
2442 cx: &mut ModelContext<Self>,
2443 ) {
2444 let adapter = if let Some(adapter) = language.lsp_adapter() {
2445 adapter
2446 } else {
2447 return;
2448 };
2449
2450 let server_name = adapter.name.clone();
2451 let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2452 cx.spawn_weak(|this, mut cx| async move {
2453 let (original_root_path, orphaned_worktrees) = stop.await;
2454 if let Some(this) = this.upgrade(&cx) {
2455 this.update(&mut cx, |this, cx| {
2456 // Attempt to restart using original server path. Fallback to passed in
2457 // path if we could not retrieve the root path
2458 let root_path = original_root_path
2459 .map(|path_buf| Arc::from(path_buf.as_path()))
2460 .unwrap_or(fallback_path);
2461
2462 this.start_language_server(worktree_id, root_path, language, cx);
2463
2464 // Lookup new server id and set it for each of the orphaned worktrees
2465 if let Some(new_server_id) = this
2466 .language_server_ids
2467 .get(&(worktree_id, server_name.clone()))
2468 .cloned()
2469 {
2470 for orphaned_worktree in orphaned_worktrees {
2471 this.language_server_ids.insert(
2472 (orphaned_worktree, server_name.clone()),
2473 new_server_id.clone(),
2474 );
2475 }
2476 }
2477 });
2478 }
2479 })
2480 .detach();
2481 }
2482
2483 fn on_lsp_progress(
2484 &mut self,
2485 progress: lsp::ProgressParams,
2486 server_id: usize,
2487 disk_based_diagnostics_progress_token: Option<String>,
2488 cx: &mut ModelContext<Self>,
2489 ) {
2490 let token = match progress.token {
2491 lsp::NumberOrString::String(token) => token,
2492 lsp::NumberOrString::Number(token) => {
2493 log::info!("skipping numeric progress token {}", token);
2494 return;
2495 }
2496 };
2497 let progress = match progress.value {
2498 lsp::ProgressParamsValue::WorkDone(value) => value,
2499 };
2500 let language_server_status =
2501 if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2502 status
2503 } else {
2504 return;
2505 };
2506
2507 if !language_server_status.progress_tokens.contains(&token) {
2508 return;
2509 }
2510
2511 let same_token =
2512 Some(token.as_ref()) == disk_based_diagnostics_progress_token.as_ref().map(|x| &**x);
2513
2514 match progress {
2515 lsp::WorkDoneProgress::Begin(report) => {
2516 if same_token {
2517 language_server_status.has_pending_diagnostic_updates = true;
2518 self.disk_based_diagnostics_started(server_id, cx);
2519 self.broadcast_language_server_update(
2520 server_id,
2521 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2522 proto::LspDiskBasedDiagnosticsUpdating {},
2523 ),
2524 );
2525 } else {
2526 self.on_lsp_work_start(
2527 server_id,
2528 token.clone(),
2529 LanguageServerProgress {
2530 message: report.message.clone(),
2531 percentage: report.percentage.map(|p| p as usize),
2532 last_update_at: Instant::now(),
2533 },
2534 cx,
2535 );
2536 self.broadcast_language_server_update(
2537 server_id,
2538 proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2539 token,
2540 message: report.message,
2541 percentage: report.percentage.map(|p| p as u32),
2542 }),
2543 );
2544 }
2545 }
2546 lsp::WorkDoneProgress::Report(report) => {
2547 if !same_token {
2548 self.on_lsp_work_progress(
2549 server_id,
2550 token.clone(),
2551 LanguageServerProgress {
2552 message: report.message.clone(),
2553 percentage: report.percentage.map(|p| p as usize),
2554 last_update_at: Instant::now(),
2555 },
2556 cx,
2557 );
2558 self.broadcast_language_server_update(
2559 server_id,
2560 proto::update_language_server::Variant::WorkProgress(
2561 proto::LspWorkProgress {
2562 token,
2563 message: report.message,
2564 percentage: report.percentage.map(|p| p as u32),
2565 },
2566 ),
2567 );
2568 }
2569 }
2570 lsp::WorkDoneProgress::End(_) => {
2571 language_server_status.progress_tokens.remove(&token);
2572
2573 if same_token {
2574 language_server_status.has_pending_diagnostic_updates = false;
2575 self.disk_based_diagnostics_finished(server_id, cx);
2576 self.broadcast_language_server_update(
2577 server_id,
2578 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2579 proto::LspDiskBasedDiagnosticsUpdated {},
2580 ),
2581 );
2582 } else {
2583 self.on_lsp_work_end(server_id, token.clone(), cx);
2584 self.broadcast_language_server_update(
2585 server_id,
2586 proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2587 token,
2588 }),
2589 );
2590 }
2591 }
2592 }
2593 }
2594
2595 fn on_lsp_work_start(
2596 &mut self,
2597 language_server_id: usize,
2598 token: String,
2599 progress: LanguageServerProgress,
2600 cx: &mut ModelContext<Self>,
2601 ) {
2602 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2603 status.pending_work.insert(token, progress);
2604 cx.notify();
2605 }
2606 }
2607
2608 fn on_lsp_work_progress(
2609 &mut self,
2610 language_server_id: usize,
2611 token: String,
2612 progress: LanguageServerProgress,
2613 cx: &mut ModelContext<Self>,
2614 ) {
2615 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2616 let entry = status
2617 .pending_work
2618 .entry(token)
2619 .or_insert(LanguageServerProgress {
2620 message: Default::default(),
2621 percentage: Default::default(),
2622 last_update_at: progress.last_update_at,
2623 });
2624 if progress.message.is_some() {
2625 entry.message = progress.message;
2626 }
2627 if progress.percentage.is_some() {
2628 entry.percentage = progress.percentage;
2629 }
2630 entry.last_update_at = progress.last_update_at;
2631 cx.notify();
2632 }
2633 }
2634
2635 fn on_lsp_work_end(
2636 &mut self,
2637 language_server_id: usize,
2638 token: String,
2639 cx: &mut ModelContext<Self>,
2640 ) {
2641 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2642 status.pending_work.remove(&token);
2643 cx.notify();
2644 }
2645 }
2646
2647 async fn on_lsp_workspace_edit(
2648 this: WeakModelHandle<Self>,
2649 params: lsp::ApplyWorkspaceEditParams,
2650 server_id: usize,
2651 adapter: Arc<LspAdapter>,
2652 language_server: Arc<LanguageServer>,
2653 mut cx: AsyncAppContext,
2654 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2655 let this = this
2656 .upgrade(&cx)
2657 .ok_or_else(|| anyhow!("project project closed"))?;
2658 let transaction = Self::deserialize_workspace_edit(
2659 this.clone(),
2660 params.edit,
2661 true,
2662 adapter.clone(),
2663 language_server.clone(),
2664 &mut cx,
2665 )
2666 .await
2667 .log_err();
2668 this.update(&mut cx, |this, _| {
2669 if let Some(transaction) = transaction {
2670 this.last_workspace_edits_by_language_server
2671 .insert(server_id, transaction);
2672 }
2673 });
2674 Ok(lsp::ApplyWorkspaceEditResponse {
2675 applied: true,
2676 failed_change: None,
2677 failure_reason: None,
2678 })
2679 }
2680
2681 fn broadcast_language_server_update(
2682 &self,
2683 language_server_id: usize,
2684 event: proto::update_language_server::Variant,
2685 ) {
2686 if let Some(project_id) = self.shared_remote_id() {
2687 self.client
2688 .send(proto::UpdateLanguageServer {
2689 project_id,
2690 language_server_id: language_server_id as u64,
2691 variant: Some(event),
2692 })
2693 .log_err();
2694 }
2695 }
2696
2697 pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2698 for server_state in self.language_servers.values() {
2699 if let LanguageServerState::Running { server, .. } = server_state {
2700 server
2701 .notify::<lsp::notification::DidChangeConfiguration>(
2702 lsp::DidChangeConfigurationParams {
2703 settings: settings.clone(),
2704 },
2705 )
2706 .ok();
2707 }
2708 }
2709 *self.language_server_settings.lock() = settings;
2710 }
2711
2712 pub fn language_server_statuses(
2713 &self,
2714 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2715 self.language_server_statuses.values()
2716 }
2717
2718 pub fn update_diagnostics(
2719 &mut self,
2720 language_server_id: usize,
2721 params: lsp::PublishDiagnosticsParams,
2722 disk_based_sources: &[String],
2723 cx: &mut ModelContext<Self>,
2724 ) -> Result<()> {
2725 let abs_path = params
2726 .uri
2727 .to_file_path()
2728 .map_err(|_| anyhow!("URI is not a file"))?;
2729 let mut diagnostics = Vec::default();
2730 let mut primary_diagnostic_group_ids = HashMap::default();
2731 let mut sources_by_group_id = HashMap::default();
2732 let mut supporting_diagnostics = HashMap::default();
2733 for diagnostic in ¶ms.diagnostics {
2734 let source = diagnostic.source.as_ref();
2735 let code = diagnostic.code.as_ref().map(|code| match code {
2736 lsp::NumberOrString::Number(code) => code.to_string(),
2737 lsp::NumberOrString::String(code) => code.clone(),
2738 });
2739 let range = range_from_lsp(diagnostic.range);
2740 let is_supporting = diagnostic
2741 .related_information
2742 .as_ref()
2743 .map_or(false, |infos| {
2744 infos.iter().any(|info| {
2745 primary_diagnostic_group_ids.contains_key(&(
2746 source,
2747 code.clone(),
2748 range_from_lsp(info.location.range),
2749 ))
2750 })
2751 });
2752
2753 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2754 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2755 });
2756
2757 if is_supporting {
2758 supporting_diagnostics.insert(
2759 (source, code.clone(), range),
2760 (diagnostic.severity, is_unnecessary),
2761 );
2762 } else {
2763 let group_id = post_inc(&mut self.next_diagnostic_group_id);
2764 let is_disk_based =
2765 source.map_or(false, |source| disk_based_sources.contains(&source));
2766
2767 sources_by_group_id.insert(group_id, source);
2768 primary_diagnostic_group_ids
2769 .insert((source, code.clone(), range.clone()), group_id);
2770
2771 diagnostics.push(DiagnosticEntry {
2772 range,
2773 diagnostic: Diagnostic {
2774 code: code.clone(),
2775 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2776 message: diagnostic.message.clone(),
2777 group_id,
2778 is_primary: true,
2779 is_valid: true,
2780 is_disk_based,
2781 is_unnecessary,
2782 },
2783 });
2784 if let Some(infos) = &diagnostic.related_information {
2785 for info in infos {
2786 if info.location.uri == params.uri && !info.message.is_empty() {
2787 let range = range_from_lsp(info.location.range);
2788 diagnostics.push(DiagnosticEntry {
2789 range,
2790 diagnostic: Diagnostic {
2791 code: code.clone(),
2792 severity: DiagnosticSeverity::INFORMATION,
2793 message: info.message.clone(),
2794 group_id,
2795 is_primary: false,
2796 is_valid: true,
2797 is_disk_based,
2798 is_unnecessary: false,
2799 },
2800 });
2801 }
2802 }
2803 }
2804 }
2805 }
2806
2807 for entry in &mut diagnostics {
2808 let diagnostic = &mut entry.diagnostic;
2809 if !diagnostic.is_primary {
2810 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2811 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2812 source,
2813 diagnostic.code.clone(),
2814 entry.range.clone(),
2815 )) {
2816 if let Some(severity) = severity {
2817 diagnostic.severity = severity;
2818 }
2819 diagnostic.is_unnecessary = is_unnecessary;
2820 }
2821 }
2822 }
2823
2824 self.update_diagnostic_entries(
2825 language_server_id,
2826 abs_path,
2827 params.version,
2828 diagnostics,
2829 cx,
2830 )?;
2831 Ok(())
2832 }
2833
2834 pub fn update_diagnostic_entries(
2835 &mut self,
2836 language_server_id: usize,
2837 abs_path: PathBuf,
2838 version: Option<i32>,
2839 diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2840 cx: &mut ModelContext<Project>,
2841 ) -> Result<(), anyhow::Error> {
2842 let (worktree, relative_path) = self
2843 .find_local_worktree(&abs_path, cx)
2844 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2845
2846 let project_path = ProjectPath {
2847 worktree_id: worktree.read(cx).id(),
2848 path: relative_path.into(),
2849 };
2850 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2851 self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2852 }
2853
2854 let updated = worktree.update(cx, |worktree, cx| {
2855 worktree
2856 .as_local_mut()
2857 .ok_or_else(|| anyhow!("not a local worktree"))?
2858 .update_diagnostics(
2859 language_server_id,
2860 project_path.path.clone(),
2861 diagnostics,
2862 cx,
2863 )
2864 })?;
2865 if updated {
2866 cx.emit(Event::DiagnosticsUpdated {
2867 language_server_id,
2868 path: project_path,
2869 });
2870 }
2871 Ok(())
2872 }
2873
2874 fn update_buffer_diagnostics(
2875 &mut self,
2876 buffer: &ModelHandle<Buffer>,
2877 mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2878 version: Option<i32>,
2879 cx: &mut ModelContext<Self>,
2880 ) -> Result<()> {
2881 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2882 Ordering::Equal
2883 .then_with(|| b.is_primary.cmp(&a.is_primary))
2884 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2885 .then_with(|| a.severity.cmp(&b.severity))
2886 .then_with(|| a.message.cmp(&b.message))
2887 }
2888
2889 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2890
2891 diagnostics.sort_unstable_by(|a, b| {
2892 Ordering::Equal
2893 .then_with(|| a.range.start.cmp(&b.range.start))
2894 .then_with(|| b.range.end.cmp(&a.range.end))
2895 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2896 });
2897
2898 let mut sanitized_diagnostics = Vec::new();
2899 let edits_since_save = Patch::new(
2900 snapshot
2901 .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2902 .collect(),
2903 );
2904 for entry in diagnostics {
2905 let start;
2906 let end;
2907 if entry.diagnostic.is_disk_based {
2908 // Some diagnostics are based on files on disk instead of buffers'
2909 // current contents. Adjust these diagnostics' ranges to reflect
2910 // any unsaved edits.
2911 start = edits_since_save.old_to_new(entry.range.start);
2912 end = edits_since_save.old_to_new(entry.range.end);
2913 } else {
2914 start = entry.range.start;
2915 end = entry.range.end;
2916 }
2917
2918 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2919 ..snapshot.clip_point_utf16(end, Bias::Right);
2920
2921 // Expand empty ranges by one character
2922 if range.start == range.end {
2923 range.end.column += 1;
2924 range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2925 if range.start == range.end && range.end.column > 0 {
2926 range.start.column -= 1;
2927 range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2928 }
2929 }
2930
2931 sanitized_diagnostics.push(DiagnosticEntry {
2932 range,
2933 diagnostic: entry.diagnostic,
2934 });
2935 }
2936 drop(edits_since_save);
2937
2938 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2939 buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2940 Ok(())
2941 }
2942
2943 pub fn reload_buffers(
2944 &self,
2945 buffers: HashSet<ModelHandle<Buffer>>,
2946 push_to_history: bool,
2947 cx: &mut ModelContext<Self>,
2948 ) -> Task<Result<ProjectTransaction>> {
2949 let mut local_buffers = Vec::new();
2950 let mut remote_buffers = None;
2951 for buffer_handle in buffers {
2952 let buffer = buffer_handle.read(cx);
2953 if buffer.is_dirty() {
2954 if let Some(file) = File::from_dyn(buffer.file()) {
2955 if file.is_local() {
2956 local_buffers.push(buffer_handle);
2957 } else {
2958 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2959 }
2960 }
2961 }
2962 }
2963
2964 let remote_buffers = self.remote_id().zip(remote_buffers);
2965 let client = self.client.clone();
2966
2967 cx.spawn(|this, mut cx| async move {
2968 let mut project_transaction = ProjectTransaction::default();
2969
2970 if let Some((project_id, remote_buffers)) = remote_buffers {
2971 let response = client
2972 .request(proto::ReloadBuffers {
2973 project_id,
2974 buffer_ids: remote_buffers
2975 .iter()
2976 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2977 .collect(),
2978 })
2979 .await?
2980 .transaction
2981 .ok_or_else(|| anyhow!("missing transaction"))?;
2982 project_transaction = this
2983 .update(&mut cx, |this, cx| {
2984 this.deserialize_project_transaction(response, push_to_history, cx)
2985 })
2986 .await?;
2987 }
2988
2989 for buffer in local_buffers {
2990 let transaction = buffer
2991 .update(&mut cx, |buffer, cx| buffer.reload(cx))
2992 .await?;
2993 buffer.update(&mut cx, |buffer, cx| {
2994 if let Some(transaction) = transaction {
2995 if !push_to_history {
2996 buffer.forget_transaction(transaction.id);
2997 }
2998 project_transaction.0.insert(cx.handle(), transaction);
2999 }
3000 });
3001 }
3002
3003 Ok(project_transaction)
3004 })
3005 }
3006
3007 pub fn format(
3008 &self,
3009 buffers: HashSet<ModelHandle<Buffer>>,
3010 push_to_history: bool,
3011 cx: &mut ModelContext<Project>,
3012 ) -> Task<Result<ProjectTransaction>> {
3013 let mut local_buffers = Vec::new();
3014 let mut remote_buffers = None;
3015 for buffer_handle in buffers {
3016 let buffer = buffer_handle.read(cx);
3017 if let Some(file) = File::from_dyn(buffer.file()) {
3018 if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
3019 if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
3020 local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
3021 }
3022 } else {
3023 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3024 }
3025 } else {
3026 return Task::ready(Ok(Default::default()));
3027 }
3028 }
3029
3030 let remote_buffers = self.remote_id().zip(remote_buffers);
3031 let client = self.client.clone();
3032
3033 cx.spawn(|this, mut cx| async move {
3034 let mut project_transaction = ProjectTransaction::default();
3035
3036 if let Some((project_id, remote_buffers)) = remote_buffers {
3037 let response = client
3038 .request(proto::FormatBuffers {
3039 project_id,
3040 buffer_ids: remote_buffers
3041 .iter()
3042 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3043 .collect(),
3044 })
3045 .await?
3046 .transaction
3047 .ok_or_else(|| anyhow!("missing transaction"))?;
3048 project_transaction = this
3049 .update(&mut cx, |this, cx| {
3050 this.deserialize_project_transaction(response, push_to_history, cx)
3051 })
3052 .await?;
3053 }
3054
3055 for (buffer, buffer_abs_path, language_server) in local_buffers {
3056 let (format_on_save, tab_size) = buffer.read_with(&cx, |buffer, cx| {
3057 let settings = cx.global::<Settings>();
3058 let language_name = buffer.language().map(|language| language.name());
3059 (
3060 settings.format_on_save(language_name.as_deref()),
3061 settings.tab_size(language_name.as_deref()),
3062 )
3063 });
3064
3065 let transaction = match format_on_save {
3066 settings::FormatOnSave::Off => continue,
3067 settings::FormatOnSave::LanguageServer => Self::format_via_lsp(
3068 &this,
3069 &buffer,
3070 &buffer_abs_path,
3071 &language_server,
3072 tab_size,
3073 &mut cx,
3074 )
3075 .await
3076 .context("failed to format via language server")?,
3077 settings::FormatOnSave::External { command, arguments } => {
3078 Self::format_via_external_command(
3079 &buffer,
3080 &buffer_abs_path,
3081 &command,
3082 &arguments,
3083 &mut cx,
3084 )
3085 .await
3086 .context(format!(
3087 "failed to format via external command {:?}",
3088 command
3089 ))?
3090 }
3091 };
3092
3093 if let Some(transaction) = transaction {
3094 if !push_to_history {
3095 buffer.update(&mut cx, |buffer, _| {
3096 buffer.forget_transaction(transaction.id)
3097 });
3098 }
3099 project_transaction.0.insert(buffer, transaction);
3100 }
3101 }
3102
3103 Ok(project_transaction)
3104 })
3105 }
3106
3107 async fn format_via_lsp(
3108 this: &ModelHandle<Self>,
3109 buffer: &ModelHandle<Buffer>,
3110 abs_path: &Path,
3111 language_server: &Arc<LanguageServer>,
3112 tab_size: NonZeroU32,
3113 cx: &mut AsyncAppContext,
3114 ) -> Result<Option<Transaction>> {
3115 let text_document =
3116 lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
3117 let capabilities = &language_server.capabilities();
3118 let lsp_edits = if capabilities
3119 .document_formatting_provider
3120 .as_ref()
3121 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3122 {
3123 language_server
3124 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3125 text_document,
3126 options: lsp::FormattingOptions {
3127 tab_size: tab_size.into(),
3128 insert_spaces: true,
3129 insert_final_newline: Some(true),
3130 ..Default::default()
3131 },
3132 work_done_progress_params: Default::default(),
3133 })
3134 .await?
3135 } else if capabilities
3136 .document_range_formatting_provider
3137 .as_ref()
3138 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3139 {
3140 let buffer_start = lsp::Position::new(0, 0);
3141 let buffer_end =
3142 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3143 language_server
3144 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3145 text_document,
3146 range: lsp::Range::new(buffer_start, buffer_end),
3147 options: lsp::FormattingOptions {
3148 tab_size: tab_size.into(),
3149 insert_spaces: true,
3150 insert_final_newline: Some(true),
3151 ..Default::default()
3152 },
3153 work_done_progress_params: Default::default(),
3154 })
3155 .await?
3156 } else {
3157 None
3158 };
3159
3160 if let Some(lsp_edits) = lsp_edits {
3161 let edits = this
3162 .update(cx, |this, cx| {
3163 this.edits_from_lsp(&buffer, lsp_edits, None, cx)
3164 })
3165 .await?;
3166 buffer.update(cx, |buffer, cx| {
3167 buffer.finalize_last_transaction();
3168 buffer.start_transaction();
3169 for (range, text) in edits {
3170 buffer.edit([(range, text)], cx);
3171 }
3172 if buffer.end_transaction(cx).is_some() {
3173 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3174 Ok(Some(transaction))
3175 } else {
3176 Ok(None)
3177 }
3178 })
3179 } else {
3180 Ok(None)
3181 }
3182 }
3183
3184 async fn format_via_external_command(
3185 buffer: &ModelHandle<Buffer>,
3186 buffer_abs_path: &Path,
3187 command: &str,
3188 arguments: &[String],
3189 cx: &mut AsyncAppContext,
3190 ) -> Result<Option<Transaction>> {
3191 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3192 let file = File::from_dyn(buffer.file())?;
3193 let worktree = file.worktree.read(cx).as_local()?;
3194 let mut worktree_path = worktree.abs_path().to_path_buf();
3195 if worktree.root_entry()?.is_file() {
3196 worktree_path.pop();
3197 }
3198 Some(worktree_path)
3199 });
3200
3201 if let Some(working_dir_path) = working_dir_path {
3202 let mut child =
3203 smol::process::Command::new(command)
3204 .args(arguments.iter().map(|arg| {
3205 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3206 }))
3207 .current_dir(&working_dir_path)
3208 .stdin(smol::process::Stdio::piped())
3209 .stdout(smol::process::Stdio::piped())
3210 .stderr(smol::process::Stdio::piped())
3211 .spawn()?;
3212 let stdin = child
3213 .stdin
3214 .as_mut()
3215 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3216 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3217 for chunk in text.chunks() {
3218 stdin.write_all(chunk.as_bytes()).await?;
3219 }
3220 stdin.flush().await?;
3221
3222 let output = child.output().await?;
3223 if !output.status.success() {
3224 return Err(anyhow!(
3225 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3226 output.status.code(),
3227 String::from_utf8_lossy(&output.stdout),
3228 String::from_utf8_lossy(&output.stderr),
3229 ));
3230 }
3231
3232 let stdout = String::from_utf8(output.stdout)?;
3233 let diff = buffer
3234 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3235 .await;
3236 Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3237 } else {
3238 Ok(None)
3239 }
3240 }
3241
3242 pub fn definition<T: ToPointUtf16>(
3243 &self,
3244 buffer: &ModelHandle<Buffer>,
3245 position: T,
3246 cx: &mut ModelContext<Self>,
3247 ) -> Task<Result<Vec<LocationLink>>> {
3248 let position = position.to_point_utf16(buffer.read(cx));
3249 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3250 }
3251
3252 pub fn references<T: ToPointUtf16>(
3253 &self,
3254 buffer: &ModelHandle<Buffer>,
3255 position: T,
3256 cx: &mut ModelContext<Self>,
3257 ) -> Task<Result<Vec<Location>>> {
3258 let position = position.to_point_utf16(buffer.read(cx));
3259 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3260 }
3261
3262 pub fn document_highlights<T: ToPointUtf16>(
3263 &self,
3264 buffer: &ModelHandle<Buffer>,
3265 position: T,
3266 cx: &mut ModelContext<Self>,
3267 ) -> Task<Result<Vec<DocumentHighlight>>> {
3268 let position = position.to_point_utf16(buffer.read(cx));
3269 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3270 }
3271
3272 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3273 if self.is_local() {
3274 let mut requests = Vec::new();
3275 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3276 let worktree_id = *worktree_id;
3277 if let Some(worktree) = self
3278 .worktree_for_id(worktree_id, cx)
3279 .and_then(|worktree| worktree.read(cx).as_local())
3280 {
3281 if let Some(LanguageServerState::Running { adapter, server }) =
3282 self.language_servers.get(server_id)
3283 {
3284 let adapter = adapter.clone();
3285 let worktree_abs_path = worktree.abs_path().clone();
3286 requests.push(
3287 server
3288 .request::<lsp::request::WorkspaceSymbol>(
3289 lsp::WorkspaceSymbolParams {
3290 query: query.to_string(),
3291 ..Default::default()
3292 },
3293 )
3294 .log_err()
3295 .map(move |response| {
3296 (
3297 adapter,
3298 worktree_id,
3299 worktree_abs_path,
3300 response.unwrap_or_default(),
3301 )
3302 }),
3303 );
3304 }
3305 }
3306 }
3307
3308 cx.spawn_weak(|this, cx| async move {
3309 let responses = futures::future::join_all(requests).await;
3310 let this = if let Some(this) = this.upgrade(&cx) {
3311 this
3312 } else {
3313 return Ok(Default::default());
3314 };
3315
3316 struct PartialSymbol {
3317 source_worktree_id: WorktreeId,
3318 worktree_id: WorktreeId,
3319 language_server_name: LanguageServerName,
3320 path: PathBuf,
3321 language: Option<Arc<Language>>,
3322 name: String,
3323 kind: lsp::SymbolKind,
3324 range: Range<PointUtf16>,
3325 signature: [u8; 32],
3326 }
3327
3328 let partial_symbols = this.read_with(&cx, |this, cx| {
3329 let mut partial_symbols = Vec::new();
3330 for (adapter, source_worktree_id, worktree_abs_path, response) in responses {
3331 for lsp_symbol in response.into_iter().flatten() {
3332 let abs_path = match lsp_symbol.location.uri.to_file_path().ok() {
3333 Some(abs_path) => abs_path,
3334 None => continue,
3335 };
3336 let mut worktree_id = source_worktree_id;
3337 let path;
3338 if let Some((worktree, rel_path)) =
3339 this.find_local_worktree(&abs_path, cx)
3340 {
3341 worktree_id = worktree.read(cx).id();
3342 path = rel_path;
3343 } else {
3344 path = relativize_path(&worktree_abs_path, &abs_path);
3345 }
3346
3347 let language = this.languages.select_language(&path).clone();
3348 let signature = this.symbol_signature(worktree_id, &path);
3349
3350 partial_symbols.push(PartialSymbol {
3351 source_worktree_id,
3352 worktree_id,
3353 language_server_name: adapter.name.clone(),
3354 name: lsp_symbol.name,
3355 kind: lsp_symbol.kind,
3356 language,
3357 path,
3358 range: range_from_lsp(lsp_symbol.location.range),
3359 signature,
3360 });
3361 }
3362 }
3363
3364 partial_symbols
3365 });
3366
3367 let mut symbols = Vec::new();
3368 for ps in partial_symbols.into_iter() {
3369 symbols.push(async move {
3370 let label = match ps.language {
3371 Some(language) => language.label_for_symbol(&ps.name, ps.kind).await,
3372 None => None,
3373 }
3374 .unwrap_or_else(|| CodeLabel::plain(ps.name.clone(), None));
3375
3376 Symbol {
3377 source_worktree_id: ps.source_worktree_id,
3378 worktree_id: ps.worktree_id,
3379 language_server_name: ps.language_server_name,
3380 name: ps.name,
3381 kind: ps.kind,
3382 label,
3383 path: ps.path,
3384 range: ps.range,
3385 signature: ps.signature,
3386 }
3387 });
3388 }
3389
3390 Ok(futures::future::join_all(symbols).await)
3391 })
3392 } else if let Some(project_id) = self.remote_id() {
3393 let request = self.client.request(proto::GetProjectSymbols {
3394 project_id,
3395 query: query.to_string(),
3396 });
3397 cx.spawn_weak(|this, cx| async move {
3398 let response = request.await?;
3399 let mut symbols = Vec::new();
3400 if let Some(this) = this.upgrade(&cx) {
3401 let new_symbols = this.read_with(&cx, |this, _| {
3402 let mut new_symbols = Vec::new();
3403 for symbol in response.symbols.into_iter() {
3404 new_symbols.push(this.deserialize_symbol(symbol));
3405 }
3406 new_symbols
3407 });
3408 symbols = futures::future::join_all(new_symbols.into_iter())
3409 .await
3410 .into_iter()
3411 .filter_map(|symbol| symbol.ok())
3412 .collect::<Vec<_>>();
3413 }
3414 Ok(symbols)
3415 })
3416 } else {
3417 Task::ready(Ok(Default::default()))
3418 }
3419 }
3420
3421 pub fn open_buffer_for_symbol(
3422 &mut self,
3423 symbol: &Symbol,
3424 cx: &mut ModelContext<Self>,
3425 ) -> Task<Result<ModelHandle<Buffer>>> {
3426 if self.is_local() {
3427 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3428 symbol.source_worktree_id,
3429 symbol.language_server_name.clone(),
3430 )) {
3431 *id
3432 } else {
3433 return Task::ready(Err(anyhow!(
3434 "language server for worktree and language not found"
3435 )));
3436 };
3437
3438 let worktree_abs_path = if let Some(worktree_abs_path) = self
3439 .worktree_for_id(symbol.worktree_id, cx)
3440 .and_then(|worktree| worktree.read(cx).as_local())
3441 .map(|local_worktree| local_worktree.abs_path())
3442 {
3443 worktree_abs_path
3444 } else {
3445 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3446 };
3447 let symbol_abs_path = worktree_abs_path.join(&symbol.path);
3448 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3449 uri
3450 } else {
3451 return Task::ready(Err(anyhow!("invalid symbol path")));
3452 };
3453
3454 self.open_local_buffer_via_lsp(
3455 symbol_uri,
3456 language_server_id,
3457 symbol.language_server_name.clone(),
3458 cx,
3459 )
3460 } else if let Some(project_id) = self.remote_id() {
3461 let request = self.client.request(proto::OpenBufferForSymbol {
3462 project_id,
3463 symbol: Some(serialize_symbol(symbol)),
3464 });
3465 cx.spawn(|this, mut cx| async move {
3466 let response = request.await?;
3467 let buffer = response.buffer.ok_or_else(|| anyhow!("invalid buffer"))?;
3468 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3469 .await
3470 })
3471 } else {
3472 Task::ready(Err(anyhow!("project does not have a remote id")))
3473 }
3474 }
3475
3476 pub fn hover<T: ToPointUtf16>(
3477 &self,
3478 buffer: &ModelHandle<Buffer>,
3479 position: T,
3480 cx: &mut ModelContext<Self>,
3481 ) -> Task<Result<Option<Hover>>> {
3482 let position = position.to_point_utf16(buffer.read(cx));
3483 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3484 }
3485
3486 pub fn completions<T: ToPointUtf16>(
3487 &self,
3488 source_buffer_handle: &ModelHandle<Buffer>,
3489 position: T,
3490 cx: &mut ModelContext<Self>,
3491 ) -> Task<Result<Vec<Completion>>> {
3492 let source_buffer_handle = source_buffer_handle.clone();
3493 let source_buffer = source_buffer_handle.read(cx);
3494 let buffer_id = source_buffer.remote_id();
3495 let language = source_buffer.language().cloned();
3496 let worktree;
3497 let buffer_abs_path;
3498 if let Some(file) = File::from_dyn(source_buffer.file()) {
3499 worktree = file.worktree.clone();
3500 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3501 } else {
3502 return Task::ready(Ok(Default::default()));
3503 };
3504
3505 let position = position.to_point_utf16(source_buffer);
3506 let anchor = source_buffer.anchor_after(position);
3507
3508 if worktree.read(cx).as_local().is_some() {
3509 let buffer_abs_path = buffer_abs_path.unwrap();
3510 let lang_server =
3511 if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3512 server.clone()
3513 } else {
3514 return Task::ready(Ok(Default::default()));
3515 };
3516
3517 cx.spawn(|_, cx| async move {
3518 let completions = lang_server
3519 .request::<lsp::request::Completion>(lsp::CompletionParams {
3520 text_document_position: lsp::TextDocumentPositionParams::new(
3521 lsp::TextDocumentIdentifier::new(
3522 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3523 ),
3524 point_to_lsp(position),
3525 ),
3526 context: Default::default(),
3527 work_done_progress_params: Default::default(),
3528 partial_result_params: Default::default(),
3529 })
3530 .await
3531 .context("lsp completion request failed")?;
3532
3533 let completions = if let Some(completions) = completions {
3534 match completions {
3535 lsp::CompletionResponse::Array(completions) => completions,
3536 lsp::CompletionResponse::List(list) => list.items,
3537 }
3538 } else {
3539 Default::default()
3540 };
3541
3542 let completions = source_buffer_handle.read_with(&cx, |this, _| {
3543 let snapshot = this.snapshot();
3544 let clipped_position = this.clip_point_utf16(position, Bias::Left);
3545 let mut range_for_token = None;
3546 completions.into_iter().filter_map(move |lsp_completion| {
3547 // For now, we can only handle additional edits if they are returned
3548 // when resolving the completion, not if they are present initially.
3549 if lsp_completion
3550 .additional_text_edits
3551 .as_ref()
3552 .map_or(false, |edits| !edits.is_empty())
3553 {
3554 return None;
3555 }
3556
3557 let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref() {
3558 // If the language server provides a range to overwrite, then
3559 // check that the range is valid.
3560 Some(lsp::CompletionTextEdit::Edit(edit)) => {
3561 let range = range_from_lsp(edit.range);
3562 let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3563 let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3564 if start != range.start || end != range.end {
3565 log::info!("completion out of expected range");
3566 return None;
3567 }
3568 (
3569 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3570 edit.new_text.clone(),
3571 )
3572 }
3573 // If the language server does not provide a range, then infer
3574 // the range based on the syntax tree.
3575 None => {
3576 if position != clipped_position {
3577 log::info!("completion out of expected range");
3578 return None;
3579 }
3580 let Range { start, end } = range_for_token
3581 .get_or_insert_with(|| {
3582 let offset = position.to_offset(&snapshot);
3583 let (range, kind) = snapshot.surrounding_word(offset);
3584 if kind == Some(CharKind::Word) {
3585 range
3586 } else {
3587 offset..offset
3588 }
3589 })
3590 .clone();
3591 let text = lsp_completion
3592 .insert_text
3593 .as_ref()
3594 .unwrap_or(&lsp_completion.label)
3595 .clone();
3596 (
3597 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3598 text.clone(),
3599 )
3600 }
3601 Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3602 log::info!("unsupported insert/replace completion");
3603 return None;
3604 }
3605 };
3606
3607 LineEnding::normalize(&mut new_text);
3608 let language = language.clone();
3609 Some(async move {
3610 let label = if let Some(language) = language {
3611 language.label_for_completion(&lsp_completion).await
3612 } else {
3613 None
3614 };
3615 Completion {
3616 old_range,
3617 new_text,
3618 label: label.unwrap_or_else(|| {
3619 CodeLabel::plain(
3620 lsp_completion.label.clone(),
3621 lsp_completion.filter_text.as_deref(),
3622 )
3623 }),
3624 lsp_completion,
3625 }
3626 })
3627 })
3628 });
3629
3630 Ok(futures::future::join_all(completions).await)
3631 })
3632 } else if let Some(project_id) = self.remote_id() {
3633 let rpc = self.client.clone();
3634 let message = proto::GetCompletions {
3635 project_id,
3636 buffer_id,
3637 position: Some(language::proto::serialize_anchor(&anchor)),
3638 version: serialize_version(&source_buffer.version()),
3639 };
3640 cx.spawn_weak(|_, mut cx| async move {
3641 let response = rpc.request(message).await?;
3642
3643 source_buffer_handle
3644 .update(&mut cx, |buffer, _| {
3645 buffer.wait_for_version(deserialize_version(response.version))
3646 })
3647 .await;
3648
3649 let completions = response.completions.into_iter().map(|completion| {
3650 language::proto::deserialize_completion(completion, language.clone())
3651 });
3652 futures::future::try_join_all(completions).await
3653 })
3654 } else {
3655 Task::ready(Ok(Default::default()))
3656 }
3657 }
3658
3659 pub fn apply_additional_edits_for_completion(
3660 &self,
3661 buffer_handle: ModelHandle<Buffer>,
3662 completion: Completion,
3663 push_to_history: bool,
3664 cx: &mut ModelContext<Self>,
3665 ) -> Task<Result<Option<Transaction>>> {
3666 let buffer = buffer_handle.read(cx);
3667 let buffer_id = buffer.remote_id();
3668
3669 if self.is_local() {
3670 let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3671 {
3672 server.clone()
3673 } else {
3674 return Task::ready(Ok(Default::default()));
3675 };
3676
3677 cx.spawn(|this, mut cx| async move {
3678 let resolved_completion = lang_server
3679 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3680 .await?;
3681 if let Some(edits) = resolved_completion.additional_text_edits {
3682 let edits = this
3683 .update(&mut cx, |this, cx| {
3684 this.edits_from_lsp(&buffer_handle, edits, None, cx)
3685 })
3686 .await?;
3687 buffer_handle.update(&mut cx, |buffer, cx| {
3688 buffer.finalize_last_transaction();
3689 buffer.start_transaction();
3690 for (range, text) in edits {
3691 buffer.edit([(range, text)], cx);
3692 }
3693 let transaction = if buffer.end_transaction(cx).is_some() {
3694 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3695 if !push_to_history {
3696 buffer.forget_transaction(transaction.id);
3697 }
3698 Some(transaction)
3699 } else {
3700 None
3701 };
3702 Ok(transaction)
3703 })
3704 } else {
3705 Ok(None)
3706 }
3707 })
3708 } else if let Some(project_id) = self.remote_id() {
3709 let client = self.client.clone();
3710 cx.spawn(|_, mut cx| async move {
3711 let response = client
3712 .request(proto::ApplyCompletionAdditionalEdits {
3713 project_id,
3714 buffer_id,
3715 completion: Some(language::proto::serialize_completion(&completion)),
3716 })
3717 .await?;
3718
3719 if let Some(transaction) = response.transaction {
3720 let transaction = language::proto::deserialize_transaction(transaction)?;
3721 buffer_handle
3722 .update(&mut cx, |buffer, _| {
3723 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3724 })
3725 .await;
3726 if push_to_history {
3727 buffer_handle.update(&mut cx, |buffer, _| {
3728 buffer.push_transaction(transaction.clone(), Instant::now());
3729 });
3730 }
3731 Ok(Some(transaction))
3732 } else {
3733 Ok(None)
3734 }
3735 })
3736 } else {
3737 Task::ready(Err(anyhow!("project does not have a remote id")))
3738 }
3739 }
3740
3741 pub fn code_actions<T: Clone + ToOffset>(
3742 &self,
3743 buffer_handle: &ModelHandle<Buffer>,
3744 range: Range<T>,
3745 cx: &mut ModelContext<Self>,
3746 ) -> Task<Result<Vec<CodeAction>>> {
3747 let buffer_handle = buffer_handle.clone();
3748 let buffer = buffer_handle.read(cx);
3749 let snapshot = buffer.snapshot();
3750 let relevant_diagnostics = snapshot
3751 .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3752 .map(|entry| entry.to_lsp_diagnostic_stub())
3753 .collect();
3754 let buffer_id = buffer.remote_id();
3755 let worktree;
3756 let buffer_abs_path;
3757 if let Some(file) = File::from_dyn(buffer.file()) {
3758 worktree = file.worktree.clone();
3759 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3760 } else {
3761 return Task::ready(Ok(Default::default()));
3762 };
3763 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3764
3765 if worktree.read(cx).as_local().is_some() {
3766 let buffer_abs_path = buffer_abs_path.unwrap();
3767 let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3768 {
3769 server.clone()
3770 } else {
3771 return Task::ready(Ok(Default::default()));
3772 };
3773
3774 let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3775 cx.foreground().spawn(async move {
3776 if !lang_server.capabilities().code_action_provider.is_some() {
3777 return Ok(Default::default());
3778 }
3779
3780 Ok(lang_server
3781 .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3782 text_document: lsp::TextDocumentIdentifier::new(
3783 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3784 ),
3785 range: lsp_range,
3786 work_done_progress_params: Default::default(),
3787 partial_result_params: Default::default(),
3788 context: lsp::CodeActionContext {
3789 diagnostics: relevant_diagnostics,
3790 only: Some(vec![
3791 lsp::CodeActionKind::QUICKFIX,
3792 lsp::CodeActionKind::REFACTOR,
3793 lsp::CodeActionKind::REFACTOR_EXTRACT,
3794 lsp::CodeActionKind::SOURCE,
3795 ]),
3796 },
3797 })
3798 .await?
3799 .unwrap_or_default()
3800 .into_iter()
3801 .filter_map(|entry| {
3802 if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3803 Some(CodeAction {
3804 range: range.clone(),
3805 lsp_action,
3806 })
3807 } else {
3808 None
3809 }
3810 })
3811 .collect())
3812 })
3813 } else if let Some(project_id) = self.remote_id() {
3814 let rpc = self.client.clone();
3815 let version = buffer.version();
3816 cx.spawn_weak(|_, mut cx| async move {
3817 let response = rpc
3818 .request(proto::GetCodeActions {
3819 project_id,
3820 buffer_id,
3821 start: Some(language::proto::serialize_anchor(&range.start)),
3822 end: Some(language::proto::serialize_anchor(&range.end)),
3823 version: serialize_version(&version),
3824 })
3825 .await?;
3826
3827 buffer_handle
3828 .update(&mut cx, |buffer, _| {
3829 buffer.wait_for_version(deserialize_version(response.version))
3830 })
3831 .await;
3832
3833 response
3834 .actions
3835 .into_iter()
3836 .map(language::proto::deserialize_code_action)
3837 .collect()
3838 })
3839 } else {
3840 Task::ready(Ok(Default::default()))
3841 }
3842 }
3843
3844 pub fn apply_code_action(
3845 &self,
3846 buffer_handle: ModelHandle<Buffer>,
3847 mut action: CodeAction,
3848 push_to_history: bool,
3849 cx: &mut ModelContext<Self>,
3850 ) -> Task<Result<ProjectTransaction>> {
3851 if self.is_local() {
3852 let buffer = buffer_handle.read(cx);
3853 let (lsp_adapter, lang_server) =
3854 if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3855 (adapter.clone(), server.clone())
3856 } else {
3857 return Task::ready(Ok(Default::default()));
3858 };
3859 let range = action.range.to_point_utf16(buffer);
3860
3861 cx.spawn(|this, mut cx| async move {
3862 if let Some(lsp_range) = action
3863 .lsp_action
3864 .data
3865 .as_mut()
3866 .and_then(|d| d.get_mut("codeActionParams"))
3867 .and_then(|d| d.get_mut("range"))
3868 {
3869 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3870 action.lsp_action = lang_server
3871 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3872 .await?;
3873 } else {
3874 let actions = this
3875 .update(&mut cx, |this, cx| {
3876 this.code_actions(&buffer_handle, action.range, cx)
3877 })
3878 .await?;
3879 action.lsp_action = actions
3880 .into_iter()
3881 .find(|a| a.lsp_action.title == action.lsp_action.title)
3882 .ok_or_else(|| anyhow!("code action is outdated"))?
3883 .lsp_action;
3884 }
3885
3886 if let Some(edit) = action.lsp_action.edit {
3887 Self::deserialize_workspace_edit(
3888 this,
3889 edit,
3890 push_to_history,
3891 lsp_adapter.clone(),
3892 lang_server.clone(),
3893 &mut cx,
3894 )
3895 .await
3896 } else if let Some(command) = action.lsp_action.command {
3897 this.update(&mut cx, |this, _| {
3898 this.last_workspace_edits_by_language_server
3899 .remove(&lang_server.server_id());
3900 });
3901 lang_server
3902 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3903 command: command.command,
3904 arguments: command.arguments.unwrap_or_default(),
3905 ..Default::default()
3906 })
3907 .await?;
3908 Ok(this.update(&mut cx, |this, _| {
3909 this.last_workspace_edits_by_language_server
3910 .remove(&lang_server.server_id())
3911 .unwrap_or_default()
3912 }))
3913 } else {
3914 Ok(ProjectTransaction::default())
3915 }
3916 })
3917 } else if let Some(project_id) = self.remote_id() {
3918 let client = self.client.clone();
3919 let request = proto::ApplyCodeAction {
3920 project_id,
3921 buffer_id: buffer_handle.read(cx).remote_id(),
3922 action: Some(language::proto::serialize_code_action(&action)),
3923 };
3924 cx.spawn(|this, mut cx| async move {
3925 let response = client
3926 .request(request)
3927 .await?
3928 .transaction
3929 .ok_or_else(|| anyhow!("missing transaction"))?;
3930 this.update(&mut cx, |this, cx| {
3931 this.deserialize_project_transaction(response, push_to_history, cx)
3932 })
3933 .await
3934 })
3935 } else {
3936 Task::ready(Err(anyhow!("project does not have a remote id")))
3937 }
3938 }
3939
3940 async fn deserialize_workspace_edit(
3941 this: ModelHandle<Self>,
3942 edit: lsp::WorkspaceEdit,
3943 push_to_history: bool,
3944 lsp_adapter: Arc<LspAdapter>,
3945 language_server: Arc<LanguageServer>,
3946 cx: &mut AsyncAppContext,
3947 ) -> Result<ProjectTransaction> {
3948 let fs = this.read_with(cx, |this, _| this.fs.clone());
3949 let mut operations = Vec::new();
3950 if let Some(document_changes) = edit.document_changes {
3951 match document_changes {
3952 lsp::DocumentChanges::Edits(edits) => {
3953 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3954 }
3955 lsp::DocumentChanges::Operations(ops) => operations = ops,
3956 }
3957 } else if let Some(changes) = edit.changes {
3958 operations.extend(changes.into_iter().map(|(uri, edits)| {
3959 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3960 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3961 uri,
3962 version: None,
3963 },
3964 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3965 })
3966 }));
3967 }
3968
3969 let mut project_transaction = ProjectTransaction::default();
3970 for operation in operations {
3971 match operation {
3972 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3973 let abs_path = op
3974 .uri
3975 .to_file_path()
3976 .map_err(|_| anyhow!("can't convert URI to path"))?;
3977
3978 if let Some(parent_path) = abs_path.parent() {
3979 fs.create_dir(parent_path).await?;
3980 }
3981 if abs_path.ends_with("/") {
3982 fs.create_dir(&abs_path).await?;
3983 } else {
3984 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3985 .await?;
3986 }
3987 }
3988 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3989 let source_abs_path = op
3990 .old_uri
3991 .to_file_path()
3992 .map_err(|_| anyhow!("can't convert URI to path"))?;
3993 let target_abs_path = op
3994 .new_uri
3995 .to_file_path()
3996 .map_err(|_| anyhow!("can't convert URI to path"))?;
3997 fs.rename(
3998 &source_abs_path,
3999 &target_abs_path,
4000 op.options.map(Into::into).unwrap_or_default(),
4001 )
4002 .await?;
4003 }
4004 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4005 let abs_path = op
4006 .uri
4007 .to_file_path()
4008 .map_err(|_| anyhow!("can't convert URI to path"))?;
4009 let options = op.options.map(Into::into).unwrap_or_default();
4010 if abs_path.ends_with("/") {
4011 fs.remove_dir(&abs_path, options).await?;
4012 } else {
4013 fs.remove_file(&abs_path, options).await?;
4014 }
4015 }
4016 lsp::DocumentChangeOperation::Edit(op) => {
4017 let buffer_to_edit = this
4018 .update(cx, |this, cx| {
4019 this.open_local_buffer_via_lsp(
4020 op.text_document.uri,
4021 language_server.server_id(),
4022 lsp_adapter.name.clone(),
4023 cx,
4024 )
4025 })
4026 .await?;
4027
4028 let edits = this
4029 .update(cx, |this, cx| {
4030 let edits = op.edits.into_iter().map(|edit| match edit {
4031 lsp::OneOf::Left(edit) => edit,
4032 lsp::OneOf::Right(edit) => edit.text_edit,
4033 });
4034 this.edits_from_lsp(
4035 &buffer_to_edit,
4036 edits,
4037 op.text_document.version,
4038 cx,
4039 )
4040 })
4041 .await?;
4042
4043 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4044 buffer.finalize_last_transaction();
4045 buffer.start_transaction();
4046 for (range, text) in edits {
4047 buffer.edit([(range, text)], cx);
4048 }
4049 let transaction = if buffer.end_transaction(cx).is_some() {
4050 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4051 if !push_to_history {
4052 buffer.forget_transaction(transaction.id);
4053 }
4054 Some(transaction)
4055 } else {
4056 None
4057 };
4058
4059 transaction
4060 });
4061 if let Some(transaction) = transaction {
4062 project_transaction.0.insert(buffer_to_edit, transaction);
4063 }
4064 }
4065 }
4066 }
4067
4068 Ok(project_transaction)
4069 }
4070
4071 pub fn prepare_rename<T: ToPointUtf16>(
4072 &self,
4073 buffer: ModelHandle<Buffer>,
4074 position: T,
4075 cx: &mut ModelContext<Self>,
4076 ) -> Task<Result<Option<Range<Anchor>>>> {
4077 let position = position.to_point_utf16(buffer.read(cx));
4078 self.request_lsp(buffer, PrepareRename { position }, cx)
4079 }
4080
4081 pub fn perform_rename<T: ToPointUtf16>(
4082 &self,
4083 buffer: ModelHandle<Buffer>,
4084 position: T,
4085 new_name: String,
4086 push_to_history: bool,
4087 cx: &mut ModelContext<Self>,
4088 ) -> Task<Result<ProjectTransaction>> {
4089 let position = position.to_point_utf16(buffer.read(cx));
4090 self.request_lsp(
4091 buffer,
4092 PerformRename {
4093 position,
4094 new_name,
4095 push_to_history,
4096 },
4097 cx,
4098 )
4099 }
4100
4101 pub fn search(
4102 &self,
4103 query: SearchQuery,
4104 cx: &mut ModelContext<Self>,
4105 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4106 if self.is_local() {
4107 let snapshots = self
4108 .visible_worktrees(cx)
4109 .filter_map(|tree| {
4110 let tree = tree.read(cx).as_local()?;
4111 Some(tree.snapshot())
4112 })
4113 .collect::<Vec<_>>();
4114
4115 let background = cx.background().clone();
4116 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4117 if path_count == 0 {
4118 return Task::ready(Ok(Default::default()));
4119 }
4120 let workers = background.num_cpus().min(path_count);
4121 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4122 cx.background()
4123 .spawn({
4124 let fs = self.fs.clone();
4125 let background = cx.background().clone();
4126 let query = query.clone();
4127 async move {
4128 let fs = &fs;
4129 let query = &query;
4130 let matching_paths_tx = &matching_paths_tx;
4131 let paths_per_worker = (path_count + workers - 1) / workers;
4132 let snapshots = &snapshots;
4133 background
4134 .scoped(|scope| {
4135 for worker_ix in 0..workers {
4136 let worker_start_ix = worker_ix * paths_per_worker;
4137 let worker_end_ix = worker_start_ix + paths_per_worker;
4138 scope.spawn(async move {
4139 let mut snapshot_start_ix = 0;
4140 let mut abs_path = PathBuf::new();
4141 for snapshot in snapshots {
4142 let snapshot_end_ix =
4143 snapshot_start_ix + snapshot.visible_file_count();
4144 if worker_end_ix <= snapshot_start_ix {
4145 break;
4146 } else if worker_start_ix > snapshot_end_ix {
4147 snapshot_start_ix = snapshot_end_ix;
4148 continue;
4149 } else {
4150 let start_in_snapshot = worker_start_ix
4151 .saturating_sub(snapshot_start_ix);
4152 let end_in_snapshot =
4153 cmp::min(worker_end_ix, snapshot_end_ix)
4154 - snapshot_start_ix;
4155
4156 for entry in snapshot
4157 .files(false, start_in_snapshot)
4158 .take(end_in_snapshot - start_in_snapshot)
4159 {
4160 if matching_paths_tx.is_closed() {
4161 break;
4162 }
4163
4164 abs_path.clear();
4165 abs_path.push(&snapshot.abs_path());
4166 abs_path.push(&entry.path);
4167 let matches = if let Some(file) =
4168 fs.open_sync(&abs_path).await.log_err()
4169 {
4170 query.detect(file).unwrap_or(false)
4171 } else {
4172 false
4173 };
4174
4175 if matches {
4176 let project_path =
4177 (snapshot.id(), entry.path.clone());
4178 if matching_paths_tx
4179 .send(project_path)
4180 .await
4181 .is_err()
4182 {
4183 break;
4184 }
4185 }
4186 }
4187
4188 snapshot_start_ix = snapshot_end_ix;
4189 }
4190 }
4191 });
4192 }
4193 })
4194 .await;
4195 }
4196 })
4197 .detach();
4198
4199 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4200 let open_buffers = self
4201 .opened_buffers
4202 .values()
4203 .filter_map(|b| b.upgrade(cx))
4204 .collect::<HashSet<_>>();
4205 cx.spawn(|this, cx| async move {
4206 for buffer in &open_buffers {
4207 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4208 buffers_tx.send((buffer.clone(), snapshot)).await?;
4209 }
4210
4211 let open_buffers = Rc::new(RefCell::new(open_buffers));
4212 while let Some(project_path) = matching_paths_rx.next().await {
4213 if buffers_tx.is_closed() {
4214 break;
4215 }
4216
4217 let this = this.clone();
4218 let open_buffers = open_buffers.clone();
4219 let buffers_tx = buffers_tx.clone();
4220 cx.spawn(|mut cx| async move {
4221 if let Some(buffer) = this
4222 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4223 .await
4224 .log_err()
4225 {
4226 if open_buffers.borrow_mut().insert(buffer.clone()) {
4227 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4228 buffers_tx.send((buffer, snapshot)).await?;
4229 }
4230 }
4231
4232 Ok::<_, anyhow::Error>(())
4233 })
4234 .detach();
4235 }
4236
4237 Ok::<_, anyhow::Error>(())
4238 })
4239 .detach_and_log_err(cx);
4240
4241 let background = cx.background().clone();
4242 cx.background().spawn(async move {
4243 let query = &query;
4244 let mut matched_buffers = Vec::new();
4245 for _ in 0..workers {
4246 matched_buffers.push(HashMap::default());
4247 }
4248 background
4249 .scoped(|scope| {
4250 for worker_matched_buffers in matched_buffers.iter_mut() {
4251 let mut buffers_rx = buffers_rx.clone();
4252 scope.spawn(async move {
4253 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4254 let buffer_matches = query
4255 .search(snapshot.as_rope())
4256 .await
4257 .iter()
4258 .map(|range| {
4259 snapshot.anchor_before(range.start)
4260 ..snapshot.anchor_after(range.end)
4261 })
4262 .collect::<Vec<_>>();
4263 if !buffer_matches.is_empty() {
4264 worker_matched_buffers
4265 .insert(buffer.clone(), buffer_matches);
4266 }
4267 }
4268 });
4269 }
4270 })
4271 .await;
4272 Ok(matched_buffers.into_iter().flatten().collect())
4273 })
4274 } else if let Some(project_id) = self.remote_id() {
4275 let request = self.client.request(query.to_proto(project_id));
4276 cx.spawn(|this, mut cx| async move {
4277 let response = request.await?;
4278 let mut result = HashMap::default();
4279 for location in response.locations {
4280 let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
4281 let target_buffer = this
4282 .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
4283 .await?;
4284 let start = location
4285 .start
4286 .and_then(deserialize_anchor)
4287 .ok_or_else(|| anyhow!("missing target start"))?;
4288 let end = location
4289 .end
4290 .and_then(deserialize_anchor)
4291 .ok_or_else(|| anyhow!("missing target end"))?;
4292 result
4293 .entry(target_buffer)
4294 .or_insert(Vec::new())
4295 .push(start..end)
4296 }
4297 Ok(result)
4298 })
4299 } else {
4300 Task::ready(Ok(Default::default()))
4301 }
4302 }
4303
4304 fn request_lsp<R: LspCommand>(
4305 &self,
4306 buffer_handle: ModelHandle<Buffer>,
4307 request: R,
4308 cx: &mut ModelContext<Self>,
4309 ) -> Task<Result<R::Response>>
4310 where
4311 <R::LspRequest as lsp::request::Request>::Result: Send,
4312 {
4313 let buffer = buffer_handle.read(cx);
4314 if self.is_local() {
4315 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4316 if let Some((file, language_server)) = file.zip(
4317 self.language_server_for_buffer(buffer, cx)
4318 .map(|(_, server)| server.clone()),
4319 ) {
4320 let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4321 return cx.spawn(|this, cx| async move {
4322 if !request.check_capabilities(&language_server.capabilities()) {
4323 return Ok(Default::default());
4324 }
4325
4326 let response = language_server
4327 .request::<R::LspRequest>(lsp_params)
4328 .await
4329 .context("lsp request failed")?;
4330 request
4331 .response_from_lsp(response, this, buffer_handle, cx)
4332 .await
4333 });
4334 }
4335 } else if let Some(project_id) = self.remote_id() {
4336 let rpc = self.client.clone();
4337 let message = request.to_proto(project_id, buffer);
4338 return cx.spawn(|this, cx| async move {
4339 let response = rpc.request(message).await?;
4340 request
4341 .response_from_proto(response, this, buffer_handle, cx)
4342 .await
4343 });
4344 }
4345 Task::ready(Ok(Default::default()))
4346 }
4347
4348 pub fn find_or_create_local_worktree(
4349 &mut self,
4350 abs_path: impl AsRef<Path>,
4351 visible: bool,
4352 cx: &mut ModelContext<Self>,
4353 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4354 let abs_path = abs_path.as_ref();
4355 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4356 Task::ready(Ok((tree.clone(), relative_path.into())))
4357 } else {
4358 let worktree = self.create_local_worktree(abs_path, visible, cx);
4359 cx.foreground()
4360 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4361 }
4362 }
4363
4364 pub fn find_local_worktree(
4365 &self,
4366 abs_path: &Path,
4367 cx: &AppContext,
4368 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4369 for tree in &self.worktrees {
4370 if let Some(tree) = tree.upgrade(cx) {
4371 if let Some(relative_path) = tree
4372 .read(cx)
4373 .as_local()
4374 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4375 {
4376 return Some((tree.clone(), relative_path.into()));
4377 }
4378 }
4379 }
4380 None
4381 }
4382
4383 pub fn is_shared(&self) -> bool {
4384 match &self.client_state {
4385 ProjectClientState::Local { is_shared, .. } => *is_shared,
4386 ProjectClientState::Remote { .. } => false,
4387 }
4388 }
4389
4390 fn create_local_worktree(
4391 &mut self,
4392 abs_path: impl AsRef<Path>,
4393 visible: bool,
4394 cx: &mut ModelContext<Self>,
4395 ) -> Task<Result<ModelHandle<Worktree>>> {
4396 let fs = self.fs.clone();
4397 let client = self.client.clone();
4398 let next_entry_id = self.next_entry_id.clone();
4399 let path: Arc<Path> = abs_path.as_ref().into();
4400 let task = self
4401 .loading_local_worktrees
4402 .entry(path.clone())
4403 .or_insert_with(|| {
4404 cx.spawn(|project, mut cx| {
4405 async move {
4406 let worktree = Worktree::local(
4407 client.clone(),
4408 path.clone(),
4409 visible,
4410 fs,
4411 next_entry_id,
4412 &mut cx,
4413 )
4414 .await;
4415 project.update(&mut cx, |project, _| {
4416 project.loading_local_worktrees.remove(&path);
4417 });
4418 let worktree = worktree?;
4419
4420 let project_id = project.update(&mut cx, |project, cx| {
4421 project.add_worktree(&worktree, cx);
4422 project.shared_remote_id()
4423 });
4424
4425 if let Some(project_id) = project_id {
4426 worktree
4427 .update(&mut cx, |worktree, cx| {
4428 worktree.as_local_mut().unwrap().share(project_id, cx)
4429 })
4430 .await
4431 .log_err();
4432 }
4433
4434 Ok(worktree)
4435 }
4436 .map_err(|err| Arc::new(err))
4437 })
4438 .shared()
4439 })
4440 .clone();
4441 cx.foreground().spawn(async move {
4442 match task.await {
4443 Ok(worktree) => Ok(worktree),
4444 Err(err) => Err(anyhow!("{}", err)),
4445 }
4446 })
4447 }
4448
4449 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4450 self.worktrees.retain(|worktree| {
4451 if let Some(worktree) = worktree.upgrade(cx) {
4452 let id = worktree.read(cx).id();
4453 if id == id_to_remove {
4454 cx.emit(Event::WorktreeRemoved(id));
4455 false
4456 } else {
4457 true
4458 }
4459 } else {
4460 false
4461 }
4462 });
4463 self.metadata_changed(true, cx);
4464 cx.notify();
4465 }
4466
4467 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4468 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
4469 if worktree.read(cx).is_local() {
4470 cx.subscribe(&worktree, |this, worktree, _, cx| {
4471 this.update_local_worktree_buffers(worktree, cx);
4472 })
4473 .detach();
4474 }
4475
4476 let push_strong_handle = {
4477 let worktree = worktree.read(cx);
4478 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4479 };
4480 if push_strong_handle {
4481 self.worktrees
4482 .push(WorktreeHandle::Strong(worktree.clone()));
4483 } else {
4484 self.worktrees
4485 .push(WorktreeHandle::Weak(worktree.downgrade()));
4486 }
4487
4488 self.metadata_changed(true, cx);
4489 cx.observe_release(&worktree, |this, worktree, cx| {
4490 this.remove_worktree(worktree.id(), cx);
4491 cx.notify();
4492 })
4493 .detach();
4494
4495 cx.emit(Event::WorktreeAdded);
4496 cx.notify();
4497 }
4498
4499 fn update_local_worktree_buffers(
4500 &mut self,
4501 worktree_handle: ModelHandle<Worktree>,
4502 cx: &mut ModelContext<Self>,
4503 ) {
4504 let snapshot = worktree_handle.read(cx).snapshot();
4505 let mut buffers_to_delete = Vec::new();
4506 let mut renamed_buffers = Vec::new();
4507 for (buffer_id, buffer) in &self.opened_buffers {
4508 if let Some(buffer) = buffer.upgrade(cx) {
4509 buffer.update(cx, |buffer, cx| {
4510 if let Some(old_file) = File::from_dyn(buffer.file()) {
4511 if old_file.worktree != worktree_handle {
4512 return;
4513 }
4514
4515 let new_file = if let Some(entry) = old_file
4516 .entry_id
4517 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
4518 {
4519 File {
4520 is_local: true,
4521 entry_id: Some(entry.id),
4522 mtime: entry.mtime,
4523 path: entry.path.clone(),
4524 worktree: worktree_handle.clone(),
4525 }
4526 } else if let Some(entry) =
4527 snapshot.entry_for_path(old_file.path().as_ref())
4528 {
4529 File {
4530 is_local: true,
4531 entry_id: Some(entry.id),
4532 mtime: entry.mtime,
4533 path: entry.path.clone(),
4534 worktree: worktree_handle.clone(),
4535 }
4536 } else {
4537 File {
4538 is_local: true,
4539 entry_id: None,
4540 path: old_file.path().clone(),
4541 mtime: old_file.mtime(),
4542 worktree: worktree_handle.clone(),
4543 }
4544 };
4545
4546 let old_path = old_file.abs_path(cx);
4547 if new_file.abs_path(cx) != old_path {
4548 renamed_buffers.push((cx.handle(), old_path));
4549 }
4550
4551 if let Some(project_id) = self.shared_remote_id() {
4552 self.client
4553 .send(proto::UpdateBufferFile {
4554 project_id,
4555 buffer_id: *buffer_id as u64,
4556 file: Some(new_file.to_proto()),
4557 })
4558 .log_err();
4559 }
4560 buffer.file_updated(Arc::new(new_file), cx).detach();
4561 }
4562 });
4563 } else {
4564 buffers_to_delete.push(*buffer_id);
4565 }
4566 }
4567
4568 for buffer_id in buffers_to_delete {
4569 self.opened_buffers.remove(&buffer_id);
4570 }
4571
4572 for (buffer, old_path) in renamed_buffers {
4573 self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4574 self.assign_language_to_buffer(&buffer, cx);
4575 self.register_buffer_with_language_server(&buffer, cx);
4576 }
4577 }
4578
4579 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4580 let new_active_entry = entry.and_then(|project_path| {
4581 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4582 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4583 Some(entry.id)
4584 });
4585 if new_active_entry != self.active_entry {
4586 self.active_entry = new_active_entry;
4587 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4588 }
4589 }
4590
4591 pub fn language_servers_running_disk_based_diagnostics<'a>(
4592 &'a self,
4593 ) -> impl 'a + Iterator<Item = usize> {
4594 self.language_server_statuses
4595 .iter()
4596 .filter_map(|(id, status)| {
4597 if status.has_pending_diagnostic_updates {
4598 Some(*id)
4599 } else {
4600 None
4601 }
4602 })
4603 }
4604
4605 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4606 let mut summary = DiagnosticSummary::default();
4607 for (_, path_summary) in self.diagnostic_summaries(cx) {
4608 summary.error_count += path_summary.error_count;
4609 summary.warning_count += path_summary.warning_count;
4610 }
4611 summary
4612 }
4613
4614 pub fn diagnostic_summaries<'a>(
4615 &'a self,
4616 cx: &'a AppContext,
4617 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4618 self.visible_worktrees(cx).flat_map(move |worktree| {
4619 let worktree = worktree.read(cx);
4620 let worktree_id = worktree.id();
4621 worktree
4622 .diagnostic_summaries()
4623 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4624 })
4625 }
4626
4627 pub fn disk_based_diagnostics_started(
4628 &mut self,
4629 language_server_id: usize,
4630 cx: &mut ModelContext<Self>,
4631 ) {
4632 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4633 }
4634
4635 pub fn disk_based_diagnostics_finished(
4636 &mut self,
4637 language_server_id: usize,
4638 cx: &mut ModelContext<Self>,
4639 ) {
4640 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4641 }
4642
4643 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4644 self.active_entry
4645 }
4646
4647 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<ProjectEntryId> {
4648 self.worktree_for_id(path.worktree_id, cx)?
4649 .read(cx)
4650 .entry_for_path(&path.path)
4651 .map(|entry| entry.id)
4652 }
4653
4654 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4655 let worktree = self.worktree_for_entry(entry_id, cx)?;
4656 let worktree = worktree.read(cx);
4657 let worktree_id = worktree.id();
4658 let path = worktree.entry_for_id(entry_id)?.path.clone();
4659 Some(ProjectPath { worktree_id, path })
4660 }
4661
4662 // RPC message handlers
4663
4664 async fn handle_request_join_project(
4665 this: ModelHandle<Self>,
4666 message: TypedEnvelope<proto::RequestJoinProject>,
4667 _: Arc<Client>,
4668 mut cx: AsyncAppContext,
4669 ) -> Result<()> {
4670 let user_id = message.payload.requester_id;
4671 if this.read_with(&cx, |project, _| {
4672 project.collaborators.values().any(|c| c.user.id == user_id)
4673 }) {
4674 this.update(&mut cx, |this, cx| {
4675 this.respond_to_join_request(user_id, true, cx)
4676 });
4677 } else {
4678 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4679 let user = user_store
4680 .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
4681 .await?;
4682 this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
4683 }
4684 Ok(())
4685 }
4686
4687 async fn handle_unregister_project(
4688 this: ModelHandle<Self>,
4689 _: TypedEnvelope<proto::UnregisterProject>,
4690 _: Arc<Client>,
4691 mut cx: AsyncAppContext,
4692 ) -> Result<()> {
4693 this.update(&mut cx, |this, cx| this.removed_from_project(cx));
4694 Ok(())
4695 }
4696
4697 async fn handle_project_unshared(
4698 this: ModelHandle<Self>,
4699 _: TypedEnvelope<proto::ProjectUnshared>,
4700 _: Arc<Client>,
4701 mut cx: AsyncAppContext,
4702 ) -> Result<()> {
4703 this.update(&mut cx, |this, cx| this.unshared(cx));
4704 Ok(())
4705 }
4706
4707 async fn handle_add_collaborator(
4708 this: ModelHandle<Self>,
4709 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4710 _: Arc<Client>,
4711 mut cx: AsyncAppContext,
4712 ) -> Result<()> {
4713 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4714 let collaborator = envelope
4715 .payload
4716 .collaborator
4717 .take()
4718 .ok_or_else(|| anyhow!("empty collaborator"))?;
4719
4720 let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
4721 this.update(&mut cx, |this, cx| {
4722 this.collaborators
4723 .insert(collaborator.peer_id, collaborator);
4724 cx.notify();
4725 });
4726
4727 Ok(())
4728 }
4729
4730 async fn handle_remove_collaborator(
4731 this: ModelHandle<Self>,
4732 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4733 _: Arc<Client>,
4734 mut cx: AsyncAppContext,
4735 ) -> Result<()> {
4736 this.update(&mut cx, |this, cx| {
4737 let peer_id = PeerId(envelope.payload.peer_id);
4738 let replica_id = this
4739 .collaborators
4740 .remove(&peer_id)
4741 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4742 .replica_id;
4743 for (_, buffer) in &this.opened_buffers {
4744 if let Some(buffer) = buffer.upgrade(cx) {
4745 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4746 }
4747 }
4748
4749 cx.emit(Event::CollaboratorLeft(peer_id));
4750 cx.notify();
4751 Ok(())
4752 })
4753 }
4754
4755 async fn handle_join_project_request_cancelled(
4756 this: ModelHandle<Self>,
4757 envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
4758 _: Arc<Client>,
4759 mut cx: AsyncAppContext,
4760 ) -> Result<()> {
4761 let user = this
4762 .update(&mut cx, |this, cx| {
4763 this.user_store.update(cx, |user_store, cx| {
4764 user_store.fetch_user(envelope.payload.requester_id, cx)
4765 })
4766 })
4767 .await?;
4768
4769 this.update(&mut cx, |_, cx| {
4770 cx.emit(Event::ContactCancelledJoinRequest(user));
4771 });
4772
4773 Ok(())
4774 }
4775
4776 async fn handle_update_project(
4777 this: ModelHandle<Self>,
4778 envelope: TypedEnvelope<proto::UpdateProject>,
4779 client: Arc<Client>,
4780 mut cx: AsyncAppContext,
4781 ) -> Result<()> {
4782 this.update(&mut cx, |this, cx| {
4783 let replica_id = this.replica_id();
4784 let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4785
4786 let mut old_worktrees_by_id = this
4787 .worktrees
4788 .drain(..)
4789 .filter_map(|worktree| {
4790 let worktree = worktree.upgrade(cx)?;
4791 Some((worktree.read(cx).id(), worktree))
4792 })
4793 .collect::<HashMap<_, _>>();
4794
4795 for worktree in envelope.payload.worktrees {
4796 if let Some(old_worktree) =
4797 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4798 {
4799 this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4800 } else {
4801 let worktree =
4802 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4803 this.add_worktree(&worktree, cx);
4804 }
4805 }
4806
4807 this.metadata_changed(true, cx);
4808 for (id, _) in old_worktrees_by_id {
4809 cx.emit(Event::WorktreeRemoved(id));
4810 }
4811
4812 Ok(())
4813 })
4814 }
4815
4816 async fn handle_update_worktree(
4817 this: ModelHandle<Self>,
4818 envelope: TypedEnvelope<proto::UpdateWorktree>,
4819 _: Arc<Client>,
4820 mut cx: AsyncAppContext,
4821 ) -> Result<()> {
4822 this.update(&mut cx, |this, cx| {
4823 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4824 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4825 worktree.update(cx, |worktree, _| {
4826 let worktree = worktree.as_remote_mut().unwrap();
4827 worktree.update_from_remote(envelope.payload);
4828 });
4829 }
4830 Ok(())
4831 })
4832 }
4833
4834 async fn handle_create_project_entry(
4835 this: ModelHandle<Self>,
4836 envelope: TypedEnvelope<proto::CreateProjectEntry>,
4837 _: Arc<Client>,
4838 mut cx: AsyncAppContext,
4839 ) -> Result<proto::ProjectEntryResponse> {
4840 let worktree = this.update(&mut cx, |this, cx| {
4841 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4842 this.worktree_for_id(worktree_id, cx)
4843 .ok_or_else(|| anyhow!("worktree not found"))
4844 })?;
4845 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4846 let entry = worktree
4847 .update(&mut cx, |worktree, cx| {
4848 let worktree = worktree.as_local_mut().unwrap();
4849 let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4850 worktree.create_entry(path, envelope.payload.is_directory, cx)
4851 })
4852 .await?;
4853 Ok(proto::ProjectEntryResponse {
4854 entry: Some((&entry).into()),
4855 worktree_scan_id: worktree_scan_id as u64,
4856 })
4857 }
4858
4859 async fn handle_rename_project_entry(
4860 this: ModelHandle<Self>,
4861 envelope: TypedEnvelope<proto::RenameProjectEntry>,
4862 _: Arc<Client>,
4863 mut cx: AsyncAppContext,
4864 ) -> Result<proto::ProjectEntryResponse> {
4865 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4866 let worktree = this.read_with(&cx, |this, cx| {
4867 this.worktree_for_entry(entry_id, cx)
4868 .ok_or_else(|| anyhow!("worktree not found"))
4869 })?;
4870 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4871 let entry = worktree
4872 .update(&mut cx, |worktree, cx| {
4873 let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4874 worktree
4875 .as_local_mut()
4876 .unwrap()
4877 .rename_entry(entry_id, new_path, cx)
4878 .ok_or_else(|| anyhow!("invalid entry"))
4879 })?
4880 .await?;
4881 Ok(proto::ProjectEntryResponse {
4882 entry: Some((&entry).into()),
4883 worktree_scan_id: worktree_scan_id as u64,
4884 })
4885 }
4886
4887 async fn handle_copy_project_entry(
4888 this: ModelHandle<Self>,
4889 envelope: TypedEnvelope<proto::CopyProjectEntry>,
4890 _: Arc<Client>,
4891 mut cx: AsyncAppContext,
4892 ) -> Result<proto::ProjectEntryResponse> {
4893 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4894 let worktree = this.read_with(&cx, |this, cx| {
4895 this.worktree_for_entry(entry_id, cx)
4896 .ok_or_else(|| anyhow!("worktree not found"))
4897 })?;
4898 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4899 let entry = worktree
4900 .update(&mut cx, |worktree, cx| {
4901 let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4902 worktree
4903 .as_local_mut()
4904 .unwrap()
4905 .copy_entry(entry_id, new_path, cx)
4906 .ok_or_else(|| anyhow!("invalid entry"))
4907 })?
4908 .await?;
4909 Ok(proto::ProjectEntryResponse {
4910 entry: Some((&entry).into()),
4911 worktree_scan_id: worktree_scan_id as u64,
4912 })
4913 }
4914
4915 async fn handle_delete_project_entry(
4916 this: ModelHandle<Self>,
4917 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4918 _: Arc<Client>,
4919 mut cx: AsyncAppContext,
4920 ) -> Result<proto::ProjectEntryResponse> {
4921 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4922 let worktree = this.read_with(&cx, |this, cx| {
4923 this.worktree_for_entry(entry_id, cx)
4924 .ok_or_else(|| anyhow!("worktree not found"))
4925 })?;
4926 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4927 worktree
4928 .update(&mut cx, |worktree, cx| {
4929 worktree
4930 .as_local_mut()
4931 .unwrap()
4932 .delete_entry(entry_id, cx)
4933 .ok_or_else(|| anyhow!("invalid entry"))
4934 })?
4935 .await?;
4936 Ok(proto::ProjectEntryResponse {
4937 entry: None,
4938 worktree_scan_id: worktree_scan_id as u64,
4939 })
4940 }
4941
4942 async fn handle_update_diagnostic_summary(
4943 this: ModelHandle<Self>,
4944 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4945 _: Arc<Client>,
4946 mut cx: AsyncAppContext,
4947 ) -> Result<()> {
4948 this.update(&mut cx, |this, cx| {
4949 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4950 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4951 if let Some(summary) = envelope.payload.summary {
4952 let project_path = ProjectPath {
4953 worktree_id,
4954 path: Path::new(&summary.path).into(),
4955 };
4956 worktree.update(cx, |worktree, _| {
4957 worktree
4958 .as_remote_mut()
4959 .unwrap()
4960 .update_diagnostic_summary(project_path.path.clone(), &summary);
4961 });
4962 cx.emit(Event::DiagnosticsUpdated {
4963 language_server_id: summary.language_server_id as usize,
4964 path: project_path,
4965 });
4966 }
4967 }
4968 Ok(())
4969 })
4970 }
4971
4972 async fn handle_start_language_server(
4973 this: ModelHandle<Self>,
4974 envelope: TypedEnvelope<proto::StartLanguageServer>,
4975 _: Arc<Client>,
4976 mut cx: AsyncAppContext,
4977 ) -> Result<()> {
4978 let server = envelope
4979 .payload
4980 .server
4981 .ok_or_else(|| anyhow!("invalid server"))?;
4982 this.update(&mut cx, |this, cx| {
4983 this.language_server_statuses.insert(
4984 server.id as usize,
4985 LanguageServerStatus {
4986 name: server.name,
4987 pending_work: Default::default(),
4988 has_pending_diagnostic_updates: false,
4989 progress_tokens: Default::default(),
4990 },
4991 );
4992 cx.notify();
4993 });
4994 Ok(())
4995 }
4996
4997 async fn handle_update_language_server(
4998 this: ModelHandle<Self>,
4999 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5000 _: Arc<Client>,
5001 mut cx: AsyncAppContext,
5002 ) -> Result<()> {
5003 let language_server_id = envelope.payload.language_server_id as usize;
5004 match envelope
5005 .payload
5006 .variant
5007 .ok_or_else(|| anyhow!("invalid variant"))?
5008 {
5009 proto::update_language_server::Variant::WorkStart(payload) => {
5010 this.update(&mut cx, |this, cx| {
5011 this.on_lsp_work_start(
5012 language_server_id,
5013 payload.token,
5014 LanguageServerProgress {
5015 message: payload.message,
5016 percentage: payload.percentage.map(|p| p as usize),
5017 last_update_at: Instant::now(),
5018 },
5019 cx,
5020 );
5021 })
5022 }
5023 proto::update_language_server::Variant::WorkProgress(payload) => {
5024 this.update(&mut cx, |this, cx| {
5025 this.on_lsp_work_progress(
5026 language_server_id,
5027 payload.token,
5028 LanguageServerProgress {
5029 message: payload.message,
5030 percentage: payload.percentage.map(|p| p as usize),
5031 last_update_at: Instant::now(),
5032 },
5033 cx,
5034 );
5035 })
5036 }
5037 proto::update_language_server::Variant::WorkEnd(payload) => {
5038 this.update(&mut cx, |this, cx| {
5039 this.on_lsp_work_end(language_server_id, payload.token, cx);
5040 })
5041 }
5042 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5043 this.update(&mut cx, |this, cx| {
5044 this.disk_based_diagnostics_started(language_server_id, cx);
5045 })
5046 }
5047 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5048 this.update(&mut cx, |this, cx| {
5049 this.disk_based_diagnostics_finished(language_server_id, cx)
5050 });
5051 }
5052 }
5053
5054 Ok(())
5055 }
5056
5057 async fn handle_update_buffer(
5058 this: ModelHandle<Self>,
5059 envelope: TypedEnvelope<proto::UpdateBuffer>,
5060 _: Arc<Client>,
5061 mut cx: AsyncAppContext,
5062 ) -> Result<()> {
5063 this.update(&mut cx, |this, cx| {
5064 let payload = envelope.payload.clone();
5065 let buffer_id = payload.buffer_id;
5066 let ops = payload
5067 .operations
5068 .into_iter()
5069 .map(|op| language::proto::deserialize_operation(op))
5070 .collect::<Result<Vec<_>, _>>()?;
5071 let is_remote = this.is_remote();
5072 match this.opened_buffers.entry(buffer_id) {
5073 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5074 OpenBuffer::Strong(buffer) => {
5075 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5076 }
5077 OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
5078 OpenBuffer::Weak(_) => {}
5079 },
5080 hash_map::Entry::Vacant(e) => {
5081 assert!(
5082 is_remote,
5083 "received buffer update from {:?}",
5084 envelope.original_sender_id
5085 );
5086 e.insert(OpenBuffer::Loading(ops));
5087 }
5088 }
5089 Ok(())
5090 })
5091 }
5092
5093 async fn handle_update_buffer_file(
5094 this: ModelHandle<Self>,
5095 envelope: TypedEnvelope<proto::UpdateBufferFile>,
5096 _: Arc<Client>,
5097 mut cx: AsyncAppContext,
5098 ) -> Result<()> {
5099 this.update(&mut cx, |this, cx| {
5100 let payload = envelope.payload.clone();
5101 let buffer_id = payload.buffer_id;
5102 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5103 let worktree = this
5104 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5105 .ok_or_else(|| anyhow!("no such worktree"))?;
5106 let file = File::from_proto(file, worktree.clone(), cx)?;
5107 let buffer = this
5108 .opened_buffers
5109 .get_mut(&buffer_id)
5110 .and_then(|b| b.upgrade(cx))
5111 .ok_or_else(|| anyhow!("no such buffer"))?;
5112 buffer.update(cx, |buffer, cx| {
5113 buffer.file_updated(Arc::new(file), cx).detach();
5114 });
5115 Ok(())
5116 })
5117 }
5118
5119 async fn handle_save_buffer(
5120 this: ModelHandle<Self>,
5121 envelope: TypedEnvelope<proto::SaveBuffer>,
5122 _: Arc<Client>,
5123 mut cx: AsyncAppContext,
5124 ) -> Result<proto::BufferSaved> {
5125 let buffer_id = envelope.payload.buffer_id;
5126 let requested_version = deserialize_version(envelope.payload.version);
5127
5128 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5129 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5130 let buffer = this
5131 .opened_buffers
5132 .get(&buffer_id)
5133 .and_then(|buffer| buffer.upgrade(cx))
5134 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5135 Ok::<_, anyhow::Error>((project_id, buffer))
5136 })?;
5137 buffer
5138 .update(&mut cx, |buffer, _| {
5139 buffer.wait_for_version(requested_version)
5140 })
5141 .await;
5142
5143 let (saved_version, fingerprint, mtime) =
5144 buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5145 Ok(proto::BufferSaved {
5146 project_id,
5147 buffer_id,
5148 version: serialize_version(&saved_version),
5149 mtime: Some(mtime.into()),
5150 fingerprint,
5151 })
5152 }
5153
5154 async fn handle_reload_buffers(
5155 this: ModelHandle<Self>,
5156 envelope: TypedEnvelope<proto::ReloadBuffers>,
5157 _: Arc<Client>,
5158 mut cx: AsyncAppContext,
5159 ) -> Result<proto::ReloadBuffersResponse> {
5160 let sender_id = envelope.original_sender_id()?;
5161 let reload = this.update(&mut cx, |this, cx| {
5162 let mut buffers = HashSet::default();
5163 for buffer_id in &envelope.payload.buffer_ids {
5164 buffers.insert(
5165 this.opened_buffers
5166 .get(buffer_id)
5167 .and_then(|buffer| buffer.upgrade(cx))
5168 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5169 );
5170 }
5171 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5172 })?;
5173
5174 let project_transaction = reload.await?;
5175 let project_transaction = this.update(&mut cx, |this, cx| {
5176 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5177 });
5178 Ok(proto::ReloadBuffersResponse {
5179 transaction: Some(project_transaction),
5180 })
5181 }
5182
5183 async fn handle_format_buffers(
5184 this: ModelHandle<Self>,
5185 envelope: TypedEnvelope<proto::FormatBuffers>,
5186 _: Arc<Client>,
5187 mut cx: AsyncAppContext,
5188 ) -> Result<proto::FormatBuffersResponse> {
5189 let sender_id = envelope.original_sender_id()?;
5190 let format = this.update(&mut cx, |this, cx| {
5191 let mut buffers = HashSet::default();
5192 for buffer_id in &envelope.payload.buffer_ids {
5193 buffers.insert(
5194 this.opened_buffers
5195 .get(buffer_id)
5196 .and_then(|buffer| buffer.upgrade(cx))
5197 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5198 );
5199 }
5200 Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
5201 })?;
5202
5203 let project_transaction = format.await?;
5204 let project_transaction = this.update(&mut cx, |this, cx| {
5205 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5206 });
5207 Ok(proto::FormatBuffersResponse {
5208 transaction: Some(project_transaction),
5209 })
5210 }
5211
5212 async fn handle_get_completions(
5213 this: ModelHandle<Self>,
5214 envelope: TypedEnvelope<proto::GetCompletions>,
5215 _: Arc<Client>,
5216 mut cx: AsyncAppContext,
5217 ) -> Result<proto::GetCompletionsResponse> {
5218 let position = envelope
5219 .payload
5220 .position
5221 .and_then(language::proto::deserialize_anchor)
5222 .ok_or_else(|| anyhow!("invalid position"))?;
5223 let version = deserialize_version(envelope.payload.version);
5224 let buffer = this.read_with(&cx, |this, cx| {
5225 this.opened_buffers
5226 .get(&envelope.payload.buffer_id)
5227 .and_then(|buffer| buffer.upgrade(cx))
5228 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5229 })?;
5230 buffer
5231 .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5232 .await;
5233 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5234 let completions = this
5235 .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5236 .await?;
5237
5238 Ok(proto::GetCompletionsResponse {
5239 completions: completions
5240 .iter()
5241 .map(language::proto::serialize_completion)
5242 .collect(),
5243 version: serialize_version(&version),
5244 })
5245 }
5246
5247 async fn handle_apply_additional_edits_for_completion(
5248 this: ModelHandle<Self>,
5249 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5250 _: Arc<Client>,
5251 mut cx: AsyncAppContext,
5252 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5253 let (buffer, completion) = this.update(&mut cx, |this, cx| {
5254 let buffer = this
5255 .opened_buffers
5256 .get(&envelope.payload.buffer_id)
5257 .and_then(|buffer| buffer.upgrade(cx))
5258 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5259 let language = buffer.read(cx).language();
5260 let completion = language::proto::deserialize_completion(
5261 envelope
5262 .payload
5263 .completion
5264 .ok_or_else(|| anyhow!("invalid completion"))?,
5265 language.cloned(),
5266 );
5267 Ok::<_, anyhow::Error>((buffer, completion))
5268 })?;
5269
5270 let completion = completion.await?;
5271
5272 let apply_additional_edits = this.update(&mut cx, |this, cx| {
5273 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5274 });
5275
5276 Ok(proto::ApplyCompletionAdditionalEditsResponse {
5277 transaction: apply_additional_edits
5278 .await?
5279 .as_ref()
5280 .map(language::proto::serialize_transaction),
5281 })
5282 }
5283
5284 async fn handle_get_code_actions(
5285 this: ModelHandle<Self>,
5286 envelope: TypedEnvelope<proto::GetCodeActions>,
5287 _: Arc<Client>,
5288 mut cx: AsyncAppContext,
5289 ) -> Result<proto::GetCodeActionsResponse> {
5290 let start = envelope
5291 .payload
5292 .start
5293 .and_then(language::proto::deserialize_anchor)
5294 .ok_or_else(|| anyhow!("invalid start"))?;
5295 let end = envelope
5296 .payload
5297 .end
5298 .and_then(language::proto::deserialize_anchor)
5299 .ok_or_else(|| anyhow!("invalid end"))?;
5300 let buffer = this.update(&mut cx, |this, cx| {
5301 this.opened_buffers
5302 .get(&envelope.payload.buffer_id)
5303 .and_then(|buffer| buffer.upgrade(cx))
5304 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5305 })?;
5306 buffer
5307 .update(&mut cx, |buffer, _| {
5308 buffer.wait_for_version(deserialize_version(envelope.payload.version))
5309 })
5310 .await;
5311
5312 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5313 let code_actions = this.update(&mut cx, |this, cx| {
5314 Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5315 })?;
5316
5317 Ok(proto::GetCodeActionsResponse {
5318 actions: code_actions
5319 .await?
5320 .iter()
5321 .map(language::proto::serialize_code_action)
5322 .collect(),
5323 version: serialize_version(&version),
5324 })
5325 }
5326
5327 async fn handle_apply_code_action(
5328 this: ModelHandle<Self>,
5329 envelope: TypedEnvelope<proto::ApplyCodeAction>,
5330 _: Arc<Client>,
5331 mut cx: AsyncAppContext,
5332 ) -> Result<proto::ApplyCodeActionResponse> {
5333 let sender_id = envelope.original_sender_id()?;
5334 let action = language::proto::deserialize_code_action(
5335 envelope
5336 .payload
5337 .action
5338 .ok_or_else(|| anyhow!("invalid action"))?,
5339 )?;
5340 let apply_code_action = this.update(&mut cx, |this, cx| {
5341 let buffer = this
5342 .opened_buffers
5343 .get(&envelope.payload.buffer_id)
5344 .and_then(|buffer| buffer.upgrade(cx))
5345 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5346 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5347 })?;
5348
5349 let project_transaction = apply_code_action.await?;
5350 let project_transaction = this.update(&mut cx, |this, cx| {
5351 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5352 });
5353 Ok(proto::ApplyCodeActionResponse {
5354 transaction: Some(project_transaction),
5355 })
5356 }
5357
5358 async fn handle_lsp_command<T: LspCommand>(
5359 this: ModelHandle<Self>,
5360 envelope: TypedEnvelope<T::ProtoRequest>,
5361 _: Arc<Client>,
5362 mut cx: AsyncAppContext,
5363 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5364 where
5365 <T::LspRequest as lsp::request::Request>::Result: Send,
5366 {
5367 let sender_id = envelope.original_sender_id()?;
5368 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5369 let buffer_handle = this.read_with(&cx, |this, _| {
5370 this.opened_buffers
5371 .get(&buffer_id)
5372 .and_then(|buffer| buffer.upgrade(&cx))
5373 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5374 })?;
5375 let request = T::from_proto(
5376 envelope.payload,
5377 this.clone(),
5378 buffer_handle.clone(),
5379 cx.clone(),
5380 )
5381 .await?;
5382 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5383 let response = this
5384 .update(&mut cx, |this, cx| {
5385 this.request_lsp(buffer_handle, request, cx)
5386 })
5387 .await?;
5388 this.update(&mut cx, |this, cx| {
5389 Ok(T::response_to_proto(
5390 response,
5391 this,
5392 sender_id,
5393 &buffer_version,
5394 cx,
5395 ))
5396 })
5397 }
5398
5399 async fn handle_get_project_symbols(
5400 this: ModelHandle<Self>,
5401 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5402 _: Arc<Client>,
5403 mut cx: AsyncAppContext,
5404 ) -> Result<proto::GetProjectSymbolsResponse> {
5405 let symbols = this
5406 .update(&mut cx, |this, cx| {
5407 this.symbols(&envelope.payload.query, cx)
5408 })
5409 .await?;
5410
5411 Ok(proto::GetProjectSymbolsResponse {
5412 symbols: symbols.iter().map(serialize_symbol).collect(),
5413 })
5414 }
5415
5416 async fn handle_search_project(
5417 this: ModelHandle<Self>,
5418 envelope: TypedEnvelope<proto::SearchProject>,
5419 _: Arc<Client>,
5420 mut cx: AsyncAppContext,
5421 ) -> Result<proto::SearchProjectResponse> {
5422 let peer_id = envelope.original_sender_id()?;
5423 let query = SearchQuery::from_proto(envelope.payload)?;
5424 let result = this
5425 .update(&mut cx, |this, cx| this.search(query, cx))
5426 .await?;
5427
5428 this.update(&mut cx, |this, cx| {
5429 let mut locations = Vec::new();
5430 for (buffer, ranges) in result {
5431 for range in ranges {
5432 let start = serialize_anchor(&range.start);
5433 let end = serialize_anchor(&range.end);
5434 let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
5435 locations.push(proto::Location {
5436 buffer: Some(buffer),
5437 start: Some(start),
5438 end: Some(end),
5439 });
5440 }
5441 }
5442 Ok(proto::SearchProjectResponse { locations })
5443 })
5444 }
5445
5446 async fn handle_open_buffer_for_symbol(
5447 this: ModelHandle<Self>,
5448 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5449 _: Arc<Client>,
5450 mut cx: AsyncAppContext,
5451 ) -> Result<proto::OpenBufferForSymbolResponse> {
5452 let peer_id = envelope.original_sender_id()?;
5453 let symbol = envelope
5454 .payload
5455 .symbol
5456 .ok_or_else(|| anyhow!("invalid symbol"))?;
5457 let symbol = this
5458 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5459 .await?;
5460 let symbol = this.read_with(&cx, |this, _| {
5461 let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
5462 if signature == symbol.signature {
5463 Ok(symbol)
5464 } else {
5465 Err(anyhow!("invalid symbol signature"))
5466 }
5467 })?;
5468 let buffer = this
5469 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5470 .await?;
5471
5472 Ok(proto::OpenBufferForSymbolResponse {
5473 buffer: Some(this.update(&mut cx, |this, cx| {
5474 this.serialize_buffer_for_peer(&buffer, peer_id, cx)
5475 })),
5476 })
5477 }
5478
5479 fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
5480 let mut hasher = Sha256::new();
5481 hasher.update(worktree_id.to_proto().to_be_bytes());
5482 hasher.update(path.to_string_lossy().as_bytes());
5483 hasher.update(self.nonce.to_be_bytes());
5484 hasher.finalize().as_slice().try_into().unwrap()
5485 }
5486
5487 async fn handle_open_buffer_by_id(
5488 this: ModelHandle<Self>,
5489 envelope: TypedEnvelope<proto::OpenBufferById>,
5490 _: Arc<Client>,
5491 mut cx: AsyncAppContext,
5492 ) -> Result<proto::OpenBufferResponse> {
5493 let peer_id = envelope.original_sender_id()?;
5494 let buffer = this
5495 .update(&mut cx, |this, cx| {
5496 this.open_buffer_by_id(envelope.payload.id, cx)
5497 })
5498 .await?;
5499 this.update(&mut cx, |this, cx| {
5500 Ok(proto::OpenBufferResponse {
5501 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5502 })
5503 })
5504 }
5505
5506 async fn handle_open_buffer_by_path(
5507 this: ModelHandle<Self>,
5508 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5509 _: Arc<Client>,
5510 mut cx: AsyncAppContext,
5511 ) -> Result<proto::OpenBufferResponse> {
5512 let peer_id = envelope.original_sender_id()?;
5513 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5514 let open_buffer = this.update(&mut cx, |this, cx| {
5515 this.open_buffer(
5516 ProjectPath {
5517 worktree_id,
5518 path: PathBuf::from(envelope.payload.path).into(),
5519 },
5520 cx,
5521 )
5522 });
5523
5524 let buffer = open_buffer.await?;
5525 this.update(&mut cx, |this, cx| {
5526 Ok(proto::OpenBufferResponse {
5527 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5528 })
5529 })
5530 }
5531
5532 fn serialize_project_transaction_for_peer(
5533 &mut self,
5534 project_transaction: ProjectTransaction,
5535 peer_id: PeerId,
5536 cx: &AppContext,
5537 ) -> proto::ProjectTransaction {
5538 let mut serialized_transaction = proto::ProjectTransaction {
5539 buffers: Default::default(),
5540 transactions: Default::default(),
5541 };
5542 for (buffer, transaction) in project_transaction.0 {
5543 serialized_transaction
5544 .buffers
5545 .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
5546 serialized_transaction
5547 .transactions
5548 .push(language::proto::serialize_transaction(&transaction));
5549 }
5550 serialized_transaction
5551 }
5552
5553 fn deserialize_project_transaction(
5554 &mut self,
5555 message: proto::ProjectTransaction,
5556 push_to_history: bool,
5557 cx: &mut ModelContext<Self>,
5558 ) -> Task<Result<ProjectTransaction>> {
5559 cx.spawn(|this, mut cx| async move {
5560 let mut project_transaction = ProjectTransaction::default();
5561 for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
5562 let buffer = this
5563 .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
5564 .await?;
5565 let transaction = language::proto::deserialize_transaction(transaction)?;
5566 project_transaction.0.insert(buffer, transaction);
5567 }
5568
5569 for (buffer, transaction) in &project_transaction.0 {
5570 buffer
5571 .update(&mut cx, |buffer, _| {
5572 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5573 })
5574 .await;
5575
5576 if push_to_history {
5577 buffer.update(&mut cx, |buffer, _| {
5578 buffer.push_transaction(transaction.clone(), Instant::now());
5579 });
5580 }
5581 }
5582
5583 Ok(project_transaction)
5584 })
5585 }
5586
5587 fn serialize_buffer_for_peer(
5588 &mut self,
5589 buffer: &ModelHandle<Buffer>,
5590 peer_id: PeerId,
5591 cx: &AppContext,
5592 ) -> proto::Buffer {
5593 let buffer_id = buffer.read(cx).remote_id();
5594 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5595 if shared_buffers.insert(buffer_id) {
5596 proto::Buffer {
5597 variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
5598 }
5599 } else {
5600 proto::Buffer {
5601 variant: Some(proto::buffer::Variant::Id(buffer_id)),
5602 }
5603 }
5604 }
5605
5606 fn deserialize_buffer(
5607 &mut self,
5608 buffer: proto::Buffer,
5609 cx: &mut ModelContext<Self>,
5610 ) -> Task<Result<ModelHandle<Buffer>>> {
5611 let replica_id = self.replica_id();
5612
5613 let opened_buffer_tx = self.opened_buffer.0.clone();
5614 let mut opened_buffer_rx = self.opened_buffer.1.clone();
5615 cx.spawn(|this, mut cx| async move {
5616 match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
5617 proto::buffer::Variant::Id(id) => {
5618 let buffer = loop {
5619 let buffer = this.read_with(&cx, |this, cx| {
5620 this.opened_buffers
5621 .get(&id)
5622 .and_then(|buffer| buffer.upgrade(cx))
5623 });
5624 if let Some(buffer) = buffer {
5625 break buffer;
5626 }
5627 opened_buffer_rx
5628 .next()
5629 .await
5630 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5631 };
5632 Ok(buffer)
5633 }
5634 proto::buffer::Variant::State(mut buffer) => {
5635 let mut buffer_worktree = None;
5636 let mut buffer_file = None;
5637 if let Some(file) = buffer.file.take() {
5638 this.read_with(&cx, |this, cx| {
5639 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5640 let worktree =
5641 this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5642 anyhow!("no worktree found for id {}", file.worktree_id)
5643 })?;
5644 buffer_file =
5645 Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5646 as Arc<dyn language::File>);
5647 buffer_worktree = Some(worktree);
5648 Ok::<_, anyhow::Error>(())
5649 })?;
5650 }
5651
5652 let buffer = cx.add_model(|cx| {
5653 Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
5654 });
5655
5656 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
5657
5658 *opened_buffer_tx.borrow_mut().borrow_mut() = ();
5659 Ok(buffer)
5660 }
5661 }
5662 })
5663 }
5664
5665 fn deserialize_symbol(
5666 &self,
5667 serialized_symbol: proto::Symbol,
5668 ) -> impl Future<Output = Result<Symbol>> {
5669 let languages = self.languages.clone();
5670 async move {
5671 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5672 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5673 let start = serialized_symbol
5674 .start
5675 .ok_or_else(|| anyhow!("invalid start"))?;
5676 let end = serialized_symbol
5677 .end
5678 .ok_or_else(|| anyhow!("invalid end"))?;
5679 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5680 let path = PathBuf::from(serialized_symbol.path);
5681 let language = languages.select_language(&path);
5682 Ok(Symbol {
5683 source_worktree_id,
5684 worktree_id,
5685 language_server_name: LanguageServerName(
5686 serialized_symbol.language_server_name.into(),
5687 ),
5688 label: {
5689 match language {
5690 Some(language) => {
5691 language
5692 .label_for_symbol(&serialized_symbol.name, kind)
5693 .await
5694 }
5695 None => None,
5696 }
5697 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5698 },
5699
5700 name: serialized_symbol.name,
5701 path,
5702 range: PointUtf16::new(start.row, start.column)
5703 ..PointUtf16::new(end.row, end.column),
5704 kind,
5705 signature: serialized_symbol
5706 .signature
5707 .try_into()
5708 .map_err(|_| anyhow!("invalid signature"))?,
5709 })
5710 }
5711 }
5712
5713 async fn handle_buffer_saved(
5714 this: ModelHandle<Self>,
5715 envelope: TypedEnvelope<proto::BufferSaved>,
5716 _: Arc<Client>,
5717 mut cx: AsyncAppContext,
5718 ) -> Result<()> {
5719 let version = deserialize_version(envelope.payload.version);
5720 let mtime = envelope
5721 .payload
5722 .mtime
5723 .ok_or_else(|| anyhow!("missing mtime"))?
5724 .into();
5725
5726 this.update(&mut cx, |this, cx| {
5727 let buffer = this
5728 .opened_buffers
5729 .get(&envelope.payload.buffer_id)
5730 .and_then(|buffer| buffer.upgrade(cx));
5731 if let Some(buffer) = buffer {
5732 buffer.update(cx, |buffer, cx| {
5733 buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5734 });
5735 }
5736 Ok(())
5737 })
5738 }
5739
5740 async fn handle_buffer_reloaded(
5741 this: ModelHandle<Self>,
5742 envelope: TypedEnvelope<proto::BufferReloaded>,
5743 _: Arc<Client>,
5744 mut cx: AsyncAppContext,
5745 ) -> Result<()> {
5746 let payload = envelope.payload;
5747 let version = deserialize_version(payload.version);
5748 let line_ending = deserialize_line_ending(
5749 proto::LineEnding::from_i32(payload.line_ending)
5750 .ok_or_else(|| anyhow!("missing line ending"))?,
5751 );
5752 let mtime = payload
5753 .mtime
5754 .ok_or_else(|| anyhow!("missing mtime"))?
5755 .into();
5756 this.update(&mut cx, |this, cx| {
5757 let buffer = this
5758 .opened_buffers
5759 .get(&payload.buffer_id)
5760 .and_then(|buffer| buffer.upgrade(cx));
5761 if let Some(buffer) = buffer {
5762 buffer.update(cx, |buffer, cx| {
5763 buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5764 });
5765 }
5766 Ok(())
5767 })
5768 }
5769
5770 pub fn match_paths<'a>(
5771 &self,
5772 query: &'a str,
5773 include_ignored: bool,
5774 smart_case: bool,
5775 max_results: usize,
5776 cancel_flag: &'a AtomicBool,
5777 cx: &AppContext,
5778 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
5779 let worktrees = self
5780 .worktrees(cx)
5781 .filter(|worktree| worktree.read(cx).is_visible())
5782 .collect::<Vec<_>>();
5783 let include_root_name = worktrees.len() > 1;
5784 let candidate_sets = worktrees
5785 .into_iter()
5786 .map(|worktree| CandidateSet {
5787 snapshot: worktree.read(cx).snapshot(),
5788 include_ignored,
5789 include_root_name,
5790 })
5791 .collect::<Vec<_>>();
5792
5793 let background = cx.background().clone();
5794 async move {
5795 fuzzy::match_paths(
5796 candidate_sets.as_slice(),
5797 query,
5798 smart_case,
5799 max_results,
5800 cancel_flag,
5801 background,
5802 )
5803 .await
5804 }
5805 }
5806
5807 fn edits_from_lsp(
5808 &mut self,
5809 buffer: &ModelHandle<Buffer>,
5810 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5811 version: Option<i32>,
5812 cx: &mut ModelContext<Self>,
5813 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5814 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5815 cx.background().spawn(async move {
5816 let snapshot = snapshot?;
5817 let mut lsp_edits = lsp_edits
5818 .into_iter()
5819 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5820 .collect::<Vec<_>>();
5821 lsp_edits.sort_by_key(|(range, _)| range.start);
5822
5823 let mut lsp_edits = lsp_edits.into_iter().peekable();
5824 let mut edits = Vec::new();
5825 while let Some((mut range, mut new_text)) = lsp_edits.next() {
5826 // Combine any LSP edits that are adjacent.
5827 //
5828 // Also, combine LSP edits that are separated from each other by only
5829 // a newline. This is important because for some code actions,
5830 // Rust-analyzer rewrites the entire buffer via a series of edits that
5831 // are separated by unchanged newline characters.
5832 //
5833 // In order for the diffing logic below to work properly, any edits that
5834 // cancel each other out must be combined into one.
5835 while let Some((next_range, next_text)) = lsp_edits.peek() {
5836 if next_range.start > range.end {
5837 if next_range.start.row > range.end.row + 1
5838 || next_range.start.column > 0
5839 || snapshot.clip_point_utf16(
5840 PointUtf16::new(range.end.row, u32::MAX),
5841 Bias::Left,
5842 ) > range.end
5843 {
5844 break;
5845 }
5846 new_text.push('\n');
5847 }
5848 range.end = next_range.end;
5849 new_text.push_str(&next_text);
5850 lsp_edits.next();
5851 }
5852
5853 if snapshot.clip_point_utf16(range.start, Bias::Left) != range.start
5854 || snapshot.clip_point_utf16(range.end, Bias::Left) != range.end
5855 {
5856 return Err(anyhow!("invalid edits received from language server"));
5857 }
5858
5859 // For multiline edits, perform a diff of the old and new text so that
5860 // we can identify the changes more precisely, preserving the locations
5861 // of any anchors positioned in the unchanged regions.
5862 if range.end.row > range.start.row {
5863 let mut offset = range.start.to_offset(&snapshot);
5864 let old_text = snapshot.text_for_range(range).collect::<String>();
5865
5866 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5867 let mut moved_since_edit = true;
5868 for change in diff.iter_all_changes() {
5869 let tag = change.tag();
5870 let value = change.value();
5871 match tag {
5872 ChangeTag::Equal => {
5873 offset += value.len();
5874 moved_since_edit = true;
5875 }
5876 ChangeTag::Delete => {
5877 let start = snapshot.anchor_after(offset);
5878 let end = snapshot.anchor_before(offset + value.len());
5879 if moved_since_edit {
5880 edits.push((start..end, String::new()));
5881 } else {
5882 edits.last_mut().unwrap().0.end = end;
5883 }
5884 offset += value.len();
5885 moved_since_edit = false;
5886 }
5887 ChangeTag::Insert => {
5888 if moved_since_edit {
5889 let anchor = snapshot.anchor_after(offset);
5890 edits.push((anchor.clone()..anchor, value.to_string()));
5891 } else {
5892 edits.last_mut().unwrap().1.push_str(value);
5893 }
5894 moved_since_edit = false;
5895 }
5896 }
5897 }
5898 } else if range.end == range.start {
5899 let anchor = snapshot.anchor_after(range.start);
5900 edits.push((anchor.clone()..anchor, new_text));
5901 } else {
5902 let edit_start = snapshot.anchor_after(range.start);
5903 let edit_end = snapshot.anchor_before(range.end);
5904 edits.push((edit_start..edit_end, new_text));
5905 }
5906 }
5907
5908 Ok(edits)
5909 })
5910 }
5911
5912 fn buffer_snapshot_for_lsp_version(
5913 &mut self,
5914 buffer: &ModelHandle<Buffer>,
5915 version: Option<i32>,
5916 cx: &AppContext,
5917 ) -> Result<TextBufferSnapshot> {
5918 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5919
5920 if let Some(version) = version {
5921 let buffer_id = buffer.read(cx).remote_id();
5922 let snapshots = self
5923 .buffer_snapshots
5924 .get_mut(&buffer_id)
5925 .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
5926 let mut found_snapshot = None;
5927 snapshots.retain(|(snapshot_version, snapshot)| {
5928 if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
5929 false
5930 } else {
5931 if *snapshot_version == version {
5932 found_snapshot = Some(snapshot.clone());
5933 }
5934 true
5935 }
5936 });
5937
5938 found_snapshot.ok_or_else(|| {
5939 anyhow!(
5940 "snapshot not found for buffer {} at version {}",
5941 buffer_id,
5942 version
5943 )
5944 })
5945 } else {
5946 Ok((buffer.read(cx)).text_snapshot())
5947 }
5948 }
5949
5950 fn language_server_for_buffer(
5951 &self,
5952 buffer: &Buffer,
5953 cx: &AppContext,
5954 ) -> Option<(&Arc<LspAdapter>, &Arc<LanguageServer>)> {
5955 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5956 let name = language.lsp_adapter()?.name.clone();
5957 let worktree_id = file.worktree_id(cx);
5958 let key = (worktree_id, name);
5959
5960 if let Some(server_id) = self.language_server_ids.get(&key) {
5961 if let Some(LanguageServerState::Running { adapter, server }) =
5962 self.language_servers.get(&server_id)
5963 {
5964 return Some((adapter, server));
5965 }
5966 }
5967 }
5968
5969 None
5970 }
5971}
5972
5973impl ProjectStore {
5974 pub fn new(db: Arc<Db>) -> Self {
5975 Self {
5976 db,
5977 projects: Default::default(),
5978 }
5979 }
5980
5981 pub fn projects<'a>(
5982 &'a self,
5983 cx: &'a AppContext,
5984 ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
5985 self.projects
5986 .iter()
5987 .filter_map(|project| project.upgrade(cx))
5988 }
5989
5990 fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
5991 if let Err(ix) = self
5992 .projects
5993 .binary_search_by_key(&project.id(), WeakModelHandle::id)
5994 {
5995 self.projects.insert(ix, project);
5996 }
5997 cx.notify();
5998 }
5999
6000 fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
6001 let mut did_change = false;
6002 self.projects.retain(|project| {
6003 if project.is_upgradable(cx) {
6004 true
6005 } else {
6006 did_change = true;
6007 false
6008 }
6009 });
6010 if did_change {
6011 cx.notify();
6012 }
6013 }
6014}
6015
6016impl WorktreeHandle {
6017 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6018 match self {
6019 WorktreeHandle::Strong(handle) => Some(handle.clone()),
6020 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6021 }
6022 }
6023}
6024
6025impl OpenBuffer {
6026 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6027 match self {
6028 OpenBuffer::Strong(handle) => Some(handle.clone()),
6029 OpenBuffer::Weak(handle) => handle.upgrade(cx),
6030 OpenBuffer::Loading(_) => None,
6031 }
6032 }
6033}
6034
6035struct CandidateSet {
6036 snapshot: Snapshot,
6037 include_ignored: bool,
6038 include_root_name: bool,
6039}
6040
6041impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
6042 type Candidates = CandidateSetIter<'a>;
6043
6044 fn id(&self) -> usize {
6045 self.snapshot.id().to_usize()
6046 }
6047
6048 fn len(&self) -> usize {
6049 if self.include_ignored {
6050 self.snapshot.file_count()
6051 } else {
6052 self.snapshot.visible_file_count()
6053 }
6054 }
6055
6056 fn prefix(&self) -> Arc<str> {
6057 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6058 self.snapshot.root_name().into()
6059 } else if self.include_root_name {
6060 format!("{}/", self.snapshot.root_name()).into()
6061 } else {
6062 "".into()
6063 }
6064 }
6065
6066 fn candidates(&'a self, start: usize) -> Self::Candidates {
6067 CandidateSetIter {
6068 traversal: self.snapshot.files(self.include_ignored, start),
6069 }
6070 }
6071}
6072
6073struct CandidateSetIter<'a> {
6074 traversal: Traversal<'a>,
6075}
6076
6077impl<'a> Iterator for CandidateSetIter<'a> {
6078 type Item = PathMatchCandidate<'a>;
6079
6080 fn next(&mut self) -> Option<Self::Item> {
6081 self.traversal.next().map(|entry| {
6082 if let EntryKind::File(char_bag) = entry.kind {
6083 PathMatchCandidate {
6084 path: &entry.path,
6085 char_bag,
6086 }
6087 } else {
6088 unreachable!()
6089 }
6090 })
6091 }
6092}
6093
6094impl Entity for ProjectStore {
6095 type Event = ();
6096}
6097
6098impl Entity for Project {
6099 type Event = Event;
6100
6101 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
6102 self.project_store.update(cx, ProjectStore::prune_projects);
6103
6104 match &self.client_state {
6105 ProjectClientState::Local { remote_id_rx, .. } => {
6106 if let Some(project_id) = *remote_id_rx.borrow() {
6107 self.client
6108 .send(proto::UnregisterProject { project_id })
6109 .log_err();
6110 }
6111 }
6112 ProjectClientState::Remote { remote_id, .. } => {
6113 self.client
6114 .send(proto::LeaveProject {
6115 project_id: *remote_id,
6116 })
6117 .log_err();
6118 }
6119 }
6120 }
6121
6122 fn app_will_quit(
6123 &mut self,
6124 _: &mut MutableAppContext,
6125 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6126 let shutdown_futures = self
6127 .language_servers
6128 .drain()
6129 .map(|(_, server_state)| async {
6130 match server_state {
6131 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6132 LanguageServerState::Starting(starting_server) => {
6133 starting_server.await?.shutdown()?.await
6134 }
6135 }
6136 })
6137 .collect::<Vec<_>>();
6138
6139 Some(
6140 async move {
6141 futures::future::join_all(shutdown_futures).await;
6142 }
6143 .boxed(),
6144 )
6145 }
6146}
6147
6148impl Collaborator {
6149 fn from_proto(
6150 message: proto::Collaborator,
6151 user_store: &ModelHandle<UserStore>,
6152 cx: &mut AsyncAppContext,
6153 ) -> impl Future<Output = Result<Self>> {
6154 let user = user_store.update(cx, |user_store, cx| {
6155 user_store.fetch_user(message.user_id, cx)
6156 });
6157
6158 async move {
6159 Ok(Self {
6160 peer_id: PeerId(message.peer_id),
6161 user: user.await?,
6162 replica_id: message.replica_id as ReplicaId,
6163 })
6164 }
6165 }
6166}
6167
6168impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6169 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6170 Self {
6171 worktree_id,
6172 path: path.as_ref().into(),
6173 }
6174 }
6175}
6176
6177impl From<lsp::CreateFileOptions> for fs::CreateOptions {
6178 fn from(options: lsp::CreateFileOptions) -> Self {
6179 Self {
6180 overwrite: options.overwrite.unwrap_or(false),
6181 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6182 }
6183 }
6184}
6185
6186impl From<lsp::RenameFileOptions> for fs::RenameOptions {
6187 fn from(options: lsp::RenameFileOptions) -> Self {
6188 Self {
6189 overwrite: options.overwrite.unwrap_or(false),
6190 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
6191 }
6192 }
6193}
6194
6195impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
6196 fn from(options: lsp::DeleteFileOptions) -> Self {
6197 Self {
6198 recursive: options.recursive.unwrap_or(false),
6199 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
6200 }
6201 }
6202}
6203
6204fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6205 proto::Symbol {
6206 source_worktree_id: symbol.source_worktree_id.to_proto(),
6207 worktree_id: symbol.worktree_id.to_proto(),
6208 language_server_name: symbol.language_server_name.0.to_string(),
6209 name: symbol.name.clone(),
6210 kind: unsafe { mem::transmute(symbol.kind) },
6211 path: symbol.path.to_string_lossy().to_string(),
6212 start: Some(proto::Point {
6213 row: symbol.range.start.row,
6214 column: symbol.range.start.column,
6215 }),
6216 end: Some(proto::Point {
6217 row: symbol.range.end.row,
6218 column: symbol.range.end.column,
6219 }),
6220 signature: symbol.signature.to_vec(),
6221 }
6222}
6223
6224fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6225 let mut path_components = path.components();
6226 let mut base_components = base.components();
6227 let mut components: Vec<Component> = Vec::new();
6228 loop {
6229 match (path_components.next(), base_components.next()) {
6230 (None, None) => break,
6231 (Some(a), None) => {
6232 components.push(a);
6233 components.extend(path_components.by_ref());
6234 break;
6235 }
6236 (None, _) => components.push(Component::ParentDir),
6237 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6238 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6239 (Some(a), Some(_)) => {
6240 components.push(Component::ParentDir);
6241 for _ in base_components {
6242 components.push(Component::ParentDir);
6243 }
6244 components.push(a);
6245 components.extend(path_components.by_ref());
6246 break;
6247 }
6248 }
6249 }
6250 components.iter().map(|c| c.as_os_str()).collect()
6251}
6252
6253impl Item for Buffer {
6254 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6255 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6256 }
6257}