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