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