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