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