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::FormattingOptions {
3480 tab_size: tab_size.into(),
3481 insert_spaces: true,
3482 insert_final_newline: Some(true),
3483 ..Default::default()
3484 },
3485 work_done_progress_params: Default::default(),
3486 })
3487 .await?
3488 } else if capabilities
3489 .document_range_formatting_provider
3490 .as_ref()
3491 .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3492 {
3493 let buffer_start = lsp::Position::new(0, 0);
3494 let buffer_end =
3495 buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3496 language_server
3497 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3498 text_document,
3499 range: lsp::Range::new(buffer_start, buffer_end),
3500 options: lsp::FormattingOptions {
3501 tab_size: tab_size.into(),
3502 insert_spaces: true,
3503 insert_final_newline: Some(true),
3504 ..Default::default()
3505 },
3506 work_done_progress_params: Default::default(),
3507 })
3508 .await?
3509 } else {
3510 None
3511 };
3512
3513 if let Some(lsp_edits) = lsp_edits {
3514 this.update(cx, |this, cx| {
3515 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
3516 })
3517 .await
3518 } else {
3519 Ok(Default::default())
3520 }
3521 }
3522
3523 async fn format_via_external_command(
3524 buffer: &ModelHandle<Buffer>,
3525 buffer_abs_path: &Path,
3526 command: &str,
3527 arguments: &[String],
3528 cx: &mut AsyncAppContext,
3529 ) -> Result<Option<Diff>> {
3530 let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3531 let file = File::from_dyn(buffer.file())?;
3532 let worktree = file.worktree.read(cx).as_local()?;
3533 let mut worktree_path = worktree.abs_path().to_path_buf();
3534 if worktree.root_entry()?.is_file() {
3535 worktree_path.pop();
3536 }
3537 Some(worktree_path)
3538 });
3539
3540 if let Some(working_dir_path) = working_dir_path {
3541 let mut child =
3542 smol::process::Command::new(command)
3543 .args(arguments.iter().map(|arg| {
3544 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3545 }))
3546 .current_dir(&working_dir_path)
3547 .stdin(smol::process::Stdio::piped())
3548 .stdout(smol::process::Stdio::piped())
3549 .stderr(smol::process::Stdio::piped())
3550 .spawn()?;
3551 let stdin = child
3552 .stdin
3553 .as_mut()
3554 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3555 let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3556 for chunk in text.chunks() {
3557 stdin.write_all(chunk.as_bytes()).await?;
3558 }
3559 stdin.flush().await?;
3560
3561 let output = child.output().await?;
3562 if !output.status.success() {
3563 return Err(anyhow!(
3564 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3565 output.status.code(),
3566 String::from_utf8_lossy(&output.stdout),
3567 String::from_utf8_lossy(&output.stderr),
3568 ));
3569 }
3570
3571 let stdout = String::from_utf8(output.stdout)?;
3572 Ok(Some(
3573 buffer
3574 .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3575 .await,
3576 ))
3577 } else {
3578 Ok(None)
3579 }
3580 }
3581
3582 pub fn 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(), GetDefinition { position }, cx)
3590 }
3591
3592 pub fn type_definition<T: ToPointUtf16>(
3593 &self,
3594 buffer: &ModelHandle<Buffer>,
3595 position: T,
3596 cx: &mut ModelContext<Self>,
3597 ) -> Task<Result<Vec<LocationLink>>> {
3598 let position = position.to_point_utf16(buffer.read(cx));
3599 self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3600 }
3601
3602 pub fn references<T: ToPointUtf16>(
3603 &self,
3604 buffer: &ModelHandle<Buffer>,
3605 position: T,
3606 cx: &mut ModelContext<Self>,
3607 ) -> Task<Result<Vec<Location>>> {
3608 let position = position.to_point_utf16(buffer.read(cx));
3609 self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3610 }
3611
3612 pub fn document_highlights<T: ToPointUtf16>(
3613 &self,
3614 buffer: &ModelHandle<Buffer>,
3615 position: T,
3616 cx: &mut ModelContext<Self>,
3617 ) -> Task<Result<Vec<DocumentHighlight>>> {
3618 let position = position.to_point_utf16(buffer.read(cx));
3619 self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3620 }
3621
3622 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3623 if self.is_local() {
3624 let mut requests = Vec::new();
3625 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3626 let worktree_id = *worktree_id;
3627 if let Some(worktree) = self
3628 .worktree_for_id(worktree_id, cx)
3629 .and_then(|worktree| worktree.read(cx).as_local())
3630 {
3631 if let Some(LanguageServerState::Running {
3632 adapter,
3633 language,
3634 server,
3635 ..
3636 }) = self.language_servers.get(server_id)
3637 {
3638 let adapter = adapter.clone();
3639 let language = language.clone();
3640 let worktree_abs_path = worktree.abs_path().clone();
3641 requests.push(
3642 server
3643 .request::<lsp::request::WorkspaceSymbol>(
3644 lsp::WorkspaceSymbolParams {
3645 query: query.to_string(),
3646 ..Default::default()
3647 },
3648 )
3649 .log_err()
3650 .map(move |response| {
3651 (
3652 adapter,
3653 language,
3654 worktree_id,
3655 worktree_abs_path,
3656 response.unwrap_or_default(),
3657 )
3658 }),
3659 );
3660 }
3661 }
3662 }
3663
3664 cx.spawn_weak(|this, cx| async move {
3665 let responses = futures::future::join_all(requests).await;
3666 let this = if let Some(this) = this.upgrade(&cx) {
3667 this
3668 } else {
3669 return Ok(Default::default());
3670 };
3671 let symbols = this.read_with(&cx, |this, cx| {
3672 let mut symbols = Vec::new();
3673 for (
3674 adapter,
3675 adapter_language,
3676 source_worktree_id,
3677 worktree_abs_path,
3678 response,
3679 ) in responses
3680 {
3681 symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3682 let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3683 let mut worktree_id = source_worktree_id;
3684 let path;
3685 if let Some((worktree, rel_path)) =
3686 this.find_local_worktree(&abs_path, cx)
3687 {
3688 worktree_id = worktree.read(cx).id();
3689 path = rel_path;
3690 } else {
3691 path = relativize_path(&worktree_abs_path, &abs_path);
3692 }
3693
3694 let project_path = ProjectPath {
3695 worktree_id,
3696 path: path.into(),
3697 };
3698 let signature = this.symbol_signature(&project_path);
3699 let adapter_language = adapter_language.clone();
3700 let language = this
3701 .languages
3702 .language_for_file(&project_path.path, None)
3703 .unwrap_or_else(move |_| adapter_language);
3704 let language_server_name = adapter.name.clone();
3705 Some(async move {
3706 let language = language.await;
3707 let label = language
3708 .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3709 .await;
3710
3711 Symbol {
3712 language_server_name,
3713 source_worktree_id,
3714 path: project_path,
3715 label: label.unwrap_or_else(|| {
3716 CodeLabel::plain(lsp_symbol.name.clone(), None)
3717 }),
3718 kind: lsp_symbol.kind,
3719 name: lsp_symbol.name,
3720 range: range_from_lsp(lsp_symbol.location.range),
3721 signature,
3722 }
3723 })
3724 }));
3725 }
3726 symbols
3727 });
3728 Ok(futures::future::join_all(symbols).await)
3729 })
3730 } else if let Some(project_id) = self.remote_id() {
3731 let request = self.client.request(proto::GetProjectSymbols {
3732 project_id,
3733 query: query.to_string(),
3734 });
3735 cx.spawn_weak(|this, cx| async move {
3736 let response = request.await?;
3737 let mut symbols = Vec::new();
3738 if let Some(this) = this.upgrade(&cx) {
3739 let new_symbols = this.read_with(&cx, |this, _| {
3740 response
3741 .symbols
3742 .into_iter()
3743 .map(|symbol| this.deserialize_symbol(symbol))
3744 .collect::<Vec<_>>()
3745 });
3746 symbols = futures::future::join_all(new_symbols)
3747 .await
3748 .into_iter()
3749 .filter_map(|symbol| symbol.log_err())
3750 .collect::<Vec<_>>();
3751 }
3752 Ok(symbols)
3753 })
3754 } else {
3755 Task::ready(Ok(Default::default()))
3756 }
3757 }
3758
3759 pub fn open_buffer_for_symbol(
3760 &mut self,
3761 symbol: &Symbol,
3762 cx: &mut ModelContext<Self>,
3763 ) -> Task<Result<ModelHandle<Buffer>>> {
3764 if self.is_local() {
3765 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3766 symbol.source_worktree_id,
3767 symbol.language_server_name.clone(),
3768 )) {
3769 *id
3770 } else {
3771 return Task::ready(Err(anyhow!(
3772 "language server for worktree and language not found"
3773 )));
3774 };
3775
3776 let worktree_abs_path = if let Some(worktree_abs_path) = self
3777 .worktree_for_id(symbol.path.worktree_id, cx)
3778 .and_then(|worktree| worktree.read(cx).as_local())
3779 .map(|local_worktree| local_worktree.abs_path())
3780 {
3781 worktree_abs_path
3782 } else {
3783 return Task::ready(Err(anyhow!("worktree not found for symbol")));
3784 };
3785 let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3786 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3787 uri
3788 } else {
3789 return Task::ready(Err(anyhow!("invalid symbol path")));
3790 };
3791
3792 self.open_local_buffer_via_lsp(
3793 symbol_uri,
3794 language_server_id,
3795 symbol.language_server_name.clone(),
3796 cx,
3797 )
3798 } else if let Some(project_id) = self.remote_id() {
3799 let request = self.client.request(proto::OpenBufferForSymbol {
3800 project_id,
3801 symbol: Some(serialize_symbol(symbol)),
3802 });
3803 cx.spawn(|this, mut cx| async move {
3804 let response = request.await?;
3805 this.update(&mut cx, |this, cx| {
3806 this.wait_for_remote_buffer(response.buffer_id, cx)
3807 })
3808 .await
3809 })
3810 } else {
3811 Task::ready(Err(anyhow!("project does not have a remote id")))
3812 }
3813 }
3814
3815 pub fn hover<T: ToPointUtf16>(
3816 &self,
3817 buffer: &ModelHandle<Buffer>,
3818 position: T,
3819 cx: &mut ModelContext<Self>,
3820 ) -> Task<Result<Option<Hover>>> {
3821 let position = position.to_point_utf16(buffer.read(cx));
3822 self.request_lsp(buffer.clone(), GetHover { position }, cx)
3823 }
3824
3825 pub fn completions<T: ToPointUtf16>(
3826 &self,
3827 buffer: &ModelHandle<Buffer>,
3828 position: T,
3829 cx: &mut ModelContext<Self>,
3830 ) -> Task<Result<Vec<Completion>>> {
3831 let position = position.to_point_utf16(buffer.read(cx));
3832 self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
3833 }
3834
3835 pub fn apply_additional_edits_for_completion(
3836 &self,
3837 buffer_handle: ModelHandle<Buffer>,
3838 completion: Completion,
3839 push_to_history: bool,
3840 cx: &mut ModelContext<Self>,
3841 ) -> Task<Result<Option<Transaction>>> {
3842 let buffer = buffer_handle.read(cx);
3843 let buffer_id = buffer.remote_id();
3844
3845 if self.is_local() {
3846 let lang_server = match self.primary_language_servers_for_buffer(buffer, cx) {
3847 Some((_, server)) => server.clone(),
3848 _ => return Task::ready(Ok(Default::default())),
3849 };
3850
3851 cx.spawn(|this, mut cx| async move {
3852 let resolved_completion = lang_server
3853 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3854 .await?;
3855
3856 if let Some(edits) = resolved_completion.additional_text_edits {
3857 let edits = this
3858 .update(&mut cx, |this, cx| {
3859 this.edits_from_lsp(
3860 &buffer_handle,
3861 edits,
3862 lang_server.server_id(),
3863 None,
3864 cx,
3865 )
3866 })
3867 .await?;
3868
3869 buffer_handle.update(&mut cx, |buffer, cx| {
3870 buffer.finalize_last_transaction();
3871 buffer.start_transaction();
3872
3873 for (range, text) in edits {
3874 let primary = &completion.old_range;
3875 let start_within = primary.start.cmp(&range.start, buffer).is_le()
3876 && primary.end.cmp(&range.start, buffer).is_ge();
3877 let end_within = range.start.cmp(&primary.end, buffer).is_le()
3878 && range.end.cmp(&primary.end, buffer).is_ge();
3879
3880 //Skip addtional edits which overlap with the primary completion edit
3881 //https://github.com/zed-industries/zed/pull/1871
3882 if !start_within && !end_within {
3883 buffer.edit([(range, text)], None, cx);
3884 }
3885 }
3886
3887 let transaction = if buffer.end_transaction(cx).is_some() {
3888 let transaction = buffer.finalize_last_transaction().unwrap().clone();
3889 if !push_to_history {
3890 buffer.forget_transaction(transaction.id);
3891 }
3892 Some(transaction)
3893 } else {
3894 None
3895 };
3896 Ok(transaction)
3897 })
3898 } else {
3899 Ok(None)
3900 }
3901 })
3902 } else if let Some(project_id) = self.remote_id() {
3903 let client = self.client.clone();
3904 cx.spawn(|_, mut cx| async move {
3905 let response = client
3906 .request(proto::ApplyCompletionAdditionalEdits {
3907 project_id,
3908 buffer_id,
3909 completion: Some(language::proto::serialize_completion(&completion)),
3910 })
3911 .await?;
3912
3913 if let Some(transaction) = response.transaction {
3914 let transaction = language::proto::deserialize_transaction(transaction)?;
3915 buffer_handle
3916 .update(&mut cx, |buffer, _| {
3917 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3918 })
3919 .await?;
3920 if push_to_history {
3921 buffer_handle.update(&mut cx, |buffer, _| {
3922 buffer.push_transaction(transaction.clone(), Instant::now());
3923 });
3924 }
3925 Ok(Some(transaction))
3926 } else {
3927 Ok(None)
3928 }
3929 })
3930 } else {
3931 Task::ready(Err(anyhow!("project does not have a remote id")))
3932 }
3933 }
3934
3935 pub fn code_actions<T: Clone + ToOffset>(
3936 &self,
3937 buffer_handle: &ModelHandle<Buffer>,
3938 range: Range<T>,
3939 cx: &mut ModelContext<Self>,
3940 ) -> Task<Result<Vec<CodeAction>>> {
3941 let buffer = buffer_handle.read(cx);
3942 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3943 self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
3944 }
3945
3946 pub fn apply_code_action(
3947 &self,
3948 buffer_handle: ModelHandle<Buffer>,
3949 mut action: CodeAction,
3950 push_to_history: bool,
3951 cx: &mut ModelContext<Self>,
3952 ) -> Task<Result<ProjectTransaction>> {
3953 if self.is_local() {
3954 let buffer = buffer_handle.read(cx);
3955 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
3956 self.language_server_for_buffer(buffer, action.server_id, cx)
3957 {
3958 (adapter.clone(), server.clone())
3959 } else {
3960 return Task::ready(Ok(Default::default()));
3961 };
3962 let range = action.range.to_point_utf16(buffer);
3963
3964 cx.spawn(|this, mut cx| async move {
3965 if let Some(lsp_range) = action
3966 .lsp_action
3967 .data
3968 .as_mut()
3969 .and_then(|d| d.get_mut("codeActionParams"))
3970 .and_then(|d| d.get_mut("range"))
3971 {
3972 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3973 action.lsp_action = lang_server
3974 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3975 .await?;
3976 } else {
3977 let actions = this
3978 .update(&mut cx, |this, cx| {
3979 this.code_actions(&buffer_handle, action.range, cx)
3980 })
3981 .await?;
3982 action.lsp_action = actions
3983 .into_iter()
3984 .find(|a| a.lsp_action.title == action.lsp_action.title)
3985 .ok_or_else(|| anyhow!("code action is outdated"))?
3986 .lsp_action;
3987 }
3988
3989 if let Some(edit) = action.lsp_action.edit {
3990 if edit.changes.is_some() || edit.document_changes.is_some() {
3991 return Self::deserialize_workspace_edit(
3992 this,
3993 edit,
3994 push_to_history,
3995 lsp_adapter.clone(),
3996 lang_server.clone(),
3997 &mut cx,
3998 )
3999 .await;
4000 }
4001 }
4002
4003 if let Some(command) = action.lsp_action.command {
4004 this.update(&mut cx, |this, _| {
4005 this.last_workspace_edits_by_language_server
4006 .remove(&lang_server.server_id());
4007 });
4008 lang_server
4009 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4010 command: command.command,
4011 arguments: command.arguments.unwrap_or_default(),
4012 ..Default::default()
4013 })
4014 .await?;
4015 return Ok(this.update(&mut cx, |this, _| {
4016 this.last_workspace_edits_by_language_server
4017 .remove(&lang_server.server_id())
4018 .unwrap_or_default()
4019 }));
4020 }
4021
4022 Ok(ProjectTransaction::default())
4023 })
4024 } else if let Some(project_id) = self.remote_id() {
4025 let client = self.client.clone();
4026 let request = proto::ApplyCodeAction {
4027 project_id,
4028 buffer_id: buffer_handle.read(cx).remote_id(),
4029 action: Some(language::proto::serialize_code_action(&action)),
4030 };
4031 cx.spawn(|this, mut cx| async move {
4032 let response = client
4033 .request(request)
4034 .await?
4035 .transaction
4036 .ok_or_else(|| anyhow!("missing transaction"))?;
4037 this.update(&mut cx, |this, cx| {
4038 this.deserialize_project_transaction(response, push_to_history, cx)
4039 })
4040 .await
4041 })
4042 } else {
4043 Task::ready(Err(anyhow!("project does not have a remote id")))
4044 }
4045 }
4046
4047 async fn deserialize_workspace_edit(
4048 this: ModelHandle<Self>,
4049 edit: lsp::WorkspaceEdit,
4050 push_to_history: bool,
4051 lsp_adapter: Arc<CachedLspAdapter>,
4052 language_server: Arc<LanguageServer>,
4053 cx: &mut AsyncAppContext,
4054 ) -> Result<ProjectTransaction> {
4055 let fs = this.read_with(cx, |this, _| this.fs.clone());
4056 let mut operations = Vec::new();
4057 if let Some(document_changes) = edit.document_changes {
4058 match document_changes {
4059 lsp::DocumentChanges::Edits(edits) => {
4060 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4061 }
4062 lsp::DocumentChanges::Operations(ops) => operations = ops,
4063 }
4064 } else if let Some(changes) = edit.changes {
4065 operations.extend(changes.into_iter().map(|(uri, edits)| {
4066 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4067 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4068 uri,
4069 version: None,
4070 },
4071 edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
4072 })
4073 }));
4074 }
4075
4076 let mut project_transaction = ProjectTransaction::default();
4077 for operation in operations {
4078 match operation {
4079 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4080 let abs_path = op
4081 .uri
4082 .to_file_path()
4083 .map_err(|_| anyhow!("can't convert URI to path"))?;
4084
4085 if let Some(parent_path) = abs_path.parent() {
4086 fs.create_dir(parent_path).await?;
4087 }
4088 if abs_path.ends_with("/") {
4089 fs.create_dir(&abs_path).await?;
4090 } else {
4091 fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4092 .await?;
4093 }
4094 }
4095
4096 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4097 let source_abs_path = op
4098 .old_uri
4099 .to_file_path()
4100 .map_err(|_| anyhow!("can't convert URI to path"))?;
4101 let target_abs_path = op
4102 .new_uri
4103 .to_file_path()
4104 .map_err(|_| anyhow!("can't convert URI to path"))?;
4105 fs.rename(
4106 &source_abs_path,
4107 &target_abs_path,
4108 op.options.map(Into::into).unwrap_or_default(),
4109 )
4110 .await?;
4111 }
4112
4113 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4114 let abs_path = op
4115 .uri
4116 .to_file_path()
4117 .map_err(|_| anyhow!("can't convert URI to path"))?;
4118 let options = op.options.map(Into::into).unwrap_or_default();
4119 if abs_path.ends_with("/") {
4120 fs.remove_dir(&abs_path, options).await?;
4121 } else {
4122 fs.remove_file(&abs_path, options).await?;
4123 }
4124 }
4125
4126 lsp::DocumentChangeOperation::Edit(op) => {
4127 let buffer_to_edit = this
4128 .update(cx, |this, cx| {
4129 this.open_local_buffer_via_lsp(
4130 op.text_document.uri,
4131 language_server.server_id(),
4132 lsp_adapter.name.clone(),
4133 cx,
4134 )
4135 })
4136 .await?;
4137
4138 let edits = this
4139 .update(cx, |this, cx| {
4140 let edits = op.edits.into_iter().map(|edit| match edit {
4141 lsp::OneOf::Left(edit) => edit,
4142 lsp::OneOf::Right(edit) => edit.text_edit,
4143 });
4144 this.edits_from_lsp(
4145 &buffer_to_edit,
4146 edits,
4147 language_server.server_id(),
4148 op.text_document.version,
4149 cx,
4150 )
4151 })
4152 .await?;
4153
4154 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4155 buffer.finalize_last_transaction();
4156 buffer.start_transaction();
4157 for (range, text) in edits {
4158 buffer.edit([(range, text)], None, cx);
4159 }
4160 let transaction = if buffer.end_transaction(cx).is_some() {
4161 let transaction = buffer.finalize_last_transaction().unwrap().clone();
4162 if !push_to_history {
4163 buffer.forget_transaction(transaction.id);
4164 }
4165 Some(transaction)
4166 } else {
4167 None
4168 };
4169
4170 transaction
4171 });
4172 if let Some(transaction) = transaction {
4173 project_transaction.0.insert(buffer_to_edit, transaction);
4174 }
4175 }
4176 }
4177 }
4178
4179 Ok(project_transaction)
4180 }
4181
4182 pub fn prepare_rename<T: ToPointUtf16>(
4183 &self,
4184 buffer: ModelHandle<Buffer>,
4185 position: T,
4186 cx: &mut ModelContext<Self>,
4187 ) -> Task<Result<Option<Range<Anchor>>>> {
4188 let position = position.to_point_utf16(buffer.read(cx));
4189 self.request_lsp(buffer, PrepareRename { position }, cx)
4190 }
4191
4192 pub fn perform_rename<T: ToPointUtf16>(
4193 &self,
4194 buffer: ModelHandle<Buffer>,
4195 position: T,
4196 new_name: String,
4197 push_to_history: bool,
4198 cx: &mut ModelContext<Self>,
4199 ) -> Task<Result<ProjectTransaction>> {
4200 let position = position.to_point_utf16(buffer.read(cx));
4201 self.request_lsp(
4202 buffer,
4203 PerformRename {
4204 position,
4205 new_name,
4206 push_to_history,
4207 },
4208 cx,
4209 )
4210 }
4211
4212 pub fn on_type_format<T: ToPointUtf16>(
4213 &self,
4214 buffer: ModelHandle<Buffer>,
4215 position: T,
4216 input: char,
4217 cx: &mut ModelContext<Self>,
4218 ) -> Task<Result<()>> {
4219 let position = position.to_point_utf16(buffer.read(cx));
4220 let edits_task = self.request_lsp(
4221 buffer.clone(),
4222 OnTypeFormatting {
4223 position,
4224 new_char: input,
4225 },
4226 cx,
4227 );
4228
4229 cx.spawn(|_project, mut cx| async move {
4230 let edits = edits_task
4231 .await
4232 .context("requesting OnTypeFormatting edits for char '{new_char}'")?;
4233
4234 if !edits.is_empty() {
4235 cx.update(|cx| {
4236 buffer.update(cx, |buffer, cx| {
4237 buffer.edit(edits, None, cx);
4238 });
4239 });
4240 }
4241
4242 Ok(())
4243 })
4244 }
4245
4246 #[allow(clippy::type_complexity)]
4247 pub fn search(
4248 &self,
4249 query: SearchQuery,
4250 cx: &mut ModelContext<Self>,
4251 ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4252 if self.is_local() {
4253 let snapshots = self
4254 .visible_worktrees(cx)
4255 .filter_map(|tree| {
4256 let tree = tree.read(cx).as_local()?;
4257 Some(tree.snapshot())
4258 })
4259 .collect::<Vec<_>>();
4260
4261 let background = cx.background().clone();
4262 let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4263 if path_count == 0 {
4264 return Task::ready(Ok(Default::default()));
4265 }
4266 let workers = background.num_cpus().min(path_count);
4267 let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4268 cx.background()
4269 .spawn({
4270 let fs = self.fs.clone();
4271 let background = cx.background().clone();
4272 let query = query.clone();
4273 async move {
4274 let fs = &fs;
4275 let query = &query;
4276 let matching_paths_tx = &matching_paths_tx;
4277 let paths_per_worker = (path_count + workers - 1) / workers;
4278 let snapshots = &snapshots;
4279 background
4280 .scoped(|scope| {
4281 for worker_ix in 0..workers {
4282 let worker_start_ix = worker_ix * paths_per_worker;
4283 let worker_end_ix = worker_start_ix + paths_per_worker;
4284 scope.spawn(async move {
4285 let mut snapshot_start_ix = 0;
4286 let mut abs_path = PathBuf::new();
4287 for snapshot in snapshots {
4288 let snapshot_end_ix =
4289 snapshot_start_ix + snapshot.visible_file_count();
4290 if worker_end_ix <= snapshot_start_ix {
4291 break;
4292 } else if worker_start_ix > snapshot_end_ix {
4293 snapshot_start_ix = snapshot_end_ix;
4294 continue;
4295 } else {
4296 let start_in_snapshot = worker_start_ix
4297 .saturating_sub(snapshot_start_ix);
4298 let end_in_snapshot =
4299 cmp::min(worker_end_ix, snapshot_end_ix)
4300 - snapshot_start_ix;
4301
4302 for entry in snapshot
4303 .files(false, start_in_snapshot)
4304 .take(end_in_snapshot - start_in_snapshot)
4305 {
4306 if matching_paths_tx.is_closed() {
4307 break;
4308 }
4309 let matches = if query
4310 .file_matches(Some(&entry.path))
4311 {
4312 abs_path.clear();
4313 abs_path.push(&snapshot.abs_path());
4314 abs_path.push(&entry.path);
4315 if let Some(file) =
4316 fs.open_sync(&abs_path).await.log_err()
4317 {
4318 query.detect(file).unwrap_or(false)
4319 } else {
4320 false
4321 }
4322 } else {
4323 false
4324 };
4325
4326 if matches {
4327 let project_path =
4328 (snapshot.id(), entry.path.clone());
4329 if matching_paths_tx
4330 .send(project_path)
4331 .await
4332 .is_err()
4333 {
4334 break;
4335 }
4336 }
4337 }
4338
4339 snapshot_start_ix = snapshot_end_ix;
4340 }
4341 }
4342 });
4343 }
4344 })
4345 .await;
4346 }
4347 })
4348 .detach();
4349
4350 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4351 let open_buffers = self
4352 .opened_buffers
4353 .values()
4354 .filter_map(|b| b.upgrade(cx))
4355 .collect::<HashSet<_>>();
4356 cx.spawn(|this, cx| async move {
4357 for buffer in &open_buffers {
4358 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4359 buffers_tx.send((buffer.clone(), snapshot)).await?;
4360 }
4361
4362 let open_buffers = Rc::new(RefCell::new(open_buffers));
4363 while let Some(project_path) = matching_paths_rx.next().await {
4364 if buffers_tx.is_closed() {
4365 break;
4366 }
4367
4368 let this = this.clone();
4369 let open_buffers = open_buffers.clone();
4370 let buffers_tx = buffers_tx.clone();
4371 cx.spawn(|mut cx| async move {
4372 if let Some(buffer) = this
4373 .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4374 .await
4375 .log_err()
4376 {
4377 if open_buffers.borrow_mut().insert(buffer.clone()) {
4378 let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4379 buffers_tx.send((buffer, snapshot)).await?;
4380 }
4381 }
4382
4383 Ok::<_, anyhow::Error>(())
4384 })
4385 .detach();
4386 }
4387
4388 Ok::<_, anyhow::Error>(())
4389 })
4390 .detach_and_log_err(cx);
4391
4392 let background = cx.background().clone();
4393 cx.background().spawn(async move {
4394 let query = &query;
4395 let mut matched_buffers = Vec::new();
4396 for _ in 0..workers {
4397 matched_buffers.push(HashMap::default());
4398 }
4399 background
4400 .scoped(|scope| {
4401 for worker_matched_buffers in matched_buffers.iter_mut() {
4402 let mut buffers_rx = buffers_rx.clone();
4403 scope.spawn(async move {
4404 while let Some((buffer, snapshot)) = buffers_rx.next().await {
4405 let buffer_matches = if query.file_matches(
4406 snapshot.file().map(|file| file.path().as_ref()),
4407 ) {
4408 query
4409 .search(snapshot.as_rope())
4410 .await
4411 .iter()
4412 .map(|range| {
4413 snapshot.anchor_before(range.start)
4414 ..snapshot.anchor_after(range.end)
4415 })
4416 .collect()
4417 } else {
4418 Vec::new()
4419 };
4420 if !buffer_matches.is_empty() {
4421 worker_matched_buffers
4422 .insert(buffer.clone(), buffer_matches);
4423 }
4424 }
4425 });
4426 }
4427 })
4428 .await;
4429 Ok(matched_buffers.into_iter().flatten().collect())
4430 })
4431 } else if let Some(project_id) = self.remote_id() {
4432 let request = self.client.request(query.to_proto(project_id));
4433 cx.spawn(|this, mut cx| async move {
4434 let response = request.await?;
4435 let mut result = HashMap::default();
4436 for location in response.locations {
4437 let target_buffer = this
4438 .update(&mut cx, |this, cx| {
4439 this.wait_for_remote_buffer(location.buffer_id, cx)
4440 })
4441 .await?;
4442 let start = location
4443 .start
4444 .and_then(deserialize_anchor)
4445 .ok_or_else(|| anyhow!("missing target start"))?;
4446 let end = location
4447 .end
4448 .and_then(deserialize_anchor)
4449 .ok_or_else(|| anyhow!("missing target end"))?;
4450 result
4451 .entry(target_buffer)
4452 .or_insert(Vec::new())
4453 .push(start..end)
4454 }
4455 Ok(result)
4456 })
4457 } else {
4458 Task::ready(Ok(Default::default()))
4459 }
4460 }
4461
4462 // TODO: Wire this up to allow selecting a server?
4463 fn request_lsp<R: LspCommand>(
4464 &self,
4465 buffer_handle: ModelHandle<Buffer>,
4466 request: R,
4467 cx: &mut ModelContext<Self>,
4468 ) -> Task<Result<R::Response>>
4469 where
4470 <R::LspRequest as lsp::request::Request>::Result: Send,
4471 {
4472 let buffer = buffer_handle.read(cx);
4473 if self.is_local() {
4474 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4475 if let Some((file, language_server)) = file.zip(
4476 self.primary_language_servers_for_buffer(buffer, cx)
4477 .map(|(_, server)| server.clone()),
4478 ) {
4479 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
4480 return cx.spawn(|this, cx| async move {
4481 if !request.check_capabilities(language_server.capabilities()) {
4482 return Ok(Default::default());
4483 }
4484
4485 let response = language_server
4486 .request::<R::LspRequest>(lsp_params)
4487 .await
4488 .context("lsp request failed")?;
4489 request
4490 .response_from_lsp(
4491 response,
4492 this,
4493 buffer_handle,
4494 language_server.server_id(),
4495 cx,
4496 )
4497 .await
4498 });
4499 }
4500 } else if let Some(project_id) = self.remote_id() {
4501 let rpc = self.client.clone();
4502 let message = request.to_proto(project_id, buffer);
4503 return cx.spawn_weak(|this, cx| async move {
4504 // Ensure the project is still alive by the time the task
4505 // is scheduled.
4506 this.upgrade(&cx)
4507 .ok_or_else(|| anyhow!("project dropped"))?;
4508
4509 let response = rpc.request(message).await?;
4510
4511 let this = this
4512 .upgrade(&cx)
4513 .ok_or_else(|| anyhow!("project dropped"))?;
4514 if this.read_with(&cx, |this, _| this.is_read_only()) {
4515 Err(anyhow!("disconnected before completing request"))
4516 } else {
4517 request
4518 .response_from_proto(response, this, buffer_handle, cx)
4519 .await
4520 }
4521 });
4522 }
4523 Task::ready(Ok(Default::default()))
4524 }
4525
4526 pub fn find_or_create_local_worktree(
4527 &mut self,
4528 abs_path: impl AsRef<Path>,
4529 visible: bool,
4530 cx: &mut ModelContext<Self>,
4531 ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4532 let abs_path = abs_path.as_ref();
4533 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4534 Task::ready(Ok((tree, relative_path)))
4535 } else {
4536 let worktree = self.create_local_worktree(abs_path, visible, cx);
4537 cx.foreground()
4538 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4539 }
4540 }
4541
4542 pub fn find_local_worktree(
4543 &self,
4544 abs_path: &Path,
4545 cx: &AppContext,
4546 ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4547 for tree in &self.worktrees {
4548 if let Some(tree) = tree.upgrade(cx) {
4549 if let Some(relative_path) = tree
4550 .read(cx)
4551 .as_local()
4552 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4553 {
4554 return Some((tree.clone(), relative_path.into()));
4555 }
4556 }
4557 }
4558 None
4559 }
4560
4561 pub fn is_shared(&self) -> bool {
4562 match &self.client_state {
4563 Some(ProjectClientState::Local { .. }) => true,
4564 _ => false,
4565 }
4566 }
4567
4568 fn create_local_worktree(
4569 &mut self,
4570 abs_path: impl AsRef<Path>,
4571 visible: bool,
4572 cx: &mut ModelContext<Self>,
4573 ) -> Task<Result<ModelHandle<Worktree>>> {
4574 let fs = self.fs.clone();
4575 let client = self.client.clone();
4576 let next_entry_id = self.next_entry_id.clone();
4577 let path: Arc<Path> = abs_path.as_ref().into();
4578 let task = self
4579 .loading_local_worktrees
4580 .entry(path.clone())
4581 .or_insert_with(|| {
4582 cx.spawn(|project, mut cx| {
4583 async move {
4584 let worktree = Worktree::local(
4585 client.clone(),
4586 path.clone(),
4587 visible,
4588 fs,
4589 next_entry_id,
4590 &mut cx,
4591 )
4592 .await;
4593
4594 project.update(&mut cx, |project, _| {
4595 project.loading_local_worktrees.remove(&path);
4596 });
4597
4598 let worktree = worktree?;
4599 project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
4600 Ok(worktree)
4601 }
4602 .map_err(Arc::new)
4603 })
4604 .shared()
4605 })
4606 .clone();
4607 cx.foreground().spawn(async move {
4608 match task.await {
4609 Ok(worktree) => Ok(worktree),
4610 Err(err) => Err(anyhow!("{}", err)),
4611 }
4612 })
4613 }
4614
4615 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4616 self.worktrees.retain(|worktree| {
4617 if let Some(worktree) = worktree.upgrade(cx) {
4618 let id = worktree.read(cx).id();
4619 if id == id_to_remove {
4620 cx.emit(Event::WorktreeRemoved(id));
4621 false
4622 } else {
4623 true
4624 }
4625 } else {
4626 false
4627 }
4628 });
4629 self.metadata_changed(cx);
4630 }
4631
4632 fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4633 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4634 if worktree.read(cx).is_local() {
4635 cx.subscribe(worktree, |this, worktree, event, cx| match event {
4636 worktree::Event::UpdatedEntries(changes) => {
4637 this.update_local_worktree_buffers(&worktree, &changes, cx);
4638 this.update_local_worktree_language_servers(&worktree, changes, cx);
4639 }
4640 worktree::Event::UpdatedGitRepositories(updated_repos) => {
4641 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4642 }
4643 })
4644 .detach();
4645 }
4646
4647 let push_strong_handle = {
4648 let worktree = worktree.read(cx);
4649 self.is_shared() || worktree.is_visible() || worktree.is_remote()
4650 };
4651 if push_strong_handle {
4652 self.worktrees
4653 .push(WorktreeHandle::Strong(worktree.clone()));
4654 } else {
4655 self.worktrees
4656 .push(WorktreeHandle::Weak(worktree.downgrade()));
4657 }
4658
4659 cx.observe_release(worktree, |this, worktree, cx| {
4660 let _ = this.remove_worktree(worktree.id(), cx);
4661 })
4662 .detach();
4663
4664 cx.emit(Event::WorktreeAdded);
4665 self.metadata_changed(cx);
4666 }
4667
4668 fn update_local_worktree_buffers(
4669 &mut self,
4670 worktree_handle: &ModelHandle<Worktree>,
4671 changes: &HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
4672 cx: &mut ModelContext<Self>,
4673 ) {
4674 let snapshot = worktree_handle.read(cx).snapshot();
4675
4676 let mut renamed_buffers = Vec::new();
4677 for (path, entry_id) in changes.keys() {
4678 let worktree_id = worktree_handle.read(cx).id();
4679 let project_path = ProjectPath {
4680 worktree_id,
4681 path: path.clone(),
4682 };
4683
4684 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
4685 Some(&buffer_id) => buffer_id,
4686 None => match self.local_buffer_ids_by_path.get(&project_path) {
4687 Some(&buffer_id) => buffer_id,
4688 None => continue,
4689 },
4690 };
4691
4692 let open_buffer = self.opened_buffers.get(&buffer_id);
4693 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
4694 buffer
4695 } else {
4696 self.opened_buffers.remove(&buffer_id);
4697 self.local_buffer_ids_by_path.remove(&project_path);
4698 self.local_buffer_ids_by_entry_id.remove(entry_id);
4699 continue;
4700 };
4701
4702 buffer.update(cx, |buffer, cx| {
4703 if let Some(old_file) = File::from_dyn(buffer.file()) {
4704 if old_file.worktree != *worktree_handle {
4705 return;
4706 }
4707
4708 let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
4709 File {
4710 is_local: true,
4711 entry_id: entry.id,
4712 mtime: entry.mtime,
4713 path: entry.path.clone(),
4714 worktree: worktree_handle.clone(),
4715 is_deleted: false,
4716 }
4717 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
4718 File {
4719 is_local: true,
4720 entry_id: entry.id,
4721 mtime: entry.mtime,
4722 path: entry.path.clone(),
4723 worktree: worktree_handle.clone(),
4724 is_deleted: false,
4725 }
4726 } else {
4727 File {
4728 is_local: true,
4729 entry_id: old_file.entry_id,
4730 path: old_file.path().clone(),
4731 mtime: old_file.mtime(),
4732 worktree: worktree_handle.clone(),
4733 is_deleted: true,
4734 }
4735 };
4736
4737 let old_path = old_file.abs_path(cx);
4738 if new_file.abs_path(cx) != old_path {
4739 renamed_buffers.push((cx.handle(), old_file.clone()));
4740 self.local_buffer_ids_by_path.remove(&project_path);
4741 self.local_buffer_ids_by_path.insert(
4742 ProjectPath {
4743 worktree_id,
4744 path: path.clone(),
4745 },
4746 buffer_id,
4747 );
4748 }
4749
4750 if new_file.entry_id != *entry_id {
4751 self.local_buffer_ids_by_entry_id.remove(entry_id);
4752 self.local_buffer_ids_by_entry_id
4753 .insert(new_file.entry_id, buffer_id);
4754 }
4755
4756 if new_file != *old_file {
4757 if let Some(project_id) = self.remote_id() {
4758 self.client
4759 .send(proto::UpdateBufferFile {
4760 project_id,
4761 buffer_id: buffer_id as u64,
4762 file: Some(new_file.to_proto()),
4763 })
4764 .log_err();
4765 }
4766
4767 buffer.file_updated(Arc::new(new_file), cx).detach();
4768 }
4769 }
4770 });
4771 }
4772
4773 for (buffer, old_file) in renamed_buffers {
4774 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
4775 self.detect_language_for_buffer(&buffer, cx);
4776 self.register_buffer_with_language_servers(&buffer, cx);
4777 }
4778 }
4779
4780 fn update_local_worktree_language_servers(
4781 &mut self,
4782 worktree_handle: &ModelHandle<Worktree>,
4783 changes: &HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
4784 cx: &mut ModelContext<Self>,
4785 ) {
4786 if changes.is_empty() {
4787 return;
4788 }
4789
4790 let worktree_id = worktree_handle.read(cx).id();
4791 let mut language_server_ids = self
4792 .language_server_ids
4793 .iter()
4794 .filter_map(|((server_worktree_id, _), server_id)| {
4795 (*server_worktree_id == worktree_id).then_some(*server_id)
4796 })
4797 .collect::<Vec<_>>();
4798 language_server_ids.sort();
4799 language_server_ids.dedup();
4800
4801 let abs_path = worktree_handle.read(cx).abs_path();
4802 for server_id in &language_server_ids {
4803 if let Some(server) = self.language_servers.get(server_id) {
4804 if let LanguageServerState::Running {
4805 server,
4806 watched_paths,
4807 ..
4808 } = server
4809 {
4810 if let Some(watched_paths) = watched_paths.get(&worktree_id) {
4811 let params = lsp::DidChangeWatchedFilesParams {
4812 changes: changes
4813 .iter()
4814 .filter_map(|((path, _), change)| {
4815 if watched_paths.is_match(&path) {
4816 Some(lsp::FileEvent {
4817 uri: lsp::Url::from_file_path(abs_path.join(path))
4818 .unwrap(),
4819 typ: match change {
4820 PathChange::Added => lsp::FileChangeType::CREATED,
4821 PathChange::Removed => lsp::FileChangeType::DELETED,
4822 PathChange::Updated
4823 | PathChange::AddedOrUpdated => {
4824 lsp::FileChangeType::CHANGED
4825 }
4826 },
4827 })
4828 } else {
4829 None
4830 }
4831 })
4832 .collect(),
4833 };
4834
4835 if !params.changes.is_empty() {
4836 server
4837 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
4838 .log_err();
4839 }
4840 }
4841 }
4842 }
4843 }
4844 }
4845
4846 fn update_local_worktree_buffers_git_repos(
4847 &mut self,
4848 worktree_handle: ModelHandle<Worktree>,
4849 repos: &HashMap<Arc<Path>, LocalRepositoryEntry>,
4850 cx: &mut ModelContext<Self>,
4851 ) {
4852 debug_assert!(worktree_handle.read(cx).is_local());
4853
4854 // Setup the pending buffers
4855 let future_buffers = self
4856 .loading_buffers_by_path
4857 .iter()
4858 .filter_map(|(path, receiver)| {
4859 let path = &path.path;
4860 let (work_directory, repo) = repos
4861 .iter()
4862 .find(|(work_directory, _)| path.starts_with(work_directory))?;
4863
4864 let repo_relative_path = path.strip_prefix(work_directory).log_err()?;
4865
4866 let receiver = receiver.clone();
4867 let repo_ptr = repo.repo_ptr.clone();
4868 let repo_relative_path = repo_relative_path.to_owned();
4869 Some(async move {
4870 pump_loading_buffer_reciever(receiver)
4871 .await
4872 .ok()
4873 .map(|buffer| (buffer, repo_relative_path, repo_ptr))
4874 })
4875 })
4876 .collect::<FuturesUnordered<_>>()
4877 .filter_map(|result| async move {
4878 let (buffer_handle, repo_relative_path, repo_ptr) = result?;
4879
4880 let lock = repo_ptr.lock();
4881 lock.load_index_text(&repo_relative_path)
4882 .map(|diff_base| (diff_base, buffer_handle))
4883 });
4884
4885 let update_diff_base_fn = update_diff_base(self);
4886 cx.spawn(|_, mut cx| async move {
4887 let diff_base_tasks = cx
4888 .background()
4889 .spawn(future_buffers.collect::<Vec<_>>())
4890 .await;
4891
4892 for (diff_base, buffer) in diff_base_tasks.into_iter() {
4893 update_diff_base_fn(Some(diff_base), buffer, &mut cx);
4894 }
4895 })
4896 .detach();
4897
4898 // And the current buffers
4899 for (_, buffer) in &self.opened_buffers {
4900 if let Some(buffer) = buffer.upgrade(cx) {
4901 let file = match File::from_dyn(buffer.read(cx).file()) {
4902 Some(file) => file,
4903 None => continue,
4904 };
4905 if file.worktree != worktree_handle {
4906 continue;
4907 }
4908
4909 let path = file.path().clone();
4910
4911 let worktree = worktree_handle.read(cx);
4912
4913 let (work_directory, repo) = match repos
4914 .iter()
4915 .find(|(work_directory, _)| path.starts_with(work_directory))
4916 {
4917 Some(repo) => repo.clone(),
4918 None => continue,
4919 };
4920
4921 let relative_repo = match path.strip_prefix(work_directory).log_err() {
4922 Some(relative_repo) => relative_repo.to_owned(),
4923 None => continue,
4924 };
4925
4926 drop(worktree);
4927
4928 let update_diff_base_fn = update_diff_base(self);
4929 let git_ptr = repo.repo_ptr.clone();
4930 let diff_base_task = cx
4931 .background()
4932 .spawn(async move { git_ptr.lock().load_index_text(&relative_repo) });
4933
4934 cx.spawn(|_, mut cx| async move {
4935 let diff_base = diff_base_task.await;
4936 update_diff_base_fn(diff_base, buffer, &mut cx);
4937 })
4938 .detach();
4939 }
4940 }
4941 }
4942
4943 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4944 let new_active_entry = entry.and_then(|project_path| {
4945 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4946 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4947 Some(entry.id)
4948 });
4949 if new_active_entry != self.active_entry {
4950 self.active_entry = new_active_entry;
4951 cx.emit(Event::ActiveEntryChanged(new_active_entry));
4952 }
4953 }
4954
4955 pub fn language_servers_running_disk_based_diagnostics(
4956 &self,
4957 ) -> impl Iterator<Item = LanguageServerId> + '_ {
4958 self.language_server_statuses
4959 .iter()
4960 .filter_map(|(id, status)| {
4961 if status.has_pending_diagnostic_updates {
4962 Some(*id)
4963 } else {
4964 None
4965 }
4966 })
4967 }
4968
4969 pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4970 let mut summary = DiagnosticSummary::default();
4971 for (_, _, path_summary) in self.diagnostic_summaries(cx) {
4972 summary.error_count += path_summary.error_count;
4973 summary.warning_count += path_summary.warning_count;
4974 }
4975 summary
4976 }
4977
4978 pub fn diagnostic_summaries<'a>(
4979 &'a self,
4980 cx: &'a AppContext,
4981 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4982 self.visible_worktrees(cx).flat_map(move |worktree| {
4983 let worktree = worktree.read(cx);
4984 let worktree_id = worktree.id();
4985 worktree
4986 .diagnostic_summaries()
4987 .map(move |(path, server_id, summary)| {
4988 (ProjectPath { worktree_id, path }, server_id, summary)
4989 })
4990 })
4991 }
4992
4993 pub fn disk_based_diagnostics_started(
4994 &mut self,
4995 language_server_id: LanguageServerId,
4996 cx: &mut ModelContext<Self>,
4997 ) {
4998 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4999 }
5000
5001 pub fn disk_based_diagnostics_finished(
5002 &mut self,
5003 language_server_id: LanguageServerId,
5004 cx: &mut ModelContext<Self>,
5005 ) {
5006 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
5007 }
5008
5009 pub fn active_entry(&self) -> Option<ProjectEntryId> {
5010 self.active_entry
5011 }
5012
5013 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
5014 self.worktree_for_id(path.worktree_id, cx)?
5015 .read(cx)
5016 .entry_for_path(&path.path)
5017 .cloned()
5018 }
5019
5020 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
5021 let worktree = self.worktree_for_entry(entry_id, cx)?;
5022 let worktree = worktree.read(cx);
5023 let worktree_id = worktree.id();
5024 let path = worktree.entry_for_id(entry_id)?.path.clone();
5025 Some(ProjectPath { worktree_id, path })
5026 }
5027
5028 // RPC message handlers
5029
5030 async fn handle_unshare_project(
5031 this: ModelHandle<Self>,
5032 _: TypedEnvelope<proto::UnshareProject>,
5033 _: Arc<Client>,
5034 mut cx: AsyncAppContext,
5035 ) -> Result<()> {
5036 this.update(&mut cx, |this, cx| {
5037 if this.is_local() {
5038 this.unshare(cx)?;
5039 } else {
5040 this.disconnected_from_host(cx);
5041 }
5042 Ok(())
5043 })
5044 }
5045
5046 async fn handle_add_collaborator(
5047 this: ModelHandle<Self>,
5048 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5049 _: Arc<Client>,
5050 mut cx: AsyncAppContext,
5051 ) -> Result<()> {
5052 let collaborator = envelope
5053 .payload
5054 .collaborator
5055 .take()
5056 .ok_or_else(|| anyhow!("empty collaborator"))?;
5057
5058 let collaborator = Collaborator::from_proto(collaborator)?;
5059 this.update(&mut cx, |this, cx| {
5060 this.shared_buffers.remove(&collaborator.peer_id);
5061 this.collaborators
5062 .insert(collaborator.peer_id, collaborator);
5063 cx.notify();
5064 });
5065
5066 Ok(())
5067 }
5068
5069 async fn handle_update_project_collaborator(
5070 this: ModelHandle<Self>,
5071 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5072 _: Arc<Client>,
5073 mut cx: AsyncAppContext,
5074 ) -> Result<()> {
5075 let old_peer_id = envelope
5076 .payload
5077 .old_peer_id
5078 .ok_or_else(|| anyhow!("missing old peer id"))?;
5079 let new_peer_id = envelope
5080 .payload
5081 .new_peer_id
5082 .ok_or_else(|| anyhow!("missing new peer id"))?;
5083 this.update(&mut cx, |this, cx| {
5084 let collaborator = this
5085 .collaborators
5086 .remove(&old_peer_id)
5087 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
5088 let is_host = collaborator.replica_id == 0;
5089 this.collaborators.insert(new_peer_id, collaborator);
5090
5091 let buffers = this.shared_buffers.remove(&old_peer_id);
5092 log::info!(
5093 "peer {} became {}. moving buffers {:?}",
5094 old_peer_id,
5095 new_peer_id,
5096 &buffers
5097 );
5098 if let Some(buffers) = buffers {
5099 this.shared_buffers.insert(new_peer_id, buffers);
5100 }
5101
5102 if is_host {
5103 this.opened_buffers
5104 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
5105 this.buffer_ordered_messages_tx
5106 .unbounded_send(BufferOrderedMessage::Resync)
5107 .unwrap();
5108 }
5109
5110 cx.emit(Event::CollaboratorUpdated {
5111 old_peer_id,
5112 new_peer_id,
5113 });
5114 cx.notify();
5115 Ok(())
5116 })
5117 }
5118
5119 async fn handle_remove_collaborator(
5120 this: ModelHandle<Self>,
5121 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5122 _: Arc<Client>,
5123 mut cx: AsyncAppContext,
5124 ) -> Result<()> {
5125 this.update(&mut cx, |this, cx| {
5126 let peer_id = envelope
5127 .payload
5128 .peer_id
5129 .ok_or_else(|| anyhow!("invalid peer id"))?;
5130 let replica_id = this
5131 .collaborators
5132 .remove(&peer_id)
5133 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
5134 .replica_id;
5135 for buffer in this.opened_buffers.values() {
5136 if let Some(buffer) = buffer.upgrade(cx) {
5137 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5138 }
5139 }
5140 this.shared_buffers.remove(&peer_id);
5141
5142 cx.emit(Event::CollaboratorLeft(peer_id));
5143 cx.notify();
5144 Ok(())
5145 })
5146 }
5147
5148 async fn handle_update_project(
5149 this: ModelHandle<Self>,
5150 envelope: TypedEnvelope<proto::UpdateProject>,
5151 _: Arc<Client>,
5152 mut cx: AsyncAppContext,
5153 ) -> Result<()> {
5154 this.update(&mut cx, |this, cx| {
5155 // Don't handle messages that were sent before the response to us joining the project
5156 if envelope.message_id > this.join_project_response_message_id {
5157 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5158 }
5159 Ok(())
5160 })
5161 }
5162
5163 async fn handle_update_worktree(
5164 this: ModelHandle<Self>,
5165 envelope: TypedEnvelope<proto::UpdateWorktree>,
5166 _: Arc<Client>,
5167 mut cx: AsyncAppContext,
5168 ) -> Result<()> {
5169 this.update(&mut cx, |this, cx| {
5170 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5171 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5172 worktree.update(cx, |worktree, _| {
5173 let worktree = worktree.as_remote_mut().unwrap();
5174 worktree.update_from_remote(envelope.payload);
5175 });
5176 }
5177 Ok(())
5178 })
5179 }
5180
5181 async fn handle_create_project_entry(
5182 this: ModelHandle<Self>,
5183 envelope: TypedEnvelope<proto::CreateProjectEntry>,
5184 _: Arc<Client>,
5185 mut cx: AsyncAppContext,
5186 ) -> Result<proto::ProjectEntryResponse> {
5187 let worktree = this.update(&mut cx, |this, cx| {
5188 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5189 this.worktree_for_id(worktree_id, cx)
5190 .ok_or_else(|| anyhow!("worktree not found"))
5191 })?;
5192 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5193 let entry = worktree
5194 .update(&mut cx, |worktree, cx| {
5195 let worktree = worktree.as_local_mut().unwrap();
5196 let path = PathBuf::from(envelope.payload.path);
5197 worktree.create_entry(path, envelope.payload.is_directory, cx)
5198 })
5199 .await?;
5200 Ok(proto::ProjectEntryResponse {
5201 entry: Some((&entry).into()),
5202 worktree_scan_id: worktree_scan_id as u64,
5203 })
5204 }
5205
5206 async fn handle_rename_project_entry(
5207 this: ModelHandle<Self>,
5208 envelope: TypedEnvelope<proto::RenameProjectEntry>,
5209 _: Arc<Client>,
5210 mut cx: AsyncAppContext,
5211 ) -> Result<proto::ProjectEntryResponse> {
5212 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5213 let worktree = this.read_with(&cx, |this, cx| {
5214 this.worktree_for_entry(entry_id, cx)
5215 .ok_or_else(|| anyhow!("worktree not found"))
5216 })?;
5217 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5218 let entry = worktree
5219 .update(&mut cx, |worktree, cx| {
5220 let new_path = PathBuf::from(envelope.payload.new_path);
5221 worktree
5222 .as_local_mut()
5223 .unwrap()
5224 .rename_entry(entry_id, new_path, cx)
5225 .ok_or_else(|| anyhow!("invalid entry"))
5226 })?
5227 .await?;
5228 Ok(proto::ProjectEntryResponse {
5229 entry: Some((&entry).into()),
5230 worktree_scan_id: worktree_scan_id as u64,
5231 })
5232 }
5233
5234 async fn handle_copy_project_entry(
5235 this: ModelHandle<Self>,
5236 envelope: TypedEnvelope<proto::CopyProjectEntry>,
5237 _: Arc<Client>,
5238 mut cx: AsyncAppContext,
5239 ) -> Result<proto::ProjectEntryResponse> {
5240 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5241 let worktree = this.read_with(&cx, |this, cx| {
5242 this.worktree_for_entry(entry_id, cx)
5243 .ok_or_else(|| anyhow!("worktree not found"))
5244 })?;
5245 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5246 let entry = worktree
5247 .update(&mut cx, |worktree, cx| {
5248 let new_path = PathBuf::from(envelope.payload.new_path);
5249 worktree
5250 .as_local_mut()
5251 .unwrap()
5252 .copy_entry(entry_id, new_path, cx)
5253 .ok_or_else(|| anyhow!("invalid entry"))
5254 })?
5255 .await?;
5256 Ok(proto::ProjectEntryResponse {
5257 entry: Some((&entry).into()),
5258 worktree_scan_id: worktree_scan_id as u64,
5259 })
5260 }
5261
5262 async fn handle_delete_project_entry(
5263 this: ModelHandle<Self>,
5264 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5265 _: Arc<Client>,
5266 mut cx: AsyncAppContext,
5267 ) -> Result<proto::ProjectEntryResponse> {
5268 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5269
5270 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
5271
5272 let worktree = this.read_with(&cx, |this, cx| {
5273 this.worktree_for_entry(entry_id, cx)
5274 .ok_or_else(|| anyhow!("worktree not found"))
5275 })?;
5276 let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5277 worktree
5278 .update(&mut cx, |worktree, cx| {
5279 worktree
5280 .as_local_mut()
5281 .unwrap()
5282 .delete_entry(entry_id, cx)
5283 .ok_or_else(|| anyhow!("invalid entry"))
5284 })?
5285 .await?;
5286 Ok(proto::ProjectEntryResponse {
5287 entry: None,
5288 worktree_scan_id: worktree_scan_id as u64,
5289 })
5290 }
5291
5292 async fn handle_update_diagnostic_summary(
5293 this: ModelHandle<Self>,
5294 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5295 _: Arc<Client>,
5296 mut cx: AsyncAppContext,
5297 ) -> Result<()> {
5298 this.update(&mut cx, |this, cx| {
5299 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5300 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5301 if let Some(summary) = envelope.payload.summary {
5302 let project_path = ProjectPath {
5303 worktree_id,
5304 path: Path::new(&summary.path).into(),
5305 };
5306 worktree.update(cx, |worktree, _| {
5307 worktree
5308 .as_remote_mut()
5309 .unwrap()
5310 .update_diagnostic_summary(project_path.path.clone(), &summary);
5311 });
5312 cx.emit(Event::DiagnosticsUpdated {
5313 language_server_id: LanguageServerId(summary.language_server_id as usize),
5314 path: project_path,
5315 });
5316 }
5317 }
5318 Ok(())
5319 })
5320 }
5321
5322 async fn handle_start_language_server(
5323 this: ModelHandle<Self>,
5324 envelope: TypedEnvelope<proto::StartLanguageServer>,
5325 _: Arc<Client>,
5326 mut cx: AsyncAppContext,
5327 ) -> Result<()> {
5328 let server = envelope
5329 .payload
5330 .server
5331 .ok_or_else(|| anyhow!("invalid server"))?;
5332 this.update(&mut cx, |this, cx| {
5333 this.language_server_statuses.insert(
5334 LanguageServerId(server.id as usize),
5335 LanguageServerStatus {
5336 name: server.name,
5337 pending_work: Default::default(),
5338 has_pending_diagnostic_updates: false,
5339 progress_tokens: Default::default(),
5340 },
5341 );
5342 cx.notify();
5343 });
5344 Ok(())
5345 }
5346
5347 async fn handle_update_language_server(
5348 this: ModelHandle<Self>,
5349 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5350 _: Arc<Client>,
5351 mut cx: AsyncAppContext,
5352 ) -> Result<()> {
5353 this.update(&mut cx, |this, cx| {
5354 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
5355
5356 match envelope
5357 .payload
5358 .variant
5359 .ok_or_else(|| anyhow!("invalid variant"))?
5360 {
5361 proto::update_language_server::Variant::WorkStart(payload) => {
5362 this.on_lsp_work_start(
5363 language_server_id,
5364 payload.token,
5365 LanguageServerProgress {
5366 message: payload.message,
5367 percentage: payload.percentage.map(|p| p as usize),
5368 last_update_at: Instant::now(),
5369 },
5370 cx,
5371 );
5372 }
5373
5374 proto::update_language_server::Variant::WorkProgress(payload) => {
5375 this.on_lsp_work_progress(
5376 language_server_id,
5377 payload.token,
5378 LanguageServerProgress {
5379 message: payload.message,
5380 percentage: payload.percentage.map(|p| p as usize),
5381 last_update_at: Instant::now(),
5382 },
5383 cx,
5384 );
5385 }
5386
5387 proto::update_language_server::Variant::WorkEnd(payload) => {
5388 this.on_lsp_work_end(language_server_id, payload.token, cx);
5389 }
5390
5391 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5392 this.disk_based_diagnostics_started(language_server_id, cx);
5393 }
5394
5395 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5396 this.disk_based_diagnostics_finished(language_server_id, cx)
5397 }
5398 }
5399
5400 Ok(())
5401 })
5402 }
5403
5404 async fn handle_update_buffer(
5405 this: ModelHandle<Self>,
5406 envelope: TypedEnvelope<proto::UpdateBuffer>,
5407 _: Arc<Client>,
5408 mut cx: AsyncAppContext,
5409 ) -> Result<proto::Ack> {
5410 this.update(&mut cx, |this, cx| {
5411 let payload = envelope.payload.clone();
5412 let buffer_id = payload.buffer_id;
5413 let ops = payload
5414 .operations
5415 .into_iter()
5416 .map(language::proto::deserialize_operation)
5417 .collect::<Result<Vec<_>, _>>()?;
5418 let is_remote = this.is_remote();
5419 match this.opened_buffers.entry(buffer_id) {
5420 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5421 OpenBuffer::Strong(buffer) => {
5422 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5423 }
5424 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5425 OpenBuffer::Weak(_) => {}
5426 },
5427 hash_map::Entry::Vacant(e) => {
5428 assert!(
5429 is_remote,
5430 "received buffer update from {:?}",
5431 envelope.original_sender_id
5432 );
5433 e.insert(OpenBuffer::Operations(ops));
5434 }
5435 }
5436 Ok(proto::Ack {})
5437 })
5438 }
5439
5440 async fn handle_create_buffer_for_peer(
5441 this: ModelHandle<Self>,
5442 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5443 _: Arc<Client>,
5444 mut cx: AsyncAppContext,
5445 ) -> Result<()> {
5446 this.update(&mut cx, |this, cx| {
5447 match envelope
5448 .payload
5449 .variant
5450 .ok_or_else(|| anyhow!("missing variant"))?
5451 {
5452 proto::create_buffer_for_peer::Variant::State(mut state) => {
5453 let mut buffer_file = None;
5454 if let Some(file) = state.file.take() {
5455 let worktree_id = WorktreeId::from_proto(file.worktree_id);
5456 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5457 anyhow!("no worktree found for id {}", file.worktree_id)
5458 })?;
5459 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5460 as Arc<dyn language::File>);
5461 }
5462
5463 let buffer_id = state.id;
5464 let buffer = cx.add_model(|_| {
5465 Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5466 });
5467 this.incomplete_remote_buffers
5468 .insert(buffer_id, Some(buffer));
5469 }
5470 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5471 let buffer = this
5472 .incomplete_remote_buffers
5473 .get(&chunk.buffer_id)
5474 .cloned()
5475 .flatten()
5476 .ok_or_else(|| {
5477 anyhow!(
5478 "received chunk for buffer {} without initial state",
5479 chunk.buffer_id
5480 )
5481 })?;
5482 let operations = chunk
5483 .operations
5484 .into_iter()
5485 .map(language::proto::deserialize_operation)
5486 .collect::<Result<Vec<_>>>()?;
5487 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5488
5489 if chunk.is_last {
5490 this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5491 this.register_buffer(&buffer, cx)?;
5492 }
5493 }
5494 }
5495
5496 Ok(())
5497 })
5498 }
5499
5500 async fn handle_update_diff_base(
5501 this: ModelHandle<Self>,
5502 envelope: TypedEnvelope<proto::UpdateDiffBase>,
5503 _: Arc<Client>,
5504 mut cx: AsyncAppContext,
5505 ) -> Result<()> {
5506 this.update(&mut cx, |this, cx| {
5507 let buffer_id = envelope.payload.buffer_id;
5508 let diff_base = envelope.payload.diff_base;
5509 if let Some(buffer) = this
5510 .opened_buffers
5511 .get_mut(&buffer_id)
5512 .and_then(|b| b.upgrade(cx))
5513 .or_else(|| {
5514 this.incomplete_remote_buffers
5515 .get(&buffer_id)
5516 .cloned()
5517 .flatten()
5518 })
5519 {
5520 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5521 }
5522 Ok(())
5523 })
5524 }
5525
5526 async fn handle_update_buffer_file(
5527 this: ModelHandle<Self>,
5528 envelope: TypedEnvelope<proto::UpdateBufferFile>,
5529 _: Arc<Client>,
5530 mut cx: AsyncAppContext,
5531 ) -> Result<()> {
5532 let buffer_id = envelope.payload.buffer_id;
5533
5534 this.update(&mut cx, |this, cx| {
5535 let payload = envelope.payload.clone();
5536 if let Some(buffer) = this
5537 .opened_buffers
5538 .get(&buffer_id)
5539 .and_then(|b| b.upgrade(cx))
5540 .or_else(|| {
5541 this.incomplete_remote_buffers
5542 .get(&buffer_id)
5543 .cloned()
5544 .flatten()
5545 })
5546 {
5547 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5548 let worktree = this
5549 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5550 .ok_or_else(|| anyhow!("no such worktree"))?;
5551 let file = File::from_proto(file, worktree, cx)?;
5552 buffer.update(cx, |buffer, cx| {
5553 buffer.file_updated(Arc::new(file), cx).detach();
5554 });
5555 this.detect_language_for_buffer(&buffer, cx);
5556 }
5557 Ok(())
5558 })
5559 }
5560
5561 async fn handle_save_buffer(
5562 this: ModelHandle<Self>,
5563 envelope: TypedEnvelope<proto::SaveBuffer>,
5564 _: Arc<Client>,
5565 mut cx: AsyncAppContext,
5566 ) -> Result<proto::BufferSaved> {
5567 let buffer_id = envelope.payload.buffer_id;
5568 let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5569 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5570 let buffer = this
5571 .opened_buffers
5572 .get(&buffer_id)
5573 .and_then(|buffer| buffer.upgrade(cx))
5574 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5575 anyhow::Ok((project_id, buffer))
5576 })?;
5577 buffer
5578 .update(&mut cx, |buffer, _| {
5579 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
5580 })
5581 .await?;
5582 let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
5583
5584 let (saved_version, fingerprint, mtime) = this
5585 .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5586 .await?;
5587 Ok(proto::BufferSaved {
5588 project_id,
5589 buffer_id,
5590 version: serialize_version(&saved_version),
5591 mtime: Some(mtime.into()),
5592 fingerprint: language::proto::serialize_fingerprint(fingerprint),
5593 })
5594 }
5595
5596 async fn handle_reload_buffers(
5597 this: ModelHandle<Self>,
5598 envelope: TypedEnvelope<proto::ReloadBuffers>,
5599 _: Arc<Client>,
5600 mut cx: AsyncAppContext,
5601 ) -> Result<proto::ReloadBuffersResponse> {
5602 let sender_id = envelope.original_sender_id()?;
5603 let reload = this.update(&mut cx, |this, cx| {
5604 let mut buffers = HashSet::default();
5605 for buffer_id in &envelope.payload.buffer_ids {
5606 buffers.insert(
5607 this.opened_buffers
5608 .get(buffer_id)
5609 .and_then(|buffer| buffer.upgrade(cx))
5610 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5611 );
5612 }
5613 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5614 })?;
5615
5616 let project_transaction = reload.await?;
5617 let project_transaction = this.update(&mut cx, |this, cx| {
5618 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5619 });
5620 Ok(proto::ReloadBuffersResponse {
5621 transaction: Some(project_transaction),
5622 })
5623 }
5624
5625 async fn handle_synchronize_buffers(
5626 this: ModelHandle<Self>,
5627 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5628 _: Arc<Client>,
5629 mut cx: AsyncAppContext,
5630 ) -> Result<proto::SynchronizeBuffersResponse> {
5631 let project_id = envelope.payload.project_id;
5632 let mut response = proto::SynchronizeBuffersResponse {
5633 buffers: Default::default(),
5634 };
5635
5636 this.update(&mut cx, |this, cx| {
5637 let Some(guest_id) = envelope.original_sender_id else {
5638 log::error!("missing original_sender_id on SynchronizeBuffers request");
5639 return;
5640 };
5641
5642 this.shared_buffers.entry(guest_id).or_default().clear();
5643 for buffer in envelope.payload.buffers {
5644 let buffer_id = buffer.id;
5645 let remote_version = language::proto::deserialize_version(&buffer.version);
5646 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5647 this.shared_buffers
5648 .entry(guest_id)
5649 .or_default()
5650 .insert(buffer_id);
5651
5652 let buffer = buffer.read(cx);
5653 response.buffers.push(proto::BufferVersion {
5654 id: buffer_id,
5655 version: language::proto::serialize_version(&buffer.version),
5656 });
5657
5658 let operations = buffer.serialize_ops(Some(remote_version), cx);
5659 let client = this.client.clone();
5660 if let Some(file) = buffer.file() {
5661 client
5662 .send(proto::UpdateBufferFile {
5663 project_id,
5664 buffer_id: buffer_id as u64,
5665 file: Some(file.to_proto()),
5666 })
5667 .log_err();
5668 }
5669
5670 client
5671 .send(proto::UpdateDiffBase {
5672 project_id,
5673 buffer_id: buffer_id as u64,
5674 diff_base: buffer.diff_base().map(Into::into),
5675 })
5676 .log_err();
5677
5678 client
5679 .send(proto::BufferReloaded {
5680 project_id,
5681 buffer_id,
5682 version: language::proto::serialize_version(buffer.saved_version()),
5683 mtime: Some(buffer.saved_mtime().into()),
5684 fingerprint: language::proto::serialize_fingerprint(
5685 buffer.saved_version_fingerprint(),
5686 ),
5687 line_ending: language::proto::serialize_line_ending(
5688 buffer.line_ending(),
5689 ) as i32,
5690 })
5691 .log_err();
5692
5693 cx.background()
5694 .spawn(
5695 async move {
5696 let operations = operations.await;
5697 for chunk in split_operations(operations) {
5698 client
5699 .request(proto::UpdateBuffer {
5700 project_id,
5701 buffer_id,
5702 operations: chunk,
5703 })
5704 .await?;
5705 }
5706 anyhow::Ok(())
5707 }
5708 .log_err(),
5709 )
5710 .detach();
5711 }
5712 }
5713 });
5714
5715 Ok(response)
5716 }
5717
5718 async fn handle_format_buffers(
5719 this: ModelHandle<Self>,
5720 envelope: TypedEnvelope<proto::FormatBuffers>,
5721 _: Arc<Client>,
5722 mut cx: AsyncAppContext,
5723 ) -> Result<proto::FormatBuffersResponse> {
5724 let sender_id = envelope.original_sender_id()?;
5725 let format = this.update(&mut cx, |this, cx| {
5726 let mut buffers = HashSet::default();
5727 for buffer_id in &envelope.payload.buffer_ids {
5728 buffers.insert(
5729 this.opened_buffers
5730 .get(buffer_id)
5731 .and_then(|buffer| buffer.upgrade(cx))
5732 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5733 );
5734 }
5735 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5736 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5737 })?;
5738
5739 let project_transaction = format.await?;
5740 let project_transaction = this.update(&mut cx, |this, cx| {
5741 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5742 });
5743 Ok(proto::FormatBuffersResponse {
5744 transaction: Some(project_transaction),
5745 })
5746 }
5747
5748 async fn handle_apply_additional_edits_for_completion(
5749 this: ModelHandle<Self>,
5750 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5751 _: Arc<Client>,
5752 mut cx: AsyncAppContext,
5753 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5754 let (buffer, completion) = this.update(&mut cx, |this, cx| {
5755 let buffer = this
5756 .opened_buffers
5757 .get(&envelope.payload.buffer_id)
5758 .and_then(|buffer| buffer.upgrade(cx))
5759 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5760 let language = buffer.read(cx).language();
5761 let completion = language::proto::deserialize_completion(
5762 envelope
5763 .payload
5764 .completion
5765 .ok_or_else(|| anyhow!("invalid completion"))?,
5766 language.cloned(),
5767 );
5768 Ok::<_, anyhow::Error>((buffer, completion))
5769 })?;
5770
5771 let completion = completion.await?;
5772
5773 let apply_additional_edits = this.update(&mut cx, |this, cx| {
5774 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5775 });
5776
5777 Ok(proto::ApplyCompletionAdditionalEditsResponse {
5778 transaction: apply_additional_edits
5779 .await?
5780 .as_ref()
5781 .map(language::proto::serialize_transaction),
5782 })
5783 }
5784
5785 async fn handle_apply_code_action(
5786 this: ModelHandle<Self>,
5787 envelope: TypedEnvelope<proto::ApplyCodeAction>,
5788 _: Arc<Client>,
5789 mut cx: AsyncAppContext,
5790 ) -> Result<proto::ApplyCodeActionResponse> {
5791 let sender_id = envelope.original_sender_id()?;
5792 let action = language::proto::deserialize_code_action(
5793 envelope
5794 .payload
5795 .action
5796 .ok_or_else(|| anyhow!("invalid action"))?,
5797 )?;
5798 let apply_code_action = this.update(&mut cx, |this, cx| {
5799 let buffer = this
5800 .opened_buffers
5801 .get(&envelope.payload.buffer_id)
5802 .and_then(|buffer| buffer.upgrade(cx))
5803 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5804 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5805 })?;
5806
5807 let project_transaction = apply_code_action.await?;
5808 let project_transaction = this.update(&mut cx, |this, cx| {
5809 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5810 });
5811 Ok(proto::ApplyCodeActionResponse {
5812 transaction: Some(project_transaction),
5813 })
5814 }
5815
5816 async fn handle_lsp_command<T: LspCommand>(
5817 this: ModelHandle<Self>,
5818 envelope: TypedEnvelope<T::ProtoRequest>,
5819 _: Arc<Client>,
5820 mut cx: AsyncAppContext,
5821 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5822 where
5823 <T::LspRequest as lsp::request::Request>::Result: Send,
5824 {
5825 let sender_id = envelope.original_sender_id()?;
5826 let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5827 let buffer_handle = this.read_with(&cx, |this, _| {
5828 this.opened_buffers
5829 .get(&buffer_id)
5830 .and_then(|buffer| buffer.upgrade(&cx))
5831 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5832 })?;
5833 let request = T::from_proto(
5834 envelope.payload,
5835 this.clone(),
5836 buffer_handle.clone(),
5837 cx.clone(),
5838 )
5839 .await?;
5840 let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5841 let response = this
5842 .update(&mut cx, |this, cx| {
5843 this.request_lsp(buffer_handle, request, cx)
5844 })
5845 .await?;
5846 this.update(&mut cx, |this, cx| {
5847 Ok(T::response_to_proto(
5848 response,
5849 this,
5850 sender_id,
5851 &buffer_version,
5852 cx,
5853 ))
5854 })
5855 }
5856
5857 async fn handle_get_project_symbols(
5858 this: ModelHandle<Self>,
5859 envelope: TypedEnvelope<proto::GetProjectSymbols>,
5860 _: Arc<Client>,
5861 mut cx: AsyncAppContext,
5862 ) -> Result<proto::GetProjectSymbolsResponse> {
5863 let symbols = this
5864 .update(&mut cx, |this, cx| {
5865 this.symbols(&envelope.payload.query, cx)
5866 })
5867 .await?;
5868
5869 Ok(proto::GetProjectSymbolsResponse {
5870 symbols: symbols.iter().map(serialize_symbol).collect(),
5871 })
5872 }
5873
5874 async fn handle_search_project(
5875 this: ModelHandle<Self>,
5876 envelope: TypedEnvelope<proto::SearchProject>,
5877 _: Arc<Client>,
5878 mut cx: AsyncAppContext,
5879 ) -> Result<proto::SearchProjectResponse> {
5880 let peer_id = envelope.original_sender_id()?;
5881 let query = SearchQuery::from_proto(envelope.payload)?;
5882 let result = this
5883 .update(&mut cx, |this, cx| this.search(query, cx))
5884 .await?;
5885
5886 this.update(&mut cx, |this, cx| {
5887 let mut locations = Vec::new();
5888 for (buffer, ranges) in result {
5889 for range in ranges {
5890 let start = serialize_anchor(&range.start);
5891 let end = serialize_anchor(&range.end);
5892 let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5893 locations.push(proto::Location {
5894 buffer_id,
5895 start: Some(start),
5896 end: Some(end),
5897 });
5898 }
5899 }
5900 Ok(proto::SearchProjectResponse { locations })
5901 })
5902 }
5903
5904 async fn handle_open_buffer_for_symbol(
5905 this: ModelHandle<Self>,
5906 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5907 _: Arc<Client>,
5908 mut cx: AsyncAppContext,
5909 ) -> Result<proto::OpenBufferForSymbolResponse> {
5910 let peer_id = envelope.original_sender_id()?;
5911 let symbol = envelope
5912 .payload
5913 .symbol
5914 .ok_or_else(|| anyhow!("invalid symbol"))?;
5915 let symbol = this
5916 .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5917 .await?;
5918 let symbol = this.read_with(&cx, |this, _| {
5919 let signature = this.symbol_signature(&symbol.path);
5920 if signature == symbol.signature {
5921 Ok(symbol)
5922 } else {
5923 Err(anyhow!("invalid symbol signature"))
5924 }
5925 })?;
5926 let buffer = this
5927 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5928 .await?;
5929
5930 Ok(proto::OpenBufferForSymbolResponse {
5931 buffer_id: this.update(&mut cx, |this, cx| {
5932 this.create_buffer_for_peer(&buffer, peer_id, cx)
5933 }),
5934 })
5935 }
5936
5937 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5938 let mut hasher = Sha256::new();
5939 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5940 hasher.update(project_path.path.to_string_lossy().as_bytes());
5941 hasher.update(self.nonce.to_be_bytes());
5942 hasher.finalize().as_slice().try_into().unwrap()
5943 }
5944
5945 async fn handle_open_buffer_by_id(
5946 this: ModelHandle<Self>,
5947 envelope: TypedEnvelope<proto::OpenBufferById>,
5948 _: Arc<Client>,
5949 mut cx: AsyncAppContext,
5950 ) -> Result<proto::OpenBufferResponse> {
5951 let peer_id = envelope.original_sender_id()?;
5952 let buffer = this
5953 .update(&mut cx, |this, cx| {
5954 this.open_buffer_by_id(envelope.payload.id, cx)
5955 })
5956 .await?;
5957 this.update(&mut cx, |this, cx| {
5958 Ok(proto::OpenBufferResponse {
5959 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5960 })
5961 })
5962 }
5963
5964 async fn handle_open_buffer_by_path(
5965 this: ModelHandle<Self>,
5966 envelope: TypedEnvelope<proto::OpenBufferByPath>,
5967 _: Arc<Client>,
5968 mut cx: AsyncAppContext,
5969 ) -> Result<proto::OpenBufferResponse> {
5970 let peer_id = envelope.original_sender_id()?;
5971 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5972 let open_buffer = this.update(&mut cx, |this, cx| {
5973 this.open_buffer(
5974 ProjectPath {
5975 worktree_id,
5976 path: PathBuf::from(envelope.payload.path).into(),
5977 },
5978 cx,
5979 )
5980 });
5981
5982 let buffer = open_buffer.await?;
5983 this.update(&mut cx, |this, cx| {
5984 Ok(proto::OpenBufferResponse {
5985 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5986 })
5987 })
5988 }
5989
5990 fn serialize_project_transaction_for_peer(
5991 &mut self,
5992 project_transaction: ProjectTransaction,
5993 peer_id: proto::PeerId,
5994 cx: &mut AppContext,
5995 ) -> proto::ProjectTransaction {
5996 let mut serialized_transaction = proto::ProjectTransaction {
5997 buffer_ids: Default::default(),
5998 transactions: Default::default(),
5999 };
6000 for (buffer, transaction) in project_transaction.0 {
6001 serialized_transaction
6002 .buffer_ids
6003 .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
6004 serialized_transaction
6005 .transactions
6006 .push(language::proto::serialize_transaction(&transaction));
6007 }
6008 serialized_transaction
6009 }
6010
6011 fn deserialize_project_transaction(
6012 &mut self,
6013 message: proto::ProjectTransaction,
6014 push_to_history: bool,
6015 cx: &mut ModelContext<Self>,
6016 ) -> Task<Result<ProjectTransaction>> {
6017 cx.spawn(|this, mut cx| async move {
6018 let mut project_transaction = ProjectTransaction::default();
6019 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
6020 {
6021 let buffer = this
6022 .update(&mut cx, |this, cx| {
6023 this.wait_for_remote_buffer(buffer_id, cx)
6024 })
6025 .await?;
6026 let transaction = language::proto::deserialize_transaction(transaction)?;
6027 project_transaction.0.insert(buffer, transaction);
6028 }
6029
6030 for (buffer, transaction) in &project_transaction.0 {
6031 buffer
6032 .update(&mut cx, |buffer, _| {
6033 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
6034 })
6035 .await?;
6036
6037 if push_to_history {
6038 buffer.update(&mut cx, |buffer, _| {
6039 buffer.push_transaction(transaction.clone(), Instant::now());
6040 });
6041 }
6042 }
6043
6044 Ok(project_transaction)
6045 })
6046 }
6047
6048 fn create_buffer_for_peer(
6049 &mut self,
6050 buffer: &ModelHandle<Buffer>,
6051 peer_id: proto::PeerId,
6052 cx: &mut AppContext,
6053 ) -> u64 {
6054 let buffer_id = buffer.read(cx).remote_id();
6055 if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
6056 updates_tx
6057 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
6058 .ok();
6059 }
6060 buffer_id
6061 }
6062
6063 fn wait_for_remote_buffer(
6064 &mut self,
6065 id: u64,
6066 cx: &mut ModelContext<Self>,
6067 ) -> Task<Result<ModelHandle<Buffer>>> {
6068 let mut opened_buffer_rx = self.opened_buffer.1.clone();
6069
6070 cx.spawn_weak(|this, mut cx| async move {
6071 let buffer = loop {
6072 let Some(this) = this.upgrade(&cx) else {
6073 return Err(anyhow!("project dropped"));
6074 };
6075 let buffer = this.read_with(&cx, |this, cx| {
6076 this.opened_buffers
6077 .get(&id)
6078 .and_then(|buffer| buffer.upgrade(cx))
6079 });
6080 if let Some(buffer) = buffer {
6081 break buffer;
6082 } else if this.read_with(&cx, |this, _| this.is_read_only()) {
6083 return Err(anyhow!("disconnected before buffer {} could be opened", id));
6084 }
6085
6086 this.update(&mut cx, |this, _| {
6087 this.incomplete_remote_buffers.entry(id).or_default();
6088 });
6089 drop(this);
6090 opened_buffer_rx
6091 .next()
6092 .await
6093 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
6094 };
6095 buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
6096 Ok(buffer)
6097 })
6098 }
6099
6100 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
6101 let project_id = match self.client_state.as_ref() {
6102 Some(ProjectClientState::Remote {
6103 sharing_has_stopped,
6104 remote_id,
6105 ..
6106 }) => {
6107 if *sharing_has_stopped {
6108 return Task::ready(Err(anyhow!(
6109 "can't synchronize remote buffers on a readonly project"
6110 )));
6111 } else {
6112 *remote_id
6113 }
6114 }
6115 Some(ProjectClientState::Local { .. }) | None => {
6116 return Task::ready(Err(anyhow!(
6117 "can't synchronize remote buffers on a local project"
6118 )))
6119 }
6120 };
6121
6122 let client = self.client.clone();
6123 cx.spawn(|this, cx| async move {
6124 let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
6125 let buffers = this
6126 .opened_buffers
6127 .iter()
6128 .filter_map(|(id, buffer)| {
6129 let buffer = buffer.upgrade(cx)?;
6130 Some(proto::BufferVersion {
6131 id: *id,
6132 version: language::proto::serialize_version(&buffer.read(cx).version),
6133 })
6134 })
6135 .collect();
6136 let incomplete_buffer_ids = this
6137 .incomplete_remote_buffers
6138 .keys()
6139 .copied()
6140 .collect::<Vec<_>>();
6141
6142 (buffers, incomplete_buffer_ids)
6143 });
6144 let response = client
6145 .request(proto::SynchronizeBuffers {
6146 project_id,
6147 buffers,
6148 })
6149 .await?;
6150
6151 let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
6152 let client = client.clone();
6153 let buffer_id = buffer.id;
6154 let remote_version = language::proto::deserialize_version(&buffer.version);
6155 this.read_with(&cx, |this, cx| {
6156 if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6157 let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
6158 cx.background().spawn(async move {
6159 let operations = operations.await;
6160 for chunk in split_operations(operations) {
6161 client
6162 .request(proto::UpdateBuffer {
6163 project_id,
6164 buffer_id,
6165 operations: chunk,
6166 })
6167 .await?;
6168 }
6169 anyhow::Ok(())
6170 })
6171 } else {
6172 Task::ready(Ok(()))
6173 }
6174 })
6175 });
6176
6177 // Any incomplete buffers have open requests waiting. Request that the host sends
6178 // creates these buffers for us again to unblock any waiting futures.
6179 for id in incomplete_buffer_ids {
6180 cx.background()
6181 .spawn(client.request(proto::OpenBufferById { project_id, id }))
6182 .detach();
6183 }
6184
6185 futures::future::join_all(send_updates_for_buffers)
6186 .await
6187 .into_iter()
6188 .collect()
6189 })
6190 }
6191
6192 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
6193 self.worktrees(cx)
6194 .map(|worktree| {
6195 let worktree = worktree.read(cx);
6196 proto::WorktreeMetadata {
6197 id: worktree.id().to_proto(),
6198 root_name: worktree.root_name().into(),
6199 visible: worktree.is_visible(),
6200 abs_path: worktree.abs_path().to_string_lossy().into(),
6201 }
6202 })
6203 .collect()
6204 }
6205
6206 fn set_worktrees_from_proto(
6207 &mut self,
6208 worktrees: Vec<proto::WorktreeMetadata>,
6209 cx: &mut ModelContext<Project>,
6210 ) -> Result<()> {
6211 let replica_id = self.replica_id();
6212 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
6213
6214 let mut old_worktrees_by_id = self
6215 .worktrees
6216 .drain(..)
6217 .filter_map(|worktree| {
6218 let worktree = worktree.upgrade(cx)?;
6219 Some((worktree.read(cx).id(), worktree))
6220 })
6221 .collect::<HashMap<_, _>>();
6222
6223 for worktree in worktrees {
6224 if let Some(old_worktree) =
6225 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
6226 {
6227 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
6228 } else {
6229 let worktree =
6230 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
6231 let _ = self.add_worktree(&worktree, cx);
6232 }
6233 }
6234
6235 self.metadata_changed(cx);
6236 for (id, _) in old_worktrees_by_id {
6237 cx.emit(Event::WorktreeRemoved(id));
6238 }
6239
6240 Ok(())
6241 }
6242
6243 fn set_collaborators_from_proto(
6244 &mut self,
6245 messages: Vec<proto::Collaborator>,
6246 cx: &mut ModelContext<Self>,
6247 ) -> Result<()> {
6248 let mut collaborators = HashMap::default();
6249 for message in messages {
6250 let collaborator = Collaborator::from_proto(message)?;
6251 collaborators.insert(collaborator.peer_id, collaborator);
6252 }
6253 for old_peer_id in self.collaborators.keys() {
6254 if !collaborators.contains_key(old_peer_id) {
6255 cx.emit(Event::CollaboratorLeft(*old_peer_id));
6256 }
6257 }
6258 self.collaborators = collaborators;
6259 Ok(())
6260 }
6261
6262 fn deserialize_symbol(
6263 &self,
6264 serialized_symbol: proto::Symbol,
6265 ) -> impl Future<Output = Result<Symbol>> {
6266 let languages = self.languages.clone();
6267 async move {
6268 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
6269 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
6270 let start = serialized_symbol
6271 .start
6272 .ok_or_else(|| anyhow!("invalid start"))?;
6273 let end = serialized_symbol
6274 .end
6275 .ok_or_else(|| anyhow!("invalid end"))?;
6276 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
6277 let path = ProjectPath {
6278 worktree_id,
6279 path: PathBuf::from(serialized_symbol.path).into(),
6280 };
6281 let language = languages
6282 .language_for_file(&path.path, None)
6283 .await
6284 .log_err();
6285 Ok(Symbol {
6286 language_server_name: LanguageServerName(
6287 serialized_symbol.language_server_name.into(),
6288 ),
6289 source_worktree_id,
6290 path,
6291 label: {
6292 match language {
6293 Some(language) => {
6294 language
6295 .label_for_symbol(&serialized_symbol.name, kind)
6296 .await
6297 }
6298 None => None,
6299 }
6300 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
6301 },
6302
6303 name: serialized_symbol.name,
6304 range: Unclipped(PointUtf16::new(start.row, start.column))
6305 ..Unclipped(PointUtf16::new(end.row, end.column)),
6306 kind,
6307 signature: serialized_symbol
6308 .signature
6309 .try_into()
6310 .map_err(|_| anyhow!("invalid signature"))?,
6311 })
6312 }
6313 }
6314
6315 async fn handle_buffer_saved(
6316 this: ModelHandle<Self>,
6317 envelope: TypedEnvelope<proto::BufferSaved>,
6318 _: Arc<Client>,
6319 mut cx: AsyncAppContext,
6320 ) -> Result<()> {
6321 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
6322 let version = deserialize_version(&envelope.payload.version);
6323 let mtime = envelope
6324 .payload
6325 .mtime
6326 .ok_or_else(|| anyhow!("missing mtime"))?
6327 .into();
6328
6329 this.update(&mut cx, |this, cx| {
6330 let buffer = this
6331 .opened_buffers
6332 .get(&envelope.payload.buffer_id)
6333 .and_then(|buffer| buffer.upgrade(cx))
6334 .or_else(|| {
6335 this.incomplete_remote_buffers
6336 .get(&envelope.payload.buffer_id)
6337 .and_then(|b| b.clone())
6338 });
6339 if let Some(buffer) = buffer {
6340 buffer.update(cx, |buffer, cx| {
6341 buffer.did_save(version, fingerprint, mtime, cx);
6342 });
6343 }
6344 Ok(())
6345 })
6346 }
6347
6348 async fn handle_buffer_reloaded(
6349 this: ModelHandle<Self>,
6350 envelope: TypedEnvelope<proto::BufferReloaded>,
6351 _: Arc<Client>,
6352 mut cx: AsyncAppContext,
6353 ) -> Result<()> {
6354 let payload = envelope.payload;
6355 let version = deserialize_version(&payload.version);
6356 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6357 let line_ending = deserialize_line_ending(
6358 proto::LineEnding::from_i32(payload.line_ending)
6359 .ok_or_else(|| anyhow!("missing line ending"))?,
6360 );
6361 let mtime = payload
6362 .mtime
6363 .ok_or_else(|| anyhow!("missing mtime"))?
6364 .into();
6365 this.update(&mut cx, |this, cx| {
6366 let buffer = this
6367 .opened_buffers
6368 .get(&payload.buffer_id)
6369 .and_then(|buffer| buffer.upgrade(cx))
6370 .or_else(|| {
6371 this.incomplete_remote_buffers
6372 .get(&payload.buffer_id)
6373 .cloned()
6374 .flatten()
6375 });
6376 if let Some(buffer) = buffer {
6377 buffer.update(cx, |buffer, cx| {
6378 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6379 });
6380 }
6381 Ok(())
6382 })
6383 }
6384
6385 #[allow(clippy::type_complexity)]
6386 pub fn edits_from_lsp(
6387 &mut self,
6388 buffer: &ModelHandle<Buffer>,
6389 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6390 server_id: LanguageServerId,
6391 version: Option<i32>,
6392 cx: &mut ModelContext<Self>,
6393 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6394 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
6395 cx.background().spawn(async move {
6396 let snapshot = snapshot?;
6397 let mut lsp_edits = lsp_edits
6398 .into_iter()
6399 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6400 .collect::<Vec<_>>();
6401 lsp_edits.sort_by_key(|(range, _)| range.start);
6402
6403 let mut lsp_edits = lsp_edits.into_iter().peekable();
6404 let mut edits = Vec::new();
6405 while let Some((range, mut new_text)) = lsp_edits.next() {
6406 // Clip invalid ranges provided by the language server.
6407 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6408 ..snapshot.clip_point_utf16(range.end, Bias::Left);
6409
6410 // Combine any LSP edits that are adjacent.
6411 //
6412 // Also, combine LSP edits that are separated from each other by only
6413 // a newline. This is important because for some code actions,
6414 // Rust-analyzer rewrites the entire buffer via a series of edits that
6415 // are separated by unchanged newline characters.
6416 //
6417 // In order for the diffing logic below to work properly, any edits that
6418 // cancel each other out must be combined into one.
6419 while let Some((next_range, next_text)) = lsp_edits.peek() {
6420 if next_range.start.0 > range.end {
6421 if next_range.start.0.row > range.end.row + 1
6422 || next_range.start.0.column > 0
6423 || snapshot.clip_point_utf16(
6424 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6425 Bias::Left,
6426 ) > range.end
6427 {
6428 break;
6429 }
6430 new_text.push('\n');
6431 }
6432 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6433 new_text.push_str(next_text);
6434 lsp_edits.next();
6435 }
6436
6437 // For multiline edits, perform a diff of the old and new text so that
6438 // we can identify the changes more precisely, preserving the locations
6439 // of any anchors positioned in the unchanged regions.
6440 if range.end.row > range.start.row {
6441 let mut offset = range.start.to_offset(&snapshot);
6442 let old_text = snapshot.text_for_range(range).collect::<String>();
6443
6444 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6445 let mut moved_since_edit = true;
6446 for change in diff.iter_all_changes() {
6447 let tag = change.tag();
6448 let value = change.value();
6449 match tag {
6450 ChangeTag::Equal => {
6451 offset += value.len();
6452 moved_since_edit = true;
6453 }
6454 ChangeTag::Delete => {
6455 let start = snapshot.anchor_after(offset);
6456 let end = snapshot.anchor_before(offset + value.len());
6457 if moved_since_edit {
6458 edits.push((start..end, String::new()));
6459 } else {
6460 edits.last_mut().unwrap().0.end = end;
6461 }
6462 offset += value.len();
6463 moved_since_edit = false;
6464 }
6465 ChangeTag::Insert => {
6466 if moved_since_edit {
6467 let anchor = snapshot.anchor_after(offset);
6468 edits.push((anchor..anchor, value.to_string()));
6469 } else {
6470 edits.last_mut().unwrap().1.push_str(value);
6471 }
6472 moved_since_edit = false;
6473 }
6474 }
6475 }
6476 } else if range.end == range.start {
6477 let anchor = snapshot.anchor_after(range.start);
6478 edits.push((anchor..anchor, new_text));
6479 } else {
6480 let edit_start = snapshot.anchor_after(range.start);
6481 let edit_end = snapshot.anchor_before(range.end);
6482 edits.push((edit_start..edit_end, new_text));
6483 }
6484 }
6485
6486 Ok(edits)
6487 })
6488 }
6489
6490 fn buffer_snapshot_for_lsp_version(
6491 &mut self,
6492 buffer: &ModelHandle<Buffer>,
6493 server_id: LanguageServerId,
6494 version: Option<i32>,
6495 cx: &AppContext,
6496 ) -> Result<TextBufferSnapshot> {
6497 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6498
6499 if let Some(version) = version {
6500 let buffer_id = buffer.read(cx).remote_id();
6501 let snapshots = self
6502 .buffer_snapshots
6503 .get_mut(&buffer_id)
6504 .and_then(|m| m.get_mut(&server_id))
6505 .ok_or_else(|| {
6506 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
6507 })?;
6508
6509 let found_snapshot = snapshots
6510 .binary_search_by_key(&version, |e| e.version)
6511 .map(|ix| snapshots[ix].snapshot.clone())
6512 .map_err(|_| {
6513 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
6514 })?;
6515
6516 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
6517 Ok(found_snapshot)
6518 } else {
6519 Ok((buffer.read(cx)).text_snapshot())
6520 }
6521 }
6522
6523 pub fn language_servers(
6524 &self,
6525 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
6526 self.language_server_ids
6527 .iter()
6528 .map(|((worktree_id, server_name), server_id)| {
6529 (*server_id, server_name.clone(), *worktree_id)
6530 })
6531 }
6532
6533 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
6534 if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
6535 Some(server.clone())
6536 } else {
6537 None
6538 }
6539 }
6540
6541 pub fn language_servers_for_buffer(
6542 &self,
6543 buffer: &Buffer,
6544 cx: &AppContext,
6545 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6546 self.language_server_ids_for_buffer(buffer, cx)
6547 .into_iter()
6548 .filter_map(|server_id| {
6549 let server = self.language_servers.get(&server_id)?;
6550 if let LanguageServerState::Running {
6551 adapter, server, ..
6552 } = server
6553 {
6554 Some((adapter, server))
6555 } else {
6556 None
6557 }
6558 })
6559 }
6560
6561 fn primary_language_servers_for_buffer(
6562 &self,
6563 buffer: &Buffer,
6564 cx: &AppContext,
6565 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6566 self.language_servers_for_buffer(buffer, cx).next()
6567 }
6568
6569 fn language_server_for_buffer(
6570 &self,
6571 buffer: &Buffer,
6572 server_id: LanguageServerId,
6573 cx: &AppContext,
6574 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6575 self.language_servers_for_buffer(buffer, cx)
6576 .find(|(_, s)| s.server_id() == server_id)
6577 }
6578
6579 fn language_server_ids_for_buffer(
6580 &self,
6581 buffer: &Buffer,
6582 cx: &AppContext,
6583 ) -> Vec<LanguageServerId> {
6584 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6585 let worktree_id = file.worktree_id(cx);
6586 language
6587 .lsp_adapters()
6588 .iter()
6589 .flat_map(|adapter| {
6590 let key = (worktree_id, adapter.name.clone());
6591 self.language_server_ids.get(&key).copied()
6592 })
6593 .collect()
6594 } else {
6595 Vec::new()
6596 }
6597 }
6598}
6599
6600impl WorktreeHandle {
6601 pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6602 match self {
6603 WorktreeHandle::Strong(handle) => Some(handle.clone()),
6604 WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6605 }
6606 }
6607}
6608
6609impl OpenBuffer {
6610 pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
6611 match self {
6612 OpenBuffer::Strong(handle) => Some(handle.clone()),
6613 OpenBuffer::Weak(handle) => handle.upgrade(cx),
6614 OpenBuffer::Operations(_) => None,
6615 }
6616 }
6617}
6618
6619pub struct PathMatchCandidateSet {
6620 pub snapshot: Snapshot,
6621 pub include_ignored: bool,
6622 pub include_root_name: bool,
6623}
6624
6625impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6626 type Candidates = PathMatchCandidateSetIter<'a>;
6627
6628 fn id(&self) -> usize {
6629 self.snapshot.id().to_usize()
6630 }
6631
6632 fn len(&self) -> usize {
6633 if self.include_ignored {
6634 self.snapshot.file_count()
6635 } else {
6636 self.snapshot.visible_file_count()
6637 }
6638 }
6639
6640 fn prefix(&self) -> Arc<str> {
6641 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6642 self.snapshot.root_name().into()
6643 } else if self.include_root_name {
6644 format!("{}/", self.snapshot.root_name()).into()
6645 } else {
6646 "".into()
6647 }
6648 }
6649
6650 fn candidates(&'a self, start: usize) -> Self::Candidates {
6651 PathMatchCandidateSetIter {
6652 traversal: self.snapshot.files(self.include_ignored, start),
6653 }
6654 }
6655}
6656
6657pub struct PathMatchCandidateSetIter<'a> {
6658 traversal: Traversal<'a>,
6659}
6660
6661impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6662 type Item = fuzzy::PathMatchCandidate<'a>;
6663
6664 fn next(&mut self) -> Option<Self::Item> {
6665 self.traversal.next().map(|entry| {
6666 if let EntryKind::File(char_bag) = entry.kind {
6667 fuzzy::PathMatchCandidate {
6668 path: &entry.path,
6669 char_bag,
6670 }
6671 } else {
6672 unreachable!()
6673 }
6674 })
6675 }
6676}
6677
6678impl Entity for Project {
6679 type Event = Event;
6680
6681 fn release(&mut self, cx: &mut gpui::AppContext) {
6682 match &self.client_state {
6683 Some(ProjectClientState::Local { .. }) => {
6684 let _ = self.unshare_internal(cx);
6685 }
6686 Some(ProjectClientState::Remote { remote_id, .. }) => {
6687 let _ = self.client.send(proto::LeaveProject {
6688 project_id: *remote_id,
6689 });
6690 self.disconnected_from_host_internal(cx);
6691 }
6692 _ => {}
6693 }
6694 }
6695
6696 fn app_will_quit(
6697 &mut self,
6698 _: &mut AppContext,
6699 ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6700 let shutdown_futures = self
6701 .language_servers
6702 .drain()
6703 .map(|(_, server_state)| async {
6704 match server_state {
6705 LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6706 LanguageServerState::Starting(starting_server) => {
6707 starting_server.await?.shutdown()?.await
6708 }
6709 }
6710 })
6711 .collect::<Vec<_>>();
6712
6713 Some(
6714 async move {
6715 futures::future::join_all(shutdown_futures).await;
6716 }
6717 .boxed(),
6718 )
6719 }
6720}
6721
6722impl Collaborator {
6723 fn from_proto(message: proto::Collaborator) -> Result<Self> {
6724 Ok(Self {
6725 peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6726 replica_id: message.replica_id as ReplicaId,
6727 })
6728 }
6729}
6730
6731impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6732 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6733 Self {
6734 worktree_id,
6735 path: path.as_ref().into(),
6736 }
6737 }
6738}
6739
6740fn split_operations(
6741 mut operations: Vec<proto::Operation>,
6742) -> impl Iterator<Item = Vec<proto::Operation>> {
6743 #[cfg(any(test, feature = "test-support"))]
6744 const CHUNK_SIZE: usize = 5;
6745
6746 #[cfg(not(any(test, feature = "test-support")))]
6747 const CHUNK_SIZE: usize = 100;
6748
6749 let mut done = false;
6750 std::iter::from_fn(move || {
6751 if done {
6752 return None;
6753 }
6754
6755 let operations = operations
6756 .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6757 .collect::<Vec<_>>();
6758 if operations.is_empty() {
6759 done = true;
6760 }
6761 Some(operations)
6762 })
6763}
6764
6765fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6766 proto::Symbol {
6767 language_server_name: symbol.language_server_name.0.to_string(),
6768 source_worktree_id: symbol.source_worktree_id.to_proto(),
6769 worktree_id: symbol.path.worktree_id.to_proto(),
6770 path: symbol.path.path.to_string_lossy().to_string(),
6771 name: symbol.name.clone(),
6772 kind: unsafe { mem::transmute(symbol.kind) },
6773 start: Some(proto::PointUtf16 {
6774 row: symbol.range.start.0.row,
6775 column: symbol.range.start.0.column,
6776 }),
6777 end: Some(proto::PointUtf16 {
6778 row: symbol.range.end.0.row,
6779 column: symbol.range.end.0.column,
6780 }),
6781 signature: symbol.signature.to_vec(),
6782 }
6783}
6784
6785fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6786 let mut path_components = path.components();
6787 let mut base_components = base.components();
6788 let mut components: Vec<Component> = Vec::new();
6789 loop {
6790 match (path_components.next(), base_components.next()) {
6791 (None, None) => break,
6792 (Some(a), None) => {
6793 components.push(a);
6794 components.extend(path_components.by_ref());
6795 break;
6796 }
6797 (None, _) => components.push(Component::ParentDir),
6798 (Some(a), Some(b)) if components.is_empty() && a == b => (),
6799 (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6800 (Some(a), Some(_)) => {
6801 components.push(Component::ParentDir);
6802 for _ in base_components {
6803 components.push(Component::ParentDir);
6804 }
6805 components.push(a);
6806 components.extend(path_components.by_ref());
6807 break;
6808 }
6809 }
6810 }
6811 components.iter().map(|c| c.as_os_str()).collect()
6812}
6813
6814impl Item for Buffer {
6815 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6816 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6817 }
6818
6819 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6820 File::from_dyn(self.file()).map(|file| ProjectPath {
6821 worktree_id: file.worktree_id(cx),
6822 path: file.path().clone(),
6823 })
6824 }
6825}
6826
6827async fn pump_loading_buffer_reciever(
6828 mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
6829) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
6830 loop {
6831 if let Some(result) = receiver.borrow().as_ref() {
6832 match result {
6833 Ok(buffer) => return Ok(buffer.to_owned()),
6834 Err(e) => return Err(e.to_owned()),
6835 }
6836 }
6837 receiver.next().await;
6838 }
6839}
6840
6841fn update_diff_base(
6842 project: &Project,
6843) -> impl Fn(Option<String>, ModelHandle<Buffer>, &mut AsyncAppContext) {
6844 let remote_id = project.remote_id();
6845 let client = project.client().clone();
6846 move |diff_base, buffer, cx| {
6847 let buffer_id = buffer.update(cx, |buffer, cx| {
6848 buffer.set_diff_base(diff_base.clone(), cx);
6849 buffer.remote_id()
6850 });
6851
6852 if let Some(project_id) = remote_id {
6853 client
6854 .send(proto::UpdateDiffBase {
6855 project_id,
6856 buffer_id: buffer_id as u64,
6857 diff_base,
6858 })
6859 .log_err();
6860 }
6861 }
6862}