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