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