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