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