1mod db;
2pub mod fs;
3mod ignore;
4mod lsp_command;
5pub mod search;
6pub mod worktree;
7
8use anyhow::{anyhow, Context, Result};
9use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
10use clock::ReplicaId;
11use collections::{hash_map, BTreeMap, HashMap, HashSet};
12use futures::{future::Shared, Future, FutureExt, StreamExt, TryFutureExt};
13use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
14use gpui::{
15 AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
16 MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
17};
18use language::{
19 point_to_lsp,
20 proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},
21 range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CharKind, CodeAction, CodeLabel,
22 Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _,
23 Language, LanguageRegistry, LanguageServerName, LocalFile, LspAdapter, OffsetRangeExt,
24 Operation, Patch, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction,
25};
26use lsp::{
27 DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer, LanguageString,
28 MarkedString,
29};
30use lsp_command::*;
31use parking_lot::Mutex;
32use postage::stream::Stream;
33use postage::watch;
34use rand::prelude::*;
35use search::SearchQuery;
36use serde::Serialize;
37use settings::Settings;
38use sha2::{Digest, Sha256};
39use similar::{ChangeTag, TextDiff};
40use std::{
41 cell::RefCell,
42 cmp::{self, Ordering},
43 convert::TryInto,
44 ffi::OsString,
45 hash::Hash,
46 mem,
47 ops::Range,
48 os::unix::{ffi::OsStrExt, prelude::OsStringExt},
49 path::{Component, Path, PathBuf},
50 rc::Rc,
51 sync::{
52 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
53 Arc,
54 },
55 time::Instant,
56};
57use thiserror::Error;
58use util::{post_inc, ResultExt, TryFutureExt as _};
59
60pub use db::Db;
61pub use fs::*;
62pub use worktree::*;
63
64pub trait Item: Entity {
65 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
66}
67
68pub struct ProjectStore {
69 db: Arc<Db>,
70 projects: Vec<WeakModelHandle<Project>>,
71}
72
73pub struct Project {
74 worktrees: Vec<WorktreeHandle>,
75 active_entry: Option<ProjectEntryId>,
76 languages: Arc<LanguageRegistry>,
77 language_servers:
78 HashMap<(WorktreeId, LanguageServerName), (Arc<dyn LspAdapter>, Arc<LanguageServer>)>,
79 started_language_servers:
80 HashMap<(WorktreeId, LanguageServerName), Task<Option<Arc<LanguageServer>>>>,
81 language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
82 language_server_settings: Arc<Mutex<serde_json::Value>>,
83 last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
84 next_language_server_id: usize,
85 client: Arc<client::Client>,
86 next_entry_id: Arc<AtomicUsize>,
87 next_diagnostic_group_id: usize,
88 user_store: ModelHandle<UserStore>,
89 project_store: ModelHandle<ProjectStore>,
90 fs: Arc<dyn Fs>,
91 client_state: ProjectClientState,
92 collaborators: HashMap<PeerId, Collaborator>,
93 client_subscriptions: Vec<client::Subscription>,
94 _subscriptions: Vec<gpui::Subscription>,
95 opened_buffer: (Rc<RefCell<watch::Sender<()>>>, watch::Receiver<()>),
96 shared_buffers: HashMap<PeerId, HashSet<u64>>,
97 loading_buffers: HashMap<
98 ProjectPath,
99 postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
100 >,
101 loading_local_worktrees:
102 HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
103 opened_buffers: HashMap<u64, OpenBuffer>,
104 buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
105 nonce: u128,
106 initialized_persistent_state: bool,
107}
108
109#[derive(Error, Debug)]
110pub enum JoinProjectError {
111 #[error("host declined join request")]
112 HostDeclined,
113 #[error("host closed the project")]
114 HostClosedProject,
115 #[error("host went offline")]
116 HostWentOffline,
117 #[error("{0}")]
118 Other(#[from] anyhow::Error),
119}
120
121enum OpenBuffer {
122 Strong(ModelHandle<Buffer>),
123 Weak(WeakModelHandle<Buffer>),
124 Loading(Vec<Operation>),
125}
126
127enum WorktreeHandle {
128 Strong(ModelHandle<Worktree>),
129 Weak(WeakModelHandle<Worktree>),
130}
131
132enum ProjectClientState {
133 Local {
134 is_shared: bool,
135 remote_id_tx: watch::Sender<Option<u64>>,
136 remote_id_rx: watch::Receiver<Option<u64>>,
137 online_tx: watch::Sender<bool>,
138 online_rx: watch::Receiver<bool>,
139 _maintain_remote_id_task: Task<Option<()>>,
140 },
141 Remote {
142 sharing_has_stopped: bool,
143 remote_id: u64,
144 replica_id: ReplicaId,
145 _detect_unshare_task: Task<Option<()>>,
146 },
147}
148
149#[derive(Clone, Debug)]
150pub struct Collaborator {
151 pub user: Arc<User>,
152 pub peer_id: PeerId,
153 pub replica_id: ReplicaId,
154}
155
156#[derive(Clone, Debug, PartialEq, Eq)]
157pub enum Event {
158 ActiveEntryChanged(Option<ProjectEntryId>),
159 WorktreeAdded,
160 WorktreeRemoved(WorktreeId),
161 DiskBasedDiagnosticsStarted {
162 language_server_id: usize,
163 },
164 DiskBasedDiagnosticsFinished {
165 language_server_id: usize,
166 },
167 DiagnosticsUpdated {
168 path: ProjectPath,
169 language_server_id: usize,
170 },
171 RemoteIdChanged(Option<u64>),
172 CollaboratorLeft(PeerId),
173 ContactRequestedJoin(Arc<User>),
174 ContactCancelledJoinRequest(Arc<User>),
175}
176
177#[derive(Serialize)]
178pub struct LanguageServerStatus {
179 pub name: String,
180 pub pending_work: BTreeMap<String, LanguageServerProgress>,
181 pub has_pending_diagnostic_updates: bool,
182 progress_tokens: HashSet<String>,
183}
184
185#[derive(Clone, Debug, Serialize)]
186pub struct LanguageServerProgress {
187 pub message: Option<String>,
188 pub percentage: Option<usize>,
189 #[serde(skip_serializing)]
190 pub last_update_at: Instant,
191}
192
193#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
194pub struct ProjectPath {
195 pub worktree_id: WorktreeId,
196 pub path: Arc<Path>,
197}
198
199#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
200pub struct DiagnosticSummary {
201 pub language_server_id: usize,
202 pub error_count: usize,
203 pub warning_count: usize,
204}
205
206#[derive(Debug, Clone)]
207pub struct Location {
208 pub buffer: ModelHandle<Buffer>,
209 pub range: Range<language::Anchor>,
210}
211
212#[derive(Debug, Clone)]
213pub struct LocationLink {
214 pub origin: Option<Location>,
215 pub target: Location,
216}
217
218#[derive(Debug)]
219pub struct DocumentHighlight {
220 pub range: Range<language::Anchor>,
221 pub kind: DocumentHighlightKind,
222}
223
224#[derive(Clone, Debug)]
225pub struct Symbol {
226 pub source_worktree_id: WorktreeId,
227 pub worktree_id: WorktreeId,
228 pub language_server_name: LanguageServerName,
229 pub path: PathBuf,
230 pub label: CodeLabel,
231 pub name: String,
232 pub kind: lsp::SymbolKind,
233 pub range: Range<PointUtf16>,
234 pub signature: [u8; 32],
235}
236
237#[derive(Clone, Debug, PartialEq)]
238pub struct HoverBlock {
239 pub text: String,
240 pub language: Option<String>,
241}
242
243impl HoverBlock {
244 fn try_new(marked_string: MarkedString) -> Option<Self> {
245 let result = match marked_string {
246 MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
247 text: value,
248 language: Some(language),
249 },
250 MarkedString::String(text) => HoverBlock {
251 text,
252 language: None,
253 },
254 };
255 if result.text.is_empty() {
256 None
257 } else {
258 Some(result)
259 }
260 }
261}
262
263#[derive(Debug)]
264pub struct Hover {
265 pub contents: Vec<HoverBlock>,
266 pub range: Option<Range<language::Anchor>>,
267}
268
269#[derive(Default)]
270pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
271
272impl DiagnosticSummary {
273 fn new<'a, T: 'a>(
274 language_server_id: usize,
275 diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
276 ) -> Self {
277 let mut this = Self {
278 language_server_id,
279 error_count: 0,
280 warning_count: 0,
281 };
282
283 for entry in diagnostics {
284 if entry.diagnostic.is_primary {
285 match entry.diagnostic.severity {
286 DiagnosticSeverity::ERROR => this.error_count += 1,
287 DiagnosticSeverity::WARNING => this.warning_count += 1,
288 _ => {}
289 }
290 }
291 }
292
293 this
294 }
295
296 pub fn is_empty(&self) -> bool {
297 self.error_count == 0 && self.warning_count == 0
298 }
299
300 pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
301 proto::DiagnosticSummary {
302 path: path.to_string_lossy().to_string(),
303 language_server_id: self.language_server_id as u64,
304 error_count: self.error_count as u32,
305 warning_count: self.warning_count as u32,
306 }
307 }
308}
309
310#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
311pub struct ProjectEntryId(usize);
312
313impl ProjectEntryId {
314 pub const MAX: Self = Self(usize::MAX);
315
316 pub fn new(counter: &AtomicUsize) -> Self {
317 Self(counter.fetch_add(1, SeqCst))
318 }
319
320 pub fn from_proto(id: u64) -> Self {
321 Self(id as usize)
322 }
323
324 pub fn to_proto(&self) -> u64 {
325 self.0 as u64
326 }
327
328 pub fn to_usize(&self) -> usize {
329 self.0
330 }
331}
332
333impl Project {
334 pub fn init(client: &Arc<Client>) {
335 client.add_model_message_handler(Self::handle_request_join_project);
336 client.add_model_message_handler(Self::handle_add_collaborator);
337 client.add_model_message_handler(Self::handle_buffer_reloaded);
338 client.add_model_message_handler(Self::handle_buffer_saved);
339 client.add_model_message_handler(Self::handle_start_language_server);
340 client.add_model_message_handler(Self::handle_update_language_server);
341 client.add_model_message_handler(Self::handle_remove_collaborator);
342 client.add_model_message_handler(Self::handle_join_project_request_cancelled);
343 client.add_model_message_handler(Self::handle_update_project);
344 client.add_model_message_handler(Self::handle_unregister_project);
345 client.add_model_message_handler(Self::handle_project_unshared);
346 client.add_model_message_handler(Self::handle_update_buffer_file);
347 client.add_model_message_handler(Self::handle_update_buffer);
348 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
349 client.add_model_message_handler(Self::handle_update_worktree);
350 client.add_model_request_handler(Self::handle_create_project_entry);
351 client.add_model_request_handler(Self::handle_rename_project_entry);
352 client.add_model_request_handler(Self::handle_copy_project_entry);
353 client.add_model_request_handler(Self::handle_delete_project_entry);
354 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
355 client.add_model_request_handler(Self::handle_apply_code_action);
356 client.add_model_request_handler(Self::handle_reload_buffers);
357 client.add_model_request_handler(Self::handle_format_buffers);
358 client.add_model_request_handler(Self::handle_get_code_actions);
359 client.add_model_request_handler(Self::handle_get_completions);
360 client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
361 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
362 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
363 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
364 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
365 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
366 client.add_model_request_handler(Self::handle_search_project);
367 client.add_model_request_handler(Self::handle_get_project_symbols);
368 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
369 client.add_model_request_handler(Self::handle_open_buffer_by_id);
370 client.add_model_request_handler(Self::handle_open_buffer_by_path);
371 client.add_model_request_handler(Self::handle_save_buffer);
372 }
373
374 pub fn local(
375 online: bool,
376 client: Arc<Client>,
377 user_store: ModelHandle<UserStore>,
378 project_store: ModelHandle<ProjectStore>,
379 languages: Arc<LanguageRegistry>,
380 fs: Arc<dyn Fs>,
381 cx: &mut MutableAppContext,
382 ) -> ModelHandle<Self> {
383 cx.add_model(|cx: &mut ModelContext<Self>| {
384 let (online_tx, online_rx) = watch::channel_with(online);
385 let (remote_id_tx, remote_id_rx) = watch::channel();
386 let _maintain_remote_id_task = cx.spawn_weak({
387 let status_rx = client.clone().status();
388 let online_rx = online_rx.clone();
389 move |this, mut cx| async move {
390 let mut stream = Stream::map(status_rx.clone(), drop)
391 .merge(Stream::map(online_rx.clone(), drop));
392 while stream.recv().await.is_some() {
393 let this = this.upgrade(&cx)?;
394 if status_rx.borrow().is_connected() && *online_rx.borrow() {
395 this.update(&mut cx, |this, cx| this.register(cx))
396 .await
397 .log_err()?;
398 } else {
399 this.update(&mut cx, |this, cx| this.unregister(cx))
400 .await
401 .log_err();
402 }
403 }
404 None
405 }
406 });
407
408 let handle = cx.weak_handle();
409 project_store.update(cx, |store, cx| store.add_project(handle, cx));
410
411 let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
412 Self {
413 worktrees: Default::default(),
414 collaborators: Default::default(),
415 opened_buffers: Default::default(),
416 shared_buffers: Default::default(),
417 loading_buffers: Default::default(),
418 loading_local_worktrees: Default::default(),
419 buffer_snapshots: Default::default(),
420 client_state: ProjectClientState::Local {
421 is_shared: false,
422 remote_id_tx,
423 remote_id_rx,
424 online_tx,
425 online_rx,
426 _maintain_remote_id_task,
427 },
428 opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
429 client_subscriptions: Vec::new(),
430 _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
431 active_entry: None,
432 languages,
433 client,
434 user_store,
435 project_store,
436 fs,
437 next_entry_id: Default::default(),
438 next_diagnostic_group_id: Default::default(),
439 language_servers: Default::default(),
440 started_language_servers: Default::default(),
441 language_server_statuses: Default::default(),
442 last_workspace_edits_by_language_server: Default::default(),
443 language_server_settings: Default::default(),
444 next_language_server_id: 0,
445 nonce: StdRng::from_entropy().gen(),
446 initialized_persistent_state: false,
447 }
448 })
449 }
450
451 pub async fn remote(
452 remote_id: u64,
453 client: Arc<Client>,
454 user_store: ModelHandle<UserStore>,
455 project_store: ModelHandle<ProjectStore>,
456 languages: Arc<LanguageRegistry>,
457 fs: Arc<dyn Fs>,
458 mut cx: AsyncAppContext,
459 ) -> Result<ModelHandle<Self>, JoinProjectError> {
460 client.authenticate_and_connect(true, &cx).await?;
461
462 let response = client
463 .request(proto::JoinProject {
464 project_id: remote_id,
465 })
466 .await?;
467
468 let response = match response.variant.ok_or_else(|| anyhow!("missing variant"))? {
469 proto::join_project_response::Variant::Accept(response) => response,
470 proto::join_project_response::Variant::Decline(decline) => {
471 match proto::join_project_response::decline::Reason::from_i32(decline.reason) {
472 Some(proto::join_project_response::decline::Reason::Declined) => {
473 Err(JoinProjectError::HostDeclined)?
474 }
475 Some(proto::join_project_response::decline::Reason::Closed) => {
476 Err(JoinProjectError::HostClosedProject)?
477 }
478 Some(proto::join_project_response::decline::Reason::WentOffline) => {
479 Err(JoinProjectError::HostWentOffline)?
480 }
481 None => Err(anyhow!("missing decline reason"))?,
482 }
483 }
484 };
485
486 let replica_id = response.replica_id as ReplicaId;
487
488 let mut worktrees = Vec::new();
489 for worktree in response.worktrees {
490 let (worktree, load_task) = cx
491 .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
492 worktrees.push(worktree);
493 load_task.detach();
494 }
495
496 let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
497 let this = cx.add_model(|cx: &mut ModelContext<Self>| {
498 let handle = cx.weak_handle();
499 project_store.update(cx, |store, cx| store.add_project(handle, cx));
500
501 let mut this = Self {
502 worktrees: Vec::new(),
503 loading_buffers: Default::default(),
504 opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
505 shared_buffers: Default::default(),
506 loading_local_worktrees: Default::default(),
507 active_entry: None,
508 collaborators: Default::default(),
509 languages,
510 user_store: user_store.clone(),
511 project_store,
512 fs,
513 next_entry_id: Default::default(),
514 next_diagnostic_group_id: Default::default(),
515 client_subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
516 _subscriptions: Default::default(),
517 client: client.clone(),
518 client_state: ProjectClientState::Remote {
519 sharing_has_stopped: false,
520 remote_id,
521 replica_id,
522 _detect_unshare_task: cx.spawn_weak(move |this, mut cx| {
523 async move {
524 let mut status = client.status();
525 let is_connected =
526 status.next().await.map_or(false, |s| s.is_connected());
527 // Even if we're initially connected, any future change of the status means we momentarily disconnected.
528 if !is_connected || status.next().await.is_some() {
529 if let Some(this) = this.upgrade(&cx) {
530 this.update(&mut cx, |this, cx| this.removed_from_project(cx))
531 }
532 }
533 Ok(())
534 }
535 .log_err()
536 }),
537 },
538 language_servers: Default::default(),
539 started_language_servers: Default::default(),
540 language_server_settings: Default::default(),
541 language_server_statuses: response
542 .language_servers
543 .into_iter()
544 .map(|server| {
545 (
546 server.id as usize,
547 LanguageServerStatus {
548 name: server.name,
549 pending_work: Default::default(),
550 has_pending_diagnostic_updates: false,
551 progress_tokens: Default::default(),
552 },
553 )
554 })
555 .collect(),
556 last_workspace_edits_by_language_server: Default::default(),
557 next_language_server_id: 0,
558 opened_buffers: Default::default(),
559 buffer_snapshots: Default::default(),
560 nonce: StdRng::from_entropy().gen(),
561 initialized_persistent_state: false,
562 };
563 for worktree in worktrees {
564 this.add_worktree(&worktree, cx);
565 }
566 this
567 });
568
569 let user_ids = response
570 .collaborators
571 .iter()
572 .map(|peer| peer.user_id)
573 .collect();
574 user_store
575 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
576 .await?;
577 let mut collaborators = HashMap::default();
578 for message in response.collaborators {
579 let collaborator = Collaborator::from_proto(message, &user_store, &mut cx).await?;
580 collaborators.insert(collaborator.peer_id, collaborator);
581 }
582
583 this.update(&mut cx, |this, _| {
584 this.collaborators = collaborators;
585 });
586
587 Ok(this)
588 }
589
590 #[cfg(any(test, feature = "test-support"))]
591 pub async fn test(
592 fs: Arc<dyn Fs>,
593 root_paths: impl IntoIterator<Item = &Path>,
594 cx: &mut gpui::TestAppContext,
595 ) -> ModelHandle<Project> {
596 if !cx.read(|cx| cx.has_global::<Settings>()) {
597 cx.update(|cx| cx.set_global(Settings::test(cx)));
598 }
599
600 let languages = Arc::new(LanguageRegistry::test());
601 let http_client = client::test::FakeHttpClient::with_404_response();
602 let client = client::Client::new(http_client.clone());
603 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
604 let project_store = cx.add_model(|_| ProjectStore::new(Db::open_fake()));
605 let project = cx.update(|cx| {
606 Project::local(true, client, user_store, project_store, languages, fs, cx)
607 });
608 for path in root_paths {
609 let (tree, _) = project
610 .update(cx, |project, cx| {
611 project.find_or_create_local_worktree(path, true, cx)
612 })
613 .await
614 .unwrap();
615 tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
616 .await;
617 }
618 project
619 }
620
621 pub fn restore_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
622 if self.is_remote() {
623 return Task::ready(Ok(()));
624 }
625
626 let db = self.project_store.read(cx).db.clone();
627 let keys = self.db_keys_for_online_state(cx);
628 let online_by_default = cx.global::<Settings>().projects_online_by_default;
629 let read_online = cx.background().spawn(async move {
630 let values = db.read(keys)?;
631 anyhow::Ok(
632 values
633 .into_iter()
634 .all(|e| e.map_or(online_by_default, |e| e == [true as u8])),
635 )
636 });
637 cx.spawn(|this, mut cx| async move {
638 let online = read_online.await.log_err().unwrap_or(false);
639 this.update(&mut cx, |this, cx| {
640 this.initialized_persistent_state = true;
641 if let ProjectClientState::Local { online_tx, .. } = &mut this.client_state {
642 let mut online_tx = online_tx.borrow_mut();
643 if *online_tx != online {
644 *online_tx = online;
645 drop(online_tx);
646 this.metadata_changed(false, cx);
647 }
648 }
649 });
650 Ok(())
651 })
652 }
653
654 fn persist_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
655 if self.is_remote() || !self.initialized_persistent_state {
656 return Task::ready(Ok(()));
657 }
658
659 let db = self.project_store.read(cx).db.clone();
660 let keys = self.db_keys_for_online_state(cx);
661 let is_online = self.is_online();
662 cx.background().spawn(async move {
663 let value = &[is_online as u8];
664 db.write(keys.into_iter().map(|key| (key, value)))
665 })
666 }
667
668 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
669 let settings = cx.global::<Settings>();
670
671 let mut language_servers_to_start = Vec::new();
672 for buffer in self.opened_buffers.values() {
673 if let Some(buffer) = buffer.upgrade(cx) {
674 let buffer = buffer.read(cx);
675 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
676 {
677 if settings.enable_language_server(Some(&language.name())) {
678 let worktree = file.worktree.read(cx);
679 language_servers_to_start.push((
680 worktree.id(),
681 worktree.as_local().unwrap().abs_path().clone(),
682 language.clone(),
683 ));
684 }
685 }
686 }
687 }
688
689 let mut language_servers_to_stop = Vec::new();
690 for language in self.languages.to_vec() {
691 if let Some(lsp_adapter) = language.lsp_adapter() {
692 if !settings.enable_language_server(Some(&language.name())) {
693 let lsp_name = lsp_adapter.name();
694 for (worktree_id, started_lsp_name) in self.started_language_servers.keys() {
695 if lsp_name == *started_lsp_name {
696 language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
697 }
698 }
699 }
700 }
701 }
702
703 // Stop all newly-disabled language servers.
704 for (worktree_id, adapter_name) in language_servers_to_stop {
705 self.stop_language_server(worktree_id, adapter_name, cx)
706 .detach();
707 }
708
709 // Start all the newly-enabled language servers.
710 for (worktree_id, worktree_path, language) in language_servers_to_start {
711 self.start_language_server(worktree_id, worktree_path, language, cx);
712 }
713
714 cx.notify();
715 }
716
717 pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
718 self.opened_buffers
719 .get(&remote_id)
720 .and_then(|buffer| buffer.upgrade(cx))
721 }
722
723 pub fn languages(&self) -> &Arc<LanguageRegistry> {
724 &self.languages
725 }
726
727 pub fn client(&self) -> Arc<Client> {
728 self.client.clone()
729 }
730
731 pub fn user_store(&self) -> ModelHandle<UserStore> {
732 self.user_store.clone()
733 }
734
735 pub fn project_store(&self) -> ModelHandle<ProjectStore> {
736 self.project_store.clone()
737 }
738
739 #[cfg(any(test, feature = "test-support"))]
740 pub fn check_invariants(&self, cx: &AppContext) {
741 if self.is_local() {
742 let mut worktree_root_paths = HashMap::default();
743 for worktree in self.worktrees(cx) {
744 let worktree = worktree.read(cx);
745 let abs_path = worktree.as_local().unwrap().abs_path().clone();
746 let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
747 assert_eq!(
748 prev_worktree_id,
749 None,
750 "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
751 abs_path,
752 worktree.id(),
753 prev_worktree_id
754 )
755 }
756 } else {
757 let replica_id = self.replica_id();
758 for buffer in self.opened_buffers.values() {
759 if let Some(buffer) = buffer.upgrade(cx) {
760 let buffer = buffer.read(cx);
761 assert_eq!(
762 buffer.deferred_ops_len(),
763 0,
764 "replica {}, buffer {} has deferred operations",
765 replica_id,
766 buffer.remote_id()
767 );
768 }
769 }
770 }
771 }
772
773 #[cfg(any(test, feature = "test-support"))]
774 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
775 let path = path.into();
776 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
777 self.opened_buffers.iter().any(|(_, buffer)| {
778 if let Some(buffer) = buffer.upgrade(cx) {
779 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
780 if file.worktree == worktree && file.path() == &path.path {
781 return true;
782 }
783 }
784 }
785 false
786 })
787 } else {
788 false
789 }
790 }
791
792 pub fn fs(&self) -> &Arc<dyn Fs> {
793 &self.fs
794 }
795
796 pub fn set_online(&mut self, online: bool, cx: &mut ModelContext<Self>) {
797 if let ProjectClientState::Local { online_tx, .. } = &mut self.client_state {
798 let mut online_tx = online_tx.borrow_mut();
799 if *online_tx != online {
800 *online_tx = online;
801 drop(online_tx);
802 self.metadata_changed(true, cx);
803 }
804 }
805 }
806
807 pub fn is_online(&self) -> bool {
808 match &self.client_state {
809 ProjectClientState::Local { online_rx, .. } => *online_rx.borrow(),
810 ProjectClientState::Remote { .. } => true,
811 }
812 }
813
814 fn unregister(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
815 self.unshared(cx);
816 if let ProjectClientState::Local { remote_id_rx, .. } = &mut self.client_state {
817 if let Some(remote_id) = *remote_id_rx.borrow() {
818 let request = self.client.request(proto::UnregisterProject {
819 project_id: remote_id,
820 });
821 return cx.spawn(|this, mut cx| async move {
822 let response = request.await;
823
824 // Unregistering the project causes the server to send out a
825 // contact update removing this project from the host's list
826 // of online projects. Wait until this contact update has been
827 // processed before clearing out this project's remote id, so
828 // that there is no moment where this project appears in the
829 // contact metadata and *also* has no remote id.
830 this.update(&mut cx, |this, cx| {
831 this.user_store()
832 .update(cx, |store, _| store.contact_updates_done())
833 })
834 .await;
835
836 this.update(&mut cx, |this, cx| {
837 if let ProjectClientState::Local { remote_id_tx, .. } =
838 &mut this.client_state
839 {
840 *remote_id_tx.borrow_mut() = None;
841 }
842 this.client_subscriptions.clear();
843 this.metadata_changed(false, cx);
844 });
845 response.map(drop)
846 });
847 }
848 }
849 Task::ready(Ok(()))
850 }
851
852 fn register(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
853 if let ProjectClientState::Local { remote_id_rx, .. } = &self.client_state {
854 if remote_id_rx.borrow().is_some() {
855 return Task::ready(Ok(()));
856 }
857 }
858
859 let response = self.client.request(proto::RegisterProject {});
860 cx.spawn(|this, mut cx| async move {
861 let remote_id = response.await?.project_id;
862 this.update(&mut cx, |this, cx| {
863 if let ProjectClientState::Local { remote_id_tx, .. } = &mut this.client_state {
864 *remote_id_tx.borrow_mut() = Some(remote_id);
865 }
866
867 this.metadata_changed(false, cx);
868 cx.emit(Event::RemoteIdChanged(Some(remote_id)));
869 this.client_subscriptions
870 .push(this.client.add_model_for_remote_entity(remote_id, cx));
871 Ok(())
872 })
873 })
874 }
875
876 pub fn remote_id(&self) -> Option<u64> {
877 match &self.client_state {
878 ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
879 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
880 }
881 }
882
883 pub fn next_remote_id(&self) -> impl Future<Output = u64> {
884 let mut id = None;
885 let mut watch = None;
886 match &self.client_state {
887 ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
888 ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
889 }
890
891 async move {
892 if let Some(id) = id {
893 return id;
894 }
895 let mut watch = watch.unwrap();
896 loop {
897 let id = *watch.borrow();
898 if let Some(id) = id {
899 return id;
900 }
901 watch.next().await;
902 }
903 }
904 }
905
906 pub fn shared_remote_id(&self) -> Option<u64> {
907 match &self.client_state {
908 ProjectClientState::Local {
909 remote_id_rx,
910 is_shared,
911 ..
912 } => {
913 if *is_shared {
914 *remote_id_rx.borrow()
915 } else {
916 None
917 }
918 }
919 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
920 }
921 }
922
923 pub fn replica_id(&self) -> ReplicaId {
924 match &self.client_state {
925 ProjectClientState::Local { .. } => 0,
926 ProjectClientState::Remote { replica_id, .. } => *replica_id,
927 }
928 }
929
930 fn metadata_changed(&mut self, persist: bool, cx: &mut ModelContext<Self>) {
931 if let ProjectClientState::Local {
932 remote_id_rx,
933 online_rx,
934 ..
935 } = &self.client_state
936 {
937 if let (Some(project_id), true) = (*remote_id_rx.borrow(), *online_rx.borrow()) {
938 self.client
939 .send(proto::UpdateProject {
940 project_id,
941 worktrees: self
942 .worktrees
943 .iter()
944 .filter_map(|worktree| {
945 worktree.upgrade(&cx).map(|worktree| {
946 worktree.read(cx).as_local().unwrap().metadata_proto()
947 })
948 })
949 .collect(),
950 })
951 .log_err();
952 }
953
954 self.project_store.update(cx, |_, cx| cx.notify());
955 if persist {
956 self.persist_state(cx).detach_and_log_err(cx);
957 }
958 cx.notify();
959 }
960 }
961
962 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
963 &self.collaborators
964 }
965
966 pub fn worktrees<'a>(
967 &'a self,
968 cx: &'a AppContext,
969 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
970 self.worktrees
971 .iter()
972 .filter_map(move |worktree| worktree.upgrade(cx))
973 }
974
975 pub fn visible_worktrees<'a>(
976 &'a self,
977 cx: &'a AppContext,
978 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
979 self.worktrees.iter().filter_map(|worktree| {
980 worktree.upgrade(cx).and_then(|worktree| {
981 if worktree.read(cx).is_visible() {
982 Some(worktree)
983 } else {
984 None
985 }
986 })
987 })
988 }
989
990 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
991 self.visible_worktrees(cx)
992 .map(|tree| tree.read(cx).root_name())
993 }
994
995 fn db_keys_for_online_state(&self, cx: &AppContext) -> Vec<String> {
996 self.worktrees
997 .iter()
998 .filter_map(|worktree| {
999 let worktree = worktree.upgrade(&cx)?.read(cx);
1000 if worktree.is_visible() {
1001 Some(format!(
1002 "project-path-online:{}",
1003 worktree.as_local().unwrap().abs_path().to_string_lossy()
1004 ))
1005 } else {
1006 None
1007 }
1008 })
1009 .collect::<Vec<_>>()
1010 }
1011
1012 pub fn worktree_for_id(
1013 &self,
1014 id: WorktreeId,
1015 cx: &AppContext,
1016 ) -> Option<ModelHandle<Worktree>> {
1017 self.worktrees(cx)
1018 .find(|worktree| worktree.read(cx).id() == id)
1019 }
1020
1021 pub fn worktree_for_entry(
1022 &self,
1023 entry_id: ProjectEntryId,
1024 cx: &AppContext,
1025 ) -> Option<ModelHandle<Worktree>> {
1026 self.worktrees(cx)
1027 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1028 }
1029
1030 pub fn worktree_id_for_entry(
1031 &self,
1032 entry_id: ProjectEntryId,
1033 cx: &AppContext,
1034 ) -> Option<WorktreeId> {
1035 self.worktree_for_entry(entry_id, cx)
1036 .map(|worktree| worktree.read(cx).id())
1037 }
1038
1039 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1040 paths.iter().all(|path| self.contains_path(&path, cx))
1041 }
1042
1043 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1044 for worktree in self.worktrees(cx) {
1045 let worktree = worktree.read(cx).as_local();
1046 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1047 return true;
1048 }
1049 }
1050 false
1051 }
1052
1053 pub fn create_entry(
1054 &mut self,
1055 project_path: impl Into<ProjectPath>,
1056 is_directory: bool,
1057 cx: &mut ModelContext<Self>,
1058 ) -> Option<Task<Result<Entry>>> {
1059 let project_path = project_path.into();
1060 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1061 if self.is_local() {
1062 Some(worktree.update(cx, |worktree, cx| {
1063 worktree
1064 .as_local_mut()
1065 .unwrap()
1066 .create_entry(project_path.path, is_directory, cx)
1067 }))
1068 } else {
1069 let client = self.client.clone();
1070 let project_id = self.remote_id().unwrap();
1071 Some(cx.spawn_weak(|_, mut cx| async move {
1072 let response = client
1073 .request(proto::CreateProjectEntry {
1074 worktree_id: project_path.worktree_id.to_proto(),
1075 project_id,
1076 path: project_path.path.as_os_str().as_bytes().to_vec(),
1077 is_directory,
1078 })
1079 .await?;
1080 let entry = response
1081 .entry
1082 .ok_or_else(|| anyhow!("missing entry in response"))?;
1083 worktree
1084 .update(&mut cx, |worktree, cx| {
1085 worktree.as_remote().unwrap().insert_entry(
1086 entry,
1087 response.worktree_scan_id as usize,
1088 cx,
1089 )
1090 })
1091 .await
1092 }))
1093 }
1094 }
1095
1096 pub fn copy_entry(
1097 &mut self,
1098 entry_id: ProjectEntryId,
1099 new_path: impl Into<Arc<Path>>,
1100 cx: &mut ModelContext<Self>,
1101 ) -> Option<Task<Result<Entry>>> {
1102 let worktree = self.worktree_for_entry(entry_id, cx)?;
1103 let new_path = new_path.into();
1104 if self.is_local() {
1105 worktree.update(cx, |worktree, cx| {
1106 worktree
1107 .as_local_mut()
1108 .unwrap()
1109 .copy_entry(entry_id, new_path, cx)
1110 })
1111 } else {
1112 let client = self.client.clone();
1113 let project_id = self.remote_id().unwrap();
1114
1115 Some(cx.spawn_weak(|_, mut cx| async move {
1116 let response = client
1117 .request(proto::CopyProjectEntry {
1118 project_id,
1119 entry_id: entry_id.to_proto(),
1120 new_path: new_path.as_os_str().as_bytes().to_vec(),
1121 })
1122 .await?;
1123 let entry = response
1124 .entry
1125 .ok_or_else(|| anyhow!("missing entry in response"))?;
1126 worktree
1127 .update(&mut cx, |worktree, cx| {
1128 worktree.as_remote().unwrap().insert_entry(
1129 entry,
1130 response.worktree_scan_id as usize,
1131 cx,
1132 )
1133 })
1134 .await
1135 }))
1136 }
1137 }
1138
1139 pub fn rename_entry(
1140 &mut self,
1141 entry_id: ProjectEntryId,
1142 new_path: impl Into<Arc<Path>>,
1143 cx: &mut ModelContext<Self>,
1144 ) -> Option<Task<Result<Entry>>> {
1145 let worktree = self.worktree_for_entry(entry_id, cx)?;
1146 let new_path = new_path.into();
1147 if self.is_local() {
1148 worktree.update(cx, |worktree, cx| {
1149 worktree
1150 .as_local_mut()
1151 .unwrap()
1152 .rename_entry(entry_id, new_path, cx)
1153 })
1154 } else {
1155 let client = self.client.clone();
1156 let project_id = self.remote_id().unwrap();
1157
1158 Some(cx.spawn_weak(|_, mut cx| async move {
1159 let response = client
1160 .request(proto::RenameProjectEntry {
1161 project_id,
1162 entry_id: entry_id.to_proto(),
1163 new_path: new_path.as_os_str().as_bytes().to_vec(),
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().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 delete_entry(
1183 &mut self,
1184 entry_id: ProjectEntryId,
1185 cx: &mut ModelContext<Self>,
1186 ) -> Option<Task<Result<()>>> {
1187 let worktree = self.worktree_for_entry(entry_id, cx)?;
1188 if self.is_local() {
1189 worktree.update(cx, |worktree, cx| {
1190 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1191 })
1192 } else {
1193 let client = self.client.clone();
1194 let project_id = self.remote_id().unwrap();
1195 Some(cx.spawn_weak(|_, mut cx| async move {
1196 let response = client
1197 .request(proto::DeleteProjectEntry {
1198 project_id,
1199 entry_id: entry_id.to_proto(),
1200 })
1201 .await?;
1202 worktree
1203 .update(&mut cx, move |worktree, cx| {
1204 worktree.as_remote().unwrap().delete_entry(
1205 entry_id,
1206 response.worktree_scan_id as usize,
1207 cx,
1208 )
1209 })
1210 .await
1211 }))
1212 }
1213 }
1214
1215 fn share(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
1216 let project_id;
1217 if let ProjectClientState::Local {
1218 remote_id_rx,
1219 is_shared,
1220 ..
1221 } = &mut self.client_state
1222 {
1223 if *is_shared {
1224 return Task::ready(Ok(()));
1225 }
1226 *is_shared = true;
1227 if let Some(id) = *remote_id_rx.borrow() {
1228 project_id = id;
1229 } else {
1230 return Task::ready(Err(anyhow!("project hasn't been registered")));
1231 }
1232 } else {
1233 return Task::ready(Err(anyhow!("can't share a remote project")));
1234 };
1235
1236 for open_buffer in self.opened_buffers.values_mut() {
1237 match open_buffer {
1238 OpenBuffer::Strong(_) => {}
1239 OpenBuffer::Weak(buffer) => {
1240 if let Some(buffer) = buffer.upgrade(cx) {
1241 *open_buffer = OpenBuffer::Strong(buffer);
1242 }
1243 }
1244 OpenBuffer::Loading(_) => unreachable!(),
1245 }
1246 }
1247
1248 for worktree_handle in self.worktrees.iter_mut() {
1249 match worktree_handle {
1250 WorktreeHandle::Strong(_) => {}
1251 WorktreeHandle::Weak(worktree) => {
1252 if let Some(worktree) = worktree.upgrade(cx) {
1253 *worktree_handle = WorktreeHandle::Strong(worktree);
1254 }
1255 }
1256 }
1257 }
1258
1259 let mut tasks = Vec::new();
1260 for worktree in self.worktrees(cx).collect::<Vec<_>>() {
1261 worktree.update(cx, |worktree, cx| {
1262 let worktree = worktree.as_local_mut().unwrap();
1263 tasks.push(worktree.share(project_id, cx));
1264 });
1265 }
1266
1267 for (server_id, status) in &self.language_server_statuses {
1268 self.client
1269 .send(proto::StartLanguageServer {
1270 project_id,
1271 server: Some(proto::LanguageServer {
1272 id: *server_id as u64,
1273 name: status.name.clone(),
1274 }),
1275 })
1276 .log_err();
1277 }
1278
1279 cx.spawn(|this, mut cx| async move {
1280 for task in tasks {
1281 task.await?;
1282 }
1283 this.update(&mut cx, |_, cx| cx.notify());
1284 Ok(())
1285 })
1286 }
1287
1288 fn unshared(&mut self, cx: &mut ModelContext<Self>) {
1289 if let ProjectClientState::Local { is_shared, .. } = &mut self.client_state {
1290 if !*is_shared {
1291 return;
1292 }
1293
1294 *is_shared = false;
1295 self.collaborators.clear();
1296 self.shared_buffers.clear();
1297 for worktree_handle in self.worktrees.iter_mut() {
1298 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1299 let is_visible = worktree.update(cx, |worktree, _| {
1300 worktree.as_local_mut().unwrap().unshare();
1301 worktree.is_visible()
1302 });
1303 if !is_visible {
1304 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1305 }
1306 }
1307 }
1308
1309 for open_buffer in self.opened_buffers.values_mut() {
1310 match open_buffer {
1311 OpenBuffer::Strong(buffer) => {
1312 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1313 }
1314 _ => {}
1315 }
1316 }
1317
1318 cx.notify();
1319 } else {
1320 log::error!("attempted to unshare a remote project");
1321 }
1322 }
1323
1324 pub fn respond_to_join_request(
1325 &mut self,
1326 requester_id: u64,
1327 allow: bool,
1328 cx: &mut ModelContext<Self>,
1329 ) {
1330 if let Some(project_id) = self.remote_id() {
1331 let share = self.share(cx);
1332 let client = self.client.clone();
1333 cx.foreground()
1334 .spawn(async move {
1335 share.await?;
1336 client.send(proto::RespondToJoinProjectRequest {
1337 requester_id,
1338 project_id,
1339 allow,
1340 })
1341 })
1342 .detach_and_log_err(cx);
1343 }
1344 }
1345
1346 fn removed_from_project(&mut self, cx: &mut ModelContext<Self>) {
1347 if let ProjectClientState::Remote {
1348 sharing_has_stopped,
1349 ..
1350 } = &mut self.client_state
1351 {
1352 *sharing_has_stopped = true;
1353 self.collaborators.clear();
1354 for worktree in &self.worktrees {
1355 if let Some(worktree) = worktree.upgrade(cx) {
1356 worktree.update(cx, |worktree, _| {
1357 if let Some(worktree) = worktree.as_remote_mut() {
1358 worktree.disconnected_from_host();
1359 }
1360 });
1361 }
1362 }
1363 cx.notify();
1364 }
1365 }
1366
1367 pub fn is_read_only(&self) -> bool {
1368 match &self.client_state {
1369 ProjectClientState::Local { .. } => false,
1370 ProjectClientState::Remote {
1371 sharing_has_stopped,
1372 ..
1373 } => *sharing_has_stopped,
1374 }
1375 }
1376
1377 pub fn is_local(&self) -> bool {
1378 match &self.client_state {
1379 ProjectClientState::Local { .. } => true,
1380 ProjectClientState::Remote { .. } => false,
1381 }
1382 }
1383
1384 pub fn is_remote(&self) -> bool {
1385 !self.is_local()
1386 }
1387
1388 pub fn create_buffer(
1389 &mut self,
1390 text: &str,
1391 language: Option<Arc<Language>>,
1392 cx: &mut ModelContext<Self>,
1393 ) -> Result<ModelHandle<Buffer>> {
1394 if self.is_remote() {
1395 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1396 }
1397
1398 let buffer = cx.add_model(|cx| {
1399 Buffer::new(self.replica_id(), text, cx)
1400 .with_language(language.unwrap_or(language::PLAIN_TEXT.clone()), cx)
1401 });
1402 self.register_buffer(&buffer, cx)?;
1403 Ok(buffer)
1404 }
1405
1406 pub fn open_path(
1407 &mut self,
1408 path: impl Into<ProjectPath>,
1409 cx: &mut ModelContext<Self>,
1410 ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1411 let task = self.open_buffer(path, cx);
1412 cx.spawn_weak(|_, cx| async move {
1413 let buffer = task.await?;
1414 let project_entry_id = buffer
1415 .read_with(&cx, |buffer, cx| {
1416 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1417 })
1418 .ok_or_else(|| anyhow!("no project entry"))?;
1419 Ok((project_entry_id, buffer.into()))
1420 })
1421 }
1422
1423 pub fn open_local_buffer(
1424 &mut self,
1425 abs_path: impl AsRef<Path>,
1426 cx: &mut ModelContext<Self>,
1427 ) -> Task<Result<ModelHandle<Buffer>>> {
1428 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1429 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1430 } else {
1431 Task::ready(Err(anyhow!("no such path")))
1432 }
1433 }
1434
1435 pub fn open_buffer(
1436 &mut self,
1437 path: impl Into<ProjectPath>,
1438 cx: &mut ModelContext<Self>,
1439 ) -> Task<Result<ModelHandle<Buffer>>> {
1440 let project_path = path.into();
1441 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1442 worktree
1443 } else {
1444 return Task::ready(Err(anyhow!("no such worktree")));
1445 };
1446
1447 // If there is already a buffer for the given path, then return it.
1448 let existing_buffer = self.get_open_buffer(&project_path, cx);
1449 if let Some(existing_buffer) = existing_buffer {
1450 return Task::ready(Ok(existing_buffer));
1451 }
1452
1453 let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1454 // If the given path is already being loaded, then wait for that existing
1455 // task to complete and return the same buffer.
1456 hash_map::Entry::Occupied(e) => e.get().clone(),
1457
1458 // Otherwise, record the fact that this path is now being loaded.
1459 hash_map::Entry::Vacant(entry) => {
1460 let (mut tx, rx) = postage::watch::channel();
1461 entry.insert(rx.clone());
1462
1463 let load_buffer = if worktree.read(cx).is_local() {
1464 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1465 } else {
1466 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1467 };
1468
1469 cx.spawn(move |this, mut cx| async move {
1470 let load_result = load_buffer.await;
1471 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1472 // Record the fact that the buffer is no longer loading.
1473 this.loading_buffers.remove(&project_path);
1474 let buffer = load_result.map_err(Arc::new)?;
1475 Ok(buffer)
1476 }));
1477 })
1478 .detach();
1479 rx
1480 }
1481 };
1482
1483 cx.foreground().spawn(async move {
1484 loop {
1485 if let Some(result) = loading_watch.borrow().as_ref() {
1486 match result {
1487 Ok(buffer) => return Ok(buffer.clone()),
1488 Err(error) => return Err(anyhow!("{}", error)),
1489 }
1490 }
1491 loading_watch.next().await;
1492 }
1493 })
1494 }
1495
1496 fn open_local_buffer_internal(
1497 &mut self,
1498 path: &Arc<Path>,
1499 worktree: &ModelHandle<Worktree>,
1500 cx: &mut ModelContext<Self>,
1501 ) -> Task<Result<ModelHandle<Buffer>>> {
1502 let load_buffer = worktree.update(cx, |worktree, cx| {
1503 let worktree = worktree.as_local_mut().unwrap();
1504 worktree.load_buffer(path, cx)
1505 });
1506 cx.spawn(|this, mut cx| async move {
1507 let buffer = load_buffer.await?;
1508 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1509 Ok(buffer)
1510 })
1511 }
1512
1513 fn open_remote_buffer_internal(
1514 &mut self,
1515 path: &Arc<Path>,
1516 worktree: &ModelHandle<Worktree>,
1517 cx: &mut ModelContext<Self>,
1518 ) -> Task<Result<ModelHandle<Buffer>>> {
1519 let rpc = self.client.clone();
1520 let project_id = self.remote_id().unwrap();
1521 let remote_worktree_id = worktree.read(cx).id();
1522 let path = path.clone();
1523 let path_string = path.to_string_lossy().to_string();
1524 cx.spawn(|this, mut cx| async move {
1525 let response = rpc
1526 .request(proto::OpenBufferByPath {
1527 project_id,
1528 worktree_id: remote_worktree_id.to_proto(),
1529 path: path_string,
1530 })
1531 .await?;
1532 let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
1533 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1534 .await
1535 })
1536 }
1537
1538 fn open_local_buffer_via_lsp(
1539 &mut self,
1540 abs_path: lsp::Url,
1541 lsp_adapter: Arc<dyn LspAdapter>,
1542 lsp_server: Arc<LanguageServer>,
1543 cx: &mut ModelContext<Self>,
1544 ) -> Task<Result<ModelHandle<Buffer>>> {
1545 cx.spawn(|this, mut cx| async move {
1546 let abs_path = abs_path
1547 .to_file_path()
1548 .map_err(|_| anyhow!("can't convert URI to path"))?;
1549 let (worktree, relative_path) = if let Some(result) =
1550 this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1551 {
1552 result
1553 } else {
1554 let worktree = this
1555 .update(&mut cx, |this, cx| {
1556 this.create_local_worktree(&abs_path, false, cx)
1557 })
1558 .await?;
1559 this.update(&mut cx, |this, cx| {
1560 this.language_servers.insert(
1561 (worktree.read(cx).id(), lsp_adapter.name()),
1562 (lsp_adapter, lsp_server),
1563 );
1564 });
1565 (worktree, PathBuf::new())
1566 };
1567
1568 let project_path = ProjectPath {
1569 worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1570 path: relative_path.into(),
1571 };
1572 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1573 .await
1574 })
1575 }
1576
1577 pub fn open_buffer_by_id(
1578 &mut self,
1579 id: u64,
1580 cx: &mut ModelContext<Self>,
1581 ) -> Task<Result<ModelHandle<Buffer>>> {
1582 if let Some(buffer) = self.buffer_for_id(id, cx) {
1583 Task::ready(Ok(buffer))
1584 } else if self.is_local() {
1585 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1586 } else if let Some(project_id) = self.remote_id() {
1587 let request = self
1588 .client
1589 .request(proto::OpenBufferById { project_id, id });
1590 cx.spawn(|this, mut cx| async move {
1591 let buffer = request
1592 .await?
1593 .buffer
1594 .ok_or_else(|| anyhow!("invalid buffer"))?;
1595 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1596 .await
1597 })
1598 } else {
1599 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1600 }
1601 }
1602
1603 pub fn save_buffer_as(
1604 &mut self,
1605 buffer: ModelHandle<Buffer>,
1606 abs_path: PathBuf,
1607 cx: &mut ModelContext<Project>,
1608 ) -> Task<Result<()>> {
1609 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1610 let old_path =
1611 File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1612 cx.spawn(|this, mut cx| async move {
1613 if let Some(old_path) = old_path {
1614 this.update(&mut cx, |this, cx| {
1615 this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1616 });
1617 }
1618 let (worktree, path) = worktree_task.await?;
1619 worktree
1620 .update(&mut cx, |worktree, cx| {
1621 worktree
1622 .as_local_mut()
1623 .unwrap()
1624 .save_buffer_as(buffer.clone(), path, cx)
1625 })
1626 .await?;
1627 this.update(&mut cx, |this, cx| {
1628 this.assign_language_to_buffer(&buffer, cx);
1629 this.register_buffer_with_language_server(&buffer, cx);
1630 });
1631 Ok(())
1632 })
1633 }
1634
1635 pub fn get_open_buffer(
1636 &mut self,
1637 path: &ProjectPath,
1638 cx: &mut ModelContext<Self>,
1639 ) -> Option<ModelHandle<Buffer>> {
1640 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1641 self.opened_buffers.values().find_map(|buffer| {
1642 let buffer = buffer.upgrade(cx)?;
1643 let file = File::from_dyn(buffer.read(cx).file())?;
1644 if file.worktree == worktree && file.path() == &path.path {
1645 Some(buffer)
1646 } else {
1647 None
1648 }
1649 })
1650 }
1651
1652 fn register_buffer(
1653 &mut self,
1654 buffer: &ModelHandle<Buffer>,
1655 cx: &mut ModelContext<Self>,
1656 ) -> Result<()> {
1657 let remote_id = buffer.read(cx).remote_id();
1658 let open_buffer = if self.is_remote() || self.is_shared() {
1659 OpenBuffer::Strong(buffer.clone())
1660 } else {
1661 OpenBuffer::Weak(buffer.downgrade())
1662 };
1663
1664 match self.opened_buffers.insert(remote_id, open_buffer) {
1665 None => {}
1666 Some(OpenBuffer::Loading(operations)) => {
1667 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1668 }
1669 Some(OpenBuffer::Weak(existing_handle)) => {
1670 if existing_handle.upgrade(cx).is_some() {
1671 Err(anyhow!(
1672 "already registered buffer with remote id {}",
1673 remote_id
1674 ))?
1675 }
1676 }
1677 Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1678 "already registered buffer with remote id {}",
1679 remote_id
1680 ))?,
1681 }
1682 cx.subscribe(buffer, |this, buffer, event, cx| {
1683 this.on_buffer_event(buffer, event, cx);
1684 })
1685 .detach();
1686
1687 self.assign_language_to_buffer(buffer, cx);
1688 self.register_buffer_with_language_server(buffer, cx);
1689 cx.observe_release(buffer, |this, buffer, cx| {
1690 if let Some(file) = File::from_dyn(buffer.file()) {
1691 if file.is_local() {
1692 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1693 if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1694 server
1695 .notify::<lsp::notification::DidCloseTextDocument>(
1696 lsp::DidCloseTextDocumentParams {
1697 text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1698 },
1699 )
1700 .log_err();
1701 }
1702 }
1703 }
1704 })
1705 .detach();
1706
1707 Ok(())
1708 }
1709
1710 fn register_buffer_with_language_server(
1711 &mut self,
1712 buffer_handle: &ModelHandle<Buffer>,
1713 cx: &mut ModelContext<Self>,
1714 ) {
1715 let buffer = buffer_handle.read(cx);
1716 let buffer_id = buffer.remote_id();
1717 if let Some(file) = File::from_dyn(buffer.file()) {
1718 if file.is_local() {
1719 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1720 let initial_snapshot = buffer.text_snapshot();
1721
1722 let mut language_server = None;
1723 let mut language_id = None;
1724 if let Some(language) = buffer.language() {
1725 let worktree_id = file.worktree_id(cx);
1726 if let Some(adapter) = language.lsp_adapter() {
1727 language_id = adapter.id_for_language(language.name().as_ref());
1728 language_server = self
1729 .language_servers
1730 .get(&(worktree_id, adapter.name()))
1731 .cloned();
1732 }
1733 }
1734
1735 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1736 if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1737 self.update_buffer_diagnostics(&buffer_handle, diagnostics, None, cx)
1738 .log_err();
1739 }
1740 }
1741
1742 if let Some((_, server)) = language_server {
1743 server
1744 .notify::<lsp::notification::DidOpenTextDocument>(
1745 lsp::DidOpenTextDocumentParams {
1746 text_document: lsp::TextDocumentItem::new(
1747 uri,
1748 language_id.unwrap_or_default(),
1749 0,
1750 initial_snapshot.text(),
1751 ),
1752 }
1753 .clone(),
1754 )
1755 .log_err();
1756 buffer_handle.update(cx, |buffer, cx| {
1757 buffer.set_completion_triggers(
1758 server
1759 .capabilities()
1760 .completion_provider
1761 .as_ref()
1762 .and_then(|provider| provider.trigger_characters.clone())
1763 .unwrap_or(Vec::new()),
1764 cx,
1765 )
1766 });
1767 self.buffer_snapshots
1768 .insert(buffer_id, vec![(0, initial_snapshot)]);
1769 }
1770 }
1771 }
1772 }
1773
1774 fn unregister_buffer_from_language_server(
1775 &mut self,
1776 buffer: &ModelHandle<Buffer>,
1777 old_path: PathBuf,
1778 cx: &mut ModelContext<Self>,
1779 ) {
1780 buffer.update(cx, |buffer, cx| {
1781 buffer.update_diagnostics(Default::default(), cx);
1782 self.buffer_snapshots.remove(&buffer.remote_id());
1783 if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1784 language_server
1785 .notify::<lsp::notification::DidCloseTextDocument>(
1786 lsp::DidCloseTextDocumentParams {
1787 text_document: lsp::TextDocumentIdentifier::new(
1788 lsp::Url::from_file_path(old_path).unwrap(),
1789 ),
1790 },
1791 )
1792 .log_err();
1793 }
1794 });
1795 }
1796
1797 fn on_buffer_event(
1798 &mut self,
1799 buffer: ModelHandle<Buffer>,
1800 event: &BufferEvent,
1801 cx: &mut ModelContext<Self>,
1802 ) -> Option<()> {
1803 match event {
1804 BufferEvent::Operation(operation) => {
1805 if let Some(project_id) = self.shared_remote_id() {
1806 let request = self.client.request(proto::UpdateBuffer {
1807 project_id,
1808 buffer_id: buffer.read(cx).remote_id(),
1809 operations: vec![language::proto::serialize_operation(&operation)],
1810 });
1811 cx.background().spawn(request).detach_and_log_err(cx);
1812 } else if let Some(project_id) = self.remote_id() {
1813 let _ = self
1814 .client
1815 .send(proto::RegisterProjectActivity { project_id });
1816 }
1817 }
1818 BufferEvent::Edited { .. } => {
1819 let (_, language_server) = self
1820 .language_server_for_buffer(buffer.read(cx), cx)?
1821 .clone();
1822 let buffer = buffer.read(cx);
1823 let file = File::from_dyn(buffer.file())?;
1824 let abs_path = file.as_local()?.abs_path(cx);
1825 let uri = lsp::Url::from_file_path(abs_path).unwrap();
1826 let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1827 let (version, prev_snapshot) = buffer_snapshots.last()?;
1828 let next_snapshot = buffer.text_snapshot();
1829 let next_version = version + 1;
1830
1831 let content_changes = buffer
1832 .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1833 .map(|edit| {
1834 let edit_start = edit.new.start.0;
1835 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1836 let new_text = next_snapshot
1837 .text_for_range(edit.new.start.1..edit.new.end.1)
1838 .collect();
1839 lsp::TextDocumentContentChangeEvent {
1840 range: Some(lsp::Range::new(
1841 point_to_lsp(edit_start),
1842 point_to_lsp(edit_end),
1843 )),
1844 range_length: None,
1845 text: new_text,
1846 }
1847 })
1848 .collect();
1849
1850 buffer_snapshots.push((next_version, next_snapshot));
1851
1852 language_server
1853 .notify::<lsp::notification::DidChangeTextDocument>(
1854 lsp::DidChangeTextDocumentParams {
1855 text_document: lsp::VersionedTextDocumentIdentifier::new(
1856 uri,
1857 next_version,
1858 ),
1859 content_changes,
1860 },
1861 )
1862 .log_err();
1863 }
1864 BufferEvent::Saved => {
1865 let file = File::from_dyn(buffer.read(cx).file())?;
1866 let worktree_id = file.worktree_id(cx);
1867 let abs_path = file.as_local()?.abs_path(cx);
1868 let text_document = lsp::TextDocumentIdentifier {
1869 uri: lsp::Url::from_file_path(abs_path).unwrap(),
1870 };
1871
1872 for (_, server) in self.language_servers_for_worktree(worktree_id) {
1873 server
1874 .notify::<lsp::notification::DidSaveTextDocument>(
1875 lsp::DidSaveTextDocumentParams {
1876 text_document: text_document.clone(),
1877 text: None,
1878 },
1879 )
1880 .log_err();
1881 }
1882
1883 // After saving a buffer, simulate disk-based diagnostics being finished for languages
1884 // that don't support a disk-based progress token.
1885 let (lsp_adapter, language_server) =
1886 self.language_server_for_buffer(buffer.read(cx), cx)?;
1887 if lsp_adapter
1888 .disk_based_diagnostics_progress_token()
1889 .is_none()
1890 {
1891 let server_id = language_server.server_id();
1892 self.disk_based_diagnostics_finished(server_id, cx);
1893 self.broadcast_language_server_update(
1894 server_id,
1895 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1896 proto::LspDiskBasedDiagnosticsUpdated {},
1897 ),
1898 );
1899 }
1900 }
1901 _ => {}
1902 }
1903
1904 None
1905 }
1906
1907 fn language_servers_for_worktree(
1908 &self,
1909 worktree_id: WorktreeId,
1910 ) -> impl Iterator<Item = &(Arc<dyn LspAdapter>, Arc<LanguageServer>)> {
1911 self.language_servers.iter().filter_map(
1912 move |((language_server_worktree_id, _), server)| {
1913 if *language_server_worktree_id == worktree_id {
1914 Some(server)
1915 } else {
1916 None
1917 }
1918 },
1919 )
1920 }
1921
1922 fn assign_language_to_buffer(
1923 &mut self,
1924 buffer: &ModelHandle<Buffer>,
1925 cx: &mut ModelContext<Self>,
1926 ) -> Option<()> {
1927 // If the buffer has a language, set it and start the language server if we haven't already.
1928 let full_path = buffer.read(cx).file()?.full_path(cx);
1929 let language = self.languages.select_language(&full_path)?;
1930 buffer.update(cx, |buffer, cx| {
1931 buffer.set_language(Some(language.clone()), cx);
1932 });
1933
1934 let file = File::from_dyn(buffer.read(cx).file())?;
1935 let worktree = file.worktree.read(cx).as_local()?;
1936 let worktree_id = worktree.id();
1937 let worktree_abs_path = worktree.abs_path().clone();
1938 self.start_language_server(worktree_id, worktree_abs_path, language, cx);
1939
1940 None
1941 }
1942
1943 fn start_language_server(
1944 &mut self,
1945 worktree_id: WorktreeId,
1946 worktree_path: Arc<Path>,
1947 language: Arc<Language>,
1948 cx: &mut ModelContext<Self>,
1949 ) {
1950 if !cx
1951 .global::<Settings>()
1952 .enable_language_server(Some(&language.name()))
1953 {
1954 return;
1955 }
1956
1957 let adapter = if let Some(adapter) = language.lsp_adapter() {
1958 adapter
1959 } else {
1960 return;
1961 };
1962 let key = (worktree_id, adapter.name());
1963 self.started_language_servers
1964 .entry(key.clone())
1965 .or_insert_with(|| {
1966 let server_id = post_inc(&mut self.next_language_server_id);
1967 let language_server = self.languages.start_language_server(
1968 server_id,
1969 language.clone(),
1970 worktree_path,
1971 self.client.http_client(),
1972 cx,
1973 );
1974 cx.spawn_weak(|this, mut cx| async move {
1975 let language_server = language_server?.await.log_err()?;
1976 let language_server = language_server
1977 .initialize(adapter.initialization_options())
1978 .await
1979 .log_err()?;
1980 let this = this.upgrade(&cx)?;
1981 let disk_based_diagnostics_progress_token =
1982 adapter.disk_based_diagnostics_progress_token();
1983
1984 language_server
1985 .on_notification::<lsp::notification::PublishDiagnostics, _>({
1986 let this = this.downgrade();
1987 let adapter = adapter.clone();
1988 move |params, mut cx| {
1989 if let Some(this) = this.upgrade(&cx) {
1990 this.update(&mut cx, |this, cx| {
1991 this.on_lsp_diagnostics_published(
1992 server_id, params, &adapter, cx,
1993 );
1994 });
1995 }
1996 }
1997 })
1998 .detach();
1999
2000 language_server
2001 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2002 let settings = this
2003 .read_with(&cx, |this, _| this.language_server_settings.clone());
2004 move |params, _| {
2005 let settings = settings.lock().clone();
2006 async move {
2007 Ok(params
2008 .items
2009 .into_iter()
2010 .map(|item| {
2011 if let Some(section) = &item.section {
2012 settings
2013 .get(section)
2014 .cloned()
2015 .unwrap_or(serde_json::Value::Null)
2016 } else {
2017 settings.clone()
2018 }
2019 })
2020 .collect())
2021 }
2022 }
2023 })
2024 .detach();
2025
2026 // Even though we don't have handling for these requests, respond to them to
2027 // avoid stalling any language server like `gopls` which waits for a response
2028 // to these requests when initializing.
2029 language_server
2030 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2031 let this = this.downgrade();
2032 move |params, mut cx| async move {
2033 if let Some(this) = this.upgrade(&cx) {
2034 this.update(&mut cx, |this, _| {
2035 if let Some(status) =
2036 this.language_server_statuses.get_mut(&server_id)
2037 {
2038 if let lsp::NumberOrString::String(token) = params.token
2039 {
2040 status.progress_tokens.insert(token);
2041 }
2042 }
2043 });
2044 }
2045 Ok(())
2046 }
2047 })
2048 .detach();
2049 language_server
2050 .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
2051 Ok(())
2052 })
2053 .detach();
2054
2055 language_server
2056 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2057 let this = this.downgrade();
2058 let adapter = adapter.clone();
2059 let language_server = language_server.clone();
2060 move |params, cx| {
2061 Self::on_lsp_workspace_edit(
2062 this,
2063 params,
2064 server_id,
2065 adapter.clone(),
2066 language_server.clone(),
2067 cx,
2068 )
2069 }
2070 })
2071 .detach();
2072
2073 language_server
2074 .on_notification::<lsp::notification::Progress, _>({
2075 let this = this.downgrade();
2076 move |params, mut cx| {
2077 if let Some(this) = this.upgrade(&cx) {
2078 this.update(&mut cx, |this, cx| {
2079 this.on_lsp_progress(
2080 params,
2081 server_id,
2082 disk_based_diagnostics_progress_token,
2083 cx,
2084 );
2085 });
2086 }
2087 }
2088 })
2089 .detach();
2090
2091 this.update(&mut cx, |this, cx| {
2092 this.language_servers
2093 .insert(key.clone(), (adapter.clone(), language_server.clone()));
2094 this.language_server_statuses.insert(
2095 server_id,
2096 LanguageServerStatus {
2097 name: language_server.name().to_string(),
2098 pending_work: Default::default(),
2099 has_pending_diagnostic_updates: false,
2100 progress_tokens: Default::default(),
2101 },
2102 );
2103 language_server
2104 .notify::<lsp::notification::DidChangeConfiguration>(
2105 lsp::DidChangeConfigurationParams {
2106 settings: this.language_server_settings.lock().clone(),
2107 },
2108 )
2109 .ok();
2110
2111 if let Some(project_id) = this.shared_remote_id() {
2112 this.client
2113 .send(proto::StartLanguageServer {
2114 project_id,
2115 server: Some(proto::LanguageServer {
2116 id: server_id as u64,
2117 name: language_server.name().to_string(),
2118 }),
2119 })
2120 .log_err();
2121 }
2122
2123 // Tell the language server about every open buffer in the worktree that matches the language.
2124 for buffer in this.opened_buffers.values() {
2125 if let Some(buffer_handle) = buffer.upgrade(cx) {
2126 let buffer = buffer_handle.read(cx);
2127 let file = if let Some(file) = File::from_dyn(buffer.file()) {
2128 file
2129 } else {
2130 continue;
2131 };
2132 let language = if let Some(language) = buffer.language() {
2133 language
2134 } else {
2135 continue;
2136 };
2137 if file.worktree.read(cx).id() != key.0
2138 || language.lsp_adapter().map(|a| a.name())
2139 != Some(key.1.clone())
2140 {
2141 continue;
2142 }
2143
2144 let file = file.as_local()?;
2145 let versions = this
2146 .buffer_snapshots
2147 .entry(buffer.remote_id())
2148 .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2149 let (version, initial_snapshot) = versions.last().unwrap();
2150 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2151 let language_id = adapter.id_for_language(language.name().as_ref());
2152 language_server
2153 .notify::<lsp::notification::DidOpenTextDocument>(
2154 lsp::DidOpenTextDocumentParams {
2155 text_document: lsp::TextDocumentItem::new(
2156 uri,
2157 language_id.unwrap_or_default(),
2158 *version,
2159 initial_snapshot.text(),
2160 ),
2161 },
2162 )
2163 .log_err()?;
2164 buffer_handle.update(cx, |buffer, cx| {
2165 buffer.set_completion_triggers(
2166 language_server
2167 .capabilities()
2168 .completion_provider
2169 .as_ref()
2170 .and_then(|provider| {
2171 provider.trigger_characters.clone()
2172 })
2173 .unwrap_or(Vec::new()),
2174 cx,
2175 )
2176 });
2177 }
2178 }
2179
2180 cx.notify();
2181 Some(())
2182 });
2183
2184 Some(language_server)
2185 })
2186 });
2187 }
2188
2189 fn stop_language_server(
2190 &mut self,
2191 worktree_id: WorktreeId,
2192 adapter_name: LanguageServerName,
2193 cx: &mut ModelContext<Self>,
2194 ) -> Task<()> {
2195 let key = (worktree_id, adapter_name);
2196 if let Some((_, language_server)) = self.language_servers.remove(&key) {
2197 self.language_server_statuses
2198 .remove(&language_server.server_id());
2199 cx.notify();
2200 }
2201
2202 if let Some(started_language_server) = self.started_language_servers.remove(&key) {
2203 cx.spawn_weak(|this, mut cx| async move {
2204 if let Some(language_server) = started_language_server.await {
2205 if let Some(shutdown) = language_server.shutdown() {
2206 shutdown.await;
2207 }
2208
2209 if let Some(this) = this.upgrade(&cx) {
2210 this.update(&mut cx, |this, cx| {
2211 this.language_server_statuses
2212 .remove(&language_server.server_id());
2213 cx.notify();
2214 });
2215 }
2216 }
2217 })
2218 } else {
2219 Task::ready(())
2220 }
2221 }
2222
2223 pub fn restart_language_servers_for_buffers(
2224 &mut self,
2225 buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2226 cx: &mut ModelContext<Self>,
2227 ) -> Option<()> {
2228 let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2229 .into_iter()
2230 .filter_map(|buffer| {
2231 let file = File::from_dyn(buffer.read(cx).file())?;
2232 let worktree = file.worktree.read(cx).as_local()?;
2233 let worktree_id = worktree.id();
2234 let worktree_abs_path = worktree.abs_path().clone();
2235 let full_path = file.full_path(cx);
2236 Some((worktree_id, worktree_abs_path, full_path))
2237 })
2238 .collect();
2239 for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2240 let language = self.languages.select_language(&full_path)?;
2241 self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2242 }
2243
2244 None
2245 }
2246
2247 fn restart_language_server(
2248 &mut self,
2249 worktree_id: WorktreeId,
2250 worktree_path: Arc<Path>,
2251 language: Arc<Language>,
2252 cx: &mut ModelContext<Self>,
2253 ) {
2254 let adapter = if let Some(adapter) = language.lsp_adapter() {
2255 adapter
2256 } else {
2257 return;
2258 };
2259
2260 let stop = self.stop_language_server(worktree_id, adapter.name(), cx);
2261 cx.spawn_weak(|this, mut cx| async move {
2262 stop.await;
2263 if let Some(this) = this.upgrade(&cx) {
2264 this.update(&mut cx, |this, cx| {
2265 this.start_language_server(worktree_id, worktree_path, language, cx);
2266 });
2267 }
2268 })
2269 .detach();
2270 }
2271
2272 fn on_lsp_diagnostics_published(
2273 &mut self,
2274 server_id: usize,
2275 mut params: lsp::PublishDiagnosticsParams,
2276 adapter: &Arc<dyn LspAdapter>,
2277 cx: &mut ModelContext<Self>,
2278 ) {
2279 adapter.process_diagnostics(&mut params);
2280 self.update_diagnostics(
2281 server_id,
2282 params,
2283 adapter.disk_based_diagnostic_sources(),
2284 cx,
2285 )
2286 .log_err();
2287 }
2288
2289 fn on_lsp_progress(
2290 &mut self,
2291 progress: lsp::ProgressParams,
2292 server_id: usize,
2293 disk_based_diagnostics_progress_token: Option<&str>,
2294 cx: &mut ModelContext<Self>,
2295 ) {
2296 let token = match progress.token {
2297 lsp::NumberOrString::String(token) => token,
2298 lsp::NumberOrString::Number(token) => {
2299 log::info!("skipping numeric progress token {}", token);
2300 return;
2301 }
2302 };
2303 let progress = match progress.value {
2304 lsp::ProgressParamsValue::WorkDone(value) => value,
2305 };
2306 let language_server_status =
2307 if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2308 status
2309 } else {
2310 return;
2311 };
2312
2313 if !language_server_status.progress_tokens.contains(&token) {
2314 return;
2315 }
2316
2317 match progress {
2318 lsp::WorkDoneProgress::Begin(report) => {
2319 if Some(token.as_str()) == disk_based_diagnostics_progress_token {
2320 language_server_status.has_pending_diagnostic_updates = true;
2321 self.disk_based_diagnostics_started(server_id, cx);
2322 self.broadcast_language_server_update(
2323 server_id,
2324 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2325 proto::LspDiskBasedDiagnosticsUpdating {},
2326 ),
2327 );
2328 } else {
2329 self.on_lsp_work_start(
2330 server_id,
2331 token.clone(),
2332 LanguageServerProgress {
2333 message: report.message.clone(),
2334 percentage: report.percentage.map(|p| p as usize),
2335 last_update_at: Instant::now(),
2336 },
2337 cx,
2338 );
2339 self.broadcast_language_server_update(
2340 server_id,
2341 proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2342 token,
2343 message: report.message,
2344 percentage: report.percentage.map(|p| p as u32),
2345 }),
2346 );
2347 }
2348 }
2349 lsp::WorkDoneProgress::Report(report) => {
2350 if Some(token.as_str()) != disk_based_diagnostics_progress_token {
2351 self.on_lsp_work_progress(
2352 server_id,
2353 token.clone(),
2354 LanguageServerProgress {
2355 message: report.message.clone(),
2356 percentage: report.percentage.map(|p| p as usize),
2357 last_update_at: Instant::now(),
2358 },
2359 cx,
2360 );
2361 self.broadcast_language_server_update(
2362 server_id,
2363 proto::update_language_server::Variant::WorkProgress(
2364 proto::LspWorkProgress {
2365 token,
2366 message: report.message,
2367 percentage: report.percentage.map(|p| p as u32),
2368 },
2369 ),
2370 );
2371 }
2372 }
2373 lsp::WorkDoneProgress::End(_) => {
2374 language_server_status.progress_tokens.remove(&token);
2375
2376 if Some(token.as_str()) == disk_based_diagnostics_progress_token {
2377 language_server_status.has_pending_diagnostic_updates = false;
2378 self.disk_based_diagnostics_finished(server_id, cx);
2379 self.broadcast_language_server_update(
2380 server_id,
2381 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2382 proto::LspDiskBasedDiagnosticsUpdated {},
2383 ),
2384 );
2385 } else {
2386 self.on_lsp_work_end(server_id, token.clone(), cx);
2387 self.broadcast_language_server_update(
2388 server_id,
2389 proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2390 token,
2391 }),
2392 );
2393 }
2394 }
2395 }
2396 }
2397
2398 fn on_lsp_work_start(
2399 &mut self,
2400 language_server_id: usize,
2401 token: String,
2402 progress: LanguageServerProgress,
2403 cx: &mut ModelContext<Self>,
2404 ) {
2405 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2406 status.pending_work.insert(token, progress);
2407 cx.notify();
2408 }
2409 }
2410
2411 fn on_lsp_work_progress(
2412 &mut self,
2413 language_server_id: usize,
2414 token: String,
2415 progress: LanguageServerProgress,
2416 cx: &mut ModelContext<Self>,
2417 ) {
2418 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2419 let entry = status
2420 .pending_work
2421 .entry(token)
2422 .or_insert(LanguageServerProgress {
2423 message: Default::default(),
2424 percentage: Default::default(),
2425 last_update_at: progress.last_update_at,
2426 });
2427 if progress.message.is_some() {
2428 entry.message = progress.message;
2429 }
2430 if progress.percentage.is_some() {
2431 entry.percentage = progress.percentage;
2432 }
2433 entry.last_update_at = progress.last_update_at;
2434 cx.notify();
2435 }
2436 }
2437
2438 fn on_lsp_work_end(
2439 &mut self,
2440 language_server_id: usize,
2441 token: String,
2442 cx: &mut ModelContext<Self>,
2443 ) {
2444 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2445 status.pending_work.remove(&token);
2446 cx.notify();
2447 }
2448 }
2449
2450 async fn on_lsp_workspace_edit(
2451 this: WeakModelHandle<Self>,
2452 params: lsp::ApplyWorkspaceEditParams,
2453 server_id: usize,
2454 adapter: Arc<dyn LspAdapter>,
2455 language_server: Arc<LanguageServer>,
2456 mut cx: AsyncAppContext,
2457 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2458 let this = this
2459 .upgrade(&cx)
2460 .ok_or_else(|| anyhow!("project project closed"))?;
2461 let transaction = Self::deserialize_workspace_edit(
2462 this.clone(),
2463 params.edit,
2464 true,
2465 adapter.clone(),
2466 language_server.clone(),
2467 &mut cx,
2468 )
2469 .await
2470 .log_err();
2471 this.update(&mut cx, |this, _| {
2472 if let Some(transaction) = transaction {
2473 this.last_workspace_edits_by_language_server
2474 .insert(server_id, transaction);
2475 }
2476 });
2477 Ok(lsp::ApplyWorkspaceEditResponse {
2478 applied: true,
2479 failed_change: None,
2480 failure_reason: None,
2481 })
2482 }
2483
2484 fn broadcast_language_server_update(
2485 &self,
2486 language_server_id: usize,
2487 event: proto::update_language_server::Variant,
2488 ) {
2489 if let Some(project_id) = self.shared_remote_id() {
2490 self.client
2491 .send(proto::UpdateLanguageServer {
2492 project_id,
2493 language_server_id: language_server_id as u64,
2494 variant: Some(event),
2495 })
2496 .log_err();
2497 }
2498 }
2499
2500 pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2501 for (_, server) in self.language_servers.values() {
2502 server
2503 .notify::<lsp::notification::DidChangeConfiguration>(
2504 lsp::DidChangeConfigurationParams {
2505 settings: settings.clone(),
2506 },
2507 )
2508 .ok();
2509 }
2510 *self.language_server_settings.lock() = settings;
2511 }
2512
2513 pub fn language_server_statuses(
2514 &self,
2515 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2516 self.language_server_statuses.values()
2517 }
2518
2519 pub fn update_diagnostics(
2520 &mut self,
2521 language_server_id: usize,
2522 params: lsp::PublishDiagnosticsParams,
2523 disk_based_sources: &[&str],
2524 cx: &mut ModelContext<Self>,
2525 ) -> Result<()> {
2526 let abs_path = params
2527 .uri
2528 .to_file_path()
2529 .map_err(|_| anyhow!("URI is not a file"))?;
2530 let mut diagnostics = Vec::default();
2531 let mut primary_diagnostic_group_ids = HashMap::default();
2532 let mut sources_by_group_id = HashMap::default();
2533 let mut supporting_diagnostics = HashMap::default();
2534 for diagnostic in ¶ms.diagnostics {
2535 let source = diagnostic.source.as_ref();
2536 let code = diagnostic.code.as_ref().map(|code| match code {
2537 lsp::NumberOrString::Number(code) => code.to_string(),
2538 lsp::NumberOrString::String(code) => code.clone(),
2539 });
2540 let range = range_from_lsp(diagnostic.range);
2541 let is_supporting = diagnostic
2542 .related_information
2543 .as_ref()
2544 .map_or(false, |infos| {
2545 infos.iter().any(|info| {
2546 primary_diagnostic_group_ids.contains_key(&(
2547 source,
2548 code.clone(),
2549 range_from_lsp(info.location.range),
2550 ))
2551 })
2552 });
2553
2554 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2555 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2556 });
2557
2558 if is_supporting {
2559 supporting_diagnostics.insert(
2560 (source, code.clone(), range),
2561 (diagnostic.severity, is_unnecessary),
2562 );
2563 } else {
2564 let group_id = post_inc(&mut self.next_diagnostic_group_id);
2565 let is_disk_based = source.map_or(false, |source| {
2566 disk_based_sources.contains(&source.as_str())
2567 });
2568
2569 sources_by_group_id.insert(group_id, source);
2570 primary_diagnostic_group_ids
2571 .insert((source, code.clone(), range.clone()), group_id);
2572
2573 diagnostics.push(DiagnosticEntry {
2574 range,
2575 diagnostic: Diagnostic {
2576 code: code.clone(),
2577 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2578 message: diagnostic.message.clone(),
2579 group_id,
2580 is_primary: true,
2581 is_valid: true,
2582 is_disk_based,
2583 is_unnecessary,
2584 },
2585 });
2586 if let Some(infos) = &diagnostic.related_information {
2587 for info in infos {
2588 if info.location.uri == params.uri && !info.message.is_empty() {
2589 let range = range_from_lsp(info.location.range);
2590 diagnostics.push(DiagnosticEntry {
2591 range,
2592 diagnostic: Diagnostic {
2593 code: code.clone(),
2594 severity: DiagnosticSeverity::INFORMATION,
2595 message: info.message.clone(),
2596 group_id,
2597 is_primary: false,
2598 is_valid: true,
2599 is_disk_based,
2600 is_unnecessary: false,
2601 },
2602 });
2603 }
2604 }
2605 }
2606 }
2607 }
2608
2609 for entry in &mut diagnostics {
2610 let diagnostic = &mut entry.diagnostic;
2611 if !diagnostic.is_primary {
2612 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2613 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2614 source,
2615 diagnostic.code.clone(),
2616 entry.range.clone(),
2617 )) {
2618 if let Some(severity) = severity {
2619 diagnostic.severity = severity;
2620 }
2621 diagnostic.is_unnecessary = is_unnecessary;
2622 }
2623 }
2624 }
2625
2626 self.update_diagnostic_entries(
2627 language_server_id,
2628 abs_path,
2629 params.version,
2630 diagnostics,
2631 cx,
2632 )?;
2633 Ok(())
2634 }
2635
2636 pub fn update_diagnostic_entries(
2637 &mut self,
2638 language_server_id: usize,
2639 abs_path: PathBuf,
2640 version: Option<i32>,
2641 diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2642 cx: &mut ModelContext<Project>,
2643 ) -> Result<(), anyhow::Error> {
2644 let (worktree, relative_path) = self
2645 .find_local_worktree(&abs_path, cx)
2646 .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2647
2648 let project_path = ProjectPath {
2649 worktree_id: worktree.read(cx).id(),
2650 path: relative_path.into(),
2651 };
2652 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2653 self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2654 }
2655
2656 let updated = worktree.update(cx, |worktree, cx| {
2657 worktree
2658 .as_local_mut()
2659 .ok_or_else(|| anyhow!("not a local worktree"))?
2660 .update_diagnostics(
2661 language_server_id,
2662 project_path.path.clone(),
2663 diagnostics,
2664 cx,
2665 )
2666 })?;
2667 if updated {
2668 cx.emit(Event::DiagnosticsUpdated {
2669 language_server_id,
2670 path: project_path,
2671 });
2672 }
2673 Ok(())
2674 }
2675
2676 fn update_buffer_diagnostics(
2677 &mut self,
2678 buffer: &ModelHandle<Buffer>,
2679 mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2680 version: Option<i32>,
2681 cx: &mut ModelContext<Self>,
2682 ) -> Result<()> {
2683 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2684 Ordering::Equal
2685 .then_with(|| b.is_primary.cmp(&a.is_primary))
2686 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2687 .then_with(|| a.severity.cmp(&b.severity))
2688 .then_with(|| a.message.cmp(&b.message))
2689 }
2690
2691 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2692
2693 diagnostics.sort_unstable_by(|a, b| {
2694 Ordering::Equal
2695 .then_with(|| a.range.start.cmp(&b.range.start))
2696 .then_with(|| b.range.end.cmp(&a.range.end))
2697 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2698 });
2699
2700 let mut sanitized_diagnostics = Vec::new();
2701 let edits_since_save = Patch::new(
2702 snapshot
2703 .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2704 .collect(),
2705 );
2706 for entry in diagnostics {
2707 let start;
2708 let end;
2709 if entry.diagnostic.is_disk_based {
2710 // Some diagnostics are based on files on disk instead of buffers'
2711 // current contents. Adjust these diagnostics' ranges to reflect
2712 // any unsaved edits.
2713 start = edits_since_save.old_to_new(entry.range.start);
2714 end = edits_since_save.old_to_new(entry.range.end);
2715 } else {
2716 start = entry.range.start;
2717 end = entry.range.end;
2718 }
2719
2720 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2721 ..snapshot.clip_point_utf16(end, Bias::Right);
2722
2723 // Expand empty ranges by one character
2724 if range.start == range.end {
2725 range.end.column += 1;
2726 range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2727 if range.start == range.end && range.end.column > 0 {
2728 range.start.column -= 1;
2729 range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2730 }
2731 }
2732
2733 sanitized_diagnostics.push(DiagnosticEntry {
2734 range,
2735 diagnostic: entry.diagnostic,
2736 });
2737 }
2738 drop(edits_since_save);
2739
2740 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2741 buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2742 Ok(())
2743 }
2744
2745 pub fn reload_buffers(
2746 &self,
2747 buffers: HashSet<ModelHandle<Buffer>>,
2748 push_to_history: bool,
2749 cx: &mut ModelContext<Self>,
2750 ) -> Task<Result<ProjectTransaction>> {
2751 let mut local_buffers = Vec::new();
2752 let mut remote_buffers = None;
2753 for buffer_handle in buffers {
2754 let buffer = buffer_handle.read(cx);
2755 if buffer.is_dirty() {
2756 if let Some(file) = File::from_dyn(buffer.file()) {
2757 if file.is_local() {
2758 local_buffers.push(buffer_handle);
2759 } else {
2760 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2761 }
2762 }
2763 }
2764 }
2765
2766 let remote_buffers = self.remote_id().zip(remote_buffers);
2767 let client = self.client.clone();
2768
2769 cx.spawn(|this, mut cx| async move {
2770 let mut project_transaction = ProjectTransaction::default();
2771
2772 if let Some((project_id, remote_buffers)) = remote_buffers {
2773 let response = client
2774 .request(proto::ReloadBuffers {
2775 project_id,
2776 buffer_ids: remote_buffers
2777 .iter()
2778 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2779 .collect(),
2780 })
2781 .await?
2782 .transaction
2783 .ok_or_else(|| anyhow!("missing transaction"))?;
2784 project_transaction = this
2785 .update(&mut cx, |this, cx| {
2786 this.deserialize_project_transaction(response, push_to_history, cx)
2787 })
2788 .await?;
2789 }
2790
2791 for buffer in local_buffers {
2792 let transaction = buffer
2793 .update(&mut cx, |buffer, cx| buffer.reload(cx))
2794 .await?;
2795 buffer.update(&mut cx, |buffer, cx| {
2796 if let Some(transaction) = transaction {
2797 if !push_to_history {
2798 buffer.forget_transaction(transaction.id);
2799 }
2800 project_transaction.0.insert(cx.handle(), transaction);
2801 }
2802 });
2803 }
2804
2805 Ok(project_transaction)
2806 })
2807 }
2808
2809 pub fn format(
2810 &self,
2811 buffers: HashSet<ModelHandle<Buffer>>,
2812 push_to_history: bool,
2813 cx: &mut ModelContext<Project>,
2814 ) -> Task<Result<ProjectTransaction>> {
2815 let mut local_buffers = Vec::new();
2816 let mut remote_buffers = None;
2817 for buffer_handle in buffers {
2818 let buffer = buffer_handle.read(cx);
2819 if let Some(file) = File::from_dyn(buffer.file()) {
2820 if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2821 if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2822 local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2823 }
2824 } else {
2825 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2826 }
2827 } else {
2828 return Task::ready(Ok(Default::default()));
2829 }
2830 }
2831
2832 let remote_buffers = self.remote_id().zip(remote_buffers);
2833 let client = self.client.clone();
2834
2835 cx.spawn(|this, mut cx| async move {
2836 let mut project_transaction = ProjectTransaction::default();
2837
2838 if let Some((project_id, remote_buffers)) = remote_buffers {
2839 let response = client
2840 .request(proto::FormatBuffers {
2841 project_id,
2842 buffer_ids: remote_buffers
2843 .iter()
2844 .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2845 .collect(),
2846 })
2847 .await?
2848 .transaction
2849 .ok_or_else(|| anyhow!("missing transaction"))?;
2850 project_transaction = this
2851 .update(&mut cx, |this, cx| {
2852 this.deserialize_project_transaction(response, push_to_history, cx)
2853 })
2854 .await?;
2855 }
2856
2857 for (buffer, buffer_abs_path, language_server) in local_buffers {
2858 let text_document = lsp::TextDocumentIdentifier::new(
2859 lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
2860 );
2861 let capabilities = &language_server.capabilities();
2862 let tab_size = cx.update(|cx| {
2863 let language_name = buffer.read(cx).language().map(|language| language.name());
2864 cx.global::<Settings>().tab_size(language_name.as_deref())
2865 });
2866 let lsp_edits = if capabilities
2867 .document_formatting_provider
2868 .as_ref()
2869 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2870 {
2871 language_server
2872 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2873 text_document,
2874 options: lsp::FormattingOptions {
2875 tab_size: tab_size.into(),
2876 insert_spaces: true,
2877 insert_final_newline: Some(true),
2878 ..Default::default()
2879 },
2880 work_done_progress_params: Default::default(),
2881 })
2882 .await?
2883 } else if capabilities
2884 .document_range_formatting_provider
2885 .as_ref()
2886 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2887 {
2888 let buffer_start = lsp::Position::new(0, 0);
2889 let buffer_end =
2890 buffer.read_with(&cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
2891 language_server
2892 .request::<lsp::request::RangeFormatting>(
2893 lsp::DocumentRangeFormattingParams {
2894 text_document,
2895 range: lsp::Range::new(buffer_start, buffer_end),
2896 options: lsp::FormattingOptions {
2897 tab_size: tab_size.into(),
2898 insert_spaces: true,
2899 insert_final_newline: Some(true),
2900 ..Default::default()
2901 },
2902 work_done_progress_params: Default::default(),
2903 },
2904 )
2905 .await?
2906 } else {
2907 continue;
2908 };
2909
2910 if let Some(lsp_edits) = lsp_edits {
2911 let edits = this
2912 .update(&mut cx, |this, cx| {
2913 this.edits_from_lsp(&buffer, lsp_edits, None, cx)
2914 })
2915 .await?;
2916 buffer.update(&mut cx, |buffer, cx| {
2917 buffer.finalize_last_transaction();
2918 buffer.start_transaction();
2919 for (range, text) in edits {
2920 buffer.edit([(range, text)], cx);
2921 }
2922 if buffer.end_transaction(cx).is_some() {
2923 let transaction = buffer.finalize_last_transaction().unwrap().clone();
2924 if !push_to_history {
2925 buffer.forget_transaction(transaction.id);
2926 }
2927 project_transaction.0.insert(cx.handle(), transaction);
2928 }
2929 });
2930 }
2931 }
2932
2933 Ok(project_transaction)
2934 })
2935 }
2936
2937 pub fn definition<T: ToPointUtf16>(
2938 &self,
2939 buffer: &ModelHandle<Buffer>,
2940 position: T,
2941 cx: &mut ModelContext<Self>,
2942 ) -> Task<Result<Vec<LocationLink>>> {
2943 let position = position.to_point_utf16(buffer.read(cx));
2944 self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
2945 }
2946
2947 pub fn references<T: ToPointUtf16>(
2948 &self,
2949 buffer: &ModelHandle<Buffer>,
2950 position: T,
2951 cx: &mut ModelContext<Self>,
2952 ) -> Task<Result<Vec<Location>>> {
2953 let position = position.to_point_utf16(buffer.read(cx));
2954 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
2955 }
2956
2957 pub fn document_highlights<T: ToPointUtf16>(
2958 &self,
2959 buffer: &ModelHandle<Buffer>,
2960 position: T,
2961 cx: &mut ModelContext<Self>,
2962 ) -> Task<Result<Vec<DocumentHighlight>>> {
2963 let position = position.to_point_utf16(buffer.read(cx));
2964
2965 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
2966 }
2967
2968 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
2969 if self.is_local() {
2970 let mut requests = Vec::new();
2971 for ((worktree_id, _), (lsp_adapter, language_server)) in self.language_servers.iter() {
2972 let worktree_id = *worktree_id;
2973 if let Some(worktree) = self
2974 .worktree_for_id(worktree_id, cx)
2975 .and_then(|worktree| worktree.read(cx).as_local())
2976 {
2977 let lsp_adapter = lsp_adapter.clone();
2978 let worktree_abs_path = worktree.abs_path().clone();
2979 requests.push(
2980 language_server
2981 .request::<lsp::request::WorkspaceSymbol>(lsp::WorkspaceSymbolParams {
2982 query: query.to_string(),
2983 ..Default::default()
2984 })
2985 .log_err()
2986 .map(move |response| {
2987 (
2988 lsp_adapter,
2989 worktree_id,
2990 worktree_abs_path,
2991 response.unwrap_or_default(),
2992 )
2993 }),
2994 );
2995 }
2996 }
2997
2998 cx.spawn_weak(|this, cx| async move {
2999 let responses = futures::future::join_all(requests).await;
3000 let this = if let Some(this) = this.upgrade(&cx) {
3001 this
3002 } else {
3003 return Ok(Default::default());
3004 };
3005 this.read_with(&cx, |this, cx| {
3006 let mut symbols = Vec::new();
3007 for (adapter, source_worktree_id, worktree_abs_path, response) in responses {
3008 symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3009 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3010 let mut worktree_id = source_worktree_id;
3011 let path;
3012 if let Some((worktree, rel_path)) =
3013 this.find_local_worktree(&abs_path, cx)
3014 {
3015 worktree_id = worktree.read(cx).id();
3016 path = rel_path;
3017 } else {
3018 path = relativize_path(&worktree_abs_path, &abs_path);
3019 }
3020
3021 let label = this
3022 .languages
3023 .select_language(&path)
3024 .and_then(|language| {
3025 language.label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3026 })
3027 .unwrap_or_else(|| CodeLabel::plain(lsp_symbol.name.clone(), None));
3028 let signature = this.symbol_signature(worktree_id, &path);
3029
3030 Some(Symbol {
3031 source_worktree_id,
3032 worktree_id,
3033 language_server_name: adapter.name(),
3034 name: lsp_symbol.name,
3035 kind: lsp_symbol.kind,
3036 label,
3037 path,
3038 range: range_from_lsp(lsp_symbol.location.range),
3039 signature,
3040 })
3041 }));
3042 }
3043 Ok(symbols)
3044 })
3045 })
3046 } else if let Some(project_id) = self.remote_id() {
3047 let request = self.client.request(proto::GetProjectSymbols {
3048 project_id,
3049 query: query.to_string(),
3050 });
3051 cx.spawn_weak(|this, cx| async move {
3052 let response = request.await?;
3053 let mut symbols = Vec::new();
3054 if let Some(this) = this.upgrade(&cx) {
3055 this.read_with(&cx, |this, _| {
3056 symbols.extend(
3057 response
3058 .symbols
3059 .into_iter()
3060 .filter_map(|symbol| this.deserialize_symbol(symbol).log_err()),
3061 );
3062 })
3063 }
3064 Ok(symbols)
3065 })
3066 } else {
3067 Task::ready(Ok(Default::default()))
3068 }
3069 }
3070
3071 pub fn open_buffer_for_symbol(
3072 &mut self,
3073 symbol: &Symbol,
3074 cx: &mut ModelContext<Self>,
3075 ) -> Task<Result<ModelHandle<Buffer>>> {
3076 if self.is_local() {
3077 let (lsp_adapter, language_server) = if let Some(server) = self.language_servers.get(&(
3078 symbol.source_worktree_id,
3079 symbol.language_server_name.clone(),
3080 )) {
3081 server.clone()
3082 } else {
3083 return Task::ready(Err(anyhow!(
3084 "language server for worktree and language not found"
3085 )));
3086 };
3087
3088 let worktree_abs_path = if let Some(worktree_abs_path) = self
3089 .worktree_for_id(symbol.worktree_id, cx)
3090 .and_then(|worktree| worktree.read(cx).as_local())
3091 .map(|local_worktree| local_worktree.abs_path())
3092 {
3093 worktree_abs_path
3094 } else {
3095 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3096 };
3097 let symbol_abs_path = worktree_abs_path.join(&symbol.path);
3098 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3099 uri
3100 } else {
3101 return Task::ready(Err(anyhow!("invalid symbol path")));
3102 };
3103
3104 self.open_local_buffer_via_lsp(symbol_uri, lsp_adapter, language_server, cx)
3105 } else if let Some(project_id) = self.remote_id() {
3106 let request = self.client.request(proto::OpenBufferForSymbol {
3107 project_id,
3108 symbol: Some(serialize_symbol(symbol)),
3109 });
3110 cx.spawn(|this, mut cx| async move {
3111 let response = request.await?;
3112 let buffer = response.buffer.ok_or_else(|| anyhow!("invalid buffer"))?;
3113 this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3114 .await
3115 })
3116 } else {
3117 Task::ready(Err(anyhow!("project does not have a remote id")))
3118 }
3119 }
3120
3121 pub fn hover<T: ToPointUtf16>(
3122 &self,
3123 buffer: &ModelHandle<Buffer>,
3124 position: T,
3125 cx: &mut ModelContext<Self>,
3126 ) -> Task<Result<Option<Hover>>> {
3127 let position = position.to_point_utf16(buffer.read(cx));
3128 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3129 }
3130
3131 pub fn completions<T: ToPointUtf16>(
3132 &self,
3133 source_buffer_handle: &ModelHandle<Buffer>,
3134 position: T,
3135 cx: &mut ModelContext<Self>,
3136 ) -> Task<Result<Vec<Completion>>> {
3137 let source_buffer_handle = source_buffer_handle.clone();
3138 let source_buffer = source_buffer_handle.read(cx);
3139 let buffer_id = source_buffer.remote_id();
3140 let language = source_buffer.language().cloned();
3141 let worktree;
3142 let buffer_abs_path;
3143 if let Some(file) = File::from_dyn(source_buffer.file()) {
3144 worktree = file.worktree.clone();
3145 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3146 } else {
3147 return Task::ready(Ok(Default::default()));
3148 };
3149
3150 let position = position.to_point_utf16(source_buffer);
3151 let anchor = source_buffer.anchor_after(position);
3152
3153 if worktree.read(cx).as_local().is_some() {
3154 let buffer_abs_path = buffer_abs_path.unwrap();
3155 let (_, lang_server) =
3156 if let Some(server) = self.language_server_for_buffer(source_buffer, cx) {
3157 server.clone()
3158 } else {
3159 return Task::ready(Ok(Default::default()));
3160 };
3161
3162 cx.spawn(|_, cx| async move {
3163 let completions = lang_server
3164 .request::<lsp::request::Completion>(lsp::CompletionParams {
3165 text_document_position: lsp::TextDocumentPositionParams::new(
3166 lsp::TextDocumentIdentifier::new(
3167 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3168 ),
3169 point_to_lsp(position),
3170 ),
3171 context: Default::default(),
3172 work_done_progress_params: Default::default(),
3173 partial_result_params: Default::default(),
3174 })
3175 .await
3176 .context("lsp completion request failed")?;
3177
3178 let completions = if let Some(completions) = completions {
3179 match completions {
3180 lsp::CompletionResponse::Array(completions) => completions,
3181 lsp::CompletionResponse::List(list) => list.items,
3182 }
3183 } else {
3184 Default::default()
3185 };
3186
3187 source_buffer_handle.read_with(&cx, |this, _| {
3188 let snapshot = this.snapshot();
3189 let clipped_position = this.clip_point_utf16(position, Bias::Left);
3190 let mut range_for_token = None;
3191 Ok(completions
3192 .into_iter()
3193 .filter_map(|lsp_completion| {
3194 // For now, we can only handle additional edits if they are returned
3195 // when resolving the completion, not if they are present initially.
3196 if lsp_completion
3197 .additional_text_edits
3198 .as_ref()
3199 .map_or(false, |edits| !edits.is_empty())
3200 {
3201 return None;
3202 }
3203
3204 let (old_range, new_text) = match lsp_completion.text_edit.as_ref() {
3205 // If the language server provides a range to overwrite, then
3206 // check that the range is valid.
3207 Some(lsp::CompletionTextEdit::Edit(edit)) => {
3208 let range = range_from_lsp(edit.range);
3209 let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3210 let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3211 if start != range.start || end != range.end {
3212 log::info!("completion out of expected range");
3213 return None;
3214 }
3215 (
3216 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3217 edit.new_text.clone(),
3218 )
3219 }
3220 // If the language server does not provide a range, then infer
3221 // the range based on the syntax tree.
3222 None => {
3223 if position != clipped_position {
3224 log::info!("completion out of expected range");
3225 return None;
3226 }
3227 let Range { start, end } = range_for_token
3228 .get_or_insert_with(|| {
3229 let offset = position.to_offset(&snapshot);
3230 let (range, kind) = snapshot.surrounding_word(offset);
3231 if kind == Some(CharKind::Word) {
3232 range
3233 } else {
3234 offset..offset
3235 }
3236 })
3237 .clone();
3238 let text = lsp_completion
3239 .insert_text
3240 .as_ref()
3241 .unwrap_or(&lsp_completion.label)
3242 .clone();
3243 (
3244 snapshot.anchor_before(start)..snapshot.anchor_after(end),
3245 text.clone(),
3246 )
3247 }
3248 Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3249 log::info!("unsupported insert/replace completion");
3250 return None;
3251 }
3252 };
3253
3254 Some(Completion {
3255 old_range,
3256 new_text,
3257 label: language
3258 .as_ref()
3259 .and_then(|l| l.label_for_completion(&lsp_completion))
3260 .unwrap_or_else(|| {
3261 CodeLabel::plain(
3262 lsp_completion.label.clone(),
3263 lsp_completion.filter_text.as_deref(),
3264 )
3265 }),
3266 lsp_completion,
3267 })
3268 })
3269 .collect())
3270 })
3271 })
3272 } else if let Some(project_id) = self.remote_id() {
3273 let rpc = self.client.clone();
3274 let message = proto::GetCompletions {
3275 project_id,
3276 buffer_id,
3277 position: Some(language::proto::serialize_anchor(&anchor)),
3278 version: serialize_version(&source_buffer.version()),
3279 };
3280 cx.spawn_weak(|_, mut cx| async move {
3281 let response = rpc.request(message).await?;
3282
3283 source_buffer_handle
3284 .update(&mut cx, |buffer, _| {
3285 buffer.wait_for_version(deserialize_version(response.version))
3286 })
3287 .await;
3288
3289 response
3290 .completions
3291 .into_iter()
3292 .map(|completion| {
3293 language::proto::deserialize_completion(completion, language.as_ref())
3294 })
3295 .collect()
3296 })
3297 } else {
3298 Task::ready(Ok(Default::default()))
3299 }
3300 }
3301
3302 pub fn apply_additional_edits_for_completion(
3303 &self,
3304 buffer_handle: ModelHandle<Buffer>,
3305 completion: Completion,
3306 push_to_history: bool,
3307 cx: &mut ModelContext<Self>,
3308 ) -> Task<Result<Option<Transaction>>> {
3309 let buffer = buffer_handle.read(cx);
3310 let buffer_id = buffer.remote_id();
3311
3312 if self.is_local() {
3313 let (_, lang_server) = if let Some(server) = self.language_server_for_buffer(buffer, cx)
3314 {
3315 server.clone()
3316 } else {
3317 return Task::ready(Ok(Default::default()));
3318 };
3319
3320 cx.spawn(|this, mut cx| async move {
3321 let resolved_completion = lang_server
3322 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3323 .await?;
3324 if let Some(edits) = resolved_completion.additional_text_edits {
3325 let edits = this
3326 .update(&mut cx, |this, cx| {
3327 this.edits_from_lsp(&buffer_handle, edits, None, cx)
3328 })
3329 .await?;
3330 buffer_handle.update(&mut cx, |buffer, cx| {
3331 buffer.finalize_last_transaction();
3332 buffer.start_transaction();
3333 for (range, text) in edits {
3334 buffer.edit([(range, text)], cx);
3335 }
3336 let transaction = if buffer.end_transaction(cx).is_some() {
3337 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3338 if !push_to_history {
3339 buffer.forget_transaction(transaction.id);
3340 }
3341 Some(transaction)
3342 } else {
3343 None
3344 };
3345 Ok(transaction)
3346 })
3347 } else {
3348 Ok(None)
3349 }
3350 })
3351 } else if let Some(project_id) = self.remote_id() {
3352 let client = self.client.clone();
3353 cx.spawn(|_, mut cx| async move {
3354 let response = client
3355 .request(proto::ApplyCompletionAdditionalEdits {
3356 project_id,
3357 buffer_id,
3358 completion: Some(language::proto::serialize_completion(&completion)),
3359 })
3360 .await?;
3361
3362 if let Some(transaction) = response.transaction {
3363 let transaction = language::proto::deserialize_transaction(transaction)?;
3364 buffer_handle
3365 .update(&mut cx, |buffer, _| {
3366 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3367 })
3368 .await;
3369 if push_to_history {
3370 buffer_handle.update(&mut cx, |buffer, _| {
3371 buffer.push_transaction(transaction.clone(), Instant::now());
3372 });
3373 }
3374 Ok(Some(transaction))
3375 } else {
3376 Ok(None)
3377 }
3378 })
3379 } else {
3380 Task::ready(Err(anyhow!("project does not have a remote id")))
3381 }
3382 }
3383
3384 pub fn code_actions<T: Clone + ToOffset>(
3385 &self,
3386 buffer_handle: &ModelHandle<Buffer>,
3387 range: Range<T>,
3388 cx: &mut ModelContext<Self>,
3389 ) -> Task<Result<Vec<CodeAction>>> {
3390 let buffer_handle = buffer_handle.clone();
3391 let buffer = buffer_handle.read(cx);
3392 let snapshot = buffer.snapshot();
3393 let relevant_diagnostics = snapshot
3394 .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3395 .map(|entry| entry.to_lsp_diagnostic_stub())
3396 .collect();
3397 let buffer_id = buffer.remote_id();
3398 let worktree;
3399 let buffer_abs_path;
3400 if let Some(file) = File::from_dyn(buffer.file()) {
3401 worktree = file.worktree.clone();
3402 buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3403 } else {
3404 return Task::ready(Ok(Default::default()));
3405 };
3406 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3407
3408 if worktree.read(cx).as_local().is_some() {
3409 let buffer_abs_path = buffer_abs_path.unwrap();
3410 let (_, lang_server) = if let Some(server) = self.language_server_for_buffer(buffer, cx)
3411 {
3412 server.clone()
3413 } else {
3414 return Task::ready(Ok(Default::default()));
3415 };
3416
3417 let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3418 cx.foreground().spawn(async move {
3419 if !lang_server.capabilities().code_action_provider.is_some() {
3420 return Ok(Default::default());
3421 }
3422
3423 Ok(lang_server
3424 .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3425 text_document: lsp::TextDocumentIdentifier::new(
3426 lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3427 ),
3428 range: lsp_range,
3429 work_done_progress_params: Default::default(),
3430 partial_result_params: Default::default(),
3431 context: lsp::CodeActionContext {
3432 diagnostics: relevant_diagnostics,
3433 only: Some(vec![
3434 lsp::CodeActionKind::QUICKFIX,
3435 lsp::CodeActionKind::REFACTOR,
3436 lsp::CodeActionKind::REFACTOR_EXTRACT,
3437 lsp::CodeActionKind::SOURCE,
3438 ]),
3439 },
3440 })
3441 .await?
3442 .unwrap_or_default()
3443 .into_iter()
3444 .filter_map(|entry| {
3445 if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3446 Some(CodeAction {
3447 range: range.clone(),
3448 lsp_action,
3449 })
3450 } else {
3451 None
3452 }
3453 })
3454 .collect())
3455 })
3456 } else if let Some(project_id) = self.remote_id() {
3457 let rpc = self.client.clone();
3458 let version = buffer.version();
3459 cx.spawn_weak(|_, mut cx| async move {
3460 let response = rpc
3461 .request(proto::GetCodeActions {
3462 project_id,
3463 buffer_id,
3464 start: Some(language::proto::serialize_anchor(&range.start)),
3465 end: Some(language::proto::serialize_anchor(&range.end)),
3466 version: serialize_version(&version),
3467 })
3468 .await?;
3469
3470 buffer_handle
3471 .update(&mut cx, |buffer, _| {
3472 buffer.wait_for_version(deserialize_version(response.version))
3473 })
3474 .await;
3475
3476 response
3477 .actions
3478 .into_iter()
3479 .map(language::proto::deserialize_code_action)
3480 .collect()
3481 })
3482 } else {
3483 Task::ready(Ok(Default::default()))
3484 }
3485 }
3486
3487 pub fn apply_code_action(
3488 &self,
3489 buffer_handle: ModelHandle<Buffer>,
3490 mut action: CodeAction,
3491 push_to_history: bool,
3492 cx: &mut ModelContext<Self>,
3493 ) -> Task<Result<ProjectTransaction>> {
3494 if self.is_local() {
3495 let buffer = buffer_handle.read(cx);
3496 let (lsp_adapter, lang_server) =
3497 if let Some(server) = self.language_server_for_buffer(buffer, cx) {
3498 server.clone()
3499 } else {
3500 return Task::ready(Ok(Default::default()));
3501 };
3502 let range = action.range.to_point_utf16(buffer);
3503
3504 cx.spawn(|this, mut cx| async move {
3505 if let Some(lsp_range) = action
3506 .lsp_action
3507 .data
3508 .as_mut()
3509 .and_then(|d| d.get_mut("codeActionParams"))
3510 .and_then(|d| d.get_mut("range"))
3511 {
3512 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3513 action.lsp_action = lang_server
3514 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3515 .await?;
3516 } else {
3517 let actions = this
3518 .update(&mut cx, |this, cx| {
3519 this.code_actions(&buffer_handle, action.range, cx)
3520 })
3521 .await?;
3522 action.lsp_action = actions
3523 .into_iter()
3524 .find(|a| a.lsp_action.title == action.lsp_action.title)
3525 .ok_or_else(|| anyhow!("code action is outdated"))?
3526 .lsp_action;
3527 }
3528
3529 if let Some(edit) = action.lsp_action.edit {
3530 Self::deserialize_workspace_edit(
3531 this,
3532 edit,
3533 push_to_history,
3534 lsp_adapter,
3535 lang_server,
3536 &mut cx,
3537 )
3538 .await
3539 } else if let Some(command) = action.lsp_action.command {
3540 this.update(&mut cx, |this, _| {
3541 this.last_workspace_edits_by_language_server
3542 .remove(&lang_server.server_id());
3543 });
3544 lang_server
3545 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3546 command: command.command,
3547 arguments: command.arguments.unwrap_or_default(),
3548 ..Default::default()
3549 })
3550 .await?;
3551 Ok(this.update(&mut cx, |this, _| {
3552 this.last_workspace_edits_by_language_server
3553 .remove(&lang_server.server_id())
3554 .unwrap_or_default()
3555 }))
3556 } else {
3557 Ok(ProjectTransaction::default())
3558 }
3559 })
3560 } else if let Some(project_id) = self.remote_id() {
3561 let client = self.client.clone();
3562 let request = proto::ApplyCodeAction {
3563 project_id,
3564 buffer_id: buffer_handle.read(cx).remote_id(),
3565 action: Some(language::proto::serialize_code_action(&action)),
3566 };
3567 cx.spawn(|this, mut cx| async move {
3568 let response = client
3569 .request(request)
3570 .await?
3571 .transaction
3572 .ok_or_else(|| anyhow!("missing transaction"))?;
3573 this.update(&mut cx, |this, cx| {
3574 this.deserialize_project_transaction(response, push_to_history, cx)
3575 })
3576 .await
3577 })
3578 } else {
3579 Task::ready(Err(anyhow!("project does not have a remote id")))
3580 }
3581 }
3582
3583 async fn deserialize_workspace_edit(
3584 this: ModelHandle<Self>,
3585 edit: lsp::WorkspaceEdit,
3586 push_to_history: bool,
3587 lsp_adapter: Arc<dyn LspAdapter>,
3588 language_server: Arc<LanguageServer>,
3589 cx: &mut AsyncAppContext,
3590 ) -> Result<ProjectTransaction> {
3591 let fs = this.read_with(cx, |this, _| this.fs.clone());
3592 let mut operations = Vec::new();
3593 if let Some(document_changes) = edit.document_changes {
3594 match document_changes {
3595 lsp::DocumentChanges::Edits(edits) => {
3596 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3597 }
3598 lsp::DocumentChanges::Operations(ops) => operations = ops,
3599 }
3600 } else if let Some(changes) = edit.changes {
3601 operations.extend(changes.into_iter().map(|(uri, edits)| {
3602 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3603 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3604 uri,
3605 version: None,
3606 },
3607 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3608 })
3609 }));
3610 }
3611
3612 let mut project_transaction = ProjectTransaction::default();
3613 for operation in operations {
3614 match operation {
3615 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3616 let abs_path = op
3617 .uri
3618 .to_file_path()
3619 .map_err(|_| anyhow!("can't convert URI to path"))?;
3620
3621 if let Some(parent_path) = abs_path.parent() {
3622 fs.create_dir(parent_path).await?;
3623 }
3624 if abs_path.ends_with("/") {
3625 fs.create_dir(&abs_path).await?;
3626 } else {
3627 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3628 .await?;
3629 }
3630 }
3631 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3632 let source_abs_path = op
3633 .old_uri
3634 .to_file_path()
3635 .map_err(|_| anyhow!("can't convert URI to path"))?;
3636 let target_abs_path = op
3637 .new_uri
3638 .to_file_path()
3639 .map_err(|_| anyhow!("can't convert URI to path"))?;
3640 fs.rename(
3641 &source_abs_path,
3642 &target_abs_path,
3643 op.options.map(Into::into).unwrap_or_default(),
3644 )
3645 .await?;
3646 }
3647 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3648 let abs_path = op
3649 .uri
3650 .to_file_path()
3651 .map_err(|_| anyhow!("can't convert URI to path"))?;
3652 let options = op.options.map(Into::into).unwrap_or_default();
3653 if abs_path.ends_with("/") {
3654 fs.remove_dir(&abs_path, options).await?;
3655 } else {
3656 fs.remove_file(&abs_path, options).await?;
3657 }
3658 }
3659 lsp::DocumentChangeOperation::Edit(op) => {
3660 let buffer_to_edit = this
3661 .update(cx, |this, cx| {
3662 this.open_local_buffer_via_lsp(
3663 op.text_document.uri,
3664 lsp_adapter.clone(),
3665 language_server.clone(),
3666 cx,
3667 )
3668 })
3669 .await?;
3670
3671 let edits = this
3672 .update(cx, |this, cx| {
3673 let edits = op.edits.into_iter().map(|edit| match edit {
3674 lsp::OneOf::Left(edit) => edit,
3675 lsp::OneOf::Right(edit) => edit.text_edit,
3676 });
3677 this.edits_from_lsp(
3678 &buffer_to_edit,
3679 edits,
3680 op.text_document.version,
3681 cx,
3682 )
3683 })
3684 .await?;
3685
3686 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3687 buffer.finalize_last_transaction();
3688 buffer.start_transaction();
3689 for (range, text) in edits {
3690 buffer.edit([(range, text)], cx);
3691 }
3692 let transaction = if buffer.end_transaction(cx).is_some() {
3693 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3694 if !push_to_history {
3695 buffer.forget_transaction(transaction.id);
3696 }
3697 Some(transaction)
3698 } else {
3699 None
3700 };
3701
3702 transaction
3703 });
3704 if let Some(transaction) = transaction {
3705 project_transaction.0.insert(buffer_to_edit, transaction);
3706 }
3707 }
3708 }
3709 }
3710
3711 Ok(project_transaction)
3712 }
3713
3714 pub fn prepare_rename<T: ToPointUtf16>(
3715 &self,
3716 buffer: ModelHandle<Buffer>,
3717 position: T,
3718 cx: &mut ModelContext<Self>,
3719 ) -> Task<Result<Option<Range<Anchor>>>> {
3720 let position = position.to_point_utf16(buffer.read(cx));
3721 self.request_lsp(buffer, PrepareRename { position }, cx)
3722 }
3723
3724 pub fn perform_rename<T: ToPointUtf16>(
3725 &self,
3726 buffer: ModelHandle<Buffer>,
3727 position: T,
3728 new_name: String,
3729 push_to_history: bool,
3730 cx: &mut ModelContext<Self>,
3731 ) -> Task<Result<ProjectTransaction>> {
3732 let position = position.to_point_utf16(buffer.read(cx));
3733 self.request_lsp(
3734 buffer,
3735 PerformRename {
3736 position,
3737 new_name,
3738 push_to_history,
3739 },
3740 cx,
3741 )
3742 }
3743
3744 pub fn search(
3745 &self,
3746 query: SearchQuery,
3747 cx: &mut ModelContext<Self>,
3748 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
3749 if self.is_local() {
3750 let snapshots = self
3751 .visible_worktrees(cx)
3752 .filter_map(|tree| {
3753 let tree = tree.read(cx).as_local()?;
3754 Some(tree.snapshot())
3755 })
3756 .collect::<Vec<_>>();
3757
3758 let background = cx.background().clone();
3759 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
3760 if path_count == 0 {
3761 return Task::ready(Ok(Default::default()));
3762 }
3763 let workers = background.num_cpus().min(path_count);
3764 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
3765 cx.background()
3766 .spawn({
3767 let fs = self.fs.clone();
3768 let background = cx.background().clone();
3769 let query = query.clone();
3770 async move {
3771 let fs = &fs;
3772 let query = &query;
3773 let matching_paths_tx = &matching_paths_tx;
3774 let paths_per_worker = (path_count + workers - 1) / workers;
3775 let snapshots = &snapshots;
3776 background
3777 .scoped(|scope| {
3778 for worker_ix in 0..workers {
3779 let worker_start_ix = worker_ix * paths_per_worker;
3780 let worker_end_ix = worker_start_ix + paths_per_worker;
3781 scope.spawn(async move {
3782 let mut snapshot_start_ix = 0;
3783 let mut abs_path = PathBuf::new();
3784 for snapshot in snapshots {
3785 let snapshot_end_ix =
3786 snapshot_start_ix + snapshot.visible_file_count();
3787 if worker_end_ix <= snapshot_start_ix {
3788 break;
3789 } else if worker_start_ix > snapshot_end_ix {
3790 snapshot_start_ix = snapshot_end_ix;
3791 continue;
3792 } else {
3793 let start_in_snapshot = worker_start_ix
3794 .saturating_sub(snapshot_start_ix);
3795 let end_in_snapshot =
3796 cmp::min(worker_end_ix, snapshot_end_ix)
3797 - snapshot_start_ix;
3798
3799 for entry in snapshot
3800 .files(false, start_in_snapshot)
3801 .take(end_in_snapshot - start_in_snapshot)
3802 {
3803 if matching_paths_tx.is_closed() {
3804 break;
3805 }
3806
3807 abs_path.clear();
3808 abs_path.push(&snapshot.abs_path());
3809 abs_path.push(&entry.path);
3810 let matches = if let Some(file) =
3811 fs.open_sync(&abs_path).await.log_err()
3812 {
3813 query.detect(file).unwrap_or(false)
3814 } else {
3815 false
3816 };
3817
3818 if matches {
3819 let project_path =
3820 (snapshot.id(), entry.path.clone());
3821 if matching_paths_tx
3822 .send(project_path)
3823 .await
3824 .is_err()
3825 {
3826 break;
3827 }
3828 }
3829 }
3830
3831 snapshot_start_ix = snapshot_end_ix;
3832 }
3833 }
3834 });
3835 }
3836 })
3837 .await;
3838 }
3839 })
3840 .detach();
3841
3842 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
3843 let open_buffers = self
3844 .opened_buffers
3845 .values()
3846 .filter_map(|b| b.upgrade(cx))
3847 .collect::<HashSet<_>>();
3848 cx.spawn(|this, cx| async move {
3849 for buffer in &open_buffers {
3850 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3851 buffers_tx.send((buffer.clone(), snapshot)).await?;
3852 }
3853
3854 let open_buffers = Rc::new(RefCell::new(open_buffers));
3855 while let Some(project_path) = matching_paths_rx.next().await {
3856 if buffers_tx.is_closed() {
3857 break;
3858 }
3859
3860 let this = this.clone();
3861 let open_buffers = open_buffers.clone();
3862 let buffers_tx = buffers_tx.clone();
3863 cx.spawn(|mut cx| async move {
3864 if let Some(buffer) = this
3865 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
3866 .await
3867 .log_err()
3868 {
3869 if open_buffers.borrow_mut().insert(buffer.clone()) {
3870 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3871 buffers_tx.send((buffer, snapshot)).await?;
3872 }
3873 }
3874
3875 Ok::<_, anyhow::Error>(())
3876 })
3877 .detach();
3878 }
3879
3880 Ok::<_, anyhow::Error>(())
3881 })
3882 .detach_and_log_err(cx);
3883
3884 let background = cx.background().clone();
3885 cx.background().spawn(async move {
3886 let query = &query;
3887 let mut matched_buffers = Vec::new();
3888 for _ in 0..workers {
3889 matched_buffers.push(HashMap::default());
3890 }
3891 background
3892 .scoped(|scope| {
3893 for worker_matched_buffers in matched_buffers.iter_mut() {
3894 let mut buffers_rx = buffers_rx.clone();
3895 scope.spawn(async move {
3896 while let Some((buffer, snapshot)) = buffers_rx.next().await {
3897 let buffer_matches = query
3898 .search(snapshot.as_rope())
3899 .await
3900 .iter()
3901 .map(|range| {
3902 snapshot.anchor_before(range.start)
3903 ..snapshot.anchor_after(range.end)
3904 })
3905 .collect::<Vec<_>>();
3906 if !buffer_matches.is_empty() {
3907 worker_matched_buffers
3908 .insert(buffer.clone(), buffer_matches);
3909 }
3910 }
3911 });
3912 }
3913 })
3914 .await;
3915 Ok(matched_buffers.into_iter().flatten().collect())
3916 })
3917 } else if let Some(project_id) = self.remote_id() {
3918 let request = self.client.request(query.to_proto(project_id));
3919 cx.spawn(|this, mut cx| async move {
3920 let response = request.await?;
3921 let mut result = HashMap::default();
3922 for location in response.locations {
3923 let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
3924 let target_buffer = this
3925 .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3926 .await?;
3927 let start = location
3928 .start
3929 .and_then(deserialize_anchor)
3930 .ok_or_else(|| anyhow!("missing target start"))?;
3931 let end = location
3932 .end
3933 .and_then(deserialize_anchor)
3934 .ok_or_else(|| anyhow!("missing target end"))?;
3935 result
3936 .entry(target_buffer)
3937 .or_insert(Vec::new())
3938 .push(start..end)
3939 }
3940 Ok(result)
3941 })
3942 } else {
3943 Task::ready(Ok(Default::default()))
3944 }
3945 }
3946
3947 fn request_lsp<R: LspCommand>(
3948 &self,
3949 buffer_handle: ModelHandle<Buffer>,
3950 request: R,
3951 cx: &mut ModelContext<Self>,
3952 ) -> Task<Result<R::Response>>
3953 where
3954 <R::LspRequest as lsp::request::Request>::Result: Send,
3955 {
3956 let buffer = buffer_handle.read(cx);
3957 if self.is_local() {
3958 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
3959 if let Some((file, (_, language_server))) =
3960 file.zip(self.language_server_for_buffer(buffer, cx).cloned())
3961 {
3962 let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
3963 return cx.spawn(|this, cx| async move {
3964 if !request.check_capabilities(&language_server.capabilities()) {
3965 return Ok(Default::default());
3966 }
3967
3968 let response = language_server
3969 .request::<R::LspRequest>(lsp_params)
3970 .await
3971 .context("lsp request failed")?;
3972 request
3973 .response_from_lsp(response, this, buffer_handle, cx)
3974 .await
3975 });
3976 }
3977 } else if let Some(project_id) = self.remote_id() {
3978 let rpc = self.client.clone();
3979 let message = request.to_proto(project_id, buffer);
3980 return cx.spawn(|this, cx| async move {
3981 let response = rpc.request(message).await?;
3982 request
3983 .response_from_proto(response, this, buffer_handle, cx)
3984 .await
3985 });
3986 }
3987 Task::ready(Ok(Default::default()))
3988 }
3989
3990 pub fn find_or_create_local_worktree(
3991 &mut self,
3992 abs_path: impl AsRef<Path>,
3993 visible: bool,
3994 cx: &mut ModelContext<Self>,
3995 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
3996 let abs_path = abs_path.as_ref();
3997 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
3998 Task::ready(Ok((tree.clone(), relative_path.into())))
3999 } else {
4000 let worktree = self.create_local_worktree(abs_path, visible, cx);
4001 cx.foreground()
4002 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4003 }
4004 }
4005
4006 pub fn find_local_worktree(
4007 &self,
4008 abs_path: &Path,
4009 cx: &AppContext,
4010 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4011 for tree in &self.worktrees {
4012 if let Some(tree) = tree.upgrade(cx) {
4013 if let Some(relative_path) = tree
4014 .read(cx)
4015 .as_local()
4016 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4017 {
4018 return Some((tree.clone(), relative_path.into()));
4019 }
4020 }
4021 }
4022 None
4023 }
4024
4025 pub fn is_shared(&self) -> bool {
4026 match &self.client_state {
4027 ProjectClientState::Local { is_shared, .. } => *is_shared,
4028 ProjectClientState::Remote { .. } => false,
4029 }
4030 }
4031
4032 fn create_local_worktree(
4033 &mut self,
4034 abs_path: impl AsRef<Path>,
4035 visible: bool,
4036 cx: &mut ModelContext<Self>,
4037 ) -> Task<Result<ModelHandle<Worktree>>> {
4038 let fs = self.fs.clone();
4039 let client = self.client.clone();
4040 let next_entry_id = self.next_entry_id.clone();
4041 let path: Arc<Path> = abs_path.as_ref().into();
4042 let task = self
4043 .loading_local_worktrees
4044 .entry(path.clone())
4045 .or_insert_with(|| {
4046 cx.spawn(|project, mut cx| {
4047 async move {
4048 let worktree = Worktree::local(
4049 client.clone(),
4050 path.clone(),
4051 visible,
4052 fs,
4053 next_entry_id,
4054 &mut cx,
4055 )
4056 .await;
4057 project.update(&mut cx, |project, _| {
4058 project.loading_local_worktrees.remove(&path);
4059 });
4060 let worktree = worktree?;
4061
4062 let project_id = project.update(&mut cx, |project, cx| {
4063 project.add_worktree(&worktree, cx);
4064 project.shared_remote_id()
4065 });
4066
4067 if let Some(project_id) = project_id {
4068 worktree
4069 .update(&mut cx, |worktree, cx| {
4070 worktree.as_local_mut().unwrap().share(project_id, cx)
4071 })
4072 .await
4073 .log_err();
4074 }
4075
4076 Ok(worktree)
4077 }
4078 .map_err(|err| Arc::new(err))
4079 })
4080 .shared()
4081 })
4082 .clone();
4083 cx.foreground().spawn(async move {
4084 match task.await {
4085 Ok(worktree) => Ok(worktree),
4086 Err(err) => Err(anyhow!("{}", err)),
4087 }
4088 })
4089 }
4090
4091 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4092 self.worktrees.retain(|worktree| {
4093 if let Some(worktree) = worktree.upgrade(cx) {
4094 let id = worktree.read(cx).id();
4095 if id == id_to_remove {
4096 cx.emit(Event::WorktreeRemoved(id));
4097 false
4098 } else {
4099 true
4100 }
4101 } else {
4102 false
4103 }
4104 });
4105 self.metadata_changed(true, cx);
4106 cx.notify();
4107 }
4108
4109 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4110 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
4111 if worktree.read(cx).is_local() {
4112 cx.subscribe(&worktree, |this, worktree, _, cx| {
4113 this.update_local_worktree_buffers(worktree, cx);
4114 })
4115 .detach();
4116 }
4117
4118 let push_strong_handle = {
4119 let worktree = worktree.read(cx);
4120 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4121 };
4122 if push_strong_handle {
4123 self.worktrees
4124 .push(WorktreeHandle::Strong(worktree.clone()));
4125 } else {
4126 self.worktrees
4127 .push(WorktreeHandle::Weak(worktree.downgrade()));
4128 }
4129
4130 self.metadata_changed(true, cx);
4131 cx.observe_release(&worktree, |this, worktree, cx| {
4132 this.remove_worktree(worktree.id(), cx);
4133 cx.notify();
4134 })
4135 .detach();
4136
4137 cx.emit(Event::WorktreeAdded);
4138 cx.notify();
4139 }
4140
4141 fn update_local_worktree_buffers(
4142 &mut self,
4143 worktree_handle: ModelHandle<Worktree>,
4144 cx: &mut ModelContext<Self>,
4145 ) {
4146 let snapshot = worktree_handle.read(cx).snapshot();
4147 let mut buffers_to_delete = Vec::new();
4148 let mut renamed_buffers = Vec::new();
4149 for (buffer_id, buffer) in &self.opened_buffers {
4150 if let Some(buffer) = buffer.upgrade(cx) {
4151 buffer.update(cx, |buffer, cx| {
4152 if let Some(old_file) = File::from_dyn(buffer.file()) {
4153 if old_file.worktree != worktree_handle {
4154 return;
4155 }
4156
4157 let new_file = if let Some(entry) = old_file
4158 .entry_id
4159 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
4160 {
4161 File {
4162 is_local: true,
4163 entry_id: Some(entry.id),
4164 mtime: entry.mtime,
4165 path: entry.path.clone(),
4166 worktree: worktree_handle.clone(),
4167 }
4168 } else if let Some(entry) =
4169 snapshot.entry_for_path(old_file.path().as_ref())
4170 {
4171 File {
4172 is_local: true,
4173 entry_id: Some(entry.id),
4174 mtime: entry.mtime,
4175 path: entry.path.clone(),
4176 worktree: worktree_handle.clone(),
4177 }
4178 } else {
4179 File {
4180 is_local: true,
4181 entry_id: None,
4182 path: old_file.path().clone(),
4183 mtime: old_file.mtime(),
4184 worktree: worktree_handle.clone(),
4185 }
4186 };
4187
4188 let old_path = old_file.abs_path(cx);
4189 if new_file.abs_path(cx) != old_path {
4190 renamed_buffers.push((cx.handle(), old_path));
4191 }
4192
4193 if let Some(project_id) = self.shared_remote_id() {
4194 self.client
4195 .send(proto::UpdateBufferFile {
4196 project_id,
4197 buffer_id: *buffer_id as u64,
4198 file: Some(new_file.to_proto()),
4199 })
4200 .log_err();
4201 }
4202 buffer.file_updated(Arc::new(new_file), cx).detach();
4203 }
4204 });
4205 } else {
4206 buffers_to_delete.push(*buffer_id);
4207 }
4208 }
4209
4210 for buffer_id in buffers_to_delete {
4211 self.opened_buffers.remove(&buffer_id);
4212 }
4213
4214 for (buffer, old_path) in renamed_buffers {
4215 self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4216 self.assign_language_to_buffer(&buffer, cx);
4217 self.register_buffer_with_language_server(&buffer, cx);
4218 }
4219 }
4220
4221 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4222 let new_active_entry = entry.and_then(|project_path| {
4223 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4224 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4225 Some(entry.id)
4226 });
4227 if new_active_entry != self.active_entry {
4228 self.active_entry = new_active_entry;
4229 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4230 }
4231 }
4232
4233 pub fn language_servers_running_disk_based_diagnostics<'a>(
4234 &'a self,
4235 ) -> impl 'a + Iterator<Item = usize> {
4236 self.language_server_statuses
4237 .iter()
4238 .filter_map(|(id, status)| {
4239 if status.has_pending_diagnostic_updates {
4240 Some(*id)
4241 } else {
4242 None
4243 }
4244 })
4245 }
4246
4247 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4248 let mut summary = DiagnosticSummary::default();
4249 for (_, path_summary) in self.diagnostic_summaries(cx) {
4250 summary.error_count += path_summary.error_count;
4251 summary.warning_count += path_summary.warning_count;
4252 }
4253 summary
4254 }
4255
4256 pub fn diagnostic_summaries<'a>(
4257 &'a self,
4258 cx: &'a AppContext,
4259 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4260 self.visible_worktrees(cx).flat_map(move |worktree| {
4261 let worktree = worktree.read(cx);
4262 let worktree_id = worktree.id();
4263 worktree
4264 .diagnostic_summaries()
4265 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4266 })
4267 }
4268
4269 pub fn disk_based_diagnostics_started(
4270 &mut self,
4271 language_server_id: usize,
4272 cx: &mut ModelContext<Self>,
4273 ) {
4274 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4275 }
4276
4277 pub fn disk_based_diagnostics_finished(
4278 &mut self,
4279 language_server_id: usize,
4280 cx: &mut ModelContext<Self>,
4281 ) {
4282 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4283 }
4284
4285 pub fn active_entry(&self) -> Option<ProjectEntryId> {
4286 self.active_entry
4287 }
4288
4289 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<ProjectEntryId> {
4290 self.worktree_for_id(path.worktree_id, cx)?
4291 .read(cx)
4292 .entry_for_path(&path.path)
4293 .map(|entry| entry.id)
4294 }
4295
4296 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4297 let worktree = self.worktree_for_entry(entry_id, cx)?;
4298 let worktree = worktree.read(cx);
4299 let worktree_id = worktree.id();
4300 let path = worktree.entry_for_id(entry_id)?.path.clone();
4301 Some(ProjectPath { worktree_id, path })
4302 }
4303
4304 // RPC message handlers
4305
4306 async fn handle_request_join_project(
4307 this: ModelHandle<Self>,
4308 message: TypedEnvelope<proto::RequestJoinProject>,
4309 _: Arc<Client>,
4310 mut cx: AsyncAppContext,
4311 ) -> Result<()> {
4312 let user_id = message.payload.requester_id;
4313 if this.read_with(&cx, |project, _| {
4314 project.collaborators.values().any(|c| c.user.id == user_id)
4315 }) {
4316 this.update(&mut cx, |this, cx| {
4317 this.respond_to_join_request(user_id, true, cx)
4318 });
4319 } else {
4320 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4321 let user = user_store
4322 .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
4323 .await?;
4324 this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
4325 }
4326 Ok(())
4327 }
4328
4329 async fn handle_unregister_project(
4330 this: ModelHandle<Self>,
4331 _: TypedEnvelope<proto::UnregisterProject>,
4332 _: Arc<Client>,
4333 mut cx: AsyncAppContext,
4334 ) -> Result<()> {
4335 this.update(&mut cx, |this, cx| this.removed_from_project(cx));
4336 Ok(())
4337 }
4338
4339 async fn handle_project_unshared(
4340 this: ModelHandle<Self>,
4341 _: TypedEnvelope<proto::ProjectUnshared>,
4342 _: Arc<Client>,
4343 mut cx: AsyncAppContext,
4344 ) -> Result<()> {
4345 this.update(&mut cx, |this, cx| this.unshared(cx));
4346 Ok(())
4347 }
4348
4349 async fn handle_add_collaborator(
4350 this: ModelHandle<Self>,
4351 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4352 _: Arc<Client>,
4353 mut cx: AsyncAppContext,
4354 ) -> Result<()> {
4355 let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4356 let collaborator = envelope
4357 .payload
4358 .collaborator
4359 .take()
4360 .ok_or_else(|| anyhow!("empty collaborator"))?;
4361
4362 let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
4363 this.update(&mut cx, |this, cx| {
4364 this.collaborators
4365 .insert(collaborator.peer_id, collaborator);
4366 cx.notify();
4367 });
4368
4369 Ok(())
4370 }
4371
4372 async fn handle_remove_collaborator(
4373 this: ModelHandle<Self>,
4374 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4375 _: Arc<Client>,
4376 mut cx: AsyncAppContext,
4377 ) -> Result<()> {
4378 this.update(&mut cx, |this, cx| {
4379 let peer_id = PeerId(envelope.payload.peer_id);
4380 let replica_id = this
4381 .collaborators
4382 .remove(&peer_id)
4383 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4384 .replica_id;
4385 for (_, buffer) in &this.opened_buffers {
4386 if let Some(buffer) = buffer.upgrade(cx) {
4387 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4388 }
4389 }
4390
4391 cx.emit(Event::CollaboratorLeft(peer_id));
4392 cx.notify();
4393 Ok(())
4394 })
4395 }
4396
4397 async fn handle_join_project_request_cancelled(
4398 this: ModelHandle<Self>,
4399 envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
4400 _: Arc<Client>,
4401 mut cx: AsyncAppContext,
4402 ) -> Result<()> {
4403 let user = this
4404 .update(&mut cx, |this, cx| {
4405 this.user_store.update(cx, |user_store, cx| {
4406 user_store.fetch_user(envelope.payload.requester_id, cx)
4407 })
4408 })
4409 .await?;
4410
4411 this.update(&mut cx, |_, cx| {
4412 cx.emit(Event::ContactCancelledJoinRequest(user));
4413 });
4414
4415 Ok(())
4416 }
4417
4418 async fn handle_update_project(
4419 this: ModelHandle<Self>,
4420 envelope: TypedEnvelope<proto::UpdateProject>,
4421 client: Arc<Client>,
4422 mut cx: AsyncAppContext,
4423 ) -> Result<()> {
4424 this.update(&mut cx, |this, cx| {
4425 let replica_id = this.replica_id();
4426 let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4427
4428 let mut old_worktrees_by_id = this
4429 .worktrees
4430 .drain(..)
4431 .filter_map(|worktree| {
4432 let worktree = worktree.upgrade(cx)?;
4433 Some((worktree.read(cx).id(), worktree))
4434 })
4435 .collect::<HashMap<_, _>>();
4436
4437 for worktree in envelope.payload.worktrees {
4438 if let Some(old_worktree) =
4439 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4440 {
4441 this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4442 } else {
4443 let worktree = proto::Worktree {
4444 id: worktree.id,
4445 root_name: worktree.root_name,
4446 entries: Default::default(),
4447 diagnostic_summaries: Default::default(),
4448 visible: worktree.visible,
4449 scan_id: 0,
4450 };
4451 let (worktree, load_task) =
4452 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4453 this.add_worktree(&worktree, cx);
4454 load_task.detach();
4455 }
4456 }
4457
4458 this.metadata_changed(true, cx);
4459 for (id, _) in old_worktrees_by_id {
4460 cx.emit(Event::WorktreeRemoved(id));
4461 }
4462
4463 Ok(())
4464 })
4465 }
4466
4467 async fn handle_update_worktree(
4468 this: ModelHandle<Self>,
4469 envelope: TypedEnvelope<proto::UpdateWorktree>,
4470 _: Arc<Client>,
4471 mut cx: AsyncAppContext,
4472 ) -> Result<()> {
4473 this.update(&mut cx, |this, cx| {
4474 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4475 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4476 worktree.update(cx, |worktree, _| {
4477 let worktree = worktree.as_remote_mut().unwrap();
4478 worktree.update_from_remote(envelope)
4479 })?;
4480 }
4481 Ok(())
4482 })
4483 }
4484
4485 async fn handle_create_project_entry(
4486 this: ModelHandle<Self>,
4487 envelope: TypedEnvelope<proto::CreateProjectEntry>,
4488 _: Arc<Client>,
4489 mut cx: AsyncAppContext,
4490 ) -> Result<proto::ProjectEntryResponse> {
4491 let worktree = this.update(&mut cx, |this, cx| {
4492 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4493 this.worktree_for_id(worktree_id, cx)
4494 .ok_or_else(|| anyhow!("worktree not found"))
4495 })?;
4496 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4497 let entry = worktree
4498 .update(&mut cx, |worktree, cx| {
4499 let worktree = worktree.as_local_mut().unwrap();
4500 let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4501 worktree.create_entry(path, envelope.payload.is_directory, cx)
4502 })
4503 .await?;
4504 Ok(proto::ProjectEntryResponse {
4505 entry: Some((&entry).into()),
4506 worktree_scan_id: worktree_scan_id as u64,
4507 })
4508 }
4509
4510 async fn handle_rename_project_entry(
4511 this: ModelHandle<Self>,
4512 envelope: TypedEnvelope<proto::RenameProjectEntry>,
4513 _: Arc<Client>,
4514 mut cx: AsyncAppContext,
4515 ) -> Result<proto::ProjectEntryResponse> {
4516 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4517 let worktree = this.read_with(&cx, |this, cx| {
4518 this.worktree_for_entry(entry_id, cx)
4519 .ok_or_else(|| anyhow!("worktree not found"))
4520 })?;
4521 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4522 let entry = worktree
4523 .update(&mut cx, |worktree, cx| {
4524 let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4525 worktree
4526 .as_local_mut()
4527 .unwrap()
4528 .rename_entry(entry_id, new_path, cx)
4529 .ok_or_else(|| anyhow!("invalid entry"))
4530 })?
4531 .await?;
4532 Ok(proto::ProjectEntryResponse {
4533 entry: Some((&entry).into()),
4534 worktree_scan_id: worktree_scan_id as u64,
4535 })
4536 }
4537
4538 async fn handle_copy_project_entry(
4539 this: ModelHandle<Self>,
4540 envelope: TypedEnvelope<proto::CopyProjectEntry>,
4541 _: Arc<Client>,
4542 mut cx: AsyncAppContext,
4543 ) -> Result<proto::ProjectEntryResponse> {
4544 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4545 let worktree = this.read_with(&cx, |this, cx| {
4546 this.worktree_for_entry(entry_id, cx)
4547 .ok_or_else(|| anyhow!("worktree not found"))
4548 })?;
4549 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4550 let entry = worktree
4551 .update(&mut cx, |worktree, cx| {
4552 let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4553 worktree
4554 .as_local_mut()
4555 .unwrap()
4556 .copy_entry(entry_id, new_path, cx)
4557 .ok_or_else(|| anyhow!("invalid entry"))
4558 })?
4559 .await?;
4560 Ok(proto::ProjectEntryResponse {
4561 entry: Some((&entry).into()),
4562 worktree_scan_id: worktree_scan_id as u64,
4563 })
4564 }
4565
4566 async fn handle_delete_project_entry(
4567 this: ModelHandle<Self>,
4568 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4569 _: Arc<Client>,
4570 mut cx: AsyncAppContext,
4571 ) -> Result<proto::ProjectEntryResponse> {
4572 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4573 let worktree = this.read_with(&cx, |this, cx| {
4574 this.worktree_for_entry(entry_id, cx)
4575 .ok_or_else(|| anyhow!("worktree not found"))
4576 })?;
4577 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4578 worktree
4579 .update(&mut cx, |worktree, cx| {
4580 worktree
4581 .as_local_mut()
4582 .unwrap()
4583 .delete_entry(entry_id, cx)
4584 .ok_or_else(|| anyhow!("invalid entry"))
4585 })?
4586 .await?;
4587 Ok(proto::ProjectEntryResponse {
4588 entry: None,
4589 worktree_scan_id: worktree_scan_id as u64,
4590 })
4591 }
4592
4593 async fn handle_update_diagnostic_summary(
4594 this: ModelHandle<Self>,
4595 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4596 _: Arc<Client>,
4597 mut cx: AsyncAppContext,
4598 ) -> Result<()> {
4599 this.update(&mut cx, |this, cx| {
4600 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4601 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4602 if let Some(summary) = envelope.payload.summary {
4603 let project_path = ProjectPath {
4604 worktree_id,
4605 path: Path::new(&summary.path).into(),
4606 };
4607 worktree.update(cx, |worktree, _| {
4608 worktree
4609 .as_remote_mut()
4610 .unwrap()
4611 .update_diagnostic_summary(project_path.path.clone(), &summary);
4612 });
4613 cx.emit(Event::DiagnosticsUpdated {
4614 language_server_id: summary.language_server_id as usize,
4615 path: project_path,
4616 });
4617 }
4618 }
4619 Ok(())
4620 })
4621 }
4622
4623 async fn handle_start_language_server(
4624 this: ModelHandle<Self>,
4625 envelope: TypedEnvelope<proto::StartLanguageServer>,
4626 _: Arc<Client>,
4627 mut cx: AsyncAppContext,
4628 ) -> Result<()> {
4629 let server = envelope
4630 .payload
4631 .server
4632 .ok_or_else(|| anyhow!("invalid server"))?;
4633 this.update(&mut cx, |this, cx| {
4634 this.language_server_statuses.insert(
4635 server.id as usize,
4636 LanguageServerStatus {
4637 name: server.name,
4638 pending_work: Default::default(),
4639 has_pending_diagnostic_updates: false,
4640 progress_tokens: Default::default(),
4641 },
4642 );
4643 cx.notify();
4644 });
4645 Ok(())
4646 }
4647
4648 async fn handle_update_language_server(
4649 this: ModelHandle<Self>,
4650 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4651 _: Arc<Client>,
4652 mut cx: AsyncAppContext,
4653 ) -> Result<()> {
4654 let language_server_id = envelope.payload.language_server_id as usize;
4655 match envelope
4656 .payload
4657 .variant
4658 .ok_or_else(|| anyhow!("invalid variant"))?
4659 {
4660 proto::update_language_server::Variant::WorkStart(payload) => {
4661 this.update(&mut cx, |this, cx| {
4662 this.on_lsp_work_start(
4663 language_server_id,
4664 payload.token,
4665 LanguageServerProgress {
4666 message: payload.message,
4667 percentage: payload.percentage.map(|p| p as usize),
4668 last_update_at: Instant::now(),
4669 },
4670 cx,
4671 );
4672 })
4673 }
4674 proto::update_language_server::Variant::WorkProgress(payload) => {
4675 this.update(&mut cx, |this, cx| {
4676 this.on_lsp_work_progress(
4677 language_server_id,
4678 payload.token,
4679 LanguageServerProgress {
4680 message: payload.message,
4681 percentage: payload.percentage.map(|p| p as usize),
4682 last_update_at: Instant::now(),
4683 },
4684 cx,
4685 );
4686 })
4687 }
4688 proto::update_language_server::Variant::WorkEnd(payload) => {
4689 this.update(&mut cx, |this, cx| {
4690 this.on_lsp_work_end(language_server_id, payload.token, cx);
4691 })
4692 }
4693 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
4694 this.update(&mut cx, |this, cx| {
4695 this.disk_based_diagnostics_started(language_server_id, cx);
4696 })
4697 }
4698 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
4699 this.update(&mut cx, |this, cx| {
4700 this.disk_based_diagnostics_finished(language_server_id, cx)
4701 });
4702 }
4703 }
4704
4705 Ok(())
4706 }
4707
4708 async fn handle_update_buffer(
4709 this: ModelHandle<Self>,
4710 envelope: TypedEnvelope<proto::UpdateBuffer>,
4711 _: Arc<Client>,
4712 mut cx: AsyncAppContext,
4713 ) -> Result<()> {
4714 this.update(&mut cx, |this, cx| {
4715 let payload = envelope.payload.clone();
4716 let buffer_id = payload.buffer_id;
4717 let ops = payload
4718 .operations
4719 .into_iter()
4720 .map(|op| language::proto::deserialize_operation(op))
4721 .collect::<Result<Vec<_>, _>>()?;
4722 let is_remote = this.is_remote();
4723 match this.opened_buffers.entry(buffer_id) {
4724 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
4725 OpenBuffer::Strong(buffer) => {
4726 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
4727 }
4728 OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
4729 OpenBuffer::Weak(_) => {}
4730 },
4731 hash_map::Entry::Vacant(e) => {
4732 assert!(
4733 is_remote,
4734 "received buffer update from {:?}",
4735 envelope.original_sender_id
4736 );
4737 e.insert(OpenBuffer::Loading(ops));
4738 }
4739 }
4740 Ok(())
4741 })
4742 }
4743
4744 async fn handle_update_buffer_file(
4745 this: ModelHandle<Self>,
4746 envelope: TypedEnvelope<proto::UpdateBufferFile>,
4747 _: Arc<Client>,
4748 mut cx: AsyncAppContext,
4749 ) -> Result<()> {
4750 this.update(&mut cx, |this, cx| {
4751 let payload = envelope.payload.clone();
4752 let buffer_id = payload.buffer_id;
4753 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
4754 let worktree = this
4755 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
4756 .ok_or_else(|| anyhow!("no such worktree"))?;
4757 let file = File::from_proto(file, worktree.clone(), cx)?;
4758 let buffer = this
4759 .opened_buffers
4760 .get_mut(&buffer_id)
4761 .and_then(|b| b.upgrade(cx))
4762 .ok_or_else(|| anyhow!("no such buffer"))?;
4763 buffer.update(cx, |buffer, cx| {
4764 buffer.file_updated(Arc::new(file), cx).detach();
4765 });
4766 Ok(())
4767 })
4768 }
4769
4770 async fn handle_save_buffer(
4771 this: ModelHandle<Self>,
4772 envelope: TypedEnvelope<proto::SaveBuffer>,
4773 _: Arc<Client>,
4774 mut cx: AsyncAppContext,
4775 ) -> Result<proto::BufferSaved> {
4776 let buffer_id = envelope.payload.buffer_id;
4777 let requested_version = deserialize_version(envelope.payload.version);
4778
4779 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
4780 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
4781 let buffer = this
4782 .opened_buffers
4783 .get(&buffer_id)
4784 .and_then(|buffer| buffer.upgrade(cx))
4785 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
4786 Ok::<_, anyhow::Error>((project_id, buffer))
4787 })?;
4788 buffer
4789 .update(&mut cx, |buffer, _| {
4790 buffer.wait_for_version(requested_version)
4791 })
4792 .await;
4793
4794 let (saved_version, fingerprint, mtime) =
4795 buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
4796 Ok(proto::BufferSaved {
4797 project_id,
4798 buffer_id,
4799 version: serialize_version(&saved_version),
4800 mtime: Some(mtime.into()),
4801 fingerprint,
4802 })
4803 }
4804
4805 async fn handle_reload_buffers(
4806 this: ModelHandle<Self>,
4807 envelope: TypedEnvelope<proto::ReloadBuffers>,
4808 _: Arc<Client>,
4809 mut cx: AsyncAppContext,
4810 ) -> Result<proto::ReloadBuffersResponse> {
4811 let sender_id = envelope.original_sender_id()?;
4812 let reload = this.update(&mut cx, |this, cx| {
4813 let mut buffers = HashSet::default();
4814 for buffer_id in &envelope.payload.buffer_ids {
4815 buffers.insert(
4816 this.opened_buffers
4817 .get(buffer_id)
4818 .and_then(|buffer| buffer.upgrade(cx))
4819 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
4820 );
4821 }
4822 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
4823 })?;
4824
4825 let project_transaction = reload.await?;
4826 let project_transaction = this.update(&mut cx, |this, cx| {
4827 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4828 });
4829 Ok(proto::ReloadBuffersResponse {
4830 transaction: Some(project_transaction),
4831 })
4832 }
4833
4834 async fn handle_format_buffers(
4835 this: ModelHandle<Self>,
4836 envelope: TypedEnvelope<proto::FormatBuffers>,
4837 _: Arc<Client>,
4838 mut cx: AsyncAppContext,
4839 ) -> Result<proto::FormatBuffersResponse> {
4840 let sender_id = envelope.original_sender_id()?;
4841 let format = this.update(&mut cx, |this, cx| {
4842 let mut buffers = HashSet::default();
4843 for buffer_id in &envelope.payload.buffer_ids {
4844 buffers.insert(
4845 this.opened_buffers
4846 .get(buffer_id)
4847 .and_then(|buffer| buffer.upgrade(cx))
4848 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
4849 );
4850 }
4851 Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
4852 })?;
4853
4854 let project_transaction = format.await?;
4855 let project_transaction = this.update(&mut cx, |this, cx| {
4856 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4857 });
4858 Ok(proto::FormatBuffersResponse {
4859 transaction: Some(project_transaction),
4860 })
4861 }
4862
4863 async fn handle_get_completions(
4864 this: ModelHandle<Self>,
4865 envelope: TypedEnvelope<proto::GetCompletions>,
4866 _: Arc<Client>,
4867 mut cx: AsyncAppContext,
4868 ) -> Result<proto::GetCompletionsResponse> {
4869 let position = envelope
4870 .payload
4871 .position
4872 .and_then(language::proto::deserialize_anchor)
4873 .ok_or_else(|| anyhow!("invalid position"))?;
4874 let version = deserialize_version(envelope.payload.version);
4875 let buffer = this.read_with(&cx, |this, cx| {
4876 this.opened_buffers
4877 .get(&envelope.payload.buffer_id)
4878 .and_then(|buffer| buffer.upgrade(cx))
4879 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
4880 })?;
4881 buffer
4882 .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
4883 .await;
4884 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
4885 let completions = this
4886 .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
4887 .await?;
4888
4889 Ok(proto::GetCompletionsResponse {
4890 completions: completions
4891 .iter()
4892 .map(language::proto::serialize_completion)
4893 .collect(),
4894 version: serialize_version(&version),
4895 })
4896 }
4897
4898 async fn handle_apply_additional_edits_for_completion(
4899 this: ModelHandle<Self>,
4900 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
4901 _: Arc<Client>,
4902 mut cx: AsyncAppContext,
4903 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
4904 let apply_additional_edits = this.update(&mut cx, |this, cx| {
4905 let buffer = this
4906 .opened_buffers
4907 .get(&envelope.payload.buffer_id)
4908 .and_then(|buffer| buffer.upgrade(cx))
4909 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
4910 let language = buffer.read(cx).language();
4911 let completion = language::proto::deserialize_completion(
4912 envelope
4913 .payload
4914 .completion
4915 .ok_or_else(|| anyhow!("invalid completion"))?,
4916 language,
4917 )?;
4918 Ok::<_, anyhow::Error>(
4919 this.apply_additional_edits_for_completion(buffer, completion, false, cx),
4920 )
4921 })?;
4922
4923 Ok(proto::ApplyCompletionAdditionalEditsResponse {
4924 transaction: apply_additional_edits
4925 .await?
4926 .as_ref()
4927 .map(language::proto::serialize_transaction),
4928 })
4929 }
4930
4931 async fn handle_get_code_actions(
4932 this: ModelHandle<Self>,
4933 envelope: TypedEnvelope<proto::GetCodeActions>,
4934 _: Arc<Client>,
4935 mut cx: AsyncAppContext,
4936 ) -> Result<proto::GetCodeActionsResponse> {
4937 let start = envelope
4938 .payload
4939 .start
4940 .and_then(language::proto::deserialize_anchor)
4941 .ok_or_else(|| anyhow!("invalid start"))?;
4942 let end = envelope
4943 .payload
4944 .end
4945 .and_then(language::proto::deserialize_anchor)
4946 .ok_or_else(|| anyhow!("invalid end"))?;
4947 let buffer = this.update(&mut cx, |this, cx| {
4948 this.opened_buffers
4949 .get(&envelope.payload.buffer_id)
4950 .and_then(|buffer| buffer.upgrade(cx))
4951 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
4952 })?;
4953 buffer
4954 .update(&mut cx, |buffer, _| {
4955 buffer.wait_for_version(deserialize_version(envelope.payload.version))
4956 })
4957 .await;
4958
4959 let version = buffer.read_with(&cx, |buffer, _| buffer.version());
4960 let code_actions = this.update(&mut cx, |this, cx| {
4961 Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
4962 })?;
4963
4964 Ok(proto::GetCodeActionsResponse {
4965 actions: code_actions
4966 .await?
4967 .iter()
4968 .map(language::proto::serialize_code_action)
4969 .collect(),
4970 version: serialize_version(&version),
4971 })
4972 }
4973
4974 async fn handle_apply_code_action(
4975 this: ModelHandle<Self>,
4976 envelope: TypedEnvelope<proto::ApplyCodeAction>,
4977 _: Arc<Client>,
4978 mut cx: AsyncAppContext,
4979 ) -> Result<proto::ApplyCodeActionResponse> {
4980 let sender_id = envelope.original_sender_id()?;
4981 let action = language::proto::deserialize_code_action(
4982 envelope
4983 .payload
4984 .action
4985 .ok_or_else(|| anyhow!("invalid action"))?,
4986 )?;
4987 let apply_code_action = this.update(&mut cx, |this, cx| {
4988 let buffer = this
4989 .opened_buffers
4990 .get(&envelope.payload.buffer_id)
4991 .and_then(|buffer| buffer.upgrade(cx))
4992 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
4993 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
4994 })?;
4995
4996 let project_transaction = apply_code_action.await?;
4997 let project_transaction = this.update(&mut cx, |this, cx| {
4998 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4999 });
5000 Ok(proto::ApplyCodeActionResponse {
5001 transaction: Some(project_transaction),
5002 })
5003 }
5004
5005 async fn handle_lsp_command<T: LspCommand>(
5006 this: ModelHandle<Self>,
5007 envelope: TypedEnvelope<T::ProtoRequest>,
5008 _: Arc<Client>,
5009 mut cx: AsyncAppContext,
5010 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5011 where
5012 <T::LspRequest as lsp::request::Request>::Result: Send,
5013 {
5014 let sender_id = envelope.original_sender_id()?;
5015 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5016 let buffer_handle = this.read_with(&cx, |this, _| {
5017 this.opened_buffers
5018 .get(&buffer_id)
5019 .and_then(|buffer| buffer.upgrade(&cx))
5020 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5021 })?;
5022 let request = T::from_proto(
5023 envelope.payload,
5024 this.clone(),
5025 buffer_handle.clone(),
5026 cx.clone(),
5027 )
5028 .await?;
5029 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5030 let response = this
5031 .update(&mut cx, |this, cx| {
5032 this.request_lsp(buffer_handle, request, cx)
5033 })
5034 .await?;
5035 this.update(&mut cx, |this, cx| {
5036 Ok(T::response_to_proto(
5037 response,
5038 this,
5039 sender_id,
5040 &buffer_version,
5041 cx,
5042 ))
5043 })
5044 }
5045
5046 async fn handle_get_project_symbols(
5047 this: ModelHandle<Self>,
5048 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5049 _: Arc<Client>,
5050 mut cx: AsyncAppContext,
5051 ) -> Result<proto::GetProjectSymbolsResponse> {
5052 let symbols = this
5053 .update(&mut cx, |this, cx| {
5054 this.symbols(&envelope.payload.query, cx)
5055 })
5056 .await?;
5057
5058 Ok(proto::GetProjectSymbolsResponse {
5059 symbols: symbols.iter().map(serialize_symbol).collect(),
5060 })
5061 }
5062
5063 async fn handle_search_project(
5064 this: ModelHandle<Self>,
5065 envelope: TypedEnvelope<proto::SearchProject>,
5066 _: Arc<Client>,
5067 mut cx: AsyncAppContext,
5068 ) -> Result<proto::SearchProjectResponse> {
5069 let peer_id = envelope.original_sender_id()?;
5070 let query = SearchQuery::from_proto(envelope.payload)?;
5071 let result = this
5072 .update(&mut cx, |this, cx| this.search(query, cx))
5073 .await?;
5074
5075 this.update(&mut cx, |this, cx| {
5076 let mut locations = Vec::new();
5077 for (buffer, ranges) in result {
5078 for range in ranges {
5079 let start = serialize_anchor(&range.start);
5080 let end = serialize_anchor(&range.end);
5081 let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
5082 locations.push(proto::Location {
5083 buffer: Some(buffer),
5084 start: Some(start),
5085 end: Some(end),
5086 });
5087 }
5088 }
5089 Ok(proto::SearchProjectResponse { locations })
5090 })
5091 }
5092
5093 async fn handle_open_buffer_for_symbol(
5094 this: ModelHandle<Self>,
5095 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5096 _: Arc<Client>,
5097 mut cx: AsyncAppContext,
5098 ) -> Result<proto::OpenBufferForSymbolResponse> {
5099 let peer_id = envelope.original_sender_id()?;
5100 let symbol = envelope
5101 .payload
5102 .symbol
5103 .ok_or_else(|| anyhow!("invalid symbol"))?;
5104 let symbol = this.read_with(&cx, |this, _| {
5105 let symbol = this.deserialize_symbol(symbol)?;
5106 let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
5107 if signature == symbol.signature {
5108 Ok(symbol)
5109 } else {
5110 Err(anyhow!("invalid symbol signature"))
5111 }
5112 })?;
5113 let buffer = this
5114 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5115 .await?;
5116
5117 Ok(proto::OpenBufferForSymbolResponse {
5118 buffer: Some(this.update(&mut cx, |this, cx| {
5119 this.serialize_buffer_for_peer(&buffer, peer_id, cx)
5120 })),
5121 })
5122 }
5123
5124 fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
5125 let mut hasher = Sha256::new();
5126 hasher.update(worktree_id.to_proto().to_be_bytes());
5127 hasher.update(path.to_string_lossy().as_bytes());
5128 hasher.update(self.nonce.to_be_bytes());
5129 hasher.finalize().as_slice().try_into().unwrap()
5130 }
5131
5132 async fn handle_open_buffer_by_id(
5133 this: ModelHandle<Self>,
5134 envelope: TypedEnvelope<proto::OpenBufferById>,
5135 _: Arc<Client>,
5136 mut cx: AsyncAppContext,
5137 ) -> Result<proto::OpenBufferResponse> {
5138 let peer_id = envelope.original_sender_id()?;
5139 let buffer = this
5140 .update(&mut cx, |this, cx| {
5141 this.open_buffer_by_id(envelope.payload.id, cx)
5142 })
5143 .await?;
5144 this.update(&mut cx, |this, cx| {
5145 Ok(proto::OpenBufferResponse {
5146 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5147 })
5148 })
5149 }
5150
5151 async fn handle_open_buffer_by_path(
5152 this: ModelHandle<Self>,
5153 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5154 _: Arc<Client>,
5155 mut cx: AsyncAppContext,
5156 ) -> Result<proto::OpenBufferResponse> {
5157 let peer_id = envelope.original_sender_id()?;
5158 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5159 let open_buffer = this.update(&mut cx, |this, cx| {
5160 this.open_buffer(
5161 ProjectPath {
5162 worktree_id,
5163 path: PathBuf::from(envelope.payload.path).into(),
5164 },
5165 cx,
5166 )
5167 });
5168
5169 let buffer = open_buffer.await?;
5170 this.update(&mut cx, |this, cx| {
5171 Ok(proto::OpenBufferResponse {
5172 buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5173 })
5174 })
5175 }
5176
5177 fn serialize_project_transaction_for_peer(
5178 &mut self,
5179 project_transaction: ProjectTransaction,
5180 peer_id: PeerId,
5181 cx: &AppContext,
5182 ) -> proto::ProjectTransaction {
5183 let mut serialized_transaction = proto::ProjectTransaction {
5184 buffers: Default::default(),
5185 transactions: Default::default(),
5186 };
5187 for (buffer, transaction) in project_transaction.0 {
5188 serialized_transaction
5189 .buffers
5190 .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
5191 serialized_transaction
5192 .transactions
5193 .push(language::proto::serialize_transaction(&transaction));
5194 }
5195 serialized_transaction
5196 }
5197
5198 fn deserialize_project_transaction(
5199 &mut self,
5200 message: proto::ProjectTransaction,
5201 push_to_history: bool,
5202 cx: &mut ModelContext<Self>,
5203 ) -> Task<Result<ProjectTransaction>> {
5204 cx.spawn(|this, mut cx| async move {
5205 let mut project_transaction = ProjectTransaction::default();
5206 for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
5207 let buffer = this
5208 .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
5209 .await?;
5210 let transaction = language::proto::deserialize_transaction(transaction)?;
5211 project_transaction.0.insert(buffer, transaction);
5212 }
5213
5214 for (buffer, transaction) in &project_transaction.0 {
5215 buffer
5216 .update(&mut cx, |buffer, _| {
5217 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5218 })
5219 .await;
5220
5221 if push_to_history {
5222 buffer.update(&mut cx, |buffer, _| {
5223 buffer.push_transaction(transaction.clone(), Instant::now());
5224 });
5225 }
5226 }
5227
5228 Ok(project_transaction)
5229 })
5230 }
5231
5232 fn serialize_buffer_for_peer(
5233 &mut self,
5234 buffer: &ModelHandle<Buffer>,
5235 peer_id: PeerId,
5236 cx: &AppContext,
5237 ) -> proto::Buffer {
5238 let buffer_id = buffer.read(cx).remote_id();
5239 let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5240 if shared_buffers.insert(buffer_id) {
5241 proto::Buffer {
5242 variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
5243 }
5244 } else {
5245 proto::Buffer {
5246 variant: Some(proto::buffer::Variant::Id(buffer_id)),
5247 }
5248 }
5249 }
5250
5251 fn deserialize_buffer(
5252 &mut self,
5253 buffer: proto::Buffer,
5254 cx: &mut ModelContext<Self>,
5255 ) -> Task<Result<ModelHandle<Buffer>>> {
5256 let replica_id = self.replica_id();
5257
5258 let opened_buffer_tx = self.opened_buffer.0.clone();
5259 let mut opened_buffer_rx = self.opened_buffer.1.clone();
5260 cx.spawn(|this, mut cx| async move {
5261 match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
5262 proto::buffer::Variant::Id(id) => {
5263 let buffer = loop {
5264 let buffer = this.read_with(&cx, |this, cx| {
5265 this.opened_buffers
5266 .get(&id)
5267 .and_then(|buffer| buffer.upgrade(cx))
5268 });
5269 if let Some(buffer) = buffer {
5270 break buffer;
5271 }
5272 opened_buffer_rx
5273 .next()
5274 .await
5275 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5276 };
5277 Ok(buffer)
5278 }
5279 proto::buffer::Variant::State(mut buffer) => {
5280 let mut buffer_worktree = None;
5281 let mut buffer_file = None;
5282 if let Some(file) = buffer.file.take() {
5283 this.read_with(&cx, |this, cx| {
5284 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5285 let worktree =
5286 this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5287 anyhow!("no worktree found for id {}", file.worktree_id)
5288 })?;
5289 buffer_file =
5290 Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5291 as Arc<dyn language::File>);
5292 buffer_worktree = Some(worktree);
5293 Ok::<_, anyhow::Error>(())
5294 })?;
5295 }
5296
5297 let buffer = cx.add_model(|cx| {
5298 Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
5299 });
5300
5301 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
5302
5303 *opened_buffer_tx.borrow_mut().borrow_mut() = ();
5304 Ok(buffer)
5305 }
5306 }
5307 })
5308 }
5309
5310 fn deserialize_symbol(&self, serialized_symbol: proto::Symbol) -> Result<Symbol> {
5311 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5312 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5313 let start = serialized_symbol
5314 .start
5315 .ok_or_else(|| anyhow!("invalid start"))?;
5316 let end = serialized_symbol
5317 .end
5318 .ok_or_else(|| anyhow!("invalid end"))?;
5319 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5320 let path = PathBuf::from(serialized_symbol.path);
5321 let language = self.languages.select_language(&path);
5322 Ok(Symbol {
5323 source_worktree_id,
5324 worktree_id,
5325 language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
5326 label: language
5327 .and_then(|language| language.label_for_symbol(&serialized_symbol.name, kind))
5328 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None)),
5329 name: serialized_symbol.name,
5330 path,
5331 range: PointUtf16::new(start.row, start.column)..PointUtf16::new(end.row, end.column),
5332 kind,
5333 signature: serialized_symbol
5334 .signature
5335 .try_into()
5336 .map_err(|_| anyhow!("invalid signature"))?,
5337 })
5338 }
5339
5340 async fn handle_buffer_saved(
5341 this: ModelHandle<Self>,
5342 envelope: TypedEnvelope<proto::BufferSaved>,
5343 _: Arc<Client>,
5344 mut cx: AsyncAppContext,
5345 ) -> Result<()> {
5346 let version = deserialize_version(envelope.payload.version);
5347 let mtime = envelope
5348 .payload
5349 .mtime
5350 .ok_or_else(|| anyhow!("missing mtime"))?
5351 .into();
5352
5353 this.update(&mut cx, |this, cx| {
5354 let buffer = this
5355 .opened_buffers
5356 .get(&envelope.payload.buffer_id)
5357 .and_then(|buffer| buffer.upgrade(cx));
5358 if let Some(buffer) = buffer {
5359 buffer.update(cx, |buffer, cx| {
5360 buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5361 });
5362 }
5363 Ok(())
5364 })
5365 }
5366
5367 async fn handle_buffer_reloaded(
5368 this: ModelHandle<Self>,
5369 envelope: TypedEnvelope<proto::BufferReloaded>,
5370 _: Arc<Client>,
5371 mut cx: AsyncAppContext,
5372 ) -> Result<()> {
5373 let payload = envelope.payload.clone();
5374 let version = deserialize_version(payload.version);
5375 let mtime = payload
5376 .mtime
5377 .ok_or_else(|| anyhow!("missing mtime"))?
5378 .into();
5379 this.update(&mut cx, |this, cx| {
5380 let buffer = this
5381 .opened_buffers
5382 .get(&payload.buffer_id)
5383 .and_then(|buffer| buffer.upgrade(cx));
5384 if let Some(buffer) = buffer {
5385 buffer.update(cx, |buffer, cx| {
5386 buffer.did_reload(version, payload.fingerprint, mtime, cx);
5387 });
5388 }
5389 Ok(())
5390 })
5391 }
5392
5393 pub fn match_paths<'a>(
5394 &self,
5395 query: &'a str,
5396 include_ignored: bool,
5397 smart_case: bool,
5398 max_results: usize,
5399 cancel_flag: &'a AtomicBool,
5400 cx: &AppContext,
5401 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
5402 let worktrees = self
5403 .worktrees(cx)
5404 .filter(|worktree| worktree.read(cx).is_visible())
5405 .collect::<Vec<_>>();
5406 let include_root_name = worktrees.len() > 1;
5407 let candidate_sets = worktrees
5408 .into_iter()
5409 .map(|worktree| CandidateSet {
5410 snapshot: worktree.read(cx).snapshot(),
5411 include_ignored,
5412 include_root_name,
5413 })
5414 .collect::<Vec<_>>();
5415
5416 let background = cx.background().clone();
5417 async move {
5418 fuzzy::match_paths(
5419 candidate_sets.as_slice(),
5420 query,
5421 smart_case,
5422 max_results,
5423 cancel_flag,
5424 background,
5425 )
5426 .await
5427 }
5428 }
5429
5430 fn edits_from_lsp(
5431 &mut self,
5432 buffer: &ModelHandle<Buffer>,
5433 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5434 version: Option<i32>,
5435 cx: &mut ModelContext<Self>,
5436 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5437 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5438 cx.background().spawn(async move {
5439 let snapshot = snapshot?;
5440 let mut lsp_edits = lsp_edits
5441 .into_iter()
5442 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5443 .collect::<Vec<_>>();
5444 lsp_edits.sort_by_key(|(range, _)| range.start);
5445
5446 let mut lsp_edits = lsp_edits.into_iter().peekable();
5447 let mut edits = Vec::new();
5448 while let Some((mut range, mut new_text)) = lsp_edits.next() {
5449 // Combine any LSP edits that are adjacent.
5450 //
5451 // Also, combine LSP edits that are separated from each other by only
5452 // a newline. This is important because for some code actions,
5453 // Rust-analyzer rewrites the entire buffer via a series of edits that
5454 // are separated by unchanged newline characters.
5455 //
5456 // In order for the diffing logic below to work properly, any edits that
5457 // cancel each other out must be combined into one.
5458 while let Some((next_range, next_text)) = lsp_edits.peek() {
5459 if next_range.start > range.end {
5460 if next_range.start.row > range.end.row + 1
5461 || next_range.start.column > 0
5462 || snapshot.clip_point_utf16(
5463 PointUtf16::new(range.end.row, u32::MAX),
5464 Bias::Left,
5465 ) > range.end
5466 {
5467 break;
5468 }
5469 new_text.push('\n');
5470 }
5471 range.end = next_range.end;
5472 new_text.push_str(&next_text);
5473 lsp_edits.next();
5474 }
5475
5476 if snapshot.clip_point_utf16(range.start, Bias::Left) != range.start
5477 || snapshot.clip_point_utf16(range.end, Bias::Left) != range.end
5478 {
5479 return Err(anyhow!("invalid edits received from language server"));
5480 }
5481
5482 // For multiline edits, perform a diff of the old and new text so that
5483 // we can identify the changes more precisely, preserving the locations
5484 // of any anchors positioned in the unchanged regions.
5485 if range.end.row > range.start.row {
5486 let mut offset = range.start.to_offset(&snapshot);
5487 let old_text = snapshot.text_for_range(range).collect::<String>();
5488
5489 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5490 let mut moved_since_edit = true;
5491 for change in diff.iter_all_changes() {
5492 let tag = change.tag();
5493 let value = change.value();
5494 match tag {
5495 ChangeTag::Equal => {
5496 offset += value.len();
5497 moved_since_edit = true;
5498 }
5499 ChangeTag::Delete => {
5500 let start = snapshot.anchor_after(offset);
5501 let end = snapshot.anchor_before(offset + value.len());
5502 if moved_since_edit {
5503 edits.push((start..end, String::new()));
5504 } else {
5505 edits.last_mut().unwrap().0.end = end;
5506 }
5507 offset += value.len();
5508 moved_since_edit = false;
5509 }
5510 ChangeTag::Insert => {
5511 if moved_since_edit {
5512 let anchor = snapshot.anchor_after(offset);
5513 edits.push((anchor.clone()..anchor, value.to_string()));
5514 } else {
5515 edits.last_mut().unwrap().1.push_str(value);
5516 }
5517 moved_since_edit = false;
5518 }
5519 }
5520 }
5521 } else if range.end == range.start {
5522 let anchor = snapshot.anchor_after(range.start);
5523 edits.push((anchor.clone()..anchor, new_text));
5524 } else {
5525 let edit_start = snapshot.anchor_after(range.start);
5526 let edit_end = snapshot.anchor_before(range.end);
5527 edits.push((edit_start..edit_end, new_text));
5528 }
5529 }
5530
5531 Ok(edits)
5532 })
5533 }
5534
5535 fn buffer_snapshot_for_lsp_version(
5536 &mut self,
5537 buffer: &ModelHandle<Buffer>,
5538 version: Option<i32>,
5539 cx: &AppContext,
5540 ) -> Result<TextBufferSnapshot> {
5541 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5542
5543 if let Some(version) = version {
5544 let buffer_id = buffer.read(cx).remote_id();
5545 let snapshots = self
5546 .buffer_snapshots
5547 .get_mut(&buffer_id)
5548 .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
5549 let mut found_snapshot = None;
5550 snapshots.retain(|(snapshot_version, snapshot)| {
5551 if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
5552 false
5553 } else {
5554 if *snapshot_version == version {
5555 found_snapshot = Some(snapshot.clone());
5556 }
5557 true
5558 }
5559 });
5560
5561 found_snapshot.ok_or_else(|| {
5562 anyhow!(
5563 "snapshot not found for buffer {} at version {}",
5564 buffer_id,
5565 version
5566 )
5567 })
5568 } else {
5569 Ok((buffer.read(cx)).text_snapshot())
5570 }
5571 }
5572
5573 fn language_server_for_buffer(
5574 &self,
5575 buffer: &Buffer,
5576 cx: &AppContext,
5577 ) -> Option<&(Arc<dyn LspAdapter>, Arc<LanguageServer>)> {
5578 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5579 let worktree_id = file.worktree_id(cx);
5580 self.language_servers
5581 .get(&(worktree_id, language.lsp_adapter()?.name()))
5582 } else {
5583 None
5584 }
5585 }
5586}
5587
5588impl ProjectStore {
5589 pub fn new(db: Arc<Db>) -> Self {
5590 Self {
5591 db,
5592 projects: Default::default(),
5593 }
5594 }
5595
5596 pub fn projects<'a>(
5597 &'a self,
5598 cx: &'a AppContext,
5599 ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
5600 self.projects
5601 .iter()
5602 .filter_map(|project| project.upgrade(cx))
5603 }
5604
5605 fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
5606 if let Err(ix) = self
5607 .projects
5608 .binary_search_by_key(&project.id(), WeakModelHandle::id)
5609 {
5610 self.projects.insert(ix, project);
5611 }
5612 cx.notify();
5613 }
5614
5615 fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
5616 let mut did_change = false;
5617 self.projects.retain(|project| {
5618 if project.is_upgradable(cx) {
5619 true
5620 } else {
5621 did_change = true;
5622 false
5623 }
5624 });
5625 if did_change {
5626 cx.notify();
5627 }
5628 }
5629}
5630
5631impl WorktreeHandle {
5632 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
5633 match self {
5634 WorktreeHandle::Strong(handle) => Some(handle.clone()),
5635 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
5636 }
5637 }
5638}
5639
5640impl OpenBuffer {
5641 pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
5642 match self {
5643 OpenBuffer::Strong(handle) => Some(handle.clone()),
5644 OpenBuffer::Weak(handle) => handle.upgrade(cx),
5645 OpenBuffer::Loading(_) => None,
5646 }
5647 }
5648}
5649
5650struct CandidateSet {
5651 snapshot: Snapshot,
5652 include_ignored: bool,
5653 include_root_name: bool,
5654}
5655
5656impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
5657 type Candidates = CandidateSetIter<'a>;
5658
5659 fn id(&self) -> usize {
5660 self.snapshot.id().to_usize()
5661 }
5662
5663 fn len(&self) -> usize {
5664 if self.include_ignored {
5665 self.snapshot.file_count()
5666 } else {
5667 self.snapshot.visible_file_count()
5668 }
5669 }
5670
5671 fn prefix(&self) -> Arc<str> {
5672 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5673 self.snapshot.root_name().into()
5674 } else if self.include_root_name {
5675 format!("{}/", self.snapshot.root_name()).into()
5676 } else {
5677 "".into()
5678 }
5679 }
5680
5681 fn candidates(&'a self, start: usize) -> Self::Candidates {
5682 CandidateSetIter {
5683 traversal: self.snapshot.files(self.include_ignored, start),
5684 }
5685 }
5686}
5687
5688struct CandidateSetIter<'a> {
5689 traversal: Traversal<'a>,
5690}
5691
5692impl<'a> Iterator for CandidateSetIter<'a> {
5693 type Item = PathMatchCandidate<'a>;
5694
5695 fn next(&mut self) -> Option<Self::Item> {
5696 self.traversal.next().map(|entry| {
5697 if let EntryKind::File(char_bag) = entry.kind {
5698 PathMatchCandidate {
5699 path: &entry.path,
5700 char_bag,
5701 }
5702 } else {
5703 unreachable!()
5704 }
5705 })
5706 }
5707}
5708
5709impl Entity for ProjectStore {
5710 type Event = ();
5711}
5712
5713impl Entity for Project {
5714 type Event = Event;
5715
5716 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
5717 self.project_store.update(cx, ProjectStore::prune_projects);
5718
5719 match &self.client_state {
5720 ProjectClientState::Local { remote_id_rx, .. } => {
5721 if let Some(project_id) = *remote_id_rx.borrow() {
5722 self.client
5723 .send(proto::UnregisterProject { project_id })
5724 .log_err();
5725 }
5726 }
5727 ProjectClientState::Remote { remote_id, .. } => {
5728 self.client
5729 .send(proto::LeaveProject {
5730 project_id: *remote_id,
5731 })
5732 .log_err();
5733 }
5734 }
5735 }
5736
5737 fn app_will_quit(
5738 &mut self,
5739 _: &mut MutableAppContext,
5740 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
5741 let shutdown_futures = self
5742 .language_servers
5743 .drain()
5744 .filter_map(|(_, (_, server))| server.shutdown())
5745 .collect::<Vec<_>>();
5746 Some(
5747 async move {
5748 futures::future::join_all(shutdown_futures).await;
5749 }
5750 .boxed(),
5751 )
5752 }
5753}
5754
5755impl Collaborator {
5756 fn from_proto(
5757 message: proto::Collaborator,
5758 user_store: &ModelHandle<UserStore>,
5759 cx: &mut AsyncAppContext,
5760 ) -> impl Future<Output = Result<Self>> {
5761 let user = user_store.update(cx, |user_store, cx| {
5762 user_store.fetch_user(message.user_id, cx)
5763 });
5764
5765 async move {
5766 Ok(Self {
5767 peer_id: PeerId(message.peer_id),
5768 user: user.await?,
5769 replica_id: message.replica_id as ReplicaId,
5770 })
5771 }
5772 }
5773}
5774
5775impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5776 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5777 Self {
5778 worktree_id,
5779 path: path.as_ref().into(),
5780 }
5781 }
5782}
5783
5784impl From<lsp::CreateFileOptions> for fs::CreateOptions {
5785 fn from(options: lsp::CreateFileOptions) -> Self {
5786 Self {
5787 overwrite: options.overwrite.unwrap_or(false),
5788 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5789 }
5790 }
5791}
5792
5793impl From<lsp::RenameFileOptions> for fs::RenameOptions {
5794 fn from(options: lsp::RenameFileOptions) -> Self {
5795 Self {
5796 overwrite: options.overwrite.unwrap_or(false),
5797 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5798 }
5799 }
5800}
5801
5802impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
5803 fn from(options: lsp::DeleteFileOptions) -> Self {
5804 Self {
5805 recursive: options.recursive.unwrap_or(false),
5806 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5807 }
5808 }
5809}
5810
5811fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
5812 proto::Symbol {
5813 source_worktree_id: symbol.source_worktree_id.to_proto(),
5814 worktree_id: symbol.worktree_id.to_proto(),
5815 language_server_name: symbol.language_server_name.0.to_string(),
5816 name: symbol.name.clone(),
5817 kind: unsafe { mem::transmute(symbol.kind) },
5818 path: symbol.path.to_string_lossy().to_string(),
5819 start: Some(proto::Point {
5820 row: symbol.range.start.row,
5821 column: symbol.range.start.column,
5822 }),
5823 end: Some(proto::Point {
5824 row: symbol.range.end.row,
5825 column: symbol.range.end.column,
5826 }),
5827 signature: symbol.signature.to_vec(),
5828 }
5829}
5830
5831fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5832 let mut path_components = path.components();
5833 let mut base_components = base.components();
5834 let mut components: Vec<Component> = Vec::new();
5835 loop {
5836 match (path_components.next(), base_components.next()) {
5837 (None, None) => break,
5838 (Some(a), None) => {
5839 components.push(a);
5840 components.extend(path_components.by_ref());
5841 break;
5842 }
5843 (None, _) => components.push(Component::ParentDir),
5844 (Some(a), Some(b)) if components.is_empty() && a == b => (),
5845 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
5846 (Some(a), Some(_)) => {
5847 components.push(Component::ParentDir);
5848 for _ in base_components {
5849 components.push(Component::ParentDir);
5850 }
5851 components.push(a);
5852 components.extend(path_components.by_ref());
5853 break;
5854 }
5855 }
5856 }
5857 components.iter().map(|c| c.as_os_str()).collect()
5858}
5859
5860impl Item for Buffer {
5861 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
5862 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5863 }
5864}
5865
5866#[cfg(test)]
5867mod tests {
5868 use crate::worktree::WorktreeHandle;
5869
5870 use super::{Event, *};
5871 use fs::RealFs;
5872 use futures::{future, StreamExt};
5873 use gpui::{executor::Deterministic, test::subscribe};
5874 use language::{
5875 tree_sitter_rust, tree_sitter_typescript, Diagnostic, FakeLspAdapter, LanguageConfig,
5876 OffsetRangeExt, Point, ToPoint,
5877 };
5878 use lsp::Url;
5879 use serde_json::json;
5880 use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc, task::Poll};
5881 use unindent::Unindent as _;
5882 use util::{assert_set_eq, test::temp_tree};
5883
5884 #[gpui::test]
5885 async fn test_populate_and_search(cx: &mut gpui::TestAppContext) {
5886 let dir = temp_tree(json!({
5887 "root": {
5888 "apple": "",
5889 "banana": {
5890 "carrot": {
5891 "date": "",
5892 "endive": "",
5893 }
5894 },
5895 "fennel": {
5896 "grape": "",
5897 }
5898 }
5899 }));
5900
5901 let root_link_path = dir.path().join("root_link");
5902 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
5903 unix::fs::symlink(
5904 &dir.path().join("root/fennel"),
5905 &dir.path().join("root/finnochio"),
5906 )
5907 .unwrap();
5908
5909 let project = Project::test(Arc::new(RealFs), [root_link_path.as_ref()], cx).await;
5910
5911 project.read_with(cx, |project, cx| {
5912 let tree = project.worktrees(cx).next().unwrap().read(cx);
5913 assert_eq!(tree.file_count(), 5);
5914 assert_eq!(
5915 tree.inode_for_path("fennel/grape"),
5916 tree.inode_for_path("finnochio/grape")
5917 );
5918 });
5919
5920 let cancel_flag = Default::default();
5921 let results = project
5922 .read_with(cx, |project, cx| {
5923 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
5924 })
5925 .await;
5926 assert_eq!(
5927 results
5928 .into_iter()
5929 .map(|result| result.path)
5930 .collect::<Vec<Arc<Path>>>(),
5931 vec![
5932 PathBuf::from("banana/carrot/date").into(),
5933 PathBuf::from("banana/carrot/endive").into(),
5934 ]
5935 );
5936 }
5937
5938 #[gpui::test]
5939 async fn test_managing_language_servers(cx: &mut gpui::TestAppContext) {
5940 cx.foreground().forbid_parking();
5941
5942 let mut rust_language = Language::new(
5943 LanguageConfig {
5944 name: "Rust".into(),
5945 path_suffixes: vec!["rs".to_string()],
5946 ..Default::default()
5947 },
5948 Some(tree_sitter_rust::language()),
5949 );
5950 let mut json_language = Language::new(
5951 LanguageConfig {
5952 name: "JSON".into(),
5953 path_suffixes: vec!["json".to_string()],
5954 ..Default::default()
5955 },
5956 None,
5957 );
5958 let mut fake_rust_servers = rust_language.set_fake_lsp_adapter(FakeLspAdapter {
5959 name: "the-rust-language-server",
5960 capabilities: lsp::ServerCapabilities {
5961 completion_provider: Some(lsp::CompletionOptions {
5962 trigger_characters: Some(vec![".".to_string(), "::".to_string()]),
5963 ..Default::default()
5964 }),
5965 ..Default::default()
5966 },
5967 ..Default::default()
5968 });
5969 let mut fake_json_servers = json_language.set_fake_lsp_adapter(FakeLspAdapter {
5970 name: "the-json-language-server",
5971 capabilities: lsp::ServerCapabilities {
5972 completion_provider: Some(lsp::CompletionOptions {
5973 trigger_characters: Some(vec![":".to_string()]),
5974 ..Default::default()
5975 }),
5976 ..Default::default()
5977 },
5978 ..Default::default()
5979 });
5980
5981 let fs = FakeFs::new(cx.background());
5982 fs.insert_tree(
5983 "/the-root",
5984 json!({
5985 "test.rs": "const A: i32 = 1;",
5986 "test2.rs": "",
5987 "Cargo.toml": "a = 1",
5988 "package.json": "{\"a\": 1}",
5989 }),
5990 )
5991 .await;
5992
5993 let project = Project::test(fs.clone(), ["/the-root".as_ref()], cx).await;
5994 project.update(cx, |project, _| {
5995 project.languages.add(Arc::new(rust_language));
5996 project.languages.add(Arc::new(json_language));
5997 });
5998
5999 // Open a buffer without an associated language server.
6000 let toml_buffer = project
6001 .update(cx, |project, cx| {
6002 project.open_local_buffer("/the-root/Cargo.toml", cx)
6003 })
6004 .await
6005 .unwrap();
6006
6007 // Open a buffer with an associated language server.
6008 let rust_buffer = project
6009 .update(cx, |project, cx| {
6010 project.open_local_buffer("/the-root/test.rs", cx)
6011 })
6012 .await
6013 .unwrap();
6014
6015 // A server is started up, and it is notified about Rust files.
6016 let mut fake_rust_server = fake_rust_servers.next().await.unwrap();
6017 assert_eq!(
6018 fake_rust_server
6019 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6020 .await
6021 .text_document,
6022 lsp::TextDocumentItem {
6023 uri: lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
6024 version: 0,
6025 text: "const A: i32 = 1;".to_string(),
6026 language_id: Default::default()
6027 }
6028 );
6029
6030 // The buffer is configured based on the language server's capabilities.
6031 rust_buffer.read_with(cx, |buffer, _| {
6032 assert_eq!(
6033 buffer.completion_triggers(),
6034 &[".".to_string(), "::".to_string()]
6035 );
6036 });
6037 toml_buffer.read_with(cx, |buffer, _| {
6038 assert!(buffer.completion_triggers().is_empty());
6039 });
6040
6041 // Edit a buffer. The changes are reported to the language server.
6042 rust_buffer.update(cx, |buffer, cx| buffer.edit([(16..16, "2")], cx));
6043 assert_eq!(
6044 fake_rust_server
6045 .receive_notification::<lsp::notification::DidChangeTextDocument>()
6046 .await
6047 .text_document,
6048 lsp::VersionedTextDocumentIdentifier::new(
6049 lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
6050 1
6051 )
6052 );
6053
6054 // Open a third buffer with a different associated language server.
6055 let json_buffer = project
6056 .update(cx, |project, cx| {
6057 project.open_local_buffer("/the-root/package.json", cx)
6058 })
6059 .await
6060 .unwrap();
6061
6062 // A json language server is started up and is only notified about the json buffer.
6063 let mut fake_json_server = fake_json_servers.next().await.unwrap();
6064 assert_eq!(
6065 fake_json_server
6066 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6067 .await
6068 .text_document,
6069 lsp::TextDocumentItem {
6070 uri: lsp::Url::from_file_path("/the-root/package.json").unwrap(),
6071 version: 0,
6072 text: "{\"a\": 1}".to_string(),
6073 language_id: Default::default()
6074 }
6075 );
6076
6077 // This buffer is configured based on the second language server's
6078 // capabilities.
6079 json_buffer.read_with(cx, |buffer, _| {
6080 assert_eq!(buffer.completion_triggers(), &[":".to_string()]);
6081 });
6082
6083 // When opening another buffer whose language server is already running,
6084 // it is also configured based on the existing language server's capabilities.
6085 let rust_buffer2 = project
6086 .update(cx, |project, cx| {
6087 project.open_local_buffer("/the-root/test2.rs", cx)
6088 })
6089 .await
6090 .unwrap();
6091 rust_buffer2.read_with(cx, |buffer, _| {
6092 assert_eq!(
6093 buffer.completion_triggers(),
6094 &[".".to_string(), "::".to_string()]
6095 );
6096 });
6097
6098 // Changes are reported only to servers matching the buffer's language.
6099 toml_buffer.update(cx, |buffer, cx| buffer.edit([(5..5, "23")], cx));
6100 rust_buffer2.update(cx, |buffer, cx| buffer.edit([(0..0, "let x = 1;")], cx));
6101 assert_eq!(
6102 fake_rust_server
6103 .receive_notification::<lsp::notification::DidChangeTextDocument>()
6104 .await
6105 .text_document,
6106 lsp::VersionedTextDocumentIdentifier::new(
6107 lsp::Url::from_file_path("/the-root/test2.rs").unwrap(),
6108 1
6109 )
6110 );
6111
6112 // Save notifications are reported to all servers.
6113 toml_buffer
6114 .update(cx, |buffer, cx| buffer.save(cx))
6115 .await
6116 .unwrap();
6117 assert_eq!(
6118 fake_rust_server
6119 .receive_notification::<lsp::notification::DidSaveTextDocument>()
6120 .await
6121 .text_document,
6122 lsp::TextDocumentIdentifier::new(
6123 lsp::Url::from_file_path("/the-root/Cargo.toml").unwrap()
6124 )
6125 );
6126 assert_eq!(
6127 fake_json_server
6128 .receive_notification::<lsp::notification::DidSaveTextDocument>()
6129 .await
6130 .text_document,
6131 lsp::TextDocumentIdentifier::new(
6132 lsp::Url::from_file_path("/the-root/Cargo.toml").unwrap()
6133 )
6134 );
6135
6136 // Renames are reported only to servers matching the buffer's language.
6137 fs.rename(
6138 Path::new("/the-root/test2.rs"),
6139 Path::new("/the-root/test3.rs"),
6140 Default::default(),
6141 )
6142 .await
6143 .unwrap();
6144 assert_eq!(
6145 fake_rust_server
6146 .receive_notification::<lsp::notification::DidCloseTextDocument>()
6147 .await
6148 .text_document,
6149 lsp::TextDocumentIdentifier::new(
6150 lsp::Url::from_file_path("/the-root/test2.rs").unwrap()
6151 ),
6152 );
6153 assert_eq!(
6154 fake_rust_server
6155 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6156 .await
6157 .text_document,
6158 lsp::TextDocumentItem {
6159 uri: lsp::Url::from_file_path("/the-root/test3.rs").unwrap(),
6160 version: 0,
6161 text: rust_buffer2.read_with(cx, |buffer, _| buffer.text()),
6162 language_id: Default::default()
6163 },
6164 );
6165
6166 rust_buffer2.update(cx, |buffer, cx| {
6167 buffer.update_diagnostics(
6168 DiagnosticSet::from_sorted_entries(
6169 vec![DiagnosticEntry {
6170 diagnostic: Default::default(),
6171 range: Anchor::MIN..Anchor::MAX,
6172 }],
6173 &buffer.snapshot(),
6174 ),
6175 cx,
6176 );
6177 assert_eq!(
6178 buffer
6179 .snapshot()
6180 .diagnostics_in_range::<_, usize>(0..buffer.len(), false)
6181 .count(),
6182 1
6183 );
6184 });
6185
6186 // When the rename changes the extension of the file, the buffer gets closed on the old
6187 // language server and gets opened on the new one.
6188 fs.rename(
6189 Path::new("/the-root/test3.rs"),
6190 Path::new("/the-root/test3.json"),
6191 Default::default(),
6192 )
6193 .await
6194 .unwrap();
6195 assert_eq!(
6196 fake_rust_server
6197 .receive_notification::<lsp::notification::DidCloseTextDocument>()
6198 .await
6199 .text_document,
6200 lsp::TextDocumentIdentifier::new(
6201 lsp::Url::from_file_path("/the-root/test3.rs").unwrap(),
6202 ),
6203 );
6204 assert_eq!(
6205 fake_json_server
6206 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6207 .await
6208 .text_document,
6209 lsp::TextDocumentItem {
6210 uri: lsp::Url::from_file_path("/the-root/test3.json").unwrap(),
6211 version: 0,
6212 text: rust_buffer2.read_with(cx, |buffer, _| buffer.text()),
6213 language_id: Default::default()
6214 },
6215 );
6216
6217 // We clear the diagnostics, since the language has changed.
6218 rust_buffer2.read_with(cx, |buffer, _| {
6219 assert_eq!(
6220 buffer
6221 .snapshot()
6222 .diagnostics_in_range::<_, usize>(0..buffer.len(), false)
6223 .count(),
6224 0
6225 );
6226 });
6227
6228 // The renamed file's version resets after changing language server.
6229 rust_buffer2.update(cx, |buffer, cx| buffer.edit([(0..0, "// ")], cx));
6230 assert_eq!(
6231 fake_json_server
6232 .receive_notification::<lsp::notification::DidChangeTextDocument>()
6233 .await
6234 .text_document,
6235 lsp::VersionedTextDocumentIdentifier::new(
6236 lsp::Url::from_file_path("/the-root/test3.json").unwrap(),
6237 1
6238 )
6239 );
6240
6241 // Restart language servers
6242 project.update(cx, |project, cx| {
6243 project.restart_language_servers_for_buffers(
6244 vec![rust_buffer.clone(), json_buffer.clone()],
6245 cx,
6246 );
6247 });
6248
6249 let mut rust_shutdown_requests = fake_rust_server
6250 .handle_request::<lsp::request::Shutdown, _, _>(|_, _| future::ready(Ok(())));
6251 let mut json_shutdown_requests = fake_json_server
6252 .handle_request::<lsp::request::Shutdown, _, _>(|_, _| future::ready(Ok(())));
6253 futures::join!(rust_shutdown_requests.next(), json_shutdown_requests.next());
6254
6255 let mut fake_rust_server = fake_rust_servers.next().await.unwrap();
6256 let mut fake_json_server = fake_json_servers.next().await.unwrap();
6257
6258 // Ensure rust document is reopened in new rust language server
6259 assert_eq!(
6260 fake_rust_server
6261 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6262 .await
6263 .text_document,
6264 lsp::TextDocumentItem {
6265 uri: lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
6266 version: 1,
6267 text: rust_buffer.read_with(cx, |buffer, _| buffer.text()),
6268 language_id: Default::default()
6269 }
6270 );
6271
6272 // Ensure json documents are reopened in new json language server
6273 assert_set_eq!(
6274 [
6275 fake_json_server
6276 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6277 .await
6278 .text_document,
6279 fake_json_server
6280 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6281 .await
6282 .text_document,
6283 ],
6284 [
6285 lsp::TextDocumentItem {
6286 uri: lsp::Url::from_file_path("/the-root/package.json").unwrap(),
6287 version: 0,
6288 text: json_buffer.read_with(cx, |buffer, _| buffer.text()),
6289 language_id: Default::default()
6290 },
6291 lsp::TextDocumentItem {
6292 uri: lsp::Url::from_file_path("/the-root/test3.json").unwrap(),
6293 version: 1,
6294 text: rust_buffer2.read_with(cx, |buffer, _| buffer.text()),
6295 language_id: Default::default()
6296 }
6297 ]
6298 );
6299
6300 // Close notifications are reported only to servers matching the buffer's language.
6301 cx.update(|_| drop(json_buffer));
6302 let close_message = lsp::DidCloseTextDocumentParams {
6303 text_document: lsp::TextDocumentIdentifier::new(
6304 lsp::Url::from_file_path("/the-root/package.json").unwrap(),
6305 ),
6306 };
6307 assert_eq!(
6308 fake_json_server
6309 .receive_notification::<lsp::notification::DidCloseTextDocument>()
6310 .await,
6311 close_message,
6312 );
6313 }
6314
6315 #[gpui::test]
6316 async fn test_single_file_worktrees_diagnostics(cx: &mut gpui::TestAppContext) {
6317 cx.foreground().forbid_parking();
6318
6319 let fs = FakeFs::new(cx.background());
6320 fs.insert_tree(
6321 "/dir",
6322 json!({
6323 "a.rs": "let a = 1;",
6324 "b.rs": "let b = 2;"
6325 }),
6326 )
6327 .await;
6328
6329 let project = Project::test(fs, ["/dir/a.rs".as_ref(), "/dir/b.rs".as_ref()], cx).await;
6330
6331 let buffer_a = project
6332 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
6333 .await
6334 .unwrap();
6335 let buffer_b = project
6336 .update(cx, |project, cx| project.open_local_buffer("/dir/b.rs", cx))
6337 .await
6338 .unwrap();
6339
6340 project.update(cx, |project, cx| {
6341 project
6342 .update_diagnostics(
6343 0,
6344 lsp::PublishDiagnosticsParams {
6345 uri: Url::from_file_path("/dir/a.rs").unwrap(),
6346 version: None,
6347 diagnostics: vec![lsp::Diagnostic {
6348 range: lsp::Range::new(
6349 lsp::Position::new(0, 4),
6350 lsp::Position::new(0, 5),
6351 ),
6352 severity: Some(lsp::DiagnosticSeverity::ERROR),
6353 message: "error 1".to_string(),
6354 ..Default::default()
6355 }],
6356 },
6357 &[],
6358 cx,
6359 )
6360 .unwrap();
6361 project
6362 .update_diagnostics(
6363 0,
6364 lsp::PublishDiagnosticsParams {
6365 uri: Url::from_file_path("/dir/b.rs").unwrap(),
6366 version: None,
6367 diagnostics: vec![lsp::Diagnostic {
6368 range: lsp::Range::new(
6369 lsp::Position::new(0, 4),
6370 lsp::Position::new(0, 5),
6371 ),
6372 severity: Some(lsp::DiagnosticSeverity::WARNING),
6373 message: "error 2".to_string(),
6374 ..Default::default()
6375 }],
6376 },
6377 &[],
6378 cx,
6379 )
6380 .unwrap();
6381 });
6382
6383 buffer_a.read_with(cx, |buffer, _| {
6384 let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
6385 assert_eq!(
6386 chunks
6387 .iter()
6388 .map(|(s, d)| (s.as_str(), *d))
6389 .collect::<Vec<_>>(),
6390 &[
6391 ("let ", None),
6392 ("a", Some(DiagnosticSeverity::ERROR)),
6393 (" = 1;", None),
6394 ]
6395 );
6396 });
6397 buffer_b.read_with(cx, |buffer, _| {
6398 let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
6399 assert_eq!(
6400 chunks
6401 .iter()
6402 .map(|(s, d)| (s.as_str(), *d))
6403 .collect::<Vec<_>>(),
6404 &[
6405 ("let ", None),
6406 ("b", Some(DiagnosticSeverity::WARNING)),
6407 (" = 2;", None),
6408 ]
6409 );
6410 });
6411 }
6412
6413 #[gpui::test]
6414 async fn test_hidden_worktrees_diagnostics(cx: &mut gpui::TestAppContext) {
6415 cx.foreground().forbid_parking();
6416
6417 let fs = FakeFs::new(cx.background());
6418 fs.insert_tree(
6419 "/root",
6420 json!({
6421 "dir": {
6422 "a.rs": "let a = 1;",
6423 },
6424 "other.rs": "let b = c;"
6425 }),
6426 )
6427 .await;
6428
6429 let project = Project::test(fs, ["/root/dir".as_ref()], cx).await;
6430
6431 let (worktree, _) = project
6432 .update(cx, |project, cx| {
6433 project.find_or_create_local_worktree("/root/other.rs", false, cx)
6434 })
6435 .await
6436 .unwrap();
6437 let worktree_id = worktree.read_with(cx, |tree, _| tree.id());
6438
6439 project.update(cx, |project, cx| {
6440 project
6441 .update_diagnostics(
6442 0,
6443 lsp::PublishDiagnosticsParams {
6444 uri: Url::from_file_path("/root/other.rs").unwrap(),
6445 version: None,
6446 diagnostics: vec![lsp::Diagnostic {
6447 range: lsp::Range::new(
6448 lsp::Position::new(0, 8),
6449 lsp::Position::new(0, 9),
6450 ),
6451 severity: Some(lsp::DiagnosticSeverity::ERROR),
6452 message: "unknown variable 'c'".to_string(),
6453 ..Default::default()
6454 }],
6455 },
6456 &[],
6457 cx,
6458 )
6459 .unwrap();
6460 });
6461
6462 let buffer = project
6463 .update(cx, |project, cx| project.open_buffer((worktree_id, ""), cx))
6464 .await
6465 .unwrap();
6466 buffer.read_with(cx, |buffer, _| {
6467 let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
6468 assert_eq!(
6469 chunks
6470 .iter()
6471 .map(|(s, d)| (s.as_str(), *d))
6472 .collect::<Vec<_>>(),
6473 &[
6474 ("let b = ", None),
6475 ("c", Some(DiagnosticSeverity::ERROR)),
6476 (";", None),
6477 ]
6478 );
6479 });
6480
6481 project.read_with(cx, |project, cx| {
6482 assert_eq!(project.diagnostic_summaries(cx).next(), None);
6483 assert_eq!(project.diagnostic_summary(cx).error_count, 0);
6484 });
6485 }
6486
6487 #[gpui::test]
6488 async fn test_disk_based_diagnostics_progress(cx: &mut gpui::TestAppContext) {
6489 cx.foreground().forbid_parking();
6490
6491 let progress_token = "the-progress-token";
6492 let mut language = Language::new(
6493 LanguageConfig {
6494 name: "Rust".into(),
6495 path_suffixes: vec!["rs".to_string()],
6496 ..Default::default()
6497 },
6498 Some(tree_sitter_rust::language()),
6499 );
6500 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
6501 disk_based_diagnostics_progress_token: Some(progress_token),
6502 disk_based_diagnostics_sources: &["disk"],
6503 ..Default::default()
6504 });
6505
6506 let fs = FakeFs::new(cx.background());
6507 fs.insert_tree(
6508 "/dir",
6509 json!({
6510 "a.rs": "fn a() { A }",
6511 "b.rs": "const y: i32 = 1",
6512 }),
6513 )
6514 .await;
6515
6516 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6517 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6518 let worktree_id =
6519 project.read_with(cx, |p, cx| p.worktrees(cx).next().unwrap().read(cx).id());
6520
6521 // Cause worktree to start the fake language server
6522 let _buffer = project
6523 .update(cx, |project, cx| project.open_local_buffer("/dir/b.rs", cx))
6524 .await
6525 .unwrap();
6526
6527 let mut events = subscribe(&project, cx);
6528
6529 let fake_server = fake_servers.next().await.unwrap();
6530 fake_server.start_progress(progress_token).await;
6531 assert_eq!(
6532 events.next().await.unwrap(),
6533 Event::DiskBasedDiagnosticsStarted {
6534 language_server_id: 0,
6535 }
6536 );
6537
6538 fake_server.notify::<lsp::notification::PublishDiagnostics>(
6539 lsp::PublishDiagnosticsParams {
6540 uri: Url::from_file_path("/dir/a.rs").unwrap(),
6541 version: None,
6542 diagnostics: vec![lsp::Diagnostic {
6543 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
6544 severity: Some(lsp::DiagnosticSeverity::ERROR),
6545 message: "undefined variable 'A'".to_string(),
6546 ..Default::default()
6547 }],
6548 },
6549 );
6550 assert_eq!(
6551 events.next().await.unwrap(),
6552 Event::DiagnosticsUpdated {
6553 language_server_id: 0,
6554 path: (worktree_id, Path::new("a.rs")).into()
6555 }
6556 );
6557
6558 fake_server.end_progress(progress_token);
6559 assert_eq!(
6560 events.next().await.unwrap(),
6561 Event::DiskBasedDiagnosticsFinished {
6562 language_server_id: 0
6563 }
6564 );
6565
6566 let buffer = project
6567 .update(cx, |p, cx| p.open_local_buffer("/dir/a.rs", cx))
6568 .await
6569 .unwrap();
6570
6571 buffer.read_with(cx, |buffer, _| {
6572 let snapshot = buffer.snapshot();
6573 let diagnostics = snapshot
6574 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
6575 .collect::<Vec<_>>();
6576 assert_eq!(
6577 diagnostics,
6578 &[DiagnosticEntry {
6579 range: Point::new(0, 9)..Point::new(0, 10),
6580 diagnostic: Diagnostic {
6581 severity: lsp::DiagnosticSeverity::ERROR,
6582 message: "undefined variable 'A'".to_string(),
6583 group_id: 0,
6584 is_primary: true,
6585 ..Default::default()
6586 }
6587 }]
6588 )
6589 });
6590
6591 // Ensure publishing empty diagnostics twice only results in one update event.
6592 fake_server.notify::<lsp::notification::PublishDiagnostics>(
6593 lsp::PublishDiagnosticsParams {
6594 uri: Url::from_file_path("/dir/a.rs").unwrap(),
6595 version: None,
6596 diagnostics: Default::default(),
6597 },
6598 );
6599 assert_eq!(
6600 events.next().await.unwrap(),
6601 Event::DiagnosticsUpdated {
6602 language_server_id: 0,
6603 path: (worktree_id, Path::new("a.rs")).into()
6604 }
6605 );
6606
6607 fake_server.notify::<lsp::notification::PublishDiagnostics>(
6608 lsp::PublishDiagnosticsParams {
6609 uri: Url::from_file_path("/dir/a.rs").unwrap(),
6610 version: None,
6611 diagnostics: Default::default(),
6612 },
6613 );
6614 cx.foreground().run_until_parked();
6615 assert_eq!(futures::poll!(events.next()), Poll::Pending);
6616 }
6617
6618 #[gpui::test]
6619 async fn test_restarting_server_with_diagnostics_running(cx: &mut gpui::TestAppContext) {
6620 cx.foreground().forbid_parking();
6621
6622 let progress_token = "the-progress-token";
6623 let mut language = Language::new(
6624 LanguageConfig {
6625 path_suffixes: vec!["rs".to_string()],
6626 ..Default::default()
6627 },
6628 None,
6629 );
6630 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
6631 disk_based_diagnostics_sources: &["disk"],
6632 disk_based_diagnostics_progress_token: Some(progress_token),
6633 ..Default::default()
6634 });
6635
6636 let fs = FakeFs::new(cx.background());
6637 fs.insert_tree("/dir", json!({ "a.rs": "" })).await;
6638
6639 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6640 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6641
6642 let buffer = project
6643 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
6644 .await
6645 .unwrap();
6646
6647 // Simulate diagnostics starting to update.
6648 let fake_server = fake_servers.next().await.unwrap();
6649 fake_server.start_progress(progress_token).await;
6650
6651 // Restart the server before the diagnostics finish updating.
6652 project.update(cx, |project, cx| {
6653 project.restart_language_servers_for_buffers([buffer], cx);
6654 });
6655 let mut events = subscribe(&project, cx);
6656
6657 // Simulate the newly started server sending more diagnostics.
6658 let fake_server = fake_servers.next().await.unwrap();
6659 fake_server.start_progress(progress_token).await;
6660 assert_eq!(
6661 events.next().await.unwrap(),
6662 Event::DiskBasedDiagnosticsStarted {
6663 language_server_id: 1
6664 }
6665 );
6666 project.read_with(cx, |project, _| {
6667 assert_eq!(
6668 project
6669 .language_servers_running_disk_based_diagnostics()
6670 .collect::<Vec<_>>(),
6671 [1]
6672 );
6673 });
6674
6675 // All diagnostics are considered done, despite the old server's diagnostic
6676 // task never completing.
6677 fake_server.end_progress(progress_token);
6678 assert_eq!(
6679 events.next().await.unwrap(),
6680 Event::DiskBasedDiagnosticsFinished {
6681 language_server_id: 1
6682 }
6683 );
6684 project.read_with(cx, |project, _| {
6685 assert_eq!(
6686 project
6687 .language_servers_running_disk_based_diagnostics()
6688 .collect::<Vec<_>>(),
6689 [0; 0]
6690 );
6691 });
6692 }
6693
6694 #[gpui::test]
6695 async fn test_toggling_enable_language_server(
6696 deterministic: Arc<Deterministic>,
6697 cx: &mut gpui::TestAppContext,
6698 ) {
6699 deterministic.forbid_parking();
6700
6701 let mut rust = Language::new(
6702 LanguageConfig {
6703 name: Arc::from("Rust"),
6704 path_suffixes: vec!["rs".to_string()],
6705 ..Default::default()
6706 },
6707 None,
6708 );
6709 let mut fake_rust_servers = rust.set_fake_lsp_adapter(FakeLspAdapter {
6710 name: "rust-lsp",
6711 ..Default::default()
6712 });
6713 let mut js = Language::new(
6714 LanguageConfig {
6715 name: Arc::from("JavaScript"),
6716 path_suffixes: vec!["js".to_string()],
6717 ..Default::default()
6718 },
6719 None,
6720 );
6721 let mut fake_js_servers = js.set_fake_lsp_adapter(FakeLspAdapter {
6722 name: "js-lsp",
6723 ..Default::default()
6724 });
6725
6726 let fs = FakeFs::new(cx.background());
6727 fs.insert_tree("/dir", json!({ "a.rs": "", "b.js": "" }))
6728 .await;
6729
6730 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6731 project.update(cx, |project, _| {
6732 project.languages.add(Arc::new(rust));
6733 project.languages.add(Arc::new(js));
6734 });
6735
6736 let _rs_buffer = project
6737 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
6738 .await
6739 .unwrap();
6740 let _js_buffer = project
6741 .update(cx, |project, cx| project.open_local_buffer("/dir/b.js", cx))
6742 .await
6743 .unwrap();
6744
6745 let mut fake_rust_server_1 = fake_rust_servers.next().await.unwrap();
6746 assert_eq!(
6747 fake_rust_server_1
6748 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6749 .await
6750 .text_document
6751 .uri
6752 .as_str(),
6753 "file:///dir/a.rs"
6754 );
6755
6756 let mut fake_js_server = fake_js_servers.next().await.unwrap();
6757 assert_eq!(
6758 fake_js_server
6759 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6760 .await
6761 .text_document
6762 .uri
6763 .as_str(),
6764 "file:///dir/b.js"
6765 );
6766
6767 // Disable Rust language server, ensuring only that server gets stopped.
6768 cx.update(|cx| {
6769 cx.update_global(|settings: &mut Settings, _| {
6770 settings.language_overrides.insert(
6771 Arc::from("Rust"),
6772 settings::LanguageSettings {
6773 enable_language_server: Some(false),
6774 ..Default::default()
6775 },
6776 );
6777 })
6778 });
6779 fake_rust_server_1
6780 .receive_notification::<lsp::notification::Exit>()
6781 .await;
6782
6783 // Enable Rust and disable JavaScript language servers, ensuring that the
6784 // former gets started again and that the latter stops.
6785 cx.update(|cx| {
6786 cx.update_global(|settings: &mut Settings, _| {
6787 settings.language_overrides.insert(
6788 Arc::from("Rust"),
6789 settings::LanguageSettings {
6790 enable_language_server: Some(true),
6791 ..Default::default()
6792 },
6793 );
6794 settings.language_overrides.insert(
6795 Arc::from("JavaScript"),
6796 settings::LanguageSettings {
6797 enable_language_server: Some(false),
6798 ..Default::default()
6799 },
6800 );
6801 })
6802 });
6803 let mut fake_rust_server_2 = fake_rust_servers.next().await.unwrap();
6804 assert_eq!(
6805 fake_rust_server_2
6806 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6807 .await
6808 .text_document
6809 .uri
6810 .as_str(),
6811 "file:///dir/a.rs"
6812 );
6813 fake_js_server
6814 .receive_notification::<lsp::notification::Exit>()
6815 .await;
6816 }
6817
6818 #[gpui::test]
6819 async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
6820 cx.foreground().forbid_parking();
6821
6822 let mut language = Language::new(
6823 LanguageConfig {
6824 name: "Rust".into(),
6825 path_suffixes: vec!["rs".to_string()],
6826 ..Default::default()
6827 },
6828 Some(tree_sitter_rust::language()),
6829 );
6830 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
6831 disk_based_diagnostics_sources: &["disk"],
6832 ..Default::default()
6833 });
6834
6835 let text = "
6836 fn a() { A }
6837 fn b() { BB }
6838 fn c() { CCC }
6839 "
6840 .unindent();
6841
6842 let fs = FakeFs::new(cx.background());
6843 fs.insert_tree("/dir", json!({ "a.rs": text })).await;
6844
6845 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6846 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6847
6848 let buffer = project
6849 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
6850 .await
6851 .unwrap();
6852
6853 let mut fake_server = fake_servers.next().await.unwrap();
6854 let open_notification = fake_server
6855 .receive_notification::<lsp::notification::DidOpenTextDocument>()
6856 .await;
6857
6858 // Edit the buffer, moving the content down
6859 buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "\n\n")], cx));
6860 let change_notification_1 = fake_server
6861 .receive_notification::<lsp::notification::DidChangeTextDocument>()
6862 .await;
6863 assert!(
6864 change_notification_1.text_document.version > open_notification.text_document.version
6865 );
6866
6867 // Report some diagnostics for the initial version of the buffer
6868 fake_server.notify::<lsp::notification::PublishDiagnostics>(
6869 lsp::PublishDiagnosticsParams {
6870 uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
6871 version: Some(open_notification.text_document.version),
6872 diagnostics: vec![
6873 lsp::Diagnostic {
6874 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
6875 severity: Some(DiagnosticSeverity::ERROR),
6876 message: "undefined variable 'A'".to_string(),
6877 source: Some("disk".to_string()),
6878 ..Default::default()
6879 },
6880 lsp::Diagnostic {
6881 range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 11)),
6882 severity: Some(DiagnosticSeverity::ERROR),
6883 message: "undefined variable 'BB'".to_string(),
6884 source: Some("disk".to_string()),
6885 ..Default::default()
6886 },
6887 lsp::Diagnostic {
6888 range: lsp::Range::new(lsp::Position::new(2, 9), lsp::Position::new(2, 12)),
6889 severity: Some(DiagnosticSeverity::ERROR),
6890 source: Some("disk".to_string()),
6891 message: "undefined variable 'CCC'".to_string(),
6892 ..Default::default()
6893 },
6894 ],
6895 },
6896 );
6897
6898 // The diagnostics have moved down since they were created.
6899 buffer.next_notification(cx).await;
6900 buffer.read_with(cx, |buffer, _| {
6901 assert_eq!(
6902 buffer
6903 .snapshot()
6904 .diagnostics_in_range::<_, Point>(Point::new(3, 0)..Point::new(5, 0), false)
6905 .collect::<Vec<_>>(),
6906 &[
6907 DiagnosticEntry {
6908 range: Point::new(3, 9)..Point::new(3, 11),
6909 diagnostic: Diagnostic {
6910 severity: DiagnosticSeverity::ERROR,
6911 message: "undefined variable 'BB'".to_string(),
6912 is_disk_based: true,
6913 group_id: 1,
6914 is_primary: true,
6915 ..Default::default()
6916 },
6917 },
6918 DiagnosticEntry {
6919 range: Point::new(4, 9)..Point::new(4, 12),
6920 diagnostic: Diagnostic {
6921 severity: DiagnosticSeverity::ERROR,
6922 message: "undefined variable 'CCC'".to_string(),
6923 is_disk_based: true,
6924 group_id: 2,
6925 is_primary: true,
6926 ..Default::default()
6927 }
6928 }
6929 ]
6930 );
6931 assert_eq!(
6932 chunks_with_diagnostics(buffer, 0..buffer.len()),
6933 [
6934 ("\n\nfn a() { ".to_string(), None),
6935 ("A".to_string(), Some(DiagnosticSeverity::ERROR)),
6936 (" }\nfn b() { ".to_string(), None),
6937 ("BB".to_string(), Some(DiagnosticSeverity::ERROR)),
6938 (" }\nfn c() { ".to_string(), None),
6939 ("CCC".to_string(), Some(DiagnosticSeverity::ERROR)),
6940 (" }\n".to_string(), None),
6941 ]
6942 );
6943 assert_eq!(
6944 chunks_with_diagnostics(buffer, Point::new(3, 10)..Point::new(4, 11)),
6945 [
6946 ("B".to_string(), Some(DiagnosticSeverity::ERROR)),
6947 (" }\nfn c() { ".to_string(), None),
6948 ("CC".to_string(), Some(DiagnosticSeverity::ERROR)),
6949 ]
6950 );
6951 });
6952
6953 // Ensure overlapping diagnostics are highlighted correctly.
6954 fake_server.notify::<lsp::notification::PublishDiagnostics>(
6955 lsp::PublishDiagnosticsParams {
6956 uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
6957 version: Some(open_notification.text_document.version),
6958 diagnostics: vec![
6959 lsp::Diagnostic {
6960 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
6961 severity: Some(DiagnosticSeverity::ERROR),
6962 message: "undefined variable 'A'".to_string(),
6963 source: Some("disk".to_string()),
6964 ..Default::default()
6965 },
6966 lsp::Diagnostic {
6967 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 12)),
6968 severity: Some(DiagnosticSeverity::WARNING),
6969 message: "unreachable statement".to_string(),
6970 source: Some("disk".to_string()),
6971 ..Default::default()
6972 },
6973 ],
6974 },
6975 );
6976
6977 buffer.next_notification(cx).await;
6978 buffer.read_with(cx, |buffer, _| {
6979 assert_eq!(
6980 buffer
6981 .snapshot()
6982 .diagnostics_in_range::<_, Point>(Point::new(2, 0)..Point::new(3, 0), false)
6983 .collect::<Vec<_>>(),
6984 &[
6985 DiagnosticEntry {
6986 range: Point::new(2, 9)..Point::new(2, 12),
6987 diagnostic: Diagnostic {
6988 severity: DiagnosticSeverity::WARNING,
6989 message: "unreachable statement".to_string(),
6990 is_disk_based: true,
6991 group_id: 4,
6992 is_primary: true,
6993 ..Default::default()
6994 }
6995 },
6996 DiagnosticEntry {
6997 range: Point::new(2, 9)..Point::new(2, 10),
6998 diagnostic: Diagnostic {
6999 severity: DiagnosticSeverity::ERROR,
7000 message: "undefined variable 'A'".to_string(),
7001 is_disk_based: true,
7002 group_id: 3,
7003 is_primary: true,
7004 ..Default::default()
7005 },
7006 }
7007 ]
7008 );
7009 assert_eq!(
7010 chunks_with_diagnostics(buffer, Point::new(2, 0)..Point::new(3, 0)),
7011 [
7012 ("fn a() { ".to_string(), None),
7013 ("A".to_string(), Some(DiagnosticSeverity::ERROR)),
7014 (" }".to_string(), Some(DiagnosticSeverity::WARNING)),
7015 ("\n".to_string(), None),
7016 ]
7017 );
7018 assert_eq!(
7019 chunks_with_diagnostics(buffer, Point::new(2, 10)..Point::new(3, 0)),
7020 [
7021 (" }".to_string(), Some(DiagnosticSeverity::WARNING)),
7022 ("\n".to_string(), None),
7023 ]
7024 );
7025 });
7026
7027 // Keep editing the buffer and ensure disk-based diagnostics get translated according to the
7028 // changes since the last save.
7029 buffer.update(cx, |buffer, cx| {
7030 buffer.edit([(Point::new(2, 0)..Point::new(2, 0), " ")], cx);
7031 buffer.edit([(Point::new(2, 8)..Point::new(2, 10), "(x: usize)")], cx);
7032 buffer.edit([(Point::new(3, 10)..Point::new(3, 10), "xxx")], cx);
7033 });
7034 let change_notification_2 = fake_server
7035 .receive_notification::<lsp::notification::DidChangeTextDocument>()
7036 .await;
7037 assert!(
7038 change_notification_2.text_document.version
7039 > change_notification_1.text_document.version
7040 );
7041
7042 // Handle out-of-order diagnostics
7043 fake_server.notify::<lsp::notification::PublishDiagnostics>(
7044 lsp::PublishDiagnosticsParams {
7045 uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
7046 version: Some(change_notification_2.text_document.version),
7047 diagnostics: vec![
7048 lsp::Diagnostic {
7049 range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 11)),
7050 severity: Some(DiagnosticSeverity::ERROR),
7051 message: "undefined variable 'BB'".to_string(),
7052 source: Some("disk".to_string()),
7053 ..Default::default()
7054 },
7055 lsp::Diagnostic {
7056 range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
7057 severity: Some(DiagnosticSeverity::WARNING),
7058 message: "undefined variable 'A'".to_string(),
7059 source: Some("disk".to_string()),
7060 ..Default::default()
7061 },
7062 ],
7063 },
7064 );
7065
7066 buffer.next_notification(cx).await;
7067 buffer.read_with(cx, |buffer, _| {
7068 assert_eq!(
7069 buffer
7070 .snapshot()
7071 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
7072 .collect::<Vec<_>>(),
7073 &[
7074 DiagnosticEntry {
7075 range: Point::new(2, 21)..Point::new(2, 22),
7076 diagnostic: Diagnostic {
7077 severity: DiagnosticSeverity::WARNING,
7078 message: "undefined variable 'A'".to_string(),
7079 is_disk_based: true,
7080 group_id: 6,
7081 is_primary: true,
7082 ..Default::default()
7083 }
7084 },
7085 DiagnosticEntry {
7086 range: Point::new(3, 9)..Point::new(3, 14),
7087 diagnostic: Diagnostic {
7088 severity: DiagnosticSeverity::ERROR,
7089 message: "undefined variable 'BB'".to_string(),
7090 is_disk_based: true,
7091 group_id: 5,
7092 is_primary: true,
7093 ..Default::default()
7094 },
7095 }
7096 ]
7097 );
7098 });
7099 }
7100
7101 #[gpui::test]
7102 async fn test_empty_diagnostic_ranges(cx: &mut gpui::TestAppContext) {
7103 cx.foreground().forbid_parking();
7104
7105 let text = concat!(
7106 "let one = ;\n", //
7107 "let two = \n",
7108 "let three = 3;\n",
7109 );
7110
7111 let fs = FakeFs::new(cx.background());
7112 fs.insert_tree("/dir", json!({ "a.rs": text })).await;
7113
7114 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
7115 let buffer = project
7116 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
7117 .await
7118 .unwrap();
7119
7120 project.update(cx, |project, cx| {
7121 project
7122 .update_buffer_diagnostics(
7123 &buffer,
7124 vec![
7125 DiagnosticEntry {
7126 range: PointUtf16::new(0, 10)..PointUtf16::new(0, 10),
7127 diagnostic: Diagnostic {
7128 severity: DiagnosticSeverity::ERROR,
7129 message: "syntax error 1".to_string(),
7130 ..Default::default()
7131 },
7132 },
7133 DiagnosticEntry {
7134 range: PointUtf16::new(1, 10)..PointUtf16::new(1, 10),
7135 diagnostic: Diagnostic {
7136 severity: DiagnosticSeverity::ERROR,
7137 message: "syntax error 2".to_string(),
7138 ..Default::default()
7139 },
7140 },
7141 ],
7142 None,
7143 cx,
7144 )
7145 .unwrap();
7146 });
7147
7148 // An empty range is extended forward to include the following character.
7149 // At the end of a line, an empty range is extended backward to include
7150 // the preceding character.
7151 buffer.read_with(cx, |buffer, _| {
7152 let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
7153 assert_eq!(
7154 chunks
7155 .iter()
7156 .map(|(s, d)| (s.as_str(), *d))
7157 .collect::<Vec<_>>(),
7158 &[
7159 ("let one = ", None),
7160 (";", Some(DiagnosticSeverity::ERROR)),
7161 ("\nlet two =", None),
7162 (" ", Some(DiagnosticSeverity::ERROR)),
7163 ("\nlet three = 3;\n", None)
7164 ]
7165 );
7166 });
7167 }
7168
7169 #[gpui::test]
7170 async fn test_edits_from_lsp_with_past_version(cx: &mut gpui::TestAppContext) {
7171 cx.foreground().forbid_parking();
7172
7173 let mut language = Language::new(
7174 LanguageConfig {
7175 name: "Rust".into(),
7176 path_suffixes: vec!["rs".to_string()],
7177 ..Default::default()
7178 },
7179 Some(tree_sitter_rust::language()),
7180 );
7181 let mut fake_servers = language.set_fake_lsp_adapter(Default::default());
7182
7183 let text = "
7184 fn a() {
7185 f1();
7186 }
7187 fn b() {
7188 f2();
7189 }
7190 fn c() {
7191 f3();
7192 }
7193 "
7194 .unindent();
7195
7196 let fs = FakeFs::new(cx.background());
7197 fs.insert_tree(
7198 "/dir",
7199 json!({
7200 "a.rs": text.clone(),
7201 }),
7202 )
7203 .await;
7204
7205 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
7206 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
7207 let buffer = project
7208 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
7209 .await
7210 .unwrap();
7211
7212 let mut fake_server = fake_servers.next().await.unwrap();
7213 let lsp_document_version = fake_server
7214 .receive_notification::<lsp::notification::DidOpenTextDocument>()
7215 .await
7216 .text_document
7217 .version;
7218
7219 // Simulate editing the buffer after the language server computes some edits.
7220 buffer.update(cx, |buffer, cx| {
7221 buffer.edit(
7222 [(
7223 Point::new(0, 0)..Point::new(0, 0),
7224 "// above first function\n",
7225 )],
7226 cx,
7227 );
7228 buffer.edit(
7229 [(
7230 Point::new(2, 0)..Point::new(2, 0),
7231 " // inside first function\n",
7232 )],
7233 cx,
7234 );
7235 buffer.edit(
7236 [(
7237 Point::new(6, 4)..Point::new(6, 4),
7238 "// inside second function ",
7239 )],
7240 cx,
7241 );
7242
7243 assert_eq!(
7244 buffer.text(),
7245 "
7246 // above first function
7247 fn a() {
7248 // inside first function
7249 f1();
7250 }
7251 fn b() {
7252 // inside second function f2();
7253 }
7254 fn c() {
7255 f3();
7256 }
7257 "
7258 .unindent()
7259 );
7260 });
7261
7262 let edits = project
7263 .update(cx, |project, cx| {
7264 project.edits_from_lsp(
7265 &buffer,
7266 vec![
7267 // replace body of first function
7268 lsp::TextEdit {
7269 range: lsp::Range::new(
7270 lsp::Position::new(0, 0),
7271 lsp::Position::new(3, 0),
7272 ),
7273 new_text: "
7274 fn a() {
7275 f10();
7276 }
7277 "
7278 .unindent(),
7279 },
7280 // edit inside second function
7281 lsp::TextEdit {
7282 range: lsp::Range::new(
7283 lsp::Position::new(4, 6),
7284 lsp::Position::new(4, 6),
7285 ),
7286 new_text: "00".into(),
7287 },
7288 // edit inside third function via two distinct edits
7289 lsp::TextEdit {
7290 range: lsp::Range::new(
7291 lsp::Position::new(7, 5),
7292 lsp::Position::new(7, 5),
7293 ),
7294 new_text: "4000".into(),
7295 },
7296 lsp::TextEdit {
7297 range: lsp::Range::new(
7298 lsp::Position::new(7, 5),
7299 lsp::Position::new(7, 6),
7300 ),
7301 new_text: "".into(),
7302 },
7303 ],
7304 Some(lsp_document_version),
7305 cx,
7306 )
7307 })
7308 .await
7309 .unwrap();
7310
7311 buffer.update(cx, |buffer, cx| {
7312 for (range, new_text) in edits {
7313 buffer.edit([(range, new_text)], cx);
7314 }
7315 assert_eq!(
7316 buffer.text(),
7317 "
7318 // above first function
7319 fn a() {
7320 // inside first function
7321 f10();
7322 }
7323 fn b() {
7324 // inside second function f200();
7325 }
7326 fn c() {
7327 f4000();
7328 }
7329 "
7330 .unindent()
7331 );
7332 });
7333 }
7334
7335 #[gpui::test]
7336 async fn test_edits_from_lsp_with_edits_on_adjacent_lines(cx: &mut gpui::TestAppContext) {
7337 cx.foreground().forbid_parking();
7338
7339 let text = "
7340 use a::b;
7341 use a::c;
7342
7343 fn f() {
7344 b();
7345 c();
7346 }
7347 "
7348 .unindent();
7349
7350 let fs = FakeFs::new(cx.background());
7351 fs.insert_tree(
7352 "/dir",
7353 json!({
7354 "a.rs": text.clone(),
7355 }),
7356 )
7357 .await;
7358
7359 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
7360 let buffer = project
7361 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
7362 .await
7363 .unwrap();
7364
7365 // Simulate the language server sending us a small edit in the form of a very large diff.
7366 // Rust-analyzer does this when performing a merge-imports code action.
7367 let edits = project
7368 .update(cx, |project, cx| {
7369 project.edits_from_lsp(
7370 &buffer,
7371 [
7372 // Replace the first use statement without editing the semicolon.
7373 lsp::TextEdit {
7374 range: lsp::Range::new(
7375 lsp::Position::new(0, 4),
7376 lsp::Position::new(0, 8),
7377 ),
7378 new_text: "a::{b, c}".into(),
7379 },
7380 // Reinsert the remainder of the file between the semicolon and the final
7381 // newline of the file.
7382 lsp::TextEdit {
7383 range: lsp::Range::new(
7384 lsp::Position::new(0, 9),
7385 lsp::Position::new(0, 9),
7386 ),
7387 new_text: "\n\n".into(),
7388 },
7389 lsp::TextEdit {
7390 range: lsp::Range::new(
7391 lsp::Position::new(0, 9),
7392 lsp::Position::new(0, 9),
7393 ),
7394 new_text: "
7395 fn f() {
7396 b();
7397 c();
7398 }"
7399 .unindent(),
7400 },
7401 // Delete everything after the first newline of the file.
7402 lsp::TextEdit {
7403 range: lsp::Range::new(
7404 lsp::Position::new(1, 0),
7405 lsp::Position::new(7, 0),
7406 ),
7407 new_text: "".into(),
7408 },
7409 ],
7410 None,
7411 cx,
7412 )
7413 })
7414 .await
7415 .unwrap();
7416
7417 buffer.update(cx, |buffer, cx| {
7418 let edits = edits
7419 .into_iter()
7420 .map(|(range, text)| {
7421 (
7422 range.start.to_point(&buffer)..range.end.to_point(&buffer),
7423 text,
7424 )
7425 })
7426 .collect::<Vec<_>>();
7427
7428 assert_eq!(
7429 edits,
7430 [
7431 (Point::new(0, 4)..Point::new(0, 8), "a::{b, c}".into()),
7432 (Point::new(1, 0)..Point::new(2, 0), "".into())
7433 ]
7434 );
7435
7436 for (range, new_text) in edits {
7437 buffer.edit([(range, new_text)], cx);
7438 }
7439 assert_eq!(
7440 buffer.text(),
7441 "
7442 use a::{b, c};
7443
7444 fn f() {
7445 b();
7446 c();
7447 }
7448 "
7449 .unindent()
7450 );
7451 });
7452 }
7453
7454 #[gpui::test]
7455 async fn test_invalid_edits_from_lsp(cx: &mut gpui::TestAppContext) {
7456 cx.foreground().forbid_parking();
7457
7458 let text = "
7459 use a::b;
7460 use a::c;
7461
7462 fn f() {
7463 b();
7464 c();
7465 }
7466 "
7467 .unindent();
7468
7469 let fs = FakeFs::new(cx.background());
7470 fs.insert_tree(
7471 "/dir",
7472 json!({
7473 "a.rs": text.clone(),
7474 }),
7475 )
7476 .await;
7477
7478 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
7479 let buffer = project
7480 .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
7481 .await
7482 .unwrap();
7483
7484 // Simulate the language server sending us edits in a non-ordered fashion,
7485 // with ranges sometimes being inverted.
7486 let edits = project
7487 .update(cx, |project, cx| {
7488 project.edits_from_lsp(
7489 &buffer,
7490 [
7491 lsp::TextEdit {
7492 range: lsp::Range::new(
7493 lsp::Position::new(0, 9),
7494 lsp::Position::new(0, 9),
7495 ),
7496 new_text: "\n\n".into(),
7497 },
7498 lsp::TextEdit {
7499 range: lsp::Range::new(
7500 lsp::Position::new(0, 8),
7501 lsp::Position::new(0, 4),
7502 ),
7503 new_text: "a::{b, c}".into(),
7504 },
7505 lsp::TextEdit {
7506 range: lsp::Range::new(
7507 lsp::Position::new(1, 0),
7508 lsp::Position::new(7, 0),
7509 ),
7510 new_text: "".into(),
7511 },
7512 lsp::TextEdit {
7513 range: lsp::Range::new(
7514 lsp::Position::new(0, 9),
7515 lsp::Position::new(0, 9),
7516 ),
7517 new_text: "
7518 fn f() {
7519 b();
7520 c();
7521 }"
7522 .unindent(),
7523 },
7524 ],
7525 None,
7526 cx,
7527 )
7528 })
7529 .await
7530 .unwrap();
7531
7532 buffer.update(cx, |buffer, cx| {
7533 let edits = edits
7534 .into_iter()
7535 .map(|(range, text)| {
7536 (
7537 range.start.to_point(&buffer)..range.end.to_point(&buffer),
7538 text,
7539 )
7540 })
7541 .collect::<Vec<_>>();
7542
7543 assert_eq!(
7544 edits,
7545 [
7546 (Point::new(0, 4)..Point::new(0, 8), "a::{b, c}".into()),
7547 (Point::new(1, 0)..Point::new(2, 0), "".into())
7548 ]
7549 );
7550
7551 for (range, new_text) in edits {
7552 buffer.edit([(range, new_text)], cx);
7553 }
7554 assert_eq!(
7555 buffer.text(),
7556 "
7557 use a::{b, c};
7558
7559 fn f() {
7560 b();
7561 c();
7562 }
7563 "
7564 .unindent()
7565 );
7566 });
7567 }
7568
7569 fn chunks_with_diagnostics<T: ToOffset + ToPoint>(
7570 buffer: &Buffer,
7571 range: Range<T>,
7572 ) -> Vec<(String, Option<DiagnosticSeverity>)> {
7573 let mut chunks: Vec<(String, Option<DiagnosticSeverity>)> = Vec::new();
7574 for chunk in buffer.snapshot().chunks(range, true) {
7575 if chunks.last().map_or(false, |prev_chunk| {
7576 prev_chunk.1 == chunk.diagnostic_severity
7577 }) {
7578 chunks.last_mut().unwrap().0.push_str(chunk.text);
7579 } else {
7580 chunks.push((chunk.text.to_string(), chunk.diagnostic_severity));
7581 }
7582 }
7583 chunks
7584 }
7585
7586 #[gpui::test]
7587 async fn test_search_worktree_without_files(cx: &mut gpui::TestAppContext) {
7588 let dir = temp_tree(json!({
7589 "root": {
7590 "dir1": {},
7591 "dir2": {
7592 "dir3": {}
7593 }
7594 }
7595 }));
7596
7597 let project = Project::test(Arc::new(RealFs), [dir.path()], cx).await;
7598 let cancel_flag = Default::default();
7599 let results = project
7600 .read_with(cx, |project, cx| {
7601 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
7602 })
7603 .await;
7604
7605 assert!(results.is_empty());
7606 }
7607
7608 #[gpui::test(iterations = 10)]
7609 async fn test_definition(cx: &mut gpui::TestAppContext) {
7610 let mut language = Language::new(
7611 LanguageConfig {
7612 name: "Rust".into(),
7613 path_suffixes: vec!["rs".to_string()],
7614 ..Default::default()
7615 },
7616 Some(tree_sitter_rust::language()),
7617 );
7618 let mut fake_servers = language.set_fake_lsp_adapter(Default::default());
7619
7620 let fs = FakeFs::new(cx.background());
7621 fs.insert_tree(
7622 "/dir",
7623 json!({
7624 "a.rs": "const fn a() { A }",
7625 "b.rs": "const y: i32 = crate::a()",
7626 }),
7627 )
7628 .await;
7629
7630 let project = Project::test(fs, ["/dir/b.rs".as_ref()], cx).await;
7631 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
7632
7633 let buffer = project
7634 .update(cx, |project, cx| project.open_local_buffer("/dir/b.rs", cx))
7635 .await
7636 .unwrap();
7637
7638 let fake_server = fake_servers.next().await.unwrap();
7639 fake_server.handle_request::<lsp::request::GotoDefinition, _, _>(|params, _| async move {
7640 let params = params.text_document_position_params;
7641 assert_eq!(
7642 params.text_document.uri.to_file_path().unwrap(),
7643 Path::new("/dir/b.rs"),
7644 );
7645 assert_eq!(params.position, lsp::Position::new(0, 22));
7646
7647 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
7648 lsp::Location::new(
7649 lsp::Url::from_file_path("/dir/a.rs").unwrap(),
7650 lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
7651 ),
7652 )))
7653 });
7654
7655 let mut definitions = project
7656 .update(cx, |project, cx| project.definition(&buffer, 22, cx))
7657 .await
7658 .unwrap();
7659
7660 assert_eq!(definitions.len(), 1);
7661 let definition = definitions.pop().unwrap();
7662 cx.update(|cx| {
7663 let target_buffer = definition.target.buffer.read(cx);
7664 assert_eq!(
7665 target_buffer
7666 .file()
7667 .unwrap()
7668 .as_local()
7669 .unwrap()
7670 .abs_path(cx),
7671 Path::new("/dir/a.rs"),
7672 );
7673 assert_eq!(definition.target.range.to_offset(target_buffer), 9..10);
7674 assert_eq!(
7675 list_worktrees(&project, cx),
7676 [("/dir/b.rs".as_ref(), true), ("/dir/a.rs".as_ref(), false)]
7677 );
7678
7679 drop(definition);
7680 });
7681 cx.read(|cx| {
7682 assert_eq!(list_worktrees(&project, cx), [("/dir/b.rs".as_ref(), true)]);
7683 });
7684
7685 fn list_worktrees<'a>(
7686 project: &'a ModelHandle<Project>,
7687 cx: &'a AppContext,
7688 ) -> Vec<(&'a Path, bool)> {
7689 project
7690 .read(cx)
7691 .worktrees(cx)
7692 .map(|worktree| {
7693 let worktree = worktree.read(cx);
7694 (
7695 worktree.as_local().unwrap().abs_path().as_ref(),
7696 worktree.is_visible(),
7697 )
7698 })
7699 .collect::<Vec<_>>()
7700 }
7701 }
7702
7703 #[gpui::test]
7704 async fn test_completions_without_edit_ranges(cx: &mut gpui::TestAppContext) {
7705 let mut language = Language::new(
7706 LanguageConfig {
7707 name: "TypeScript".into(),
7708 path_suffixes: vec!["ts".to_string()],
7709 ..Default::default()
7710 },
7711 Some(tree_sitter_typescript::language_typescript()),
7712 );
7713 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
7714
7715 let fs = FakeFs::new(cx.background());
7716 fs.insert_tree(
7717 "/dir",
7718 json!({
7719 "a.ts": "",
7720 }),
7721 )
7722 .await;
7723
7724 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
7725 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
7726 let buffer = project
7727 .update(cx, |p, cx| p.open_local_buffer("/dir/a.ts", cx))
7728 .await
7729 .unwrap();
7730
7731 let fake_server = fake_language_servers.next().await.unwrap();
7732
7733 let text = "let a = b.fqn";
7734 buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
7735 let completions = project.update(cx, |project, cx| {
7736 project.completions(&buffer, text.len(), cx)
7737 });
7738
7739 fake_server
7740 .handle_request::<lsp::request::Completion, _, _>(|_, _| async move {
7741 Ok(Some(lsp::CompletionResponse::Array(vec![
7742 lsp::CompletionItem {
7743 label: "fullyQualifiedName?".into(),
7744 insert_text: Some("fullyQualifiedName".into()),
7745 ..Default::default()
7746 },
7747 ])))
7748 })
7749 .next()
7750 .await;
7751 let completions = completions.await.unwrap();
7752 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
7753 assert_eq!(completions.len(), 1);
7754 assert_eq!(completions[0].new_text, "fullyQualifiedName");
7755 assert_eq!(
7756 completions[0].old_range.to_offset(&snapshot),
7757 text.len() - 3..text.len()
7758 );
7759
7760 let text = "let a = \"atoms/cmp\"";
7761 buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
7762 let completions = project.update(cx, |project, cx| {
7763 project.completions(&buffer, text.len() - 1, cx)
7764 });
7765
7766 fake_server
7767 .handle_request::<lsp::request::Completion, _, _>(|_, _| async move {
7768 Ok(Some(lsp::CompletionResponse::Array(vec![
7769 lsp::CompletionItem {
7770 label: "component".into(),
7771 ..Default::default()
7772 },
7773 ])))
7774 })
7775 .next()
7776 .await;
7777 let completions = completions.await.unwrap();
7778 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
7779 assert_eq!(completions.len(), 1);
7780 assert_eq!(completions[0].new_text, "component");
7781 assert_eq!(
7782 completions[0].old_range.to_offset(&snapshot),
7783 text.len() - 4..text.len() - 1
7784 );
7785 }
7786
7787 #[gpui::test(iterations = 10)]
7788 async fn test_apply_code_actions_with_commands(cx: &mut gpui::TestAppContext) {
7789 let mut language = Language::new(
7790 LanguageConfig {
7791 name: "TypeScript".into(),
7792 path_suffixes: vec!["ts".to_string()],
7793 ..Default::default()
7794 },
7795 None,
7796 );
7797 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
7798
7799 let fs = FakeFs::new(cx.background());
7800 fs.insert_tree(
7801 "/dir",
7802 json!({
7803 "a.ts": "a",
7804 }),
7805 )
7806 .await;
7807
7808 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
7809 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
7810 let buffer = project
7811 .update(cx, |p, cx| p.open_local_buffer("/dir/a.ts", cx))
7812 .await
7813 .unwrap();
7814
7815 let fake_server = fake_language_servers.next().await.unwrap();
7816
7817 // Language server returns code actions that contain commands, and not edits.
7818 let actions = project.update(cx, |project, cx| project.code_actions(&buffer, 0..0, cx));
7819 fake_server
7820 .handle_request::<lsp::request::CodeActionRequest, _, _>(|_, _| async move {
7821 Ok(Some(vec![
7822 lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
7823 title: "The code action".into(),
7824 command: Some(lsp::Command {
7825 title: "The command".into(),
7826 command: "_the/command".into(),
7827 arguments: Some(vec![json!("the-argument")]),
7828 }),
7829 ..Default::default()
7830 }),
7831 lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
7832 title: "two".into(),
7833 ..Default::default()
7834 }),
7835 ]))
7836 })
7837 .next()
7838 .await;
7839
7840 let action = actions.await.unwrap()[0].clone();
7841 let apply = project.update(cx, |project, cx| {
7842 project.apply_code_action(buffer.clone(), action, true, cx)
7843 });
7844
7845 // Resolving the code action does not populate its edits. In absence of
7846 // edits, we must execute the given command.
7847 fake_server.handle_request::<lsp::request::CodeActionResolveRequest, _, _>(
7848 |action, _| async move { Ok(action) },
7849 );
7850
7851 // While executing the command, the language server sends the editor
7852 // a `workspaceEdit` request.
7853 fake_server
7854 .handle_request::<lsp::request::ExecuteCommand, _, _>({
7855 let fake = fake_server.clone();
7856 move |params, _| {
7857 assert_eq!(params.command, "_the/command");
7858 let fake = fake.clone();
7859 async move {
7860 fake.server
7861 .request::<lsp::request::ApplyWorkspaceEdit>(
7862 lsp::ApplyWorkspaceEditParams {
7863 label: None,
7864 edit: lsp::WorkspaceEdit {
7865 changes: Some(
7866 [(
7867 lsp::Url::from_file_path("/dir/a.ts").unwrap(),
7868 vec![lsp::TextEdit {
7869 range: lsp::Range::new(
7870 lsp::Position::new(0, 0),
7871 lsp::Position::new(0, 0),
7872 ),
7873 new_text: "X".into(),
7874 }],
7875 )]
7876 .into_iter()
7877 .collect(),
7878 ),
7879 ..Default::default()
7880 },
7881 },
7882 )
7883 .await
7884 .unwrap();
7885 Ok(Some(json!(null)))
7886 }
7887 }
7888 })
7889 .next()
7890 .await;
7891
7892 // Applying the code action returns a project transaction containing the edits
7893 // sent by the language server in its `workspaceEdit` request.
7894 let transaction = apply.await.unwrap();
7895 assert!(transaction.0.contains_key(&buffer));
7896 buffer.update(cx, |buffer, cx| {
7897 assert_eq!(buffer.text(), "Xa");
7898 buffer.undo(cx);
7899 assert_eq!(buffer.text(), "a");
7900 });
7901 }
7902
7903 #[gpui::test]
7904 async fn test_save_file(cx: &mut gpui::TestAppContext) {
7905 let fs = FakeFs::new(cx.background());
7906 fs.insert_tree(
7907 "/dir",
7908 json!({
7909 "file1": "the old contents",
7910 }),
7911 )
7912 .await;
7913
7914 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
7915 let buffer = project
7916 .update(cx, |p, cx| p.open_local_buffer("/dir/file1", cx))
7917 .await
7918 .unwrap();
7919 buffer
7920 .update(cx, |buffer, cx| {
7921 assert_eq!(buffer.text(), "the old contents");
7922 buffer.edit([(0..0, "a line of text.\n".repeat(10 * 1024))], cx);
7923 buffer.save(cx)
7924 })
7925 .await
7926 .unwrap();
7927
7928 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
7929 assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
7930 }
7931
7932 #[gpui::test]
7933 async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) {
7934 let fs = FakeFs::new(cx.background());
7935 fs.insert_tree(
7936 "/dir",
7937 json!({
7938 "file1": "the old contents",
7939 }),
7940 )
7941 .await;
7942
7943 let project = Project::test(fs.clone(), ["/dir/file1".as_ref()], cx).await;
7944 let buffer = project
7945 .update(cx, |p, cx| p.open_local_buffer("/dir/file1", cx))
7946 .await
7947 .unwrap();
7948 buffer
7949 .update(cx, |buffer, cx| {
7950 buffer.edit([(0..0, "a line of text.\n".repeat(10 * 1024))], cx);
7951 buffer.save(cx)
7952 })
7953 .await
7954 .unwrap();
7955
7956 let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
7957 assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
7958 }
7959
7960 #[gpui::test]
7961 async fn test_save_as(cx: &mut gpui::TestAppContext) {
7962 let fs = FakeFs::new(cx.background());
7963 fs.insert_tree("/dir", json!({})).await;
7964
7965 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
7966 let buffer = project.update(cx, |project, cx| {
7967 project.create_buffer("", None, cx).unwrap()
7968 });
7969 buffer.update(cx, |buffer, cx| {
7970 buffer.edit([(0..0, "abc")], cx);
7971 assert!(buffer.is_dirty());
7972 assert!(!buffer.has_conflict());
7973 });
7974 project
7975 .update(cx, |project, cx| {
7976 project.save_buffer_as(buffer.clone(), "/dir/file1".into(), cx)
7977 })
7978 .await
7979 .unwrap();
7980 assert_eq!(fs.load(Path::new("/dir/file1")).await.unwrap(), "abc");
7981 buffer.read_with(cx, |buffer, cx| {
7982 assert_eq!(buffer.file().unwrap().full_path(cx), Path::new("dir/file1"));
7983 assert!(!buffer.is_dirty());
7984 assert!(!buffer.has_conflict());
7985 });
7986
7987 let opened_buffer = project
7988 .update(cx, |project, cx| {
7989 project.open_local_buffer("/dir/file1", cx)
7990 })
7991 .await
7992 .unwrap();
7993 assert_eq!(opened_buffer, buffer);
7994 }
7995
7996 #[gpui::test(retries = 5)]
7997 async fn test_rescan_and_remote_updates(cx: &mut gpui::TestAppContext) {
7998 let dir = temp_tree(json!({
7999 "a": {
8000 "file1": "",
8001 "file2": "",
8002 "file3": "",
8003 },
8004 "b": {
8005 "c": {
8006 "file4": "",
8007 "file5": "",
8008 }
8009 }
8010 }));
8011
8012 let project = Project::test(Arc::new(RealFs), [dir.path()], cx).await;
8013 let rpc = project.read_with(cx, |p, _| p.client.clone());
8014
8015 let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
8016 let buffer = project.update(cx, |p, cx| p.open_local_buffer(dir.path().join(path), cx));
8017 async move { buffer.await.unwrap() }
8018 };
8019 let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
8020 project.read_with(cx, |project, cx| {
8021 let tree = project.worktrees(cx).next().unwrap();
8022 tree.read(cx)
8023 .entry_for_path(path)
8024 .expect(&format!("no entry for path {}", path))
8025 .id
8026 })
8027 };
8028
8029 let buffer2 = buffer_for_path("a/file2", cx).await;
8030 let buffer3 = buffer_for_path("a/file3", cx).await;
8031 let buffer4 = buffer_for_path("b/c/file4", cx).await;
8032 let buffer5 = buffer_for_path("b/c/file5", cx).await;
8033
8034 let file2_id = id_for_path("a/file2", &cx);
8035 let file3_id = id_for_path("a/file3", &cx);
8036 let file4_id = id_for_path("b/c/file4", &cx);
8037
8038 // Create a remote copy of this worktree.
8039 let tree = project.read_with(cx, |project, cx| project.worktrees(cx).next().unwrap());
8040 let initial_snapshot = tree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
8041 let (remote, load_task) = cx.update(|cx| {
8042 Worktree::remote(
8043 1,
8044 1,
8045 initial_snapshot.to_proto(&Default::default(), true),
8046 rpc.clone(),
8047 cx,
8048 )
8049 });
8050 // tree
8051 load_task.await;
8052
8053 cx.read(|cx| {
8054 assert!(!buffer2.read(cx).is_dirty());
8055 assert!(!buffer3.read(cx).is_dirty());
8056 assert!(!buffer4.read(cx).is_dirty());
8057 assert!(!buffer5.read(cx).is_dirty());
8058 });
8059
8060 // Rename and delete files and directories.
8061 tree.flush_fs_events(&cx).await;
8062 std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
8063 std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
8064 std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
8065 std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
8066 tree.flush_fs_events(&cx).await;
8067
8068 let expected_paths = vec![
8069 "a",
8070 "a/file1",
8071 "a/file2.new",
8072 "b",
8073 "d",
8074 "d/file3",
8075 "d/file4",
8076 ];
8077
8078 cx.read(|app| {
8079 assert_eq!(
8080 tree.read(app)
8081 .paths()
8082 .map(|p| p.to_str().unwrap())
8083 .collect::<Vec<_>>(),
8084 expected_paths
8085 );
8086
8087 assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
8088 assert_eq!(id_for_path("d/file3", &cx), file3_id);
8089 assert_eq!(id_for_path("d/file4", &cx), file4_id);
8090
8091 assert_eq!(
8092 buffer2.read(app).file().unwrap().path().as_ref(),
8093 Path::new("a/file2.new")
8094 );
8095 assert_eq!(
8096 buffer3.read(app).file().unwrap().path().as_ref(),
8097 Path::new("d/file3")
8098 );
8099 assert_eq!(
8100 buffer4.read(app).file().unwrap().path().as_ref(),
8101 Path::new("d/file4")
8102 );
8103 assert_eq!(
8104 buffer5.read(app).file().unwrap().path().as_ref(),
8105 Path::new("b/c/file5")
8106 );
8107
8108 assert!(!buffer2.read(app).file().unwrap().is_deleted());
8109 assert!(!buffer3.read(app).file().unwrap().is_deleted());
8110 assert!(!buffer4.read(app).file().unwrap().is_deleted());
8111 assert!(buffer5.read(app).file().unwrap().is_deleted());
8112 });
8113
8114 // Update the remote worktree. Check that it becomes consistent with the
8115 // local worktree.
8116 remote.update(cx, |remote, cx| {
8117 let update_message = tree.read(cx).as_local().unwrap().snapshot().build_update(
8118 &initial_snapshot,
8119 1,
8120 1,
8121 true,
8122 );
8123 remote
8124 .as_remote_mut()
8125 .unwrap()
8126 .snapshot
8127 .apply_remote_update(update_message)
8128 .unwrap();
8129
8130 assert_eq!(
8131 remote
8132 .paths()
8133 .map(|p| p.to_str().unwrap())
8134 .collect::<Vec<_>>(),
8135 expected_paths
8136 );
8137 });
8138 }
8139
8140 #[gpui::test]
8141 async fn test_buffer_deduping(cx: &mut gpui::TestAppContext) {
8142 let fs = FakeFs::new(cx.background());
8143 fs.insert_tree(
8144 "/dir",
8145 json!({
8146 "a.txt": "a-contents",
8147 "b.txt": "b-contents",
8148 }),
8149 )
8150 .await;
8151
8152 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
8153
8154 // Spawn multiple tasks to open paths, repeating some paths.
8155 let (buffer_a_1, buffer_b, buffer_a_2) = project.update(cx, |p, cx| {
8156 (
8157 p.open_local_buffer("/dir/a.txt", cx),
8158 p.open_local_buffer("/dir/b.txt", cx),
8159 p.open_local_buffer("/dir/a.txt", cx),
8160 )
8161 });
8162
8163 let buffer_a_1 = buffer_a_1.await.unwrap();
8164 let buffer_a_2 = buffer_a_2.await.unwrap();
8165 let buffer_b = buffer_b.await.unwrap();
8166 assert_eq!(buffer_a_1.read_with(cx, |b, _| b.text()), "a-contents");
8167 assert_eq!(buffer_b.read_with(cx, |b, _| b.text()), "b-contents");
8168
8169 // There is only one buffer per path.
8170 let buffer_a_id = buffer_a_1.id();
8171 assert_eq!(buffer_a_2.id(), buffer_a_id);
8172
8173 // Open the same path again while it is still open.
8174 drop(buffer_a_1);
8175 let buffer_a_3 = project
8176 .update(cx, |p, cx| p.open_local_buffer("/dir/a.txt", cx))
8177 .await
8178 .unwrap();
8179
8180 // There's still only one buffer per path.
8181 assert_eq!(buffer_a_3.id(), buffer_a_id);
8182 }
8183
8184 #[gpui::test]
8185 async fn test_buffer_is_dirty(cx: &mut gpui::TestAppContext) {
8186 let fs = FakeFs::new(cx.background());
8187 fs.insert_tree(
8188 "/dir",
8189 json!({
8190 "file1": "abc",
8191 "file2": "def",
8192 "file3": "ghi",
8193 }),
8194 )
8195 .await;
8196
8197 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
8198
8199 let buffer1 = project
8200 .update(cx, |p, cx| p.open_local_buffer("/dir/file1", cx))
8201 .await
8202 .unwrap();
8203 let events = Rc::new(RefCell::new(Vec::new()));
8204
8205 // initially, the buffer isn't dirty.
8206 buffer1.update(cx, |buffer, cx| {
8207 cx.subscribe(&buffer1, {
8208 let events = events.clone();
8209 move |_, _, event, _| match event {
8210 BufferEvent::Operation(_) => {}
8211 _ => events.borrow_mut().push(event.clone()),
8212 }
8213 })
8214 .detach();
8215
8216 assert!(!buffer.is_dirty());
8217 assert!(events.borrow().is_empty());
8218
8219 buffer.edit([(1..2, "")], cx);
8220 });
8221
8222 // after the first edit, the buffer is dirty, and emits a dirtied event.
8223 buffer1.update(cx, |buffer, cx| {
8224 assert!(buffer.text() == "ac");
8225 assert!(buffer.is_dirty());
8226 assert_eq!(
8227 *events.borrow(),
8228 &[language::Event::Edited, language::Event::DirtyChanged]
8229 );
8230 events.borrow_mut().clear();
8231 buffer.did_save(
8232 buffer.version(),
8233 buffer.as_rope().fingerprint(),
8234 buffer.file().unwrap().mtime(),
8235 None,
8236 cx,
8237 );
8238 });
8239
8240 // after saving, the buffer is not dirty, and emits a saved event.
8241 buffer1.update(cx, |buffer, cx| {
8242 assert!(!buffer.is_dirty());
8243 assert_eq!(*events.borrow(), &[language::Event::Saved]);
8244 events.borrow_mut().clear();
8245
8246 buffer.edit([(1..1, "B")], cx);
8247 buffer.edit([(2..2, "D")], cx);
8248 });
8249
8250 // after editing again, the buffer is dirty, and emits another dirty event.
8251 buffer1.update(cx, |buffer, cx| {
8252 assert!(buffer.text() == "aBDc");
8253 assert!(buffer.is_dirty());
8254 assert_eq!(
8255 *events.borrow(),
8256 &[
8257 language::Event::Edited,
8258 language::Event::DirtyChanged,
8259 language::Event::Edited,
8260 ],
8261 );
8262 events.borrow_mut().clear();
8263
8264 // After restoring the buffer to its previously-saved state,
8265 // the buffer is not considered dirty anymore.
8266 buffer.edit([(1..3, "")], cx);
8267 assert!(buffer.text() == "ac");
8268 assert!(!buffer.is_dirty());
8269 });
8270
8271 assert_eq!(
8272 *events.borrow(),
8273 &[language::Event::Edited, language::Event::DirtyChanged]
8274 );
8275
8276 // When a file is deleted, the buffer is considered dirty.
8277 let events = Rc::new(RefCell::new(Vec::new()));
8278 let buffer2 = project
8279 .update(cx, |p, cx| p.open_local_buffer("/dir/file2", cx))
8280 .await
8281 .unwrap();
8282 buffer2.update(cx, |_, cx| {
8283 cx.subscribe(&buffer2, {
8284 let events = events.clone();
8285 move |_, _, event, _| events.borrow_mut().push(event.clone())
8286 })
8287 .detach();
8288 });
8289
8290 fs.remove_file("/dir/file2".as_ref(), Default::default())
8291 .await
8292 .unwrap();
8293 buffer2.condition(&cx, |b, _| b.is_dirty()).await;
8294 assert_eq!(
8295 *events.borrow(),
8296 &[
8297 language::Event::DirtyChanged,
8298 language::Event::FileHandleChanged
8299 ]
8300 );
8301
8302 // When a file is already dirty when deleted, we don't emit a Dirtied event.
8303 let events = Rc::new(RefCell::new(Vec::new()));
8304 let buffer3 = project
8305 .update(cx, |p, cx| p.open_local_buffer("/dir/file3", cx))
8306 .await
8307 .unwrap();
8308 buffer3.update(cx, |_, cx| {
8309 cx.subscribe(&buffer3, {
8310 let events = events.clone();
8311 move |_, _, event, _| events.borrow_mut().push(event.clone())
8312 })
8313 .detach();
8314 });
8315
8316 buffer3.update(cx, |buffer, cx| {
8317 buffer.edit([(0..0, "x")], cx);
8318 });
8319 events.borrow_mut().clear();
8320 fs.remove_file("/dir/file3".as_ref(), Default::default())
8321 .await
8322 .unwrap();
8323 buffer3
8324 .condition(&cx, |_, _| !events.borrow().is_empty())
8325 .await;
8326 assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
8327 cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
8328 }
8329
8330 #[gpui::test]
8331 async fn test_buffer_file_changes_on_disk(cx: &mut gpui::TestAppContext) {
8332 let initial_contents = "aaa\nbbbbb\nc\n";
8333 let fs = FakeFs::new(cx.background());
8334 fs.insert_tree(
8335 "/dir",
8336 json!({
8337 "the-file": initial_contents,
8338 }),
8339 )
8340 .await;
8341 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
8342 let buffer = project
8343 .update(cx, |p, cx| p.open_local_buffer("/dir/the-file", cx))
8344 .await
8345 .unwrap();
8346
8347 let anchors = (0..3)
8348 .map(|row| buffer.read_with(cx, |b, _| b.anchor_before(Point::new(row, 1))))
8349 .collect::<Vec<_>>();
8350
8351 // Change the file on disk, adding two new lines of text, and removing
8352 // one line.
8353 buffer.read_with(cx, |buffer, _| {
8354 assert!(!buffer.is_dirty());
8355 assert!(!buffer.has_conflict());
8356 });
8357 let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
8358 fs.save("/dir/the-file".as_ref(), &new_contents.into())
8359 .await
8360 .unwrap();
8361
8362 // Because the buffer was not modified, it is reloaded from disk. Its
8363 // contents are edited according to the diff between the old and new
8364 // file contents.
8365 buffer
8366 .condition(&cx, |buffer, _| buffer.text() == new_contents)
8367 .await;
8368
8369 buffer.update(cx, |buffer, _| {
8370 assert_eq!(buffer.text(), new_contents);
8371 assert!(!buffer.is_dirty());
8372 assert!(!buffer.has_conflict());
8373
8374 let anchor_positions = anchors
8375 .iter()
8376 .map(|anchor| anchor.to_point(&*buffer))
8377 .collect::<Vec<_>>();
8378 assert_eq!(
8379 anchor_positions,
8380 [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
8381 );
8382 });
8383
8384 // Modify the buffer
8385 buffer.update(cx, |buffer, cx| {
8386 buffer.edit([(0..0, " ")], cx);
8387 assert!(buffer.is_dirty());
8388 assert!(!buffer.has_conflict());
8389 });
8390
8391 // Change the file on disk again, adding blank lines to the beginning.
8392 fs.save(
8393 "/dir/the-file".as_ref(),
8394 &"\n\n\nAAAA\naaa\nBB\nbbbbb\n".into(),
8395 )
8396 .await
8397 .unwrap();
8398
8399 // Because the buffer is modified, it doesn't reload from disk, but is
8400 // marked as having a conflict.
8401 buffer
8402 .condition(&cx, |buffer, _| buffer.has_conflict())
8403 .await;
8404 }
8405
8406 #[gpui::test]
8407 async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
8408 cx.foreground().forbid_parking();
8409
8410 let fs = FakeFs::new(cx.background());
8411 fs.insert_tree(
8412 "/the-dir",
8413 json!({
8414 "a.rs": "
8415 fn foo(mut v: Vec<usize>) {
8416 for x in &v {
8417 v.push(1);
8418 }
8419 }
8420 "
8421 .unindent(),
8422 }),
8423 )
8424 .await;
8425
8426 let project = Project::test(fs.clone(), ["/the-dir".as_ref()], cx).await;
8427 let buffer = project
8428 .update(cx, |p, cx| p.open_local_buffer("/the-dir/a.rs", cx))
8429 .await
8430 .unwrap();
8431
8432 let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
8433 let message = lsp::PublishDiagnosticsParams {
8434 uri: buffer_uri.clone(),
8435 diagnostics: vec![
8436 lsp::Diagnostic {
8437 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
8438 severity: Some(DiagnosticSeverity::WARNING),
8439 message: "error 1".to_string(),
8440 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
8441 location: lsp::Location {
8442 uri: buffer_uri.clone(),
8443 range: lsp::Range::new(
8444 lsp::Position::new(1, 8),
8445 lsp::Position::new(1, 9),
8446 ),
8447 },
8448 message: "error 1 hint 1".to_string(),
8449 }]),
8450 ..Default::default()
8451 },
8452 lsp::Diagnostic {
8453 range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
8454 severity: Some(DiagnosticSeverity::HINT),
8455 message: "error 1 hint 1".to_string(),
8456 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
8457 location: lsp::Location {
8458 uri: buffer_uri.clone(),
8459 range: lsp::Range::new(
8460 lsp::Position::new(1, 8),
8461 lsp::Position::new(1, 9),
8462 ),
8463 },
8464 message: "original diagnostic".to_string(),
8465 }]),
8466 ..Default::default()
8467 },
8468 lsp::Diagnostic {
8469 range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
8470 severity: Some(DiagnosticSeverity::ERROR),
8471 message: "error 2".to_string(),
8472 related_information: Some(vec![
8473 lsp::DiagnosticRelatedInformation {
8474 location: lsp::Location {
8475 uri: buffer_uri.clone(),
8476 range: lsp::Range::new(
8477 lsp::Position::new(1, 13),
8478 lsp::Position::new(1, 15),
8479 ),
8480 },
8481 message: "error 2 hint 1".to_string(),
8482 },
8483 lsp::DiagnosticRelatedInformation {
8484 location: lsp::Location {
8485 uri: buffer_uri.clone(),
8486 range: lsp::Range::new(
8487 lsp::Position::new(1, 13),
8488 lsp::Position::new(1, 15),
8489 ),
8490 },
8491 message: "error 2 hint 2".to_string(),
8492 },
8493 ]),
8494 ..Default::default()
8495 },
8496 lsp::Diagnostic {
8497 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
8498 severity: Some(DiagnosticSeverity::HINT),
8499 message: "error 2 hint 1".to_string(),
8500 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
8501 location: lsp::Location {
8502 uri: buffer_uri.clone(),
8503 range: lsp::Range::new(
8504 lsp::Position::new(2, 8),
8505 lsp::Position::new(2, 17),
8506 ),
8507 },
8508 message: "original diagnostic".to_string(),
8509 }]),
8510 ..Default::default()
8511 },
8512 lsp::Diagnostic {
8513 range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
8514 severity: Some(DiagnosticSeverity::HINT),
8515 message: "error 2 hint 2".to_string(),
8516 related_information: Some(vec![lsp::DiagnosticRelatedInformation {
8517 location: lsp::Location {
8518 uri: buffer_uri.clone(),
8519 range: lsp::Range::new(
8520 lsp::Position::new(2, 8),
8521 lsp::Position::new(2, 17),
8522 ),
8523 },
8524 message: "original diagnostic".to_string(),
8525 }]),
8526 ..Default::default()
8527 },
8528 ],
8529 version: None,
8530 };
8531
8532 project
8533 .update(cx, |p, cx| p.update_diagnostics(0, message, &[], cx))
8534 .unwrap();
8535 let buffer = buffer.read_with(cx, |buffer, _| buffer.snapshot());
8536
8537 assert_eq!(
8538 buffer
8539 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
8540 .collect::<Vec<_>>(),
8541 &[
8542 DiagnosticEntry {
8543 range: Point::new(1, 8)..Point::new(1, 9),
8544 diagnostic: Diagnostic {
8545 severity: DiagnosticSeverity::WARNING,
8546 message: "error 1".to_string(),
8547 group_id: 0,
8548 is_primary: true,
8549 ..Default::default()
8550 }
8551 },
8552 DiagnosticEntry {
8553 range: Point::new(1, 8)..Point::new(1, 9),
8554 diagnostic: Diagnostic {
8555 severity: DiagnosticSeverity::HINT,
8556 message: "error 1 hint 1".to_string(),
8557 group_id: 0,
8558 is_primary: false,
8559 ..Default::default()
8560 }
8561 },
8562 DiagnosticEntry {
8563 range: Point::new(1, 13)..Point::new(1, 15),
8564 diagnostic: Diagnostic {
8565 severity: DiagnosticSeverity::HINT,
8566 message: "error 2 hint 1".to_string(),
8567 group_id: 1,
8568 is_primary: false,
8569 ..Default::default()
8570 }
8571 },
8572 DiagnosticEntry {
8573 range: Point::new(1, 13)..Point::new(1, 15),
8574 diagnostic: Diagnostic {
8575 severity: DiagnosticSeverity::HINT,
8576 message: "error 2 hint 2".to_string(),
8577 group_id: 1,
8578 is_primary: false,
8579 ..Default::default()
8580 }
8581 },
8582 DiagnosticEntry {
8583 range: Point::new(2, 8)..Point::new(2, 17),
8584 diagnostic: Diagnostic {
8585 severity: DiagnosticSeverity::ERROR,
8586 message: "error 2".to_string(),
8587 group_id: 1,
8588 is_primary: true,
8589 ..Default::default()
8590 }
8591 }
8592 ]
8593 );
8594
8595 assert_eq!(
8596 buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
8597 &[
8598 DiagnosticEntry {
8599 range: Point::new(1, 8)..Point::new(1, 9),
8600 diagnostic: Diagnostic {
8601 severity: DiagnosticSeverity::WARNING,
8602 message: "error 1".to_string(),
8603 group_id: 0,
8604 is_primary: true,
8605 ..Default::default()
8606 }
8607 },
8608 DiagnosticEntry {
8609 range: Point::new(1, 8)..Point::new(1, 9),
8610 diagnostic: Diagnostic {
8611 severity: DiagnosticSeverity::HINT,
8612 message: "error 1 hint 1".to_string(),
8613 group_id: 0,
8614 is_primary: false,
8615 ..Default::default()
8616 }
8617 },
8618 ]
8619 );
8620 assert_eq!(
8621 buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
8622 &[
8623 DiagnosticEntry {
8624 range: Point::new(1, 13)..Point::new(1, 15),
8625 diagnostic: Diagnostic {
8626 severity: DiagnosticSeverity::HINT,
8627 message: "error 2 hint 1".to_string(),
8628 group_id: 1,
8629 is_primary: false,
8630 ..Default::default()
8631 }
8632 },
8633 DiagnosticEntry {
8634 range: Point::new(1, 13)..Point::new(1, 15),
8635 diagnostic: Diagnostic {
8636 severity: DiagnosticSeverity::HINT,
8637 message: "error 2 hint 2".to_string(),
8638 group_id: 1,
8639 is_primary: false,
8640 ..Default::default()
8641 }
8642 },
8643 DiagnosticEntry {
8644 range: Point::new(2, 8)..Point::new(2, 17),
8645 diagnostic: Diagnostic {
8646 severity: DiagnosticSeverity::ERROR,
8647 message: "error 2".to_string(),
8648 group_id: 1,
8649 is_primary: true,
8650 ..Default::default()
8651 }
8652 }
8653 ]
8654 );
8655 }
8656
8657 #[gpui::test]
8658 async fn test_rename(cx: &mut gpui::TestAppContext) {
8659 cx.foreground().forbid_parking();
8660
8661 let mut language = Language::new(
8662 LanguageConfig {
8663 name: "Rust".into(),
8664 path_suffixes: vec!["rs".to_string()],
8665 ..Default::default()
8666 },
8667 Some(tree_sitter_rust::language()),
8668 );
8669 let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
8670 capabilities: lsp::ServerCapabilities {
8671 rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
8672 prepare_provider: Some(true),
8673 work_done_progress_options: Default::default(),
8674 })),
8675 ..Default::default()
8676 },
8677 ..Default::default()
8678 });
8679
8680 let fs = FakeFs::new(cx.background());
8681 fs.insert_tree(
8682 "/dir",
8683 json!({
8684 "one.rs": "const ONE: usize = 1;",
8685 "two.rs": "const TWO: usize = one::ONE + one::ONE;"
8686 }),
8687 )
8688 .await;
8689
8690 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
8691 project.update(cx, |project, _| project.languages.add(Arc::new(language)));
8692 let buffer = project
8693 .update(cx, |project, cx| {
8694 project.open_local_buffer("/dir/one.rs", cx)
8695 })
8696 .await
8697 .unwrap();
8698
8699 let fake_server = fake_servers.next().await.unwrap();
8700
8701 let response = project.update(cx, |project, cx| {
8702 project.prepare_rename(buffer.clone(), 7, cx)
8703 });
8704 fake_server
8705 .handle_request::<lsp::request::PrepareRenameRequest, _, _>(|params, _| async move {
8706 assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
8707 assert_eq!(params.position, lsp::Position::new(0, 7));
8708 Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
8709 lsp::Position::new(0, 6),
8710 lsp::Position::new(0, 9),
8711 ))))
8712 })
8713 .next()
8714 .await
8715 .unwrap();
8716 let range = response.await.unwrap().unwrap();
8717 let range = buffer.read_with(cx, |buffer, _| range.to_offset(buffer));
8718 assert_eq!(range, 6..9);
8719
8720 let response = project.update(cx, |project, cx| {
8721 project.perform_rename(buffer.clone(), 7, "THREE".to_string(), true, cx)
8722 });
8723 fake_server
8724 .handle_request::<lsp::request::Rename, _, _>(|params, _| async move {
8725 assert_eq!(
8726 params.text_document_position.text_document.uri.as_str(),
8727 "file:///dir/one.rs"
8728 );
8729 assert_eq!(
8730 params.text_document_position.position,
8731 lsp::Position::new(0, 7)
8732 );
8733 assert_eq!(params.new_name, "THREE");
8734 Ok(Some(lsp::WorkspaceEdit {
8735 changes: Some(
8736 [
8737 (
8738 lsp::Url::from_file_path("/dir/one.rs").unwrap(),
8739 vec![lsp::TextEdit::new(
8740 lsp::Range::new(
8741 lsp::Position::new(0, 6),
8742 lsp::Position::new(0, 9),
8743 ),
8744 "THREE".to_string(),
8745 )],
8746 ),
8747 (
8748 lsp::Url::from_file_path("/dir/two.rs").unwrap(),
8749 vec![
8750 lsp::TextEdit::new(
8751 lsp::Range::new(
8752 lsp::Position::new(0, 24),
8753 lsp::Position::new(0, 27),
8754 ),
8755 "THREE".to_string(),
8756 ),
8757 lsp::TextEdit::new(
8758 lsp::Range::new(
8759 lsp::Position::new(0, 35),
8760 lsp::Position::new(0, 38),
8761 ),
8762 "THREE".to_string(),
8763 ),
8764 ],
8765 ),
8766 ]
8767 .into_iter()
8768 .collect(),
8769 ),
8770 ..Default::default()
8771 }))
8772 })
8773 .next()
8774 .await
8775 .unwrap();
8776 let mut transaction = response.await.unwrap().0;
8777 assert_eq!(transaction.len(), 2);
8778 assert_eq!(
8779 transaction
8780 .remove_entry(&buffer)
8781 .unwrap()
8782 .0
8783 .read_with(cx, |buffer, _| buffer.text()),
8784 "const THREE: usize = 1;"
8785 );
8786 assert_eq!(
8787 transaction
8788 .into_keys()
8789 .next()
8790 .unwrap()
8791 .read_with(cx, |buffer, _| buffer.text()),
8792 "const TWO: usize = one::THREE + one::THREE;"
8793 );
8794 }
8795
8796 #[gpui::test]
8797 async fn test_search(cx: &mut gpui::TestAppContext) {
8798 let fs = FakeFs::new(cx.background());
8799 fs.insert_tree(
8800 "/dir",
8801 json!({
8802 "one.rs": "const ONE: usize = 1;",
8803 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
8804 "three.rs": "const THREE: usize = one::ONE + two::TWO;",
8805 "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
8806 }),
8807 )
8808 .await;
8809 let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
8810 assert_eq!(
8811 search(&project, SearchQuery::text("TWO", false, true), cx)
8812 .await
8813 .unwrap(),
8814 HashMap::from_iter([
8815 ("two.rs".to_string(), vec![6..9]),
8816 ("three.rs".to_string(), vec![37..40])
8817 ])
8818 );
8819
8820 let buffer_4 = project
8821 .update(cx, |project, cx| {
8822 project.open_local_buffer("/dir/four.rs", cx)
8823 })
8824 .await
8825 .unwrap();
8826 buffer_4.update(cx, |buffer, cx| {
8827 let text = "two::TWO";
8828 buffer.edit([(20..28, text), (31..43, text)], cx);
8829 });
8830
8831 assert_eq!(
8832 search(&project, SearchQuery::text("TWO", false, true), cx)
8833 .await
8834 .unwrap(),
8835 HashMap::from_iter([
8836 ("two.rs".to_string(), vec![6..9]),
8837 ("three.rs".to_string(), vec![37..40]),
8838 ("four.rs".to_string(), vec![25..28, 36..39])
8839 ])
8840 );
8841
8842 async fn search(
8843 project: &ModelHandle<Project>,
8844 query: SearchQuery,
8845 cx: &mut gpui::TestAppContext,
8846 ) -> Result<HashMap<String, Vec<Range<usize>>>> {
8847 let results = project
8848 .update(cx, |project, cx| project.search(query, cx))
8849 .await?;
8850
8851 Ok(results
8852 .into_iter()
8853 .map(|(buffer, ranges)| {
8854 buffer.read_with(cx, |buffer, _| {
8855 let path = buffer.file().unwrap().path().to_string_lossy().to_string();
8856 let ranges = ranges
8857 .into_iter()
8858 .map(|range| range.to_offset(buffer))
8859 .collect::<Vec<_>>();
8860 (path, ranges)
8861 })
8862 })
8863 .collect())
8864 }
8865 }
8866}