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