1pub mod debounced_delay;
2pub mod lsp_command;
3pub mod lsp_ext_command;
4mod prettier_support;
5pub mod project_settings;
6pub mod search;
7mod task_inventory;
8pub mod terminals;
9
10#[cfg(test)]
11mod project_tests;
12
13use anyhow::{anyhow, bail, Context as _, Result};
14use async_trait::async_trait;
15use client::{
16 proto, Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore,
17};
18use clock::ReplicaId;
19use collections::{hash_map, BTreeMap, HashMap, HashSet, VecDeque};
20use copilot::Copilot;
21use debounced_delay::DebouncedDelay;
22use fs::repository::GitRepository;
23use futures::{
24 channel::mpsc::{self, UnboundedReceiver},
25 future::{try_join_all, Shared},
26 select,
27 stream::FuturesUnordered,
28 AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
29};
30use globset::{Glob, GlobSet, GlobSetBuilder};
31use gpui::{
32 AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, Context, Entity, EventEmitter,
33 Model, ModelContext, PromptLevel, Task, WeakModel,
34};
35use itertools::Itertools;
36use language::{
37 language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind},
38 markdown, point_to_lsp,
39 proto::{
40 deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
41 serialize_anchor, serialize_version, split_operations,
42 },
43 range_from_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, Capability, CodeAction,
44 CodeLabel, Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Documentation,
45 Event as BufferEvent, File as _, Language, LanguageRegistry, LanguageServerName, LocalFile,
46 LspAdapterDelegate, Operation, Patch, PendingLanguageServer, PointUtf16, TextBufferSnapshot,
47 ToOffset, ToPointUtf16, Transaction, Unclipped,
48};
49use log::error;
50use lsp::{
51 DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
52 DocumentHighlightKind, LanguageServer, LanguageServerBinary, LanguageServerId,
53 MessageActionItem, OneOf, ServerHealthStatus, ServerStatus,
54};
55use lsp_command::*;
56use node_runtime::NodeRuntime;
57use parking_lot::{Mutex, RwLock};
58use postage::watch;
59use prettier_support::{DefaultPrettier, PrettierInstance};
60use project_settings::{LspSettings, ProjectSettings};
61use rand::prelude::*;
62use worktree::LocalSnapshot;
63
64use rpc::{ErrorCode, ErrorExt as _};
65use search::SearchQuery;
66use serde::Serialize;
67use settings::{watch_config_file, Settings, SettingsStore};
68use sha2::{Digest, Sha256};
69use similar::{ChangeTag, TextDiff};
70use smol::channel::{Receiver, Sender};
71use smol::lock::Semaphore;
72use std::{
73 cmp::{self, Ordering},
74 convert::TryInto,
75 env,
76 ffi::OsStr,
77 hash::Hash,
78 mem,
79 num::NonZeroU32,
80 ops::Range,
81 path::{self, Component, Path, PathBuf},
82 process::Stdio,
83 str,
84 sync::{
85 atomic::{AtomicUsize, Ordering::SeqCst},
86 Arc,
87 },
88 time::{Duration, Instant},
89};
90use task::static_source::StaticSource;
91use terminals::Terminals;
92use text::{Anchor, BufferId};
93use util::{
94 debug_panic, defer,
95 http::HttpClient,
96 merge_json_value_into,
97 paths::{LOCAL_SETTINGS_RELATIVE_PATH, LOCAL_TASKS_RELATIVE_PATH},
98 post_inc, ResultExt, TryFutureExt as _,
99};
100use worktree::{Snapshot, Traversal};
101
102pub use fs::*;
103pub use language::Location;
104#[cfg(any(test, feature = "test-support"))]
105pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
106#[cfg(feature = "test-support")]
107pub use task_inventory::test_inventory::*;
108pub use task_inventory::{Inventory, TaskSourceKind};
109pub use worktree::{
110 DiagnosticSummary, Entry, EntryKind, File, LocalWorktree, PathChange, ProjectEntryId,
111 RepositoryEntry, UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId,
112 WorktreeSettings, FS_WATCH_LATENCY,
113};
114
115const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
116const SERVER_REINSTALL_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
117const SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
118pub const SERVER_PROGRESS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(100);
119
120pub trait Item {
121 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
122 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
123}
124
125pub struct Project {
126 worktrees: Vec<WorktreeHandle>,
127 active_entry: Option<ProjectEntryId>,
128 buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
129 pending_language_server_update: Option<BufferOrderedMessage>,
130 flush_language_server_update: Option<Task<()>>,
131
132 languages: Arc<LanguageRegistry>,
133 supplementary_language_servers:
134 HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
135 language_servers: HashMap<LanguageServerId, LanguageServerState>,
136 language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
137 language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
138 last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
139 language_server_watched_paths: HashMap<LanguageServerId, HashMap<WorktreeId, GlobSet>>,
140 client: Arc<client::Client>,
141 next_entry_id: Arc<AtomicUsize>,
142 join_project_response_message_id: u32,
143 next_diagnostic_group_id: usize,
144 user_store: Model<UserStore>,
145 fs: Arc<dyn Fs>,
146 client_state: ProjectClientState,
147 collaborators: HashMap<proto::PeerId, Collaborator>,
148 client_subscriptions: Vec<client::Subscription>,
149 _subscriptions: Vec<gpui::Subscription>,
150 next_buffer_id: BufferId,
151 opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
152 shared_buffers: HashMap<proto::PeerId, HashSet<BufferId>>,
153 #[allow(clippy::type_complexity)]
154 loading_buffers_by_path: HashMap<
155 ProjectPath,
156 postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
157 >,
158 #[allow(clippy::type_complexity)]
159 loading_local_worktrees:
160 HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
161 opened_buffers: HashMap<BufferId, OpenBuffer>,
162 local_buffer_ids_by_path: HashMap<ProjectPath, BufferId>,
163 local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, BufferId>,
164 /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
165 /// Used for re-issuing buffer requests when peers temporarily disconnect
166 incomplete_remote_buffers: HashMap<BufferId, Option<Model<Buffer>>>,
167 buffer_snapshots: HashMap<BufferId, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
168 buffers_being_formatted: HashSet<BufferId>,
169 buffers_needing_diff: HashSet<WeakModel<Buffer>>,
170 git_diff_debouncer: DebouncedDelay,
171 nonce: u128,
172 _maintain_buffer_languages: Task<()>,
173 _maintain_workspace_config: Task<Result<()>>,
174 terminals: Terminals,
175 copilot_lsp_subscription: Option<gpui::Subscription>,
176 copilot_log_subscription: Option<lsp::Subscription>,
177 current_lsp_settings: HashMap<Arc<str>, LspSettings>,
178 node: Option<Arc<dyn NodeRuntime>>,
179 default_prettier: DefaultPrettier,
180 prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
181 prettier_instances: HashMap<PathBuf, PrettierInstance>,
182 tasks: Model<Inventory>,
183 hosted_project_id: Option<ProjectId>,
184}
185
186pub enum LanguageServerToQuery {
187 Primary,
188 Other(LanguageServerId),
189}
190
191struct LspBufferSnapshot {
192 version: i32,
193 snapshot: TextBufferSnapshot,
194}
195
196/// Message ordered with respect to buffer operations
197#[derive(Debug)]
198enum BufferOrderedMessage {
199 Operation {
200 buffer_id: BufferId,
201 operation: proto::Operation,
202 },
203 LanguageServerUpdate {
204 language_server_id: LanguageServerId,
205 message: proto::update_language_server::Variant,
206 },
207 Resync,
208}
209
210enum LocalProjectUpdate {
211 WorktreesChanged,
212 CreateBufferForPeer {
213 peer_id: proto::PeerId,
214 buffer_id: BufferId,
215 },
216}
217
218enum OpenBuffer {
219 Strong(Model<Buffer>),
220 Weak(WeakModel<Buffer>),
221 Operations(Vec<Operation>),
222}
223
224#[derive(Clone)]
225enum WorktreeHandle {
226 Strong(Model<Worktree>),
227 Weak(WeakModel<Worktree>),
228}
229
230#[derive(Debug)]
231enum ProjectClientState {
232 Local,
233 Shared {
234 remote_id: u64,
235 updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
236 _send_updates: Task<Result<()>>,
237 },
238 Remote {
239 sharing_has_stopped: bool,
240 capability: Capability,
241 remote_id: u64,
242 replica_id: ReplicaId,
243 },
244}
245
246/// A prompt requested by LSP server.
247#[derive(Clone, Debug)]
248pub struct LanguageServerPromptRequest {
249 pub level: PromptLevel,
250 pub message: String,
251 pub actions: Vec<MessageActionItem>,
252 pub lsp_name: String,
253 response_channel: Sender<MessageActionItem>,
254}
255
256impl LanguageServerPromptRequest {
257 pub async fn respond(self, index: usize) -> Option<()> {
258 if let Some(response) = self.actions.into_iter().nth(index) {
259 self.response_channel.send(response).await.ok()
260 } else {
261 None
262 }
263 }
264}
265impl PartialEq for LanguageServerPromptRequest {
266 fn eq(&self, other: &Self) -> bool {
267 self.message == other.message && self.actions == other.actions
268 }
269}
270
271#[derive(Clone, Debug, PartialEq)]
272pub enum Event {
273 LanguageServerAdded(LanguageServerId),
274 LanguageServerRemoved(LanguageServerId),
275 LanguageServerLog(LanguageServerId, String),
276 Notification(String),
277 LanguageServerPrompt(LanguageServerPromptRequest),
278 ActiveEntryChanged(Option<ProjectEntryId>),
279 ActivateProjectPanel,
280 WorktreeAdded,
281 WorktreeRemoved(WorktreeId),
282 WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
283 DiskBasedDiagnosticsStarted {
284 language_server_id: LanguageServerId,
285 },
286 DiskBasedDiagnosticsFinished {
287 language_server_id: LanguageServerId,
288 },
289 DiagnosticsUpdated {
290 path: ProjectPath,
291 language_server_id: LanguageServerId,
292 },
293 RemoteIdChanged(Option<u64>),
294 DisconnectedFromHost,
295 Closed,
296 DeletedEntry(ProjectEntryId),
297 CollaboratorUpdated {
298 old_peer_id: proto::PeerId,
299 new_peer_id: proto::PeerId,
300 },
301 CollaboratorJoined(proto::PeerId),
302 CollaboratorLeft(proto::PeerId),
303 RefreshInlayHints,
304 RevealInProjectPanel(ProjectEntryId),
305}
306
307pub enum LanguageServerState {
308 Starting(Task<Option<Arc<LanguageServer>>>),
309
310 Running {
311 language: Arc<Language>,
312 adapter: Arc<CachedLspAdapter>,
313 server: Arc<LanguageServer>,
314 simulate_disk_based_diagnostics_completion: Option<Task<()>>,
315 },
316}
317
318#[derive(Serialize)]
319pub struct LanguageServerStatus {
320 pub name: String,
321 pub pending_work: BTreeMap<String, LanguageServerProgress>,
322 pub has_pending_diagnostic_updates: bool,
323 progress_tokens: HashSet<String>,
324}
325
326#[derive(Clone, Debug, Serialize)]
327pub struct LanguageServerProgress {
328 pub message: Option<String>,
329 pub percentage: Option<usize>,
330 #[serde(skip_serializing)]
331 pub last_update_at: Instant,
332}
333
334#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
335pub struct ProjectPath {
336 pub worktree_id: WorktreeId,
337 pub path: Arc<Path>,
338}
339
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct InlayHint {
342 pub position: language::Anchor,
343 pub label: InlayHintLabel,
344 pub kind: Option<InlayHintKind>,
345 pub padding_left: bool,
346 pub padding_right: bool,
347 pub tooltip: Option<InlayHintTooltip>,
348 pub resolve_state: ResolveState,
349}
350
351#[derive(Debug, Clone, PartialEq, Eq)]
352pub enum ResolveState {
353 Resolved,
354 CanResolve(LanguageServerId, Option<lsp::LSPAny>),
355 Resolving,
356}
357
358impl InlayHint {
359 pub fn text(&self) -> String {
360 match &self.label {
361 InlayHintLabel::String(s) => s.to_owned(),
362 InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
363 }
364 }
365}
366
367#[derive(Debug, Clone, PartialEq, Eq)]
368pub enum InlayHintLabel {
369 String(String),
370 LabelParts(Vec<InlayHintLabelPart>),
371}
372
373#[derive(Debug, Clone, PartialEq, Eq)]
374pub struct InlayHintLabelPart {
375 pub value: String,
376 pub tooltip: Option<InlayHintLabelPartTooltip>,
377 pub location: Option<(LanguageServerId, lsp::Location)>,
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
381pub enum InlayHintTooltip {
382 String(String),
383 MarkupContent(MarkupContent),
384}
385
386#[derive(Debug, Clone, PartialEq, Eq)]
387pub enum InlayHintLabelPartTooltip {
388 String(String),
389 MarkupContent(MarkupContent),
390}
391
392#[derive(Debug, Clone, PartialEq, Eq)]
393pub struct MarkupContent {
394 pub kind: HoverBlockKind,
395 pub value: String,
396}
397
398#[derive(Debug, Clone)]
399pub struct LocationLink {
400 pub origin: Option<Location>,
401 pub target: Location,
402}
403
404#[derive(Debug)]
405pub struct DocumentHighlight {
406 pub range: Range<language::Anchor>,
407 pub kind: DocumentHighlightKind,
408}
409
410#[derive(Clone, Debug)]
411pub struct Symbol {
412 pub language_server_name: LanguageServerName,
413 pub source_worktree_id: WorktreeId,
414 pub path: ProjectPath,
415 pub label: CodeLabel,
416 pub name: String,
417 pub kind: lsp::SymbolKind,
418 pub range: Range<Unclipped<PointUtf16>>,
419 pub signature: [u8; 32],
420}
421
422#[derive(Clone, Debug, PartialEq)]
423pub struct HoverBlock {
424 pub text: String,
425 pub kind: HoverBlockKind,
426}
427
428#[derive(Clone, Debug, PartialEq, Eq)]
429pub enum HoverBlockKind {
430 PlainText,
431 Markdown,
432 Code { language: String },
433}
434
435#[derive(Debug)]
436pub struct Hover {
437 pub contents: Vec<HoverBlock>,
438 pub range: Option<Range<language::Anchor>>,
439 pub language: Option<Arc<Language>>,
440}
441
442impl Hover {
443 pub fn is_empty(&self) -> bool {
444 self.contents.iter().all(|block| block.text.is_empty())
445 }
446}
447
448#[derive(Default)]
449pub struct ProjectTransaction(pub HashMap<Model<Buffer>, language::Transaction>);
450
451#[derive(Debug, Clone, Copy, PartialEq, Eq)]
452pub enum FormatTrigger {
453 Save,
454 Manual,
455}
456
457// Currently, formatting operations are represented differently depending on
458// whether they come from a language server or an external command.
459enum FormatOperation {
460 Lsp(Vec<(Range<Anchor>, String)>),
461 External(Diff),
462 Prettier(Diff),
463}
464
465impl FormatTrigger {
466 fn from_proto(value: i32) -> FormatTrigger {
467 match value {
468 0 => FormatTrigger::Save,
469 1 => FormatTrigger::Manual,
470 _ => FormatTrigger::Save,
471 }
472 }
473}
474#[derive(Clone, Debug, PartialEq)]
475enum SearchMatchCandidate {
476 OpenBuffer {
477 buffer: Model<Buffer>,
478 // This might be an unnamed file without representation on filesystem
479 path: Option<Arc<Path>>,
480 },
481 Path {
482 worktree_id: WorktreeId,
483 is_ignored: bool,
484 path: Arc<Path>,
485 },
486}
487
488type SearchMatchCandidateIndex = usize;
489impl SearchMatchCandidate {
490 fn path(&self) -> Option<Arc<Path>> {
491 match self {
492 SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
493 SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
494 }
495 }
496}
497
498impl Project {
499 pub fn init_settings(cx: &mut AppContext) {
500 WorktreeSettings::register(cx);
501 ProjectSettings::register(cx);
502 }
503
504 pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
505 Self::init_settings(cx);
506
507 client.add_model_message_handler(Self::handle_add_collaborator);
508 client.add_model_message_handler(Self::handle_update_project_collaborator);
509 client.add_model_message_handler(Self::handle_remove_collaborator);
510 client.add_model_message_handler(Self::handle_buffer_reloaded);
511 client.add_model_message_handler(Self::handle_buffer_saved);
512 client.add_model_message_handler(Self::handle_start_language_server);
513 client.add_model_message_handler(Self::handle_update_language_server);
514 client.add_model_message_handler(Self::handle_update_project);
515 client.add_model_message_handler(Self::handle_unshare_project);
516 client.add_model_message_handler(Self::handle_create_buffer_for_peer);
517 client.add_model_message_handler(Self::handle_update_buffer_file);
518 client.add_model_request_handler(Self::handle_update_buffer);
519 client.add_model_message_handler(Self::handle_update_diagnostic_summary);
520 client.add_model_message_handler(Self::handle_update_worktree);
521 client.add_model_message_handler(Self::handle_update_worktree_settings);
522 client.add_model_request_handler(Self::handle_create_project_entry);
523 client.add_model_request_handler(Self::handle_rename_project_entry);
524 client.add_model_request_handler(Self::handle_copy_project_entry);
525 client.add_model_request_handler(Self::handle_delete_project_entry);
526 client.add_model_request_handler(Self::handle_expand_project_entry);
527 client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
528 client.add_model_request_handler(Self::handle_resolve_completion_documentation);
529 client.add_model_request_handler(Self::handle_apply_code_action);
530 client.add_model_request_handler(Self::handle_on_type_formatting);
531 client.add_model_request_handler(Self::handle_inlay_hints);
532 client.add_model_request_handler(Self::handle_resolve_inlay_hint);
533 client.add_model_request_handler(Self::handle_refresh_inlay_hints);
534 client.add_model_request_handler(Self::handle_reload_buffers);
535 client.add_model_request_handler(Self::handle_synchronize_buffers);
536 client.add_model_request_handler(Self::handle_format_buffers);
537 client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
538 client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
539 client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
540 client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
541 client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
542 client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
543 client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
544 client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
545 client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
546 client.add_model_request_handler(Self::handle_search_project);
547 client.add_model_request_handler(Self::handle_get_project_symbols);
548 client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
549 client.add_model_request_handler(Self::handle_open_buffer_by_id);
550 client.add_model_request_handler(Self::handle_open_buffer_by_path);
551 client.add_model_request_handler(Self::handle_save_buffer);
552 client.add_model_message_handler(Self::handle_update_diff_base);
553 client.add_model_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
554 }
555
556 pub fn local(
557 client: Arc<Client>,
558 node: Arc<dyn NodeRuntime>,
559 user_store: Model<UserStore>,
560 languages: Arc<LanguageRegistry>,
561 fs: Arc<dyn Fs>,
562 cx: &mut AppContext,
563 ) -> Model<Self> {
564 cx.new_model(|cx: &mut ModelContext<Self>| {
565 let (tx, rx) = mpsc::unbounded();
566 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
567 .detach();
568 let copilot_lsp_subscription =
569 Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
570 let tasks = Inventory::new(cx);
571
572 Self {
573 worktrees: Vec::new(),
574 buffer_ordered_messages_tx: tx,
575 flush_language_server_update: None,
576 pending_language_server_update: None,
577 collaborators: Default::default(),
578 next_buffer_id: BufferId::new(1).unwrap(),
579 opened_buffers: Default::default(),
580 shared_buffers: Default::default(),
581 incomplete_remote_buffers: Default::default(),
582 loading_buffers_by_path: Default::default(),
583 loading_local_worktrees: Default::default(),
584 local_buffer_ids_by_path: Default::default(),
585 local_buffer_ids_by_entry_id: Default::default(),
586 buffer_snapshots: Default::default(),
587 join_project_response_message_id: 0,
588 client_state: ProjectClientState::Local,
589 opened_buffer: watch::channel(),
590 client_subscriptions: Vec::new(),
591 _subscriptions: vec![
592 cx.observe_global::<SettingsStore>(Self::on_settings_changed),
593 cx.on_release(Self::release),
594 cx.on_app_quit(Self::shutdown_language_servers),
595 ],
596 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
597 _maintain_workspace_config: Self::maintain_workspace_config(cx),
598 active_entry: None,
599 languages,
600 client,
601 user_store,
602 fs,
603 next_entry_id: Default::default(),
604 next_diagnostic_group_id: Default::default(),
605 supplementary_language_servers: HashMap::default(),
606 language_servers: Default::default(),
607 language_server_ids: HashMap::default(),
608 language_server_statuses: Default::default(),
609 last_workspace_edits_by_language_server: Default::default(),
610 language_server_watched_paths: HashMap::default(),
611 buffers_being_formatted: Default::default(),
612 buffers_needing_diff: Default::default(),
613 git_diff_debouncer: DebouncedDelay::new(),
614 nonce: StdRng::from_entropy().gen(),
615 terminals: Terminals {
616 local_handles: Vec::new(),
617 },
618 copilot_lsp_subscription,
619 copilot_log_subscription: None,
620 current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
621 node: Some(node),
622 default_prettier: DefaultPrettier::default(),
623 prettiers_per_worktree: HashMap::default(),
624 prettier_instances: HashMap::default(),
625 tasks,
626 hosted_project_id: None,
627 }
628 })
629 }
630
631 pub async fn remote(
632 remote_id: u64,
633 client: Arc<Client>,
634 user_store: Model<UserStore>,
635 languages: Arc<LanguageRegistry>,
636 fs: Arc<dyn Fs>,
637 cx: AsyncAppContext,
638 ) -> Result<Model<Self>> {
639 client.authenticate_and_connect(true, &cx).await?;
640
641 let subscription = client.subscribe_to_entity(remote_id)?;
642 let response = client
643 .request_envelope(proto::JoinProject {
644 project_id: remote_id,
645 })
646 .await?;
647 Self::from_join_project_response(
648 response,
649 subscription,
650 client,
651 user_store,
652 languages,
653 fs,
654 cx,
655 )
656 .await
657 }
658 async fn from_join_project_response(
659 response: TypedEnvelope<proto::JoinProjectResponse>,
660 subscription: PendingEntitySubscription<Project>,
661 client: Arc<Client>,
662 user_store: Model<UserStore>,
663 languages: Arc<LanguageRegistry>,
664 fs: Arc<dyn Fs>,
665 mut cx: AsyncAppContext,
666 ) -> Result<Model<Self>> {
667 let remote_id = response.payload.project_id;
668 let role = response.payload.role();
669 let this = cx.new_model(|cx| {
670 let replica_id = response.payload.replica_id as ReplicaId;
671 let tasks = Inventory::new(cx);
672 // BIG CAUTION NOTE: The order in which we initialize fields here matters and it should match what's done in Self::local.
673 // Otherwise, you might run into issues where worktree id on remote is different than what's on local host.
674 // That's because Worktree's identifier is entity id, which should probably be changed.
675 let mut worktrees = Vec::new();
676 for worktree in response.payload.worktrees {
677 let worktree =
678 Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
679 worktrees.push(worktree);
680 }
681
682 let (tx, rx) = mpsc::unbounded();
683 cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
684 .detach();
685 let copilot_lsp_subscription =
686 Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
687 let mut this = Self {
688 worktrees: Vec::new(),
689 buffer_ordered_messages_tx: tx,
690 pending_language_server_update: None,
691 flush_language_server_update: None,
692 loading_buffers_by_path: Default::default(),
693 next_buffer_id: BufferId::new(1).unwrap(),
694 opened_buffer: watch::channel(),
695 shared_buffers: Default::default(),
696 incomplete_remote_buffers: Default::default(),
697 loading_local_worktrees: Default::default(),
698 local_buffer_ids_by_path: Default::default(),
699 local_buffer_ids_by_entry_id: Default::default(),
700 active_entry: None,
701 collaborators: Default::default(),
702 join_project_response_message_id: response.message_id,
703 _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
704 _maintain_workspace_config: Self::maintain_workspace_config(cx),
705 languages,
706 user_store: user_store.clone(),
707 fs,
708 next_entry_id: Default::default(),
709 next_diagnostic_group_id: Default::default(),
710 client_subscriptions: Default::default(),
711 _subscriptions: vec![
712 cx.on_release(Self::release),
713 cx.on_app_quit(Self::shutdown_language_servers),
714 ],
715 client: client.clone(),
716 client_state: ProjectClientState::Remote {
717 sharing_has_stopped: false,
718 capability: Capability::ReadWrite,
719 remote_id,
720 replica_id,
721 },
722 supplementary_language_servers: HashMap::default(),
723 language_servers: Default::default(),
724 language_server_ids: HashMap::default(),
725 language_server_statuses: response
726 .payload
727 .language_servers
728 .into_iter()
729 .map(|server| {
730 (
731 LanguageServerId(server.id as usize),
732 LanguageServerStatus {
733 name: server.name,
734 pending_work: Default::default(),
735 has_pending_diagnostic_updates: false,
736 progress_tokens: Default::default(),
737 },
738 )
739 })
740 .collect(),
741 last_workspace_edits_by_language_server: Default::default(),
742 language_server_watched_paths: HashMap::default(),
743 opened_buffers: Default::default(),
744 buffers_being_formatted: Default::default(),
745 buffers_needing_diff: Default::default(),
746 git_diff_debouncer: DebouncedDelay::new(),
747 buffer_snapshots: Default::default(),
748 nonce: StdRng::from_entropy().gen(),
749 terminals: Terminals {
750 local_handles: Vec::new(),
751 },
752 copilot_lsp_subscription,
753 copilot_log_subscription: None,
754 current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
755 node: None,
756 default_prettier: DefaultPrettier::default(),
757 prettiers_per_worktree: HashMap::default(),
758 prettier_instances: HashMap::default(),
759 tasks,
760 hosted_project_id: None,
761 };
762 this.set_role(role, cx);
763 for worktree in worktrees {
764 let _ = this.add_worktree(&worktree, cx);
765 }
766 this
767 })?;
768 let subscription = subscription.set_model(&this, &mut cx);
769
770 let user_ids = response
771 .payload
772 .collaborators
773 .iter()
774 .map(|peer| peer.user_id)
775 .collect();
776 user_store
777 .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
778 .await?;
779
780 this.update(&mut cx, |this, cx| {
781 this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
782 this.client_subscriptions.push(subscription);
783 anyhow::Ok(())
784 })??;
785
786 Ok(this)
787 }
788
789 pub async fn hosted(
790 remote_id: ProjectId,
791 user_store: Model<UserStore>,
792 client: Arc<Client>,
793 languages: Arc<LanguageRegistry>,
794 fs: Arc<dyn Fs>,
795 cx: AsyncAppContext,
796 ) -> Result<Model<Self>> {
797 client.authenticate_and_connect(true, &cx).await?;
798
799 let subscription = client.subscribe_to_entity(remote_id.0)?;
800 let response = client
801 .request_envelope(proto::JoinHostedProject {
802 project_id: remote_id.0,
803 })
804 .await?;
805 Self::from_join_project_response(
806 response,
807 subscription,
808 client,
809 user_store,
810 languages,
811 fs,
812 cx,
813 )
814 .await
815 }
816
817 fn release(&mut self, cx: &mut AppContext) {
818 match &self.client_state {
819 ProjectClientState::Local => {}
820 ProjectClientState::Shared { .. } => {
821 let _ = self.unshare_internal(cx);
822 }
823 ProjectClientState::Remote { remote_id, .. } => {
824 let _ = self.client.send(proto::LeaveProject {
825 project_id: *remote_id,
826 });
827 self.disconnected_from_host_internal(cx);
828 }
829 }
830 }
831
832 fn shutdown_language_servers(
833 &mut self,
834 _cx: &mut ModelContext<Self>,
835 ) -> impl Future<Output = ()> {
836 let shutdown_futures = self
837 .language_servers
838 .drain()
839 .map(|(_, server_state)| async {
840 use LanguageServerState::*;
841 match server_state {
842 Running { server, .. } => server.shutdown()?.await,
843 Starting(task) => task.await?.shutdown()?.await,
844 }
845 })
846 .collect::<Vec<_>>();
847
848 async move {
849 futures::future::join_all(shutdown_futures).await;
850 }
851 }
852
853 #[cfg(any(test, feature = "test-support"))]
854 pub async fn test(
855 fs: Arc<dyn Fs>,
856 root_paths: impl IntoIterator<Item = &Path>,
857 cx: &mut gpui::TestAppContext,
858 ) -> Model<Project> {
859 use clock::FakeSystemClock;
860
861 let mut languages = LanguageRegistry::test();
862 languages.set_executor(cx.executor());
863 let clock = Arc::new(FakeSystemClock::default());
864 let http_client = util::http::FakeHttpClient::with_404_response();
865 let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
866 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
867 let project = cx.update(|cx| {
868 Project::local(
869 client,
870 node_runtime::FakeNodeRuntime::new(),
871 user_store,
872 Arc::new(languages),
873 fs,
874 cx,
875 )
876 });
877 for path in root_paths {
878 let (tree, _) = project
879 .update(cx, |project, cx| {
880 project.find_or_create_local_worktree(path, true, cx)
881 })
882 .await
883 .unwrap();
884 tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
885 .await;
886 }
887 project
888 }
889
890 fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
891 let mut language_servers_to_start = Vec::new();
892 let mut language_formatters_to_check = Vec::new();
893 for buffer in self.opened_buffers.values() {
894 if let Some(buffer) = buffer.upgrade() {
895 let buffer = buffer.read(cx);
896 let buffer_file = File::from_dyn(buffer.file());
897 let buffer_language = buffer.language();
898 let settings = language_settings(buffer_language, buffer.file(), cx);
899 if let Some(language) = buffer_language {
900 if settings.enable_language_server {
901 if let Some(file) = buffer_file {
902 language_servers_to_start
903 .push((file.worktree.clone(), Arc::clone(language)));
904 }
905 }
906 language_formatters_to_check.push((
907 buffer_file.map(|f| f.worktree_id(cx)),
908 Arc::clone(language),
909 settings.clone(),
910 ));
911 }
912 }
913 }
914
915 let mut language_servers_to_stop = Vec::new();
916 let mut language_servers_to_restart = Vec::new();
917 let languages = self.languages.to_vec();
918
919 let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
920 let current_lsp_settings = &self.current_lsp_settings;
921 for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
922 let language = languages.iter().find_map(|l| {
923 let adapter = self
924 .languages
925 .lsp_adapters(l)
926 .iter()
927 .find(|adapter| &adapter.name == started_lsp_name)?
928 .clone();
929 Some((l, adapter))
930 });
931 if let Some((language, adapter)) = language {
932 let worktree = self.worktree_for_id(*worktree_id, cx);
933 let file = worktree.as_ref().and_then(|tree| {
934 tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
935 });
936 if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
937 language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
938 } else if let Some(worktree) = worktree {
939 let server_name = &adapter.name.0;
940 match (
941 current_lsp_settings.get(server_name),
942 new_lsp_settings.get(server_name),
943 ) {
944 (None, None) => {}
945 (Some(_), None) | (None, Some(_)) => {
946 language_servers_to_restart.push((worktree, Arc::clone(language)));
947 }
948 (Some(current_lsp_settings), Some(new_lsp_settings)) => {
949 if current_lsp_settings != new_lsp_settings {
950 language_servers_to_restart.push((worktree, Arc::clone(language)));
951 }
952 }
953 }
954 }
955 }
956 }
957 self.current_lsp_settings = new_lsp_settings;
958
959 // Stop all newly-disabled language servers.
960 for (worktree_id, adapter_name) in language_servers_to_stop {
961 self.stop_language_server(worktree_id, adapter_name, cx)
962 .detach();
963 }
964
965 let mut prettier_plugins_by_worktree = HashMap::default();
966 for (worktree, language, settings) in language_formatters_to_check {
967 if let Some(plugins) = prettier_support::prettier_plugins_for_language(
968 &self.languages,
969 &language,
970 &settings,
971 ) {
972 prettier_plugins_by_worktree
973 .entry(worktree)
974 .or_insert_with(|| HashSet::default())
975 .extend(plugins);
976 }
977 }
978 for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
979 self.install_default_prettier(worktree, prettier_plugins, cx);
980 }
981
982 // Start all the newly-enabled language servers.
983 for (worktree, language) in language_servers_to_start {
984 self.start_language_servers(&worktree, language, cx);
985 }
986
987 // Restart all language servers with changed initialization options.
988 for (worktree, language) in language_servers_to_restart {
989 self.restart_language_servers(worktree, language, cx);
990 }
991
992 if self.copilot_lsp_subscription.is_none() {
993 if let Some(copilot) = Copilot::global(cx) {
994 for buffer in self.opened_buffers.values() {
995 if let Some(buffer) = buffer.upgrade() {
996 self.register_buffer_with_copilot(&buffer, cx);
997 }
998 }
999 self.copilot_lsp_subscription = Some(subscribe_for_copilot_events(&copilot, cx));
1000 }
1001 }
1002
1003 cx.notify();
1004 }
1005
1006 pub fn buffer_for_id(&self, remote_id: BufferId) -> Option<Model<Buffer>> {
1007 self.opened_buffers
1008 .get(&remote_id)
1009 .and_then(|buffer| buffer.upgrade())
1010 }
1011
1012 pub fn languages(&self) -> &Arc<LanguageRegistry> {
1013 &self.languages
1014 }
1015
1016 pub fn client(&self) -> Arc<Client> {
1017 self.client.clone()
1018 }
1019
1020 pub fn user_store(&self) -> Model<UserStore> {
1021 self.user_store.clone()
1022 }
1023
1024 pub fn opened_buffers(&self) -> Vec<Model<Buffer>> {
1025 self.opened_buffers
1026 .values()
1027 .filter_map(|b| b.upgrade())
1028 .collect()
1029 }
1030
1031 #[cfg(any(test, feature = "test-support"))]
1032 pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1033 let path = path.into();
1034 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
1035 self.opened_buffers.iter().any(|(_, buffer)| {
1036 if let Some(buffer) = buffer.upgrade() {
1037 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1038 if file.worktree == worktree && file.path() == &path.path {
1039 return true;
1040 }
1041 }
1042 }
1043 false
1044 })
1045 } else {
1046 false
1047 }
1048 }
1049
1050 pub fn fs(&self) -> &Arc<dyn Fs> {
1051 &self.fs
1052 }
1053
1054 pub fn remote_id(&self) -> Option<u64> {
1055 match self.client_state {
1056 ProjectClientState::Local => None,
1057 ProjectClientState::Shared { remote_id, .. }
1058 | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1059 }
1060 }
1061
1062 pub fn hosted_project_id(&self) -> Option<ProjectId> {
1063 self.hosted_project_id
1064 }
1065
1066 pub fn replica_id(&self) -> ReplicaId {
1067 match self.client_state {
1068 ProjectClientState::Remote { replica_id, .. } => replica_id,
1069 _ => 0,
1070 }
1071 }
1072
1073 fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
1074 if let ProjectClientState::Shared { updates_tx, .. } = &mut self.client_state {
1075 updates_tx
1076 .unbounded_send(LocalProjectUpdate::WorktreesChanged)
1077 .ok();
1078 }
1079 cx.notify();
1080 }
1081
1082 pub fn task_inventory(&self) -> &Model<Inventory> {
1083 &self.tasks
1084 }
1085
1086 pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1087 &self.collaborators
1088 }
1089
1090 pub fn host(&self) -> Option<&Collaborator> {
1091 self.collaborators.values().find(|c| c.replica_id == 0)
1092 }
1093
1094 /// Collect all worktrees, including ones that don't appear in the project panel
1095 pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
1096 self.worktrees
1097 .iter()
1098 .filter_map(move |worktree| worktree.upgrade())
1099 }
1100
1101 /// Collect all user-visible worktrees, the ones that appear in the project panel
1102 pub fn visible_worktrees<'a>(
1103 &'a self,
1104 cx: &'a AppContext,
1105 ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1106 self.worktrees.iter().filter_map(|worktree| {
1107 worktree.upgrade().and_then(|worktree| {
1108 if worktree.read(cx).is_visible() {
1109 Some(worktree)
1110 } else {
1111 None
1112 }
1113 })
1114 })
1115 }
1116
1117 pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1118 self.visible_worktrees(cx)
1119 .map(|tree| tree.read(cx).root_name())
1120 }
1121
1122 pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1123 self.worktrees()
1124 .find(|worktree| worktree.read(cx).id() == id)
1125 }
1126
1127 pub fn worktree_for_entry(
1128 &self,
1129 entry_id: ProjectEntryId,
1130 cx: &AppContext,
1131 ) -> Option<Model<Worktree>> {
1132 self.worktrees()
1133 .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1134 }
1135
1136 pub fn worktree_id_for_entry(
1137 &self,
1138 entry_id: ProjectEntryId,
1139 cx: &AppContext,
1140 ) -> Option<WorktreeId> {
1141 self.worktree_for_entry(entry_id, cx)
1142 .map(|worktree| worktree.read(cx).id())
1143 }
1144
1145 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1146 paths.iter().all(|path| self.contains_path(path, cx))
1147 }
1148
1149 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1150 for worktree in self.worktrees() {
1151 let worktree = worktree.read(cx).as_local();
1152 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1153 return true;
1154 }
1155 }
1156 false
1157 }
1158
1159 pub fn create_entry(
1160 &mut self,
1161 project_path: impl Into<ProjectPath>,
1162 is_directory: bool,
1163 cx: &mut ModelContext<Self>,
1164 ) -> Task<Result<Option<Entry>>> {
1165 let project_path = project_path.into();
1166 let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1167 return Task::ready(Ok(None));
1168 };
1169 if self.is_local() {
1170 worktree.update(cx, |worktree, cx| {
1171 worktree
1172 .as_local_mut()
1173 .unwrap()
1174 .create_entry(project_path.path, is_directory, cx)
1175 })
1176 } else {
1177 let client = self.client.clone();
1178 let project_id = self.remote_id().unwrap();
1179 cx.spawn(move |_, mut cx| async move {
1180 let response = client
1181 .request(proto::CreateProjectEntry {
1182 worktree_id: project_path.worktree_id.to_proto(),
1183 project_id,
1184 path: project_path.path.to_string_lossy().into(),
1185 is_directory,
1186 })
1187 .await?;
1188 match response.entry {
1189 Some(entry) => worktree
1190 .update(&mut cx, |worktree, cx| {
1191 worktree.as_remote_mut().unwrap().insert_entry(
1192 entry,
1193 response.worktree_scan_id as usize,
1194 cx,
1195 )
1196 })?
1197 .await
1198 .map(Some),
1199 None => Ok(None),
1200 }
1201 })
1202 }
1203 }
1204
1205 pub fn copy_entry(
1206 &mut self,
1207 entry_id: ProjectEntryId,
1208 new_path: impl Into<Arc<Path>>,
1209 cx: &mut ModelContext<Self>,
1210 ) -> Task<Result<Option<Entry>>> {
1211 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1212 return Task::ready(Ok(None));
1213 };
1214 let new_path = new_path.into();
1215 if self.is_local() {
1216 worktree.update(cx, |worktree, cx| {
1217 worktree
1218 .as_local_mut()
1219 .unwrap()
1220 .copy_entry(entry_id, new_path, cx)
1221 })
1222 } else {
1223 let client = self.client.clone();
1224 let project_id = self.remote_id().unwrap();
1225
1226 cx.spawn(move |_, mut cx| async move {
1227 let response = client
1228 .request(proto::CopyProjectEntry {
1229 project_id,
1230 entry_id: entry_id.to_proto(),
1231 new_path: new_path.to_string_lossy().into(),
1232 })
1233 .await?;
1234 match response.entry {
1235 Some(entry) => worktree
1236 .update(&mut cx, |worktree, cx| {
1237 worktree.as_remote_mut().unwrap().insert_entry(
1238 entry,
1239 response.worktree_scan_id as usize,
1240 cx,
1241 )
1242 })?
1243 .await
1244 .map(Some),
1245 None => Ok(None),
1246 }
1247 })
1248 }
1249 }
1250
1251 pub fn rename_entry(
1252 &mut self,
1253 entry_id: ProjectEntryId,
1254 new_path: impl Into<Arc<Path>>,
1255 cx: &mut ModelContext<Self>,
1256 ) -> Task<Result<Option<Entry>>> {
1257 let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1258 return Task::ready(Ok(None));
1259 };
1260 let new_path = new_path.into();
1261 if self.is_local() {
1262 worktree.update(cx, |worktree, cx| {
1263 worktree
1264 .as_local_mut()
1265 .unwrap()
1266 .rename_entry(entry_id, new_path, cx)
1267 })
1268 } else {
1269 let client = self.client.clone();
1270 let project_id = self.remote_id().unwrap();
1271
1272 cx.spawn(move |_, mut cx| async move {
1273 let response = client
1274 .request(proto::RenameProjectEntry {
1275 project_id,
1276 entry_id: entry_id.to_proto(),
1277 new_path: new_path.to_string_lossy().into(),
1278 })
1279 .await?;
1280 match response.entry {
1281 Some(entry) => worktree
1282 .update(&mut cx, |worktree, cx| {
1283 worktree.as_remote_mut().unwrap().insert_entry(
1284 entry,
1285 response.worktree_scan_id as usize,
1286 cx,
1287 )
1288 })?
1289 .await
1290 .map(Some),
1291 None => Ok(None),
1292 }
1293 })
1294 }
1295 }
1296
1297 pub fn delete_entry(
1298 &mut self,
1299 entry_id: ProjectEntryId,
1300 cx: &mut ModelContext<Self>,
1301 ) -> Option<Task<Result<()>>> {
1302 let worktree = self.worktree_for_entry(entry_id, cx)?;
1303
1304 cx.emit(Event::DeletedEntry(entry_id));
1305
1306 if self.is_local() {
1307 worktree.update(cx, |worktree, cx| {
1308 worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1309 })
1310 } else {
1311 let client = self.client.clone();
1312 let project_id = self.remote_id().unwrap();
1313 Some(cx.spawn(move |_, mut cx| async move {
1314 let response = client
1315 .request(proto::DeleteProjectEntry {
1316 project_id,
1317 entry_id: entry_id.to_proto(),
1318 })
1319 .await?;
1320 worktree
1321 .update(&mut cx, move |worktree, cx| {
1322 worktree.as_remote_mut().unwrap().delete_entry(
1323 entry_id,
1324 response.worktree_scan_id as usize,
1325 cx,
1326 )
1327 })?
1328 .await
1329 }))
1330 }
1331 }
1332
1333 pub fn expand_entry(
1334 &mut self,
1335 worktree_id: WorktreeId,
1336 entry_id: ProjectEntryId,
1337 cx: &mut ModelContext<Self>,
1338 ) -> Option<Task<Result<()>>> {
1339 let worktree = self.worktree_for_id(worktree_id, cx)?;
1340 if self.is_local() {
1341 worktree.update(cx, |worktree, cx| {
1342 worktree.as_local_mut().unwrap().expand_entry(entry_id, cx)
1343 })
1344 } else {
1345 let worktree = worktree.downgrade();
1346 let request = self.client.request(proto::ExpandProjectEntry {
1347 project_id: self.remote_id().unwrap(),
1348 entry_id: entry_id.to_proto(),
1349 });
1350 Some(cx.spawn(move |_, mut cx| async move {
1351 let response = request.await?;
1352 if let Some(worktree) = worktree.upgrade() {
1353 worktree
1354 .update(&mut cx, |worktree, _| {
1355 worktree
1356 .as_remote_mut()
1357 .unwrap()
1358 .wait_for_snapshot(response.worktree_scan_id as usize)
1359 })?
1360 .await?;
1361 }
1362 Ok(())
1363 }))
1364 }
1365 }
1366
1367 pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1368 if !matches!(self.client_state, ProjectClientState::Local) {
1369 return Err(anyhow!("project was already shared"));
1370 }
1371 self.client_subscriptions.push(
1372 self.client
1373 .subscribe_to_entity(project_id)?
1374 .set_model(&cx.handle(), &mut cx.to_async()),
1375 );
1376
1377 for open_buffer in self.opened_buffers.values_mut() {
1378 match open_buffer {
1379 OpenBuffer::Strong(_) => {}
1380 OpenBuffer::Weak(buffer) => {
1381 if let Some(buffer) = buffer.upgrade() {
1382 *open_buffer = OpenBuffer::Strong(buffer);
1383 }
1384 }
1385 OpenBuffer::Operations(_) => unreachable!(),
1386 }
1387 }
1388
1389 for worktree_handle in self.worktrees.iter_mut() {
1390 match worktree_handle {
1391 WorktreeHandle::Strong(_) => {}
1392 WorktreeHandle::Weak(worktree) => {
1393 if let Some(worktree) = worktree.upgrade() {
1394 *worktree_handle = WorktreeHandle::Strong(worktree);
1395 }
1396 }
1397 }
1398 }
1399
1400 for (server_id, status) in &self.language_server_statuses {
1401 self.client
1402 .send(proto::StartLanguageServer {
1403 project_id,
1404 server: Some(proto::LanguageServer {
1405 id: server_id.0 as u64,
1406 name: status.name.clone(),
1407 }),
1408 })
1409 .log_err();
1410 }
1411
1412 let store = cx.global::<SettingsStore>();
1413 for worktree in self.worktrees() {
1414 let worktree_id = worktree.read(cx).id().to_proto();
1415 for (path, content) in store.local_settings(worktree.entity_id().as_u64() as usize) {
1416 self.client
1417 .send(proto::UpdateWorktreeSettings {
1418 project_id,
1419 worktree_id,
1420 path: path.to_string_lossy().into(),
1421 content: Some(content),
1422 })
1423 .log_err();
1424 }
1425 }
1426
1427 let (updates_tx, mut updates_rx) = mpsc::unbounded();
1428 let client = self.client.clone();
1429 self.client_state = ProjectClientState::Shared {
1430 remote_id: project_id,
1431 updates_tx,
1432 _send_updates: cx.spawn(move |this, mut cx| async move {
1433 while let Some(update) = updates_rx.next().await {
1434 match update {
1435 LocalProjectUpdate::WorktreesChanged => {
1436 let worktrees = this.update(&mut cx, |this, _cx| {
1437 this.worktrees().collect::<Vec<_>>()
1438 })?;
1439 let update_project = this
1440 .update(&mut cx, |this, cx| {
1441 this.client.request(proto::UpdateProject {
1442 project_id,
1443 worktrees: this.worktree_metadata_protos(cx),
1444 })
1445 })?
1446 .await;
1447 if update_project.is_ok() {
1448 for worktree in worktrees {
1449 worktree.update(&mut cx, |worktree, cx| {
1450 let worktree = worktree.as_local_mut().unwrap();
1451 worktree.share(project_id, cx).detach_and_log_err(cx)
1452 })?;
1453 }
1454 }
1455 }
1456 LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1457 let buffer = this.update(&mut cx, |this, _| {
1458 let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1459 let shared_buffers =
1460 this.shared_buffers.entry(peer_id).or_default();
1461 if shared_buffers.insert(buffer_id) {
1462 if let OpenBuffer::Strong(buffer) = buffer {
1463 Some(buffer.clone())
1464 } else {
1465 None
1466 }
1467 } else {
1468 None
1469 }
1470 })?;
1471
1472 let Some(buffer) = buffer else { continue };
1473 let operations =
1474 buffer.update(&mut cx, |b, cx| b.serialize_ops(None, cx))?;
1475 let operations = operations.await;
1476 let state = buffer.update(&mut cx, |buffer, _| buffer.to_proto())?;
1477
1478 let initial_state = proto::CreateBufferForPeer {
1479 project_id,
1480 peer_id: Some(peer_id),
1481 variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1482 };
1483 if client.send(initial_state).log_err().is_some() {
1484 let client = client.clone();
1485 cx.background_executor()
1486 .spawn(async move {
1487 let mut chunks = split_operations(operations).peekable();
1488 while let Some(chunk) = chunks.next() {
1489 let is_last = chunks.peek().is_none();
1490 client.send(proto::CreateBufferForPeer {
1491 project_id,
1492 peer_id: Some(peer_id),
1493 variant: Some(
1494 proto::create_buffer_for_peer::Variant::Chunk(
1495 proto::BufferChunk {
1496 buffer_id: buffer_id.into(),
1497 operations: chunk,
1498 is_last,
1499 },
1500 ),
1501 ),
1502 })?;
1503 }
1504 anyhow::Ok(())
1505 })
1506 .await
1507 .log_err();
1508 }
1509 }
1510 }
1511 }
1512 Ok(())
1513 }),
1514 };
1515
1516 self.metadata_changed(cx);
1517 cx.emit(Event::RemoteIdChanged(Some(project_id)));
1518 cx.notify();
1519 Ok(())
1520 }
1521
1522 pub fn reshared(
1523 &mut self,
1524 message: proto::ResharedProject,
1525 cx: &mut ModelContext<Self>,
1526 ) -> Result<()> {
1527 self.shared_buffers.clear();
1528 self.set_collaborators_from_proto(message.collaborators, cx)?;
1529 self.metadata_changed(cx);
1530 Ok(())
1531 }
1532
1533 pub fn rejoined(
1534 &mut self,
1535 message: proto::RejoinedProject,
1536 message_id: u32,
1537 cx: &mut ModelContext<Self>,
1538 ) -> Result<()> {
1539 cx.update_global::<SettingsStore, _>(|store, cx| {
1540 for worktree in &self.worktrees {
1541 store
1542 .clear_local_settings(worktree.handle_id(), cx)
1543 .log_err();
1544 }
1545 });
1546
1547 self.join_project_response_message_id = message_id;
1548 self.set_worktrees_from_proto(message.worktrees, cx)?;
1549 self.set_collaborators_from_proto(message.collaborators, cx)?;
1550 self.language_server_statuses = message
1551 .language_servers
1552 .into_iter()
1553 .map(|server| {
1554 (
1555 LanguageServerId(server.id as usize),
1556 LanguageServerStatus {
1557 name: server.name,
1558 pending_work: Default::default(),
1559 has_pending_diagnostic_updates: false,
1560 progress_tokens: Default::default(),
1561 },
1562 )
1563 })
1564 .collect();
1565 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
1566 .unwrap();
1567 cx.notify();
1568 Ok(())
1569 }
1570
1571 pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1572 self.unshare_internal(cx)?;
1573 self.metadata_changed(cx);
1574 cx.notify();
1575 Ok(())
1576 }
1577
1578 fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1579 if self.is_remote() {
1580 return Err(anyhow!("attempted to unshare a remote project"));
1581 }
1582
1583 if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
1584 self.client_state = ProjectClientState::Local;
1585 self.collaborators.clear();
1586 self.shared_buffers.clear();
1587 self.client_subscriptions.clear();
1588
1589 for worktree_handle in self.worktrees.iter_mut() {
1590 if let WorktreeHandle::Strong(worktree) = worktree_handle {
1591 let is_visible = worktree.update(cx, |worktree, _| {
1592 worktree.as_local_mut().unwrap().unshare();
1593 worktree.is_visible()
1594 });
1595 if !is_visible {
1596 *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1597 }
1598 }
1599 }
1600
1601 for open_buffer in self.opened_buffers.values_mut() {
1602 // Wake up any tasks waiting for peers' edits to this buffer.
1603 if let Some(buffer) = open_buffer.upgrade() {
1604 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1605 }
1606
1607 if let OpenBuffer::Strong(buffer) = open_buffer {
1608 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1609 }
1610 }
1611
1612 self.client.send(proto::UnshareProject {
1613 project_id: remote_id,
1614 })?;
1615
1616 Ok(())
1617 } else {
1618 Err(anyhow!("attempted to unshare an unshared project"))
1619 }
1620 }
1621
1622 pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1623 self.disconnected_from_host_internal(cx);
1624 cx.emit(Event::DisconnectedFromHost);
1625 cx.notify();
1626 }
1627
1628 pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut ModelContext<Self>) {
1629 let new_capability =
1630 if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
1631 Capability::ReadWrite
1632 } else {
1633 Capability::ReadOnly
1634 };
1635 if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
1636 if *capability == new_capability {
1637 return;
1638 }
1639
1640 *capability = new_capability;
1641 for buffer in self.opened_buffers() {
1642 buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
1643 }
1644 }
1645 }
1646
1647 fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1648 if let ProjectClientState::Remote {
1649 sharing_has_stopped,
1650 ..
1651 } = &mut self.client_state
1652 {
1653 *sharing_has_stopped = true;
1654
1655 self.collaborators.clear();
1656
1657 for worktree in &self.worktrees {
1658 if let Some(worktree) = worktree.upgrade() {
1659 worktree.update(cx, |worktree, _| {
1660 if let Some(worktree) = worktree.as_remote_mut() {
1661 worktree.disconnected_from_host();
1662 }
1663 });
1664 }
1665 }
1666
1667 for open_buffer in self.opened_buffers.values_mut() {
1668 // Wake up any tasks waiting for peers' edits to this buffer.
1669 if let Some(buffer) = open_buffer.upgrade() {
1670 buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1671 }
1672
1673 if let OpenBuffer::Strong(buffer) = open_buffer {
1674 *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1675 }
1676 }
1677
1678 // Wake up all futures currently waiting on a buffer to get opened,
1679 // to give them a chance to fail now that we've disconnected.
1680 *self.opened_buffer.0.borrow_mut() = ();
1681 }
1682 }
1683
1684 pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1685 cx.emit(Event::Closed);
1686 }
1687
1688 pub fn is_disconnected(&self) -> bool {
1689 match &self.client_state {
1690 ProjectClientState::Remote {
1691 sharing_has_stopped,
1692 ..
1693 } => *sharing_has_stopped,
1694 _ => false,
1695 }
1696 }
1697
1698 pub fn capability(&self) -> Capability {
1699 match &self.client_state {
1700 ProjectClientState::Remote { capability, .. } => *capability,
1701 ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
1702 }
1703 }
1704
1705 pub fn is_read_only(&self) -> bool {
1706 self.is_disconnected() || self.capability() == Capability::ReadOnly
1707 }
1708
1709 pub fn is_local(&self) -> bool {
1710 match &self.client_state {
1711 ProjectClientState::Local | ProjectClientState::Shared { .. } => true,
1712 ProjectClientState::Remote { .. } => false,
1713 }
1714 }
1715
1716 pub fn is_remote(&self) -> bool {
1717 !self.is_local()
1718 }
1719
1720 pub fn create_buffer(
1721 &mut self,
1722 text: &str,
1723 language: Option<Arc<Language>>,
1724 cx: &mut ModelContext<Self>,
1725 ) -> Result<Model<Buffer>> {
1726 if self.is_remote() {
1727 return Err(anyhow!("creating buffers as a guest is not supported yet"));
1728 }
1729 let id = self.next_buffer_id.next();
1730 let buffer = cx.new_model(|cx| {
1731 Buffer::new(self.replica_id(), id, text)
1732 .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1733 });
1734 self.register_buffer(&buffer, cx)?;
1735 Ok(buffer)
1736 }
1737
1738 pub fn open_path(
1739 &mut self,
1740 path: ProjectPath,
1741 cx: &mut ModelContext<Self>,
1742 ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1743 let task = self.open_buffer(path.clone(), cx);
1744 cx.spawn(move |_, cx| async move {
1745 let buffer = task.await?;
1746 let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1747 File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1748 })?;
1749
1750 let buffer: &AnyModel = &buffer;
1751 Ok((project_entry_id, buffer.clone()))
1752 })
1753 }
1754
1755 pub fn open_local_buffer(
1756 &mut self,
1757 abs_path: impl AsRef<Path>,
1758 cx: &mut ModelContext<Self>,
1759 ) -> Task<Result<Model<Buffer>>> {
1760 if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1761 self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1762 } else {
1763 Task::ready(Err(anyhow!("no such path")))
1764 }
1765 }
1766
1767 pub fn open_buffer(
1768 &mut self,
1769 path: impl Into<ProjectPath>,
1770 cx: &mut ModelContext<Self>,
1771 ) -> Task<Result<Model<Buffer>>> {
1772 let project_path = path.into();
1773 let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1774 worktree
1775 } else {
1776 return Task::ready(Err(anyhow!("no such worktree")));
1777 };
1778
1779 // If there is already a buffer for the given path, then return it.
1780 let existing_buffer = self.get_open_buffer(&project_path, cx);
1781 if let Some(existing_buffer) = existing_buffer {
1782 return Task::ready(Ok(existing_buffer));
1783 }
1784
1785 let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1786 // If the given path is already being loaded, then wait for that existing
1787 // task to complete and return the same buffer.
1788 hash_map::Entry::Occupied(e) => e.get().clone(),
1789
1790 // Otherwise, record the fact that this path is now being loaded.
1791 hash_map::Entry::Vacant(entry) => {
1792 let (mut tx, rx) = postage::watch::channel();
1793 entry.insert(rx.clone());
1794
1795 let load_buffer = if worktree.read(cx).is_local() {
1796 self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1797 } else {
1798 self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1799 };
1800
1801 let project_path = project_path.clone();
1802 cx.spawn(move |this, mut cx| async move {
1803 let load_result = load_buffer.await;
1804 *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1805 // Record the fact that the buffer is no longer loading.
1806 this.loading_buffers_by_path.remove(&project_path);
1807 let buffer = load_result.map_err(Arc::new)?;
1808 Ok(buffer)
1809 })?);
1810 anyhow::Ok(())
1811 })
1812 .detach();
1813 rx
1814 }
1815 };
1816
1817 cx.background_executor().spawn(async move {
1818 wait_for_loading_buffer(loading_watch)
1819 .await
1820 .map_err(|e| e.cloned())
1821 })
1822 }
1823
1824 fn open_local_buffer_internal(
1825 &mut self,
1826 path: &Arc<Path>,
1827 worktree: &Model<Worktree>,
1828 cx: &mut ModelContext<Self>,
1829 ) -> Task<Result<Model<Buffer>>> {
1830 let buffer_id = self.next_buffer_id.next();
1831 let load_buffer = worktree.update(cx, |worktree, cx| {
1832 let worktree = worktree.as_local_mut().unwrap();
1833 worktree.load_buffer(buffer_id, path, cx)
1834 });
1835 cx.spawn(move |this, mut cx| async move {
1836 let buffer = load_buffer.await?;
1837 this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))??;
1838 Ok(buffer)
1839 })
1840 }
1841
1842 fn open_remote_buffer_internal(
1843 &mut self,
1844 path: &Arc<Path>,
1845 worktree: &Model<Worktree>,
1846 cx: &mut ModelContext<Self>,
1847 ) -> Task<Result<Model<Buffer>>> {
1848 let rpc = self.client.clone();
1849 let project_id = self.remote_id().unwrap();
1850 let remote_worktree_id = worktree.read(cx).id();
1851 let path = path.clone();
1852 let path_string = path.to_string_lossy().to_string();
1853 cx.spawn(move |this, mut cx| async move {
1854 let response = rpc
1855 .request(proto::OpenBufferByPath {
1856 project_id,
1857 worktree_id: remote_worktree_id.to_proto(),
1858 path: path_string,
1859 })
1860 .await?;
1861 let buffer_id = BufferId::new(response.buffer_id)?;
1862 this.update(&mut cx, |this, cx| {
1863 this.wait_for_remote_buffer(buffer_id, cx)
1864 })?
1865 .await
1866 })
1867 }
1868
1869 /// LanguageServerName is owned, because it is inserted into a map
1870 pub fn open_local_buffer_via_lsp(
1871 &mut self,
1872 abs_path: lsp::Url,
1873 language_server_id: LanguageServerId,
1874 language_server_name: LanguageServerName,
1875 cx: &mut ModelContext<Self>,
1876 ) -> Task<Result<Model<Buffer>>> {
1877 cx.spawn(move |this, mut cx| async move {
1878 let abs_path = abs_path
1879 .to_file_path()
1880 .map_err(|_| anyhow!("can't convert URI to path"))?;
1881 let (worktree, relative_path) = if let Some(result) =
1882 this.update(&mut cx, |this, cx| this.find_local_worktree(&abs_path, cx))?
1883 {
1884 result
1885 } else {
1886 let worktree = this
1887 .update(&mut cx, |this, cx| {
1888 this.create_local_worktree(&abs_path, false, cx)
1889 })?
1890 .await?;
1891 this.update(&mut cx, |this, cx| {
1892 this.language_server_ids.insert(
1893 (worktree.read(cx).id(), language_server_name),
1894 language_server_id,
1895 );
1896 })
1897 .ok();
1898 (worktree, PathBuf::new())
1899 };
1900
1901 let project_path = ProjectPath {
1902 worktree_id: worktree.update(&mut cx, |worktree, _| worktree.id())?,
1903 path: relative_path.into(),
1904 };
1905 this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))?
1906 .await
1907 })
1908 }
1909
1910 pub fn open_buffer_by_id(
1911 &mut self,
1912 id: BufferId,
1913 cx: &mut ModelContext<Self>,
1914 ) -> Task<Result<Model<Buffer>>> {
1915 if let Some(buffer) = self.buffer_for_id(id) {
1916 Task::ready(Ok(buffer))
1917 } else if self.is_local() {
1918 Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1919 } else if let Some(project_id) = self.remote_id() {
1920 let request = self.client.request(proto::OpenBufferById {
1921 project_id,
1922 id: id.into(),
1923 });
1924 cx.spawn(move |this, mut cx| async move {
1925 let buffer_id = BufferId::new(request.await?.buffer_id)?;
1926 this.update(&mut cx, |this, cx| {
1927 this.wait_for_remote_buffer(buffer_id, cx)
1928 })?
1929 .await
1930 })
1931 } else {
1932 Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1933 }
1934 }
1935
1936 pub fn save_buffers(
1937 &self,
1938 buffers: HashSet<Model<Buffer>>,
1939 cx: &mut ModelContext<Self>,
1940 ) -> Task<Result<()>> {
1941 cx.spawn(move |this, mut cx| async move {
1942 let save_tasks = buffers.into_iter().filter_map(|buffer| {
1943 this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1944 .ok()
1945 });
1946 try_join_all(save_tasks).await?;
1947 Ok(())
1948 })
1949 }
1950
1951 pub fn save_buffer(
1952 &self,
1953 buffer: Model<Buffer>,
1954 cx: &mut ModelContext<Self>,
1955 ) -> Task<Result<()>> {
1956 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1957 return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1958 };
1959 let worktree = file.worktree.clone();
1960 let path = file.path.clone();
1961 worktree.update(cx, |worktree, cx| match worktree {
1962 Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1963 Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1964 })
1965 }
1966
1967 pub fn save_buffer_as(
1968 &mut self,
1969 buffer: Model<Buffer>,
1970 abs_path: PathBuf,
1971 cx: &mut ModelContext<Self>,
1972 ) -> Task<Result<()>> {
1973 let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1974 let old_file = File::from_dyn(buffer.read(cx).file())
1975 .filter(|f| f.is_local())
1976 .cloned();
1977 cx.spawn(move |this, mut cx| async move {
1978 if let Some(old_file) = &old_file {
1979 this.update(&mut cx, |this, cx| {
1980 this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1981 })?;
1982 }
1983 let (worktree, path) = worktree_task.await?;
1984 worktree
1985 .update(&mut cx, |worktree, cx| match worktree {
1986 Worktree::Local(worktree) => {
1987 worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1988 }
1989 Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1990 })?
1991 .await?;
1992
1993 this.update(&mut cx, |this, cx| {
1994 this.detect_language_for_buffer(&buffer, cx);
1995 this.register_buffer_with_language_servers(&buffer, cx);
1996 })?;
1997 Ok(())
1998 })
1999 }
2000
2001 pub fn get_open_buffer(
2002 &mut self,
2003 path: &ProjectPath,
2004 cx: &mut ModelContext<Self>,
2005 ) -> Option<Model<Buffer>> {
2006 let worktree = self.worktree_for_id(path.worktree_id, cx)?;
2007 self.opened_buffers.values().find_map(|buffer| {
2008 let buffer = buffer.upgrade()?;
2009 let file = File::from_dyn(buffer.read(cx).file())?;
2010 if file.worktree == worktree && file.path() == &path.path {
2011 Some(buffer)
2012 } else {
2013 None
2014 }
2015 })
2016 }
2017
2018 fn register_buffer(
2019 &mut self,
2020 buffer: &Model<Buffer>,
2021 cx: &mut ModelContext<Self>,
2022 ) -> Result<()> {
2023 self.request_buffer_diff_recalculation(buffer, cx);
2024 buffer.update(cx, |buffer, _| {
2025 buffer.set_language_registry(self.languages.clone())
2026 });
2027
2028 let remote_id = buffer.read(cx).remote_id();
2029 let is_remote = self.is_remote();
2030 let open_buffer = if is_remote || self.is_shared() {
2031 OpenBuffer::Strong(buffer.clone())
2032 } else {
2033 OpenBuffer::Weak(buffer.downgrade())
2034 };
2035
2036 match self.opened_buffers.entry(remote_id) {
2037 hash_map::Entry::Vacant(entry) => {
2038 entry.insert(open_buffer);
2039 }
2040 hash_map::Entry::Occupied(mut entry) => {
2041 if let OpenBuffer::Operations(operations) = entry.get_mut() {
2042 buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
2043 } else if entry.get().upgrade().is_some() {
2044 if is_remote {
2045 return Ok(());
2046 } else {
2047 debug_panic!("buffer {} was already registered", remote_id);
2048 Err(anyhow!("buffer {} was already registered", remote_id))?;
2049 }
2050 }
2051 entry.insert(open_buffer);
2052 }
2053 }
2054 cx.subscribe(buffer, |this, buffer, event, cx| {
2055 this.on_buffer_event(buffer, event, cx);
2056 })
2057 .detach();
2058
2059 if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2060 if file.is_local {
2061 self.local_buffer_ids_by_path.insert(
2062 ProjectPath {
2063 worktree_id: file.worktree_id(cx),
2064 path: file.path.clone(),
2065 },
2066 remote_id,
2067 );
2068
2069 if let Some(entry_id) = file.entry_id {
2070 self.local_buffer_ids_by_entry_id
2071 .insert(entry_id, remote_id);
2072 }
2073 }
2074 }
2075
2076 self.detect_language_for_buffer(buffer, cx);
2077 self.register_buffer_with_language_servers(buffer, cx);
2078 self.register_buffer_with_copilot(buffer, cx);
2079 cx.observe_release(buffer, |this, buffer, cx| {
2080 if let Some(file) = File::from_dyn(buffer.file()) {
2081 if file.is_local() {
2082 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2083 for server in this.language_servers_for_buffer(buffer, cx) {
2084 server
2085 .1
2086 .notify::<lsp::notification::DidCloseTextDocument>(
2087 lsp::DidCloseTextDocumentParams {
2088 text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
2089 },
2090 )
2091 .log_err();
2092 }
2093 }
2094 }
2095 })
2096 .detach();
2097
2098 *self.opened_buffer.0.borrow_mut() = ();
2099 Ok(())
2100 }
2101
2102 fn register_buffer_with_language_servers(
2103 &mut self,
2104 buffer_handle: &Model<Buffer>,
2105 cx: &mut ModelContext<Self>,
2106 ) {
2107 let buffer = buffer_handle.read(cx);
2108 let buffer_id = buffer.remote_id();
2109
2110 if let Some(file) = File::from_dyn(buffer.file()) {
2111 if !file.is_local() {
2112 return;
2113 }
2114
2115 let abs_path = file.abs_path(cx);
2116 let uri = lsp::Url::from_file_path(&abs_path)
2117 .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
2118 let initial_snapshot = buffer.text_snapshot();
2119 let language = buffer.language().cloned();
2120 let worktree_id = file.worktree_id(cx);
2121
2122 if let Some(local_worktree) = file.worktree.read(cx).as_local() {
2123 for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
2124 self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
2125 .log_err();
2126 }
2127 }
2128
2129 if let Some(language) = language {
2130 for adapter in self.languages.lsp_adapters(&language) {
2131 let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
2132 let server = self
2133 .language_server_ids
2134 .get(&(worktree_id, adapter.name.clone()))
2135 .and_then(|id| self.language_servers.get(id))
2136 .and_then(|server_state| {
2137 if let LanguageServerState::Running { server, .. } = server_state {
2138 Some(server.clone())
2139 } else {
2140 None
2141 }
2142 });
2143 let server = match server {
2144 Some(server) => server,
2145 None => continue,
2146 };
2147
2148 server
2149 .notify::<lsp::notification::DidOpenTextDocument>(
2150 lsp::DidOpenTextDocumentParams {
2151 text_document: lsp::TextDocumentItem::new(
2152 uri.clone(),
2153 language_id.unwrap_or_default(),
2154 0,
2155 initial_snapshot.text(),
2156 ),
2157 },
2158 )
2159 .log_err();
2160
2161 buffer_handle.update(cx, |buffer, cx| {
2162 buffer.set_completion_triggers(
2163 server
2164 .capabilities()
2165 .completion_provider
2166 .as_ref()
2167 .and_then(|provider| provider.trigger_characters.clone())
2168 .unwrap_or_default(),
2169 cx,
2170 );
2171 });
2172
2173 let snapshot = LspBufferSnapshot {
2174 version: 0,
2175 snapshot: initial_snapshot.clone(),
2176 };
2177 self.buffer_snapshots
2178 .entry(buffer_id)
2179 .or_default()
2180 .insert(server.server_id(), vec![snapshot]);
2181 }
2182 }
2183 }
2184 }
2185
2186 fn unregister_buffer_from_language_servers(
2187 &mut self,
2188 buffer: &Model<Buffer>,
2189 old_file: &File,
2190 cx: &mut ModelContext<Self>,
2191 ) {
2192 let old_path = match old_file.as_local() {
2193 Some(local) => local.abs_path(cx),
2194 None => return,
2195 };
2196
2197 buffer.update(cx, |buffer, cx| {
2198 let worktree_id = old_file.worktree_id(cx);
2199 let ids = &self.language_server_ids;
2200
2201 if let Some(language) = buffer.language().cloned() {
2202 for adapter in self.languages.lsp_adapters(&language) {
2203 if let Some(server_id) = ids.get(&(worktree_id, adapter.name.clone())) {
2204 buffer.update_diagnostics(*server_id, Default::default(), cx);
2205 }
2206 }
2207 }
2208
2209 self.buffer_snapshots.remove(&buffer.remote_id());
2210 let file_url = lsp::Url::from_file_path(old_path).unwrap();
2211 for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2212 language_server
2213 .notify::<lsp::notification::DidCloseTextDocument>(
2214 lsp::DidCloseTextDocumentParams {
2215 text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
2216 },
2217 )
2218 .log_err();
2219 }
2220 });
2221 }
2222
2223 fn register_buffer_with_copilot(
2224 &self,
2225 buffer_handle: &Model<Buffer>,
2226 cx: &mut ModelContext<Self>,
2227 ) {
2228 if let Some(copilot) = Copilot::global(cx) {
2229 copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
2230 }
2231 }
2232
2233 async fn send_buffer_ordered_messages(
2234 this: WeakModel<Self>,
2235 rx: UnboundedReceiver<BufferOrderedMessage>,
2236 mut cx: AsyncAppContext,
2237 ) -> Result<()> {
2238 const MAX_BATCH_SIZE: usize = 128;
2239
2240 let mut operations_by_buffer_id = HashMap::default();
2241 async fn flush_operations(
2242 this: &WeakModel<Project>,
2243 operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2244 needs_resync_with_host: &mut bool,
2245 is_local: bool,
2246 cx: &mut AsyncAppContext,
2247 ) -> Result<()> {
2248 for (buffer_id, operations) in operations_by_buffer_id.drain() {
2249 let request = this.update(cx, |this, _| {
2250 let project_id = this.remote_id()?;
2251 Some(this.client.request(proto::UpdateBuffer {
2252 buffer_id: buffer_id.into(),
2253 project_id,
2254 operations,
2255 }))
2256 })?;
2257 if let Some(request) = request {
2258 if request.await.is_err() && !is_local {
2259 *needs_resync_with_host = true;
2260 break;
2261 }
2262 }
2263 }
2264 Ok(())
2265 }
2266
2267 let mut needs_resync_with_host = false;
2268 let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2269
2270 while let Some(changes) = changes.next().await {
2271 let is_local = this.update(&mut cx, |this, _| this.is_local())?;
2272
2273 for change in changes {
2274 match change {
2275 BufferOrderedMessage::Operation {
2276 buffer_id,
2277 operation,
2278 } => {
2279 if needs_resync_with_host {
2280 continue;
2281 }
2282
2283 operations_by_buffer_id
2284 .entry(buffer_id)
2285 .or_insert(Vec::new())
2286 .push(operation);
2287 }
2288
2289 BufferOrderedMessage::Resync => {
2290 operations_by_buffer_id.clear();
2291 if this
2292 .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2293 .await
2294 .is_ok()
2295 {
2296 needs_resync_with_host = false;
2297 }
2298 }
2299
2300 BufferOrderedMessage::LanguageServerUpdate {
2301 language_server_id,
2302 message,
2303 } => {
2304 flush_operations(
2305 &this,
2306 &mut operations_by_buffer_id,
2307 &mut needs_resync_with_host,
2308 is_local,
2309 &mut cx,
2310 )
2311 .await?;
2312
2313 this.update(&mut cx, |this, _| {
2314 if let Some(project_id) = this.remote_id() {
2315 this.client
2316 .send(proto::UpdateLanguageServer {
2317 project_id,
2318 language_server_id: language_server_id.0 as u64,
2319 variant: Some(message),
2320 })
2321 .log_err();
2322 }
2323 })?;
2324 }
2325 }
2326 }
2327
2328 flush_operations(
2329 &this,
2330 &mut operations_by_buffer_id,
2331 &mut needs_resync_with_host,
2332 is_local,
2333 &mut cx,
2334 )
2335 .await?;
2336 }
2337
2338 Ok(())
2339 }
2340
2341 fn on_buffer_event(
2342 &mut self,
2343 buffer: Model<Buffer>,
2344 event: &BufferEvent,
2345 cx: &mut ModelContext<Self>,
2346 ) -> Option<()> {
2347 if matches!(
2348 event,
2349 BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2350 ) {
2351 self.request_buffer_diff_recalculation(&buffer, cx);
2352 }
2353
2354 match event {
2355 BufferEvent::Operation(operation) => {
2356 self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2357 buffer_id: buffer.read(cx).remote_id(),
2358 operation: language::proto::serialize_operation(operation),
2359 })
2360 .ok();
2361 }
2362
2363 BufferEvent::Edited { .. } => {
2364 let buffer = buffer.read(cx);
2365 let file = File::from_dyn(buffer.file())?;
2366 let abs_path = file.as_local()?.abs_path(cx);
2367 let uri = lsp::Url::from_file_path(abs_path).unwrap();
2368 let next_snapshot = buffer.text_snapshot();
2369
2370 let language_servers: Vec<_> = self
2371 .language_servers_for_buffer(buffer, cx)
2372 .map(|i| i.1.clone())
2373 .collect();
2374
2375 for language_server in language_servers {
2376 let language_server = language_server.clone();
2377
2378 let buffer_snapshots = self
2379 .buffer_snapshots
2380 .get_mut(&buffer.remote_id())
2381 .and_then(|m| m.get_mut(&language_server.server_id()))?;
2382 let previous_snapshot = buffer_snapshots.last()?;
2383
2384 let build_incremental_change = || {
2385 buffer
2386 .edits_since::<(PointUtf16, usize)>(
2387 previous_snapshot.snapshot.version(),
2388 )
2389 .map(|edit| {
2390 let edit_start = edit.new.start.0;
2391 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
2392 let new_text = next_snapshot
2393 .text_for_range(edit.new.start.1..edit.new.end.1)
2394 .collect();
2395 lsp::TextDocumentContentChangeEvent {
2396 range: Some(lsp::Range::new(
2397 point_to_lsp(edit_start),
2398 point_to_lsp(edit_end),
2399 )),
2400 range_length: None,
2401 text: new_text,
2402 }
2403 })
2404 .collect()
2405 };
2406
2407 let document_sync_kind = language_server
2408 .capabilities()
2409 .text_document_sync
2410 .as_ref()
2411 .and_then(|sync| match sync {
2412 lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
2413 lsp::TextDocumentSyncCapability::Options(options) => options.change,
2414 });
2415
2416 let content_changes: Vec<_> = match document_sync_kind {
2417 Some(lsp::TextDocumentSyncKind::FULL) => {
2418 vec![lsp::TextDocumentContentChangeEvent {
2419 range: None,
2420 range_length: None,
2421 text: next_snapshot.text(),
2422 }]
2423 }
2424 Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
2425 _ => {
2426 #[cfg(any(test, feature = "test-support"))]
2427 {
2428 build_incremental_change()
2429 }
2430
2431 #[cfg(not(any(test, feature = "test-support")))]
2432 {
2433 continue;
2434 }
2435 }
2436 };
2437
2438 let next_version = previous_snapshot.version + 1;
2439
2440 buffer_snapshots.push(LspBufferSnapshot {
2441 version: next_version,
2442 snapshot: next_snapshot.clone(),
2443 });
2444
2445 language_server
2446 .notify::<lsp::notification::DidChangeTextDocument>(
2447 lsp::DidChangeTextDocumentParams {
2448 text_document: lsp::VersionedTextDocumentIdentifier::new(
2449 uri.clone(),
2450 next_version,
2451 ),
2452 content_changes,
2453 },
2454 )
2455 .log_err();
2456 }
2457 }
2458
2459 BufferEvent::Saved => {
2460 let file = File::from_dyn(buffer.read(cx).file())?;
2461 let worktree_id = file.worktree_id(cx);
2462 let abs_path = file.as_local()?.abs_path(cx);
2463 let text_document = lsp::TextDocumentIdentifier {
2464 uri: lsp::Url::from_file_path(abs_path).unwrap(),
2465 };
2466
2467 for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
2468 let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
2469
2470 server
2471 .notify::<lsp::notification::DidSaveTextDocument>(
2472 lsp::DidSaveTextDocumentParams {
2473 text_document: text_document.clone(),
2474 text,
2475 },
2476 )
2477 .log_err();
2478 }
2479
2480 let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2481 for language_server_id in language_server_ids {
2482 if let Some(LanguageServerState::Running {
2483 adapter,
2484 simulate_disk_based_diagnostics_completion,
2485 ..
2486 }) = self.language_servers.get_mut(&language_server_id)
2487 {
2488 // After saving a buffer using a language server that doesn't provide
2489 // a disk-based progress token, kick off a timer that will reset every
2490 // time the buffer is saved. If the timer eventually fires, simulate
2491 // disk-based diagnostics being finished so that other pieces of UI
2492 // (e.g., project diagnostics view, diagnostic status bar) can update.
2493 // We don't emit an event right away because the language server might take
2494 // some time to publish diagnostics.
2495 if adapter.disk_based_diagnostics_progress_token.is_none() {
2496 const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2497 Duration::from_secs(1);
2498
2499 let task = cx.spawn(move |this, mut cx| async move {
2500 cx.background_executor().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2501 if let Some(this) = this.upgrade() {
2502 this.update(&mut cx, |this, cx| {
2503 this.disk_based_diagnostics_finished(
2504 language_server_id,
2505 cx,
2506 );
2507 this.enqueue_buffer_ordered_message(
2508 BufferOrderedMessage::LanguageServerUpdate {
2509 language_server_id,
2510 message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2511 },
2512 )
2513 .ok();
2514 }).ok();
2515 }
2516 });
2517 *simulate_disk_based_diagnostics_completion = Some(task);
2518 }
2519 }
2520 }
2521 }
2522 BufferEvent::FileHandleChanged => {
2523 let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
2524 return None;
2525 };
2526
2527 let remote_id = buffer.read(cx).remote_id();
2528 if let Some(entry_id) = file.entry_id {
2529 match self.local_buffer_ids_by_entry_id.get(&entry_id) {
2530 Some(_) => {
2531 return None;
2532 }
2533 None => {
2534 self.local_buffer_ids_by_entry_id
2535 .insert(entry_id, remote_id);
2536 }
2537 }
2538 };
2539 self.local_buffer_ids_by_path.insert(
2540 ProjectPath {
2541 worktree_id: file.worktree_id(cx),
2542 path: file.path.clone(),
2543 },
2544 remote_id,
2545 );
2546 }
2547 _ => {}
2548 }
2549
2550 None
2551 }
2552
2553 fn request_buffer_diff_recalculation(
2554 &mut self,
2555 buffer: &Model<Buffer>,
2556 cx: &mut ModelContext<Self>,
2557 ) {
2558 self.buffers_needing_diff.insert(buffer.downgrade());
2559 let first_insertion = self.buffers_needing_diff.len() == 1;
2560
2561 let settings = ProjectSettings::get_global(cx);
2562 let delay = if let Some(delay) = settings.git.gutter_debounce {
2563 delay
2564 } else {
2565 if first_insertion {
2566 let this = cx.weak_model();
2567 cx.defer(move |cx| {
2568 if let Some(this) = this.upgrade() {
2569 this.update(cx, |this, cx| {
2570 this.recalculate_buffer_diffs(cx).detach();
2571 });
2572 }
2573 });
2574 }
2575 return;
2576 };
2577
2578 const MIN_DELAY: u64 = 50;
2579 let delay = delay.max(MIN_DELAY);
2580 let duration = Duration::from_millis(delay);
2581
2582 self.git_diff_debouncer
2583 .fire_new(duration, cx, move |this, cx| {
2584 this.recalculate_buffer_diffs(cx)
2585 });
2586 }
2587
2588 fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2589 let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2590 cx.spawn(move |this, mut cx| async move {
2591 let tasks: Vec<_> = buffers
2592 .iter()
2593 .filter_map(|buffer| {
2594 let buffer = buffer.upgrade()?;
2595 buffer
2596 .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
2597 .ok()
2598 .flatten()
2599 })
2600 .collect();
2601
2602 futures::future::join_all(tasks).await;
2603
2604 this.update(&mut cx, |this, cx| {
2605 if !this.buffers_needing_diff.is_empty() {
2606 this.recalculate_buffer_diffs(cx).detach();
2607 } else {
2608 // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2609 for buffer in buffers {
2610 if let Some(buffer) = buffer.upgrade() {
2611 buffer.update(cx, |_, cx| cx.notify());
2612 }
2613 }
2614 }
2615 })
2616 .ok();
2617 })
2618 }
2619
2620 fn language_servers_for_worktree(
2621 &self,
2622 worktree_id: WorktreeId,
2623 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2624 self.language_server_ids
2625 .iter()
2626 .filter_map(move |((language_server_worktree_id, _), id)| {
2627 if *language_server_worktree_id == worktree_id {
2628 if let Some(LanguageServerState::Running {
2629 adapter,
2630 language,
2631 server,
2632 ..
2633 }) = self.language_servers.get(id)
2634 {
2635 return Some((adapter, language, server));
2636 }
2637 }
2638 None
2639 })
2640 }
2641
2642 fn maintain_buffer_languages(
2643 languages: Arc<LanguageRegistry>,
2644 cx: &mut ModelContext<Project>,
2645 ) -> Task<()> {
2646 let mut subscription = languages.subscribe();
2647 let mut prev_reload_count = languages.reload_count();
2648 cx.spawn(move |project, mut cx| async move {
2649 while let Some(()) = subscription.next().await {
2650 if let Some(project) = project.upgrade() {
2651 // If the language registry has been reloaded, then remove and
2652 // re-assign the languages on all open buffers.
2653 let reload_count = languages.reload_count();
2654 if reload_count > prev_reload_count {
2655 prev_reload_count = reload_count;
2656 project
2657 .update(&mut cx, |this, cx| {
2658 let buffers = this
2659 .opened_buffers
2660 .values()
2661 .filter_map(|b| b.upgrade())
2662 .collect::<Vec<_>>();
2663 for buffer in buffers {
2664 if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
2665 {
2666 this.unregister_buffer_from_language_servers(
2667 &buffer, &f, cx,
2668 );
2669 buffer
2670 .update(cx, |buffer, cx| buffer.set_language(None, cx));
2671 }
2672 }
2673 })
2674 .ok();
2675 }
2676
2677 project
2678 .update(&mut cx, |project, cx| {
2679 let mut plain_text_buffers = Vec::new();
2680 let mut buffers_with_unknown_injections = Vec::new();
2681 for buffer in project.opened_buffers.values() {
2682 if let Some(handle) = buffer.upgrade() {
2683 let buffer = &handle.read(cx);
2684 if buffer.language().is_none()
2685 || buffer.language() == Some(&*language::PLAIN_TEXT)
2686 {
2687 plain_text_buffers.push(handle);
2688 } else if buffer.contains_unknown_injections() {
2689 buffers_with_unknown_injections.push(handle);
2690 }
2691 }
2692 }
2693
2694 for buffer in plain_text_buffers {
2695 project.detect_language_for_buffer(&buffer, cx);
2696 project.register_buffer_with_language_servers(&buffer, cx);
2697 }
2698
2699 for buffer in buffers_with_unknown_injections {
2700 buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2701 }
2702 })
2703 .ok();
2704 }
2705 }
2706 })
2707 }
2708
2709 fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<Result<()>> {
2710 let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2711 let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2712
2713 let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
2714 *settings_changed_tx.borrow_mut() = ();
2715 });
2716
2717 cx.spawn(move |this, mut cx| async move {
2718 while let Some(()) = settings_changed_rx.next().await {
2719 let servers: Vec<_> = this.update(&mut cx, |this, _| {
2720 this.language_servers
2721 .values()
2722 .filter_map(|state| match state {
2723 LanguageServerState::Starting(_) => None,
2724 LanguageServerState::Running {
2725 adapter, server, ..
2726 } => Some((adapter.clone(), server.clone())),
2727 })
2728 .collect()
2729 })?;
2730
2731 for (adapter, server) in servers {
2732 let settings =
2733 cx.update(|cx| adapter.workspace_configuration(server.root_path(), cx))?;
2734
2735 server
2736 .notify::<lsp::notification::DidChangeConfiguration>(
2737 lsp::DidChangeConfigurationParams { settings },
2738 )
2739 .ok();
2740 }
2741 }
2742
2743 drop(settings_observation);
2744 anyhow::Ok(())
2745 })
2746 }
2747
2748 fn detect_language_for_buffer(
2749 &mut self,
2750 buffer_handle: &Model<Buffer>,
2751 cx: &mut ModelContext<Self>,
2752 ) -> Option<()> {
2753 // If the buffer has a language, set it and start the language server if we haven't already.
2754 let buffer = buffer_handle.read(cx);
2755 let full_path = buffer.file()?.full_path(cx);
2756 let content = buffer.as_rope();
2757 let new_language = self
2758 .languages
2759 .language_for_file(&full_path, Some(content))
2760 .now_or_never()?
2761 .ok()?;
2762 self.set_language_for_buffer(buffer_handle, new_language, cx);
2763 None
2764 }
2765
2766 pub fn set_language_for_buffer(
2767 &mut self,
2768 buffer: &Model<Buffer>,
2769 new_language: Arc<Language>,
2770 cx: &mut ModelContext<Self>,
2771 ) {
2772 buffer.update(cx, |buffer, cx| {
2773 if buffer.language().map_or(true, |old_language| {
2774 !Arc::ptr_eq(old_language, &new_language)
2775 }) {
2776 buffer.set_language(Some(new_language.clone()), cx);
2777 }
2778 });
2779
2780 let buffer_file = buffer.read(cx).file().cloned();
2781 let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
2782 let buffer_file = File::from_dyn(buffer_file.as_ref());
2783 let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2784 if let Some(prettier_plugins) = prettier_support::prettier_plugins_for_language(
2785 &self.languages,
2786 &new_language,
2787 &settings,
2788 ) {
2789 self.install_default_prettier(worktree, prettier_plugins, cx);
2790 };
2791 if let Some(file) = buffer_file {
2792 let worktree = file.worktree.clone();
2793 if worktree.read(cx).is_local() {
2794 self.start_language_servers(&worktree, new_language, cx);
2795 }
2796 }
2797 }
2798
2799 fn start_language_servers(
2800 &mut self,
2801 worktree: &Model<Worktree>,
2802 language: Arc<Language>,
2803 cx: &mut ModelContext<Self>,
2804 ) {
2805 let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
2806 let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
2807 if !settings.enable_language_server {
2808 return;
2809 }
2810
2811 for adapter in self.languages.clone().lsp_adapters(&language) {
2812 self.start_language_server(worktree, adapter.clone(), language.clone(), cx);
2813 }
2814 }
2815
2816 fn start_language_server(
2817 &mut self,
2818 worktree_handle: &Model<Worktree>,
2819 adapter: Arc<CachedLspAdapter>,
2820 language: Arc<Language>,
2821 cx: &mut ModelContext<Self>,
2822 ) {
2823 if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2824 return;
2825 }
2826
2827 let worktree = worktree_handle.read(cx);
2828 let worktree_id = worktree.id();
2829 let worktree_path = worktree.abs_path();
2830 let key = (worktree_id, adapter.name.clone());
2831 if self.language_server_ids.contains_key(&key) {
2832 return;
2833 }
2834
2835 let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
2836 let pending_server = match self.languages.create_pending_language_server(
2837 stderr_capture.clone(),
2838 language.clone(),
2839 adapter.clone(),
2840 Arc::clone(&worktree_path),
2841 ProjectLspAdapterDelegate::new(self, worktree_handle, cx),
2842 cx,
2843 ) {
2844 Some(pending_server) => pending_server,
2845 None => return,
2846 };
2847
2848 let project_settings =
2849 ProjectSettings::get(Some((worktree_id.to_proto() as usize, Path::new(""))), cx);
2850 let lsp = project_settings.lsp.get(&adapter.name.0);
2851 let override_options = lsp.and_then(|s| s.initialization_options.clone());
2852
2853 let server_id = pending_server.server_id;
2854 let container_dir = pending_server.container_dir.clone();
2855 let state = LanguageServerState::Starting({
2856 let adapter = adapter.clone();
2857 let server_name = adapter.name.0.clone();
2858 let language = language.clone();
2859 let key = key.clone();
2860
2861 cx.spawn(move |this, mut cx| async move {
2862 let result = Self::setup_and_insert_language_server(
2863 this.clone(),
2864 &worktree_path,
2865 override_options,
2866 pending_server,
2867 adapter.clone(),
2868 language.clone(),
2869 server_id,
2870 key,
2871 &mut cx,
2872 )
2873 .await;
2874
2875 match result {
2876 Ok(server) => {
2877 stderr_capture.lock().take();
2878 server
2879 }
2880
2881 Err(err) => {
2882 log::error!("failed to start language server {server_name:?}: {err}");
2883 log::error!("server stderr: {:?}", stderr_capture.lock().take());
2884
2885 let this = this.upgrade()?;
2886 let container_dir = container_dir?;
2887
2888 let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
2889 if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2890 let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
2891 log::error!("Hit {max} reinstallation attempts for {server_name:?}");
2892 return None;
2893 }
2894
2895 log::info!(
2896 "retrying installation of language server {server_name:?} in {}s",
2897 SERVER_REINSTALL_DEBOUNCE_TIMEOUT.as_secs()
2898 );
2899 cx.background_executor()
2900 .timer(SERVER_REINSTALL_DEBOUNCE_TIMEOUT)
2901 .await;
2902
2903 let installation_test_binary = adapter
2904 .installation_test_binary(container_dir.to_path_buf())
2905 .await;
2906
2907 this.update(&mut cx, |_, cx| {
2908 Self::check_errored_server(
2909 language,
2910 adapter,
2911 server_id,
2912 installation_test_binary,
2913 cx,
2914 )
2915 })
2916 .ok();
2917
2918 None
2919 }
2920 }
2921 })
2922 });
2923
2924 self.language_servers.insert(server_id, state);
2925 self.language_server_ids.insert(key, server_id);
2926 }
2927
2928 fn reinstall_language_server(
2929 &mut self,
2930 language: Arc<Language>,
2931 adapter: Arc<CachedLspAdapter>,
2932 server_id: LanguageServerId,
2933 cx: &mut ModelContext<Self>,
2934 ) -> Option<Task<()>> {
2935 log::info!("beginning to reinstall server");
2936
2937 let existing_server = match self.language_servers.remove(&server_id) {
2938 Some(LanguageServerState::Running { server, .. }) => Some(server),
2939 _ => None,
2940 };
2941
2942 for worktree in &self.worktrees {
2943 if let Some(worktree) = worktree.upgrade() {
2944 let key = (worktree.read(cx).id(), adapter.name.clone());
2945 self.language_server_ids.remove(&key);
2946 }
2947 }
2948
2949 Some(cx.spawn(move |this, mut cx| async move {
2950 if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2951 log::info!("shutting down existing server");
2952 task.await;
2953 }
2954
2955 // TODO: This is race-safe with regards to preventing new instances from
2956 // starting while deleting, but existing instances in other projects are going
2957 // to be very confused and messed up
2958 let Some(task) = this
2959 .update(&mut cx, |this, cx| {
2960 this.languages.delete_server_container(adapter.clone(), cx)
2961 })
2962 .log_err()
2963 else {
2964 return;
2965 };
2966 task.await;
2967
2968 this.update(&mut cx, |this, cx| {
2969 let worktrees = this.worktrees.clone();
2970 for worktree in worktrees {
2971 if let Some(worktree) = worktree.upgrade() {
2972 this.start_language_server(
2973 &worktree,
2974 adapter.clone(),
2975 language.clone(),
2976 cx,
2977 );
2978 }
2979 }
2980 })
2981 .ok();
2982 }))
2983 }
2984
2985 #[allow(clippy::too_many_arguments)]
2986 async fn setup_and_insert_language_server(
2987 this: WeakModel<Self>,
2988 worktree_path: &Path,
2989 override_initialization_options: Option<serde_json::Value>,
2990 pending_server: PendingLanguageServer,
2991 adapter: Arc<CachedLspAdapter>,
2992 language: Arc<Language>,
2993 server_id: LanguageServerId,
2994 key: (WorktreeId, LanguageServerName),
2995 cx: &mut AsyncAppContext,
2996 ) -> Result<Option<Arc<LanguageServer>>> {
2997 let language_server = Self::setup_pending_language_server(
2998 this.clone(),
2999 override_initialization_options,
3000 pending_server,
3001 worktree_path,
3002 adapter.clone(),
3003 server_id,
3004 cx,
3005 )
3006 .await?;
3007
3008 let this = match this.upgrade() {
3009 Some(this) => this,
3010 None => return Err(anyhow!("failed to upgrade project handle")),
3011 };
3012
3013 this.update(cx, |this, cx| {
3014 this.insert_newly_running_language_server(
3015 language,
3016 adapter,
3017 language_server.clone(),
3018 server_id,
3019 key,
3020 cx,
3021 )
3022 })??;
3023
3024 Ok(Some(language_server))
3025 }
3026
3027 async fn setup_pending_language_server(
3028 this: WeakModel<Self>,
3029 override_options: Option<serde_json::Value>,
3030 pending_server: PendingLanguageServer,
3031 worktree_path: &Path,
3032 adapter: Arc<CachedLspAdapter>,
3033 server_id: LanguageServerId,
3034 cx: &mut AsyncAppContext,
3035 ) -> Result<Arc<LanguageServer>> {
3036 let workspace_config =
3037 cx.update(|cx| adapter.workspace_configuration(worktree_path, cx))?;
3038 let language_server = pending_server.task.await?;
3039
3040 let name = language_server.name();
3041 language_server
3042 .on_notification::<lsp::notification::PublishDiagnostics, _>({
3043 let adapter = adapter.clone();
3044 let this = this.clone();
3045 move |mut params, mut cx| {
3046 let adapter = adapter.clone();
3047 if let Some(this) = this.upgrade() {
3048 adapter.process_diagnostics(&mut params);
3049 this.update(&mut cx, |this, cx| {
3050 this.update_diagnostics(
3051 server_id,
3052 params,
3053 &adapter.disk_based_diagnostic_sources,
3054 cx,
3055 )
3056 .log_err();
3057 })
3058 .ok();
3059 }
3060 }
3061 })
3062 .detach();
3063
3064 language_server
3065 .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
3066 let adapter = adapter.clone();
3067 let worktree_path = worktree_path.to_path_buf();
3068 move |params, cx| {
3069 let adapter = adapter.clone();
3070 let worktree_path = worktree_path.clone();
3071 async move {
3072 let workspace_config =
3073 cx.update(|cx| adapter.workspace_configuration(&worktree_path, cx))?;
3074 Ok(params
3075 .items
3076 .into_iter()
3077 .map(|item| {
3078 if let Some(section) = &item.section {
3079 workspace_config
3080 .get(section)
3081 .cloned()
3082 .unwrap_or(serde_json::Value::Null)
3083 } else {
3084 workspace_config.clone()
3085 }
3086 })
3087 .collect())
3088 }
3089 }
3090 })
3091 .detach();
3092
3093 // Even though we don't have handling for these requests, respond to them to
3094 // avoid stalling any language server like `gopls` which waits for a response
3095 // to these requests when initializing.
3096 language_server
3097 .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
3098 let this = this.clone();
3099 move |params, mut cx| {
3100 let this = this.clone();
3101 async move {
3102 this.update(&mut cx, |this, _| {
3103 if let Some(status) = this.language_server_statuses.get_mut(&server_id)
3104 {
3105 if let lsp::NumberOrString::String(token) = params.token {
3106 status.progress_tokens.insert(token);
3107 }
3108 }
3109 })?;
3110
3111 Ok(())
3112 }
3113 }
3114 })
3115 .detach();
3116
3117 language_server
3118 .on_request::<lsp::request::RegisterCapability, _, _>({
3119 let this = this.clone();
3120 move |params, mut cx| {
3121 let this = this.clone();
3122 async move {
3123 for reg in params.registrations {
3124 if reg.method == "workspace/didChangeWatchedFiles" {
3125 if let Some(options) = reg.register_options {
3126 let options = serde_json::from_value(options)?;
3127 this.update(&mut cx, |this, cx| {
3128 this.on_lsp_did_change_watched_files(
3129 server_id, options, cx,
3130 );
3131 })?;
3132 }
3133 }
3134 }
3135 Ok(())
3136 }
3137 }
3138 })
3139 .detach();
3140
3141 language_server
3142 .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
3143 let adapter = adapter.clone();
3144 let this = this.clone();
3145 move |params, cx| {
3146 Self::on_lsp_workspace_edit(
3147 this.clone(),
3148 params,
3149 server_id,
3150 adapter.clone(),
3151 cx,
3152 )
3153 }
3154 })
3155 .detach();
3156
3157 language_server
3158 .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
3159 let this = this.clone();
3160 move |(), mut cx| {
3161 let this = this.clone();
3162 async move {
3163 this.update(&mut cx, |project, cx| {
3164 cx.emit(Event::RefreshInlayHints);
3165 project.remote_id().map(|project_id| {
3166 project.client.send(proto::RefreshInlayHints { project_id })
3167 })
3168 })?
3169 .transpose()?;
3170 Ok(())
3171 }
3172 }
3173 })
3174 .detach();
3175
3176 language_server
3177 .on_request::<lsp::request::ShowMessageRequest, _, _>({
3178 let this = this.clone();
3179 let name = name.to_string();
3180 move |params, mut cx| {
3181 let this = this.clone();
3182 let name = name.to_string();
3183 async move {
3184 if let Some(actions) = params.actions {
3185 let (tx, mut rx) = smol::channel::bounded(1);
3186 let request = LanguageServerPromptRequest {
3187 level: match params.typ {
3188 lsp::MessageType::ERROR => PromptLevel::Critical,
3189 lsp::MessageType::WARNING => PromptLevel::Warning,
3190 _ => PromptLevel::Info,
3191 },
3192 message: params.message,
3193 actions,
3194 response_channel: tx,
3195 lsp_name: name.clone(),
3196 };
3197
3198 if let Ok(_) = this.update(&mut cx, |_, cx| {
3199 cx.emit(Event::LanguageServerPrompt(request));
3200 }) {
3201 let response = rx.next().await;
3202
3203 Ok(response)
3204 } else {
3205 Ok(None)
3206 }
3207 } else {
3208 Ok(None)
3209 }
3210 }
3211 }
3212 })
3213 .detach();
3214
3215 let disk_based_diagnostics_progress_token =
3216 adapter.disk_based_diagnostics_progress_token.clone();
3217
3218 language_server
3219 .on_notification::<ServerStatus, _>({
3220 let this = this.clone();
3221 let name = name.to_string();
3222 move |params, mut cx| {
3223 let this = this.clone();
3224 let name = name.to_string();
3225 if let Some(ref message) = params.message {
3226 let message = message.trim();
3227 if !message.is_empty() {
3228 let formatted_message = format!(
3229 "Language server {name} (id {server_id}) status update: {message}"
3230 );
3231 match params.health {
3232 ServerHealthStatus::Ok => log::info!("{}", formatted_message),
3233 ServerHealthStatus::Warning => log::warn!("{}", formatted_message),
3234 ServerHealthStatus::Error => {
3235 log::error!("{}", formatted_message);
3236 let (tx, _rx) = smol::channel::bounded(1);
3237 let request = LanguageServerPromptRequest {
3238 level: PromptLevel::Critical,
3239 message: params.message.unwrap_or_default(),
3240 actions: Vec::new(),
3241 response_channel: tx,
3242 lsp_name: name.clone(),
3243 };
3244 let _ = this
3245 .update(&mut cx, |_, cx| {
3246 cx.emit(Event::LanguageServerPrompt(request));
3247 })
3248 .ok();
3249 }
3250 ServerHealthStatus::Other(status) => {
3251 log::info!(
3252 "Unknown server health: {status}\n{formatted_message}"
3253 )
3254 }
3255 }
3256 }
3257 }
3258 }
3259 })
3260 .detach();
3261
3262 language_server
3263 .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
3264 if let Some(this) = this.upgrade() {
3265 this.update(&mut cx, |this, cx| {
3266 this.on_lsp_progress(
3267 params,
3268 server_id,
3269 disk_based_diagnostics_progress_token.clone(),
3270 cx,
3271 );
3272 })
3273 .ok();
3274 }
3275 })
3276 .detach();
3277
3278 let mut initialization_options = adapter.adapter.initialization_options();
3279 match (&mut initialization_options, override_options) {
3280 (Some(initialization_options), Some(override_options)) => {
3281 merge_json_value_into(override_options, initialization_options);
3282 }
3283 (None, override_options) => initialization_options = override_options,
3284 _ => {}
3285 }
3286 let language_server = cx
3287 .update(|cx| language_server.initialize(initialization_options, cx))?
3288 .await?;
3289
3290 language_server
3291 .notify::<lsp::notification::DidChangeConfiguration>(
3292 lsp::DidChangeConfigurationParams {
3293 settings: workspace_config,
3294 },
3295 )
3296 .ok();
3297
3298 Ok(language_server)
3299 }
3300
3301 fn insert_newly_running_language_server(
3302 &mut self,
3303 language: Arc<Language>,
3304 adapter: Arc<CachedLspAdapter>,
3305 language_server: Arc<LanguageServer>,
3306 server_id: LanguageServerId,
3307 key: (WorktreeId, LanguageServerName),
3308 cx: &mut ModelContext<Self>,
3309 ) -> Result<()> {
3310 // If the language server for this key doesn't match the server id, don't store the
3311 // server. Which will cause it to be dropped, killing the process
3312 if self
3313 .language_server_ids
3314 .get(&key)
3315 .map(|id| id != &server_id)
3316 .unwrap_or(false)
3317 {
3318 return Ok(());
3319 }
3320
3321 // Update language_servers collection with Running variant of LanguageServerState
3322 // indicating that the server is up and running and ready
3323 self.language_servers.insert(
3324 server_id,
3325 LanguageServerState::Running {
3326 adapter: adapter.clone(),
3327 language: language.clone(),
3328 server: language_server.clone(),
3329 simulate_disk_based_diagnostics_completion: None,
3330 },
3331 );
3332
3333 self.language_server_statuses.insert(
3334 server_id,
3335 LanguageServerStatus {
3336 name: language_server.name().to_string(),
3337 pending_work: Default::default(),
3338 has_pending_diagnostic_updates: false,
3339 progress_tokens: Default::default(),
3340 },
3341 );
3342
3343 cx.emit(Event::LanguageServerAdded(server_id));
3344
3345 if let Some(project_id) = self.remote_id() {
3346 self.client.send(proto::StartLanguageServer {
3347 project_id,
3348 server: Some(proto::LanguageServer {
3349 id: server_id.0 as u64,
3350 name: language_server.name().to_string(),
3351 }),
3352 })?;
3353 }
3354
3355 // Tell the language server about every open buffer in the worktree that matches the language.
3356 for buffer in self.opened_buffers.values() {
3357 if let Some(buffer_handle) = buffer.upgrade() {
3358 let buffer = buffer_handle.read(cx);
3359 let file = match File::from_dyn(buffer.file()) {
3360 Some(file) => file,
3361 None => continue,
3362 };
3363 let language = match buffer.language() {
3364 Some(language) => language,
3365 None => continue,
3366 };
3367
3368 if file.worktree.read(cx).id() != key.0
3369 || !self
3370 .languages
3371 .lsp_adapters(&language)
3372 .iter()
3373 .any(|a| a.name == key.1)
3374 {
3375 continue;
3376 }
3377
3378 let file = match file.as_local() {
3379 Some(file) => file,
3380 None => continue,
3381 };
3382
3383 let versions = self
3384 .buffer_snapshots
3385 .entry(buffer.remote_id())
3386 .or_default()
3387 .entry(server_id)
3388 .or_insert_with(|| {
3389 vec![LspBufferSnapshot {
3390 version: 0,
3391 snapshot: buffer.text_snapshot(),
3392 }]
3393 });
3394
3395 let snapshot = versions.last().unwrap();
3396 let version = snapshot.version;
3397 let initial_snapshot = &snapshot.snapshot;
3398 let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3399 language_server.notify::<lsp::notification::DidOpenTextDocument>(
3400 lsp::DidOpenTextDocumentParams {
3401 text_document: lsp::TextDocumentItem::new(
3402 uri,
3403 adapter
3404 .language_ids
3405 .get(language.name().as_ref())
3406 .cloned()
3407 .unwrap_or_default(),
3408 version,
3409 initial_snapshot.text(),
3410 ),
3411 },
3412 )?;
3413
3414 buffer_handle.update(cx, |buffer, cx| {
3415 buffer.set_completion_triggers(
3416 language_server
3417 .capabilities()
3418 .completion_provider
3419 .as_ref()
3420 .and_then(|provider| provider.trigger_characters.clone())
3421 .unwrap_or_default(),
3422 cx,
3423 )
3424 });
3425 }
3426 }
3427
3428 cx.notify();
3429 Ok(())
3430 }
3431
3432 // Returns a list of all of the worktrees which no longer have a language server and the root path
3433 // for the stopped server
3434 fn stop_language_server(
3435 &mut self,
3436 worktree_id: WorktreeId,
3437 adapter_name: LanguageServerName,
3438 cx: &mut ModelContext<Self>,
3439 ) -> Task<Vec<WorktreeId>> {
3440 let key = (worktree_id, adapter_name);
3441 if let Some(server_id) = self.language_server_ids.remove(&key) {
3442 let name = key.1 .0;
3443 log::info!("stopping language server {name}");
3444
3445 // Remove other entries for this language server as well
3446 let mut orphaned_worktrees = vec![worktree_id];
3447 let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3448 for other_key in other_keys {
3449 if self.language_server_ids.get(&other_key) == Some(&server_id) {
3450 self.language_server_ids.remove(&other_key);
3451 orphaned_worktrees.push(other_key.0);
3452 }
3453 }
3454
3455 for buffer in self.opened_buffers.values() {
3456 if let Some(buffer) = buffer.upgrade() {
3457 buffer.update(cx, |buffer, cx| {
3458 buffer.update_diagnostics(server_id, Default::default(), cx);
3459 });
3460 }
3461 }
3462 for worktree in &self.worktrees {
3463 if let Some(worktree) = worktree.upgrade() {
3464 worktree.update(cx, |worktree, cx| {
3465 if let Some(worktree) = worktree.as_local_mut() {
3466 worktree.clear_diagnostics_for_language_server(server_id, cx);
3467 }
3468 });
3469 }
3470 }
3471
3472 self.language_server_watched_paths.remove(&server_id);
3473 self.language_server_statuses.remove(&server_id);
3474 cx.notify();
3475
3476 let server_state = self.language_servers.remove(&server_id);
3477 cx.emit(Event::LanguageServerRemoved(server_id));
3478 cx.spawn(move |_, cx| async move {
3479 Self::shutdown_language_server(server_state, name, cx).await;
3480 orphaned_worktrees
3481 })
3482 } else {
3483 Task::ready(Vec::new())
3484 }
3485 }
3486
3487 async fn shutdown_language_server(
3488 server_state: Option<LanguageServerState>,
3489 name: Arc<str>,
3490 cx: AsyncAppContext,
3491 ) {
3492 let server = match server_state {
3493 Some(LanguageServerState::Starting(task)) => {
3494 let mut timer = cx
3495 .background_executor()
3496 .timer(SERVER_LAUNCHING_BEFORE_SHUTDOWN_TIMEOUT)
3497 .fuse();
3498
3499 select! {
3500 server = task.fuse() => server,
3501 _ = timer => {
3502 log::info!(
3503 "timeout waiting for language server {} to finish launching before stopping",
3504 name
3505 );
3506 None
3507 },
3508 }
3509 }
3510
3511 Some(LanguageServerState::Running { server, .. }) => Some(server),
3512
3513 None => None,
3514 };
3515
3516 if let Some(server) = server {
3517 if let Some(shutdown) = server.shutdown() {
3518 shutdown.await;
3519 }
3520 }
3521 }
3522
3523 pub fn restart_language_servers_for_buffers(
3524 &mut self,
3525 buffers: impl IntoIterator<Item = Model<Buffer>>,
3526 cx: &mut ModelContext<Self>,
3527 ) -> Option<()> {
3528 let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
3529 .into_iter()
3530 .filter_map(|buffer| {
3531 let buffer = buffer.read(cx);
3532 let file = File::from_dyn(buffer.file())?;
3533 let full_path = file.full_path(cx);
3534 let language = self
3535 .languages
3536 .language_for_file(&full_path, Some(buffer.as_rope()))
3537 .now_or_never()?
3538 .ok()?;
3539 Some((file.worktree.clone(), language))
3540 })
3541 .collect();
3542 for (worktree, language) in language_server_lookup_info {
3543 self.restart_language_servers(worktree, language, cx);
3544 }
3545
3546 None
3547 }
3548
3549 fn restart_language_servers(
3550 &mut self,
3551 worktree: Model<Worktree>,
3552 language: Arc<Language>,
3553 cx: &mut ModelContext<Self>,
3554 ) {
3555 let worktree_id = worktree.read(cx).id();
3556
3557 let stop_tasks = self
3558 .languages
3559 .clone()
3560 .lsp_adapters(&language)
3561 .iter()
3562 .map(|adapter| {
3563 let stop_task = self.stop_language_server(worktree_id, adapter.name.clone(), cx);
3564 (stop_task, adapter.name.clone())
3565 })
3566 .collect::<Vec<_>>();
3567 if stop_tasks.is_empty() {
3568 return;
3569 }
3570
3571 cx.spawn(move |this, mut cx| async move {
3572 // For each stopped language server, record all of the worktrees with which
3573 // it was associated.
3574 let mut affected_worktrees = Vec::new();
3575 for (stop_task, language_server_name) in stop_tasks {
3576 for affected_worktree_id in stop_task.await {
3577 affected_worktrees.push((affected_worktree_id, language_server_name.clone()));
3578 }
3579 }
3580
3581 this.update(&mut cx, |this, cx| {
3582 // Restart the language server for the given worktree.
3583 this.start_language_servers(&worktree, language.clone(), cx);
3584
3585 // Lookup new server ids and set them for each of the orphaned worktrees
3586 for (affected_worktree_id, language_server_name) in affected_worktrees {
3587 if let Some(new_server_id) = this
3588 .language_server_ids
3589 .get(&(worktree_id, language_server_name.clone()))
3590 .cloned()
3591 {
3592 this.language_server_ids
3593 .insert((affected_worktree_id, language_server_name), new_server_id);
3594 }
3595 }
3596 })
3597 .ok();
3598 })
3599 .detach();
3600 }
3601
3602 fn check_errored_server(
3603 language: Arc<Language>,
3604 adapter: Arc<CachedLspAdapter>,
3605 server_id: LanguageServerId,
3606 installation_test_binary: Option<LanguageServerBinary>,
3607 cx: &mut ModelContext<Self>,
3608 ) {
3609 if !adapter.can_be_reinstalled() {
3610 log::info!(
3611 "Validation check requested for {:?} but it cannot be reinstalled",
3612 adapter.name.0
3613 );
3614 return;
3615 }
3616
3617 cx.spawn(move |this, mut cx| async move {
3618 log::info!("About to spawn test binary");
3619
3620 // A lack of test binary counts as a failure
3621 let process = installation_test_binary.and_then(|binary| {
3622 smol::process::Command::new(&binary.path)
3623 .current_dir(&binary.path)
3624 .args(binary.arguments)
3625 .stdin(Stdio::piped())
3626 .stdout(Stdio::piped())
3627 .stderr(Stdio::inherit())
3628 .kill_on_drop(true)
3629 .spawn()
3630 .ok()
3631 });
3632
3633 const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3634 let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
3635
3636 let mut errored = false;
3637 if let Some(mut process) = process {
3638 futures::select! {
3639 status = process.status().fuse() => match status {
3640 Ok(status) => errored = !status.success(),
3641 Err(_) => errored = true,
3642 },
3643
3644 _ = timeout => {
3645 log::info!("test binary time-ed out, this counts as a success");
3646 _ = process.kill();
3647 }
3648 }
3649 } else {
3650 log::warn!("test binary failed to launch");
3651 errored = true;
3652 }
3653
3654 if errored {
3655 log::warn!("test binary check failed");
3656 let task = this
3657 .update(&mut cx, move |this, cx| {
3658 this.reinstall_language_server(language, adapter, server_id, cx)
3659 })
3660 .ok()
3661 .flatten();
3662
3663 if let Some(task) = task {
3664 task.await;
3665 }
3666 }
3667 })
3668 .detach();
3669 }
3670
3671 fn enqueue_language_server_progress(
3672 &mut self,
3673 message: BufferOrderedMessage,
3674 cx: &mut ModelContext<Self>,
3675 ) {
3676 self.pending_language_server_update.replace(message);
3677 self.flush_language_server_update.get_or_insert_with(|| {
3678 cx.spawn(|this, mut cx| async move {
3679 cx.background_executor()
3680 .timer(SERVER_PROGRESS_DEBOUNCE_TIMEOUT)
3681 .await;
3682 this.update(&mut cx, |this, _| {
3683 this.flush_language_server_update.take();
3684 if let Some(update) = this.pending_language_server_update.take() {
3685 this.enqueue_buffer_ordered_message(update).ok();
3686 }
3687 })
3688 .ok();
3689 })
3690 });
3691 }
3692
3693 fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3694 if let Some(pending_message) = self.pending_language_server_update.take() {
3695 self.flush_language_server_update.take();
3696 self.buffer_ordered_messages_tx
3697 .unbounded_send(pending_message)
3698 .map_err(|e| anyhow!(e))?;
3699 }
3700 self.buffer_ordered_messages_tx
3701 .unbounded_send(message)
3702 .map_err(|e| anyhow!(e))
3703 }
3704
3705 fn on_lsp_progress(
3706 &mut self,
3707 progress: lsp::ProgressParams,
3708 language_server_id: LanguageServerId,
3709 disk_based_diagnostics_progress_token: Option<String>,
3710 cx: &mut ModelContext<Self>,
3711 ) {
3712 let token = match progress.token {
3713 lsp::NumberOrString::String(token) => token,
3714 lsp::NumberOrString::Number(token) => {
3715 log::info!("skipping numeric progress token {}", token);
3716 return;
3717 }
3718 };
3719 let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3720 let language_server_status =
3721 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3722 status
3723 } else {
3724 return;
3725 };
3726
3727 if !language_server_status.progress_tokens.contains(&token) {
3728 return;
3729 }
3730
3731 let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3732 .as_ref()
3733 .map_or(false, |disk_based_token| {
3734 token.starts_with(disk_based_token)
3735 });
3736
3737 match progress {
3738 lsp::WorkDoneProgress::Begin(report) => {
3739 if is_disk_based_diagnostics_progress {
3740 language_server_status.has_pending_diagnostic_updates = true;
3741 self.disk_based_diagnostics_started(language_server_id, cx);
3742 self.enqueue_buffer_ordered_message(BufferOrderedMessage::LanguageServerUpdate {
3743 language_server_id,
3744 message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3745 })
3746 .ok();
3747 } else {
3748 self.on_lsp_work_start(
3749 language_server_id,
3750 token.clone(),
3751 LanguageServerProgress {
3752 message: report.message.clone(),
3753 percentage: report.percentage.map(|p| p as usize),
3754 last_update_at: Instant::now(),
3755 },
3756 cx,
3757 );
3758 self.enqueue_buffer_ordered_message(
3759 BufferOrderedMessage::LanguageServerUpdate {
3760 language_server_id,
3761 message: proto::update_language_server::Variant::WorkStart(
3762 proto::LspWorkStart {
3763 token,
3764 message: report.message,
3765 percentage: report.percentage,
3766 },
3767 ),
3768 },
3769 )
3770 .ok();
3771 }
3772 }
3773 lsp::WorkDoneProgress::Report(report) => {
3774 if !is_disk_based_diagnostics_progress {
3775 self.on_lsp_work_progress(
3776 language_server_id,
3777 token.clone(),
3778 LanguageServerProgress {
3779 message: report.message.clone(),
3780 percentage: report.percentage.map(|p| p as usize),
3781 last_update_at: Instant::now(),
3782 },
3783 cx,
3784 );
3785 self.enqueue_language_server_progress(
3786 BufferOrderedMessage::LanguageServerUpdate {
3787 language_server_id,
3788 message: proto::update_language_server::Variant::WorkProgress(
3789 proto::LspWorkProgress {
3790 token,
3791 message: report.message,
3792 percentage: report.percentage,
3793 },
3794 ),
3795 },
3796 cx,
3797 );
3798 }
3799 }
3800 lsp::WorkDoneProgress::End(_) => {
3801 language_server_status.progress_tokens.remove(&token);
3802
3803 if is_disk_based_diagnostics_progress {
3804 language_server_status.has_pending_diagnostic_updates = false;
3805 self.disk_based_diagnostics_finished(language_server_id, cx);
3806 self.enqueue_buffer_ordered_message(
3807 BufferOrderedMessage::LanguageServerUpdate {
3808 language_server_id,
3809 message:
3810 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3811 Default::default(),
3812 ),
3813 },
3814 )
3815 .ok();
3816 } else {
3817 self.on_lsp_work_end(language_server_id, token.clone(), cx);
3818 self.enqueue_buffer_ordered_message(
3819 BufferOrderedMessage::LanguageServerUpdate {
3820 language_server_id,
3821 message: proto::update_language_server::Variant::WorkEnd(
3822 proto::LspWorkEnd { token },
3823 ),
3824 },
3825 )
3826 .ok();
3827 }
3828 }
3829 }
3830 }
3831
3832 fn on_lsp_work_start(
3833 &mut self,
3834 language_server_id: LanguageServerId,
3835 token: String,
3836 progress: LanguageServerProgress,
3837 cx: &mut ModelContext<Self>,
3838 ) {
3839 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3840 status.pending_work.insert(token, progress);
3841 cx.notify();
3842 }
3843 }
3844
3845 fn on_lsp_work_progress(
3846 &mut self,
3847 language_server_id: LanguageServerId,
3848 token: String,
3849 progress: LanguageServerProgress,
3850 cx: &mut ModelContext<Self>,
3851 ) {
3852 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3853 let entry = status
3854 .pending_work
3855 .entry(token)
3856 .or_insert(LanguageServerProgress {
3857 message: Default::default(),
3858 percentage: Default::default(),
3859 last_update_at: progress.last_update_at,
3860 });
3861 if progress.message.is_some() {
3862 entry.message = progress.message;
3863 }
3864 if progress.percentage.is_some() {
3865 entry.percentage = progress.percentage;
3866 }
3867 entry.last_update_at = progress.last_update_at;
3868 cx.notify();
3869 }
3870 }
3871
3872 fn on_lsp_work_end(
3873 &mut self,
3874 language_server_id: LanguageServerId,
3875 token: String,
3876 cx: &mut ModelContext<Self>,
3877 ) {
3878 if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3879 cx.emit(Event::RefreshInlayHints);
3880 status.pending_work.remove(&token);
3881 cx.notify();
3882 }
3883 }
3884
3885 fn on_lsp_did_change_watched_files(
3886 &mut self,
3887 language_server_id: LanguageServerId,
3888 params: DidChangeWatchedFilesRegistrationOptions,
3889 cx: &mut ModelContext<Self>,
3890 ) {
3891 let watched_paths = self
3892 .language_server_watched_paths
3893 .entry(language_server_id)
3894 .or_default();
3895
3896 let mut builders = HashMap::default();
3897 for watcher in params.watchers {
3898 for worktree in &self.worktrees {
3899 if let Some(worktree) = worktree.upgrade() {
3900 let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3901 if let Some(abs_path) = tree.abs_path().to_str() {
3902 let relative_glob_pattern = match &watcher.glob_pattern {
3903 lsp::GlobPattern::String(s) => s
3904 .strip_prefix(abs_path)
3905 .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3906 lsp::GlobPattern::Relative(rp) => {
3907 let base_uri = match &rp.base_uri {
3908 lsp::OneOf::Left(workspace_folder) => &workspace_folder.uri,
3909 lsp::OneOf::Right(base_uri) => base_uri,
3910 };
3911 base_uri.to_file_path().ok().and_then(|file_path| {
3912 (file_path.to_str() == Some(abs_path))
3913 .then_some(rp.pattern.as_str())
3914 })
3915 }
3916 };
3917 if let Some(relative_glob_pattern) = relative_glob_pattern {
3918 let literal_prefix = glob_literal_prefix(relative_glob_pattern);
3919 tree.as_local_mut()
3920 .unwrap()
3921 .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3922 if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3923 builders
3924 .entry(tree.id())
3925 .or_insert_with(|| GlobSetBuilder::new())
3926 .add(glob);
3927 }
3928 return true;
3929 }
3930 }
3931 false
3932 });
3933 if glob_is_inside_worktree {
3934 break;
3935 }
3936 }
3937 }
3938 }
3939
3940 watched_paths.clear();
3941 for (worktree_id, builder) in builders {
3942 if let Ok(globset) = builder.build() {
3943 watched_paths.insert(worktree_id, globset);
3944 }
3945 }
3946
3947 cx.notify();
3948 }
3949
3950 async fn on_lsp_workspace_edit(
3951 this: WeakModel<Self>,
3952 params: lsp::ApplyWorkspaceEditParams,
3953 server_id: LanguageServerId,
3954 adapter: Arc<CachedLspAdapter>,
3955 mut cx: AsyncAppContext,
3956 ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3957 let this = this
3958 .upgrade()
3959 .ok_or_else(|| anyhow!("project project closed"))?;
3960 let language_server = this
3961 .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
3962 .ok_or_else(|| anyhow!("language server not found"))?;
3963 let transaction = Self::deserialize_workspace_edit(
3964 this.clone(),
3965 params.edit,
3966 true,
3967 adapter.clone(),
3968 language_server.clone(),
3969 &mut cx,
3970 )
3971 .await
3972 .log_err();
3973 this.update(&mut cx, |this, _| {
3974 if let Some(transaction) = transaction {
3975 this.last_workspace_edits_by_language_server
3976 .insert(server_id, transaction);
3977 }
3978 })?;
3979 Ok(lsp::ApplyWorkspaceEditResponse {
3980 applied: true,
3981 failed_change: None,
3982 failure_reason: None,
3983 })
3984 }
3985
3986 pub fn language_server_statuses(
3987 &self,
3988 ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3989 self.language_server_statuses.values()
3990 }
3991
3992 pub fn update_diagnostics(
3993 &mut self,
3994 language_server_id: LanguageServerId,
3995 mut params: lsp::PublishDiagnosticsParams,
3996 disk_based_sources: &[String],
3997 cx: &mut ModelContext<Self>,
3998 ) -> Result<()> {
3999 let abs_path = params
4000 .uri
4001 .to_file_path()
4002 .map_err(|_| anyhow!("URI is not a file"))?;
4003 let mut diagnostics = Vec::default();
4004 let mut primary_diagnostic_group_ids = HashMap::default();
4005 let mut sources_by_group_id = HashMap::default();
4006 let mut supporting_diagnostics = HashMap::default();
4007
4008 // Ensure that primary diagnostics are always the most severe
4009 params.diagnostics.sort_by_key(|item| item.severity);
4010
4011 for diagnostic in ¶ms.diagnostics {
4012 let source = diagnostic.source.as_ref();
4013 let code = diagnostic.code.as_ref().map(|code| match code {
4014 lsp::NumberOrString::Number(code) => code.to_string(),
4015 lsp::NumberOrString::String(code) => code.clone(),
4016 });
4017 let range = range_from_lsp(diagnostic.range);
4018 let is_supporting = diagnostic
4019 .related_information
4020 .as_ref()
4021 .map_or(false, |infos| {
4022 infos.iter().any(|info| {
4023 primary_diagnostic_group_ids.contains_key(&(
4024 source,
4025 code.clone(),
4026 range_from_lsp(info.location.range),
4027 ))
4028 })
4029 });
4030
4031 let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
4032 tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
4033 });
4034
4035 if is_supporting {
4036 supporting_diagnostics.insert(
4037 (source, code.clone(), range),
4038 (diagnostic.severity, is_unnecessary),
4039 );
4040 } else {
4041 let group_id = post_inc(&mut self.next_diagnostic_group_id);
4042 let is_disk_based =
4043 source.map_or(false, |source| disk_based_sources.contains(source));
4044
4045 sources_by_group_id.insert(group_id, source);
4046 primary_diagnostic_group_ids
4047 .insert((source, code.clone(), range.clone()), group_id);
4048
4049 diagnostics.push(DiagnosticEntry {
4050 range,
4051 diagnostic: Diagnostic {
4052 source: diagnostic.source.clone(),
4053 code: code.clone(),
4054 severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
4055 message: diagnostic.message.trim().to_string(),
4056 group_id,
4057 is_primary: true,
4058 is_disk_based,
4059 is_unnecessary,
4060 },
4061 });
4062 if let Some(infos) = &diagnostic.related_information {
4063 for info in infos {
4064 if info.location.uri == params.uri && !info.message.is_empty() {
4065 let range = range_from_lsp(info.location.range);
4066 diagnostics.push(DiagnosticEntry {
4067 range,
4068 diagnostic: Diagnostic {
4069 source: diagnostic.source.clone(),
4070 code: code.clone(),
4071 severity: DiagnosticSeverity::INFORMATION,
4072 message: info.message.trim().to_string(),
4073 group_id,
4074 is_primary: false,
4075 is_disk_based,
4076 is_unnecessary: false,
4077 },
4078 });
4079 }
4080 }
4081 }
4082 }
4083 }
4084
4085 for entry in &mut diagnostics {
4086 let diagnostic = &mut entry.diagnostic;
4087 if !diagnostic.is_primary {
4088 let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
4089 if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
4090 source,
4091 diagnostic.code.clone(),
4092 entry.range.clone(),
4093 )) {
4094 if let Some(severity) = severity {
4095 diagnostic.severity = severity;
4096 }
4097 diagnostic.is_unnecessary = is_unnecessary;
4098 }
4099 }
4100 }
4101
4102 self.update_diagnostic_entries(
4103 language_server_id,
4104 abs_path,
4105 params.version,
4106 diagnostics,
4107 cx,
4108 )?;
4109 Ok(())
4110 }
4111
4112 pub fn update_diagnostic_entries(
4113 &mut self,
4114 server_id: LanguageServerId,
4115 abs_path: PathBuf,
4116 version: Option<i32>,
4117 diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4118 cx: &mut ModelContext<Project>,
4119 ) -> Result<(), anyhow::Error> {
4120 let (worktree, relative_path) = self
4121 .find_local_worktree(&abs_path, cx)
4122 .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
4123
4124 let project_path = ProjectPath {
4125 worktree_id: worktree.read(cx).id(),
4126 path: relative_path.into(),
4127 };
4128
4129 if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
4130 self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
4131 }
4132
4133 let updated = worktree.update(cx, |worktree, cx| {
4134 worktree
4135 .as_local_mut()
4136 .ok_or_else(|| anyhow!("not a local worktree"))?
4137 .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
4138 })?;
4139 if updated {
4140 cx.emit(Event::DiagnosticsUpdated {
4141 language_server_id: server_id,
4142 path: project_path,
4143 });
4144 }
4145 Ok(())
4146 }
4147
4148 fn update_buffer_diagnostics(
4149 &mut self,
4150 buffer: &Model<Buffer>,
4151 server_id: LanguageServerId,
4152 version: Option<i32>,
4153 mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4154 cx: &mut ModelContext<Self>,
4155 ) -> Result<()> {
4156 fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
4157 Ordering::Equal
4158 .then_with(|| b.is_primary.cmp(&a.is_primary))
4159 .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
4160 .then_with(|| a.severity.cmp(&b.severity))
4161 .then_with(|| a.message.cmp(&b.message))
4162 }
4163
4164 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
4165
4166 diagnostics.sort_unstable_by(|a, b| {
4167 Ordering::Equal
4168 .then_with(|| a.range.start.cmp(&b.range.start))
4169 .then_with(|| b.range.end.cmp(&a.range.end))
4170 .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
4171 });
4172
4173 let mut sanitized_diagnostics = Vec::new();
4174 let edits_since_save = Patch::new(
4175 snapshot
4176 .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
4177 .collect(),
4178 );
4179 for entry in diagnostics {
4180 let start;
4181 let end;
4182 if entry.diagnostic.is_disk_based {
4183 // Some diagnostics are based on files on disk instead of buffers'
4184 // current contents. Adjust these diagnostics' ranges to reflect
4185 // any unsaved edits.
4186 start = edits_since_save.old_to_new(entry.range.start);
4187 end = edits_since_save.old_to_new(entry.range.end);
4188 } else {
4189 start = entry.range.start;
4190 end = entry.range.end;
4191 }
4192
4193 let mut range = snapshot.clip_point_utf16(start, Bias::Left)
4194 ..snapshot.clip_point_utf16(end, Bias::Right);
4195
4196 // Expand empty ranges by one codepoint
4197 if range.start == range.end {
4198 // This will be go to the next boundary when being clipped
4199 range.end.column += 1;
4200 range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
4201 if range.start == range.end && range.end.column > 0 {
4202 range.start.column -= 1;
4203 range.start = snapshot.clip_point_utf16(Unclipped(range.start), Bias::Left);
4204 }
4205 }
4206
4207 sanitized_diagnostics.push(DiagnosticEntry {
4208 range,
4209 diagnostic: entry.diagnostic,
4210 });
4211 }
4212 drop(edits_since_save);
4213
4214 let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
4215 buffer.update(cx, |buffer, cx| {
4216 buffer.update_diagnostics(server_id, set, cx)
4217 });
4218 Ok(())
4219 }
4220
4221 pub fn reload_buffers(
4222 &self,
4223 buffers: HashSet<Model<Buffer>>,
4224 push_to_history: bool,
4225 cx: &mut ModelContext<Self>,
4226 ) -> Task<Result<ProjectTransaction>> {
4227 let mut local_buffers = Vec::new();
4228 let mut remote_buffers = None;
4229 for buffer_handle in buffers {
4230 let buffer = buffer_handle.read(cx);
4231 if buffer.is_dirty() {
4232 if let Some(file) = File::from_dyn(buffer.file()) {
4233 if file.is_local() {
4234 local_buffers.push(buffer_handle);
4235 } else {
4236 remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
4237 }
4238 }
4239 }
4240 }
4241
4242 let remote_buffers = self.remote_id().zip(remote_buffers);
4243 let client = self.client.clone();
4244
4245 cx.spawn(move |this, mut cx| async move {
4246 let mut project_transaction = ProjectTransaction::default();
4247
4248 if let Some((project_id, remote_buffers)) = remote_buffers {
4249 let response = client
4250 .request(proto::ReloadBuffers {
4251 project_id,
4252 buffer_ids: remote_buffers
4253 .iter()
4254 .filter_map(|buffer| {
4255 buffer
4256 .update(&mut cx, |buffer, _| buffer.remote_id().into())
4257 .ok()
4258 })
4259 .collect(),
4260 })
4261 .await?
4262 .transaction
4263 .ok_or_else(|| anyhow!("missing transaction"))?;
4264 project_transaction = this
4265 .update(&mut cx, |this, cx| {
4266 this.deserialize_project_transaction(response, push_to_history, cx)
4267 })?
4268 .await?;
4269 }
4270
4271 for buffer in local_buffers {
4272 let transaction = buffer
4273 .update(&mut cx, |buffer, cx| buffer.reload(cx))?
4274 .await?;
4275 buffer.update(&mut cx, |buffer, cx| {
4276 if let Some(transaction) = transaction {
4277 if !push_to_history {
4278 buffer.forget_transaction(transaction.id);
4279 }
4280 project_transaction.0.insert(cx.handle(), transaction);
4281 }
4282 })?;
4283 }
4284
4285 Ok(project_transaction)
4286 })
4287 }
4288
4289 pub fn format(
4290 &mut self,
4291 buffers: HashSet<Model<Buffer>>,
4292 push_to_history: bool,
4293 trigger: FormatTrigger,
4294 cx: &mut ModelContext<Project>,
4295 ) -> Task<anyhow::Result<ProjectTransaction>> {
4296 if self.is_local() {
4297 let mut buffers_with_paths = buffers
4298 .into_iter()
4299 .filter_map(|buffer_handle| {
4300 let buffer = buffer_handle.read(cx);
4301 let file = File::from_dyn(buffer.file())?;
4302 let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4303 Some((buffer_handle, buffer_abs_path))
4304 })
4305 .collect::<Vec<_>>();
4306
4307 cx.spawn(move |project, mut cx| async move {
4308 // Do not allow multiple concurrent formatting requests for the
4309 // same buffer.
4310 project.update(&mut cx, |this, cx| {
4311 buffers_with_paths.retain(|(buffer, _)| {
4312 this.buffers_being_formatted
4313 .insert(buffer.read(cx).remote_id())
4314 });
4315 })?;
4316
4317 let _cleanup = defer({
4318 let this = project.clone();
4319 let mut cx = cx.clone();
4320 let buffers = &buffers_with_paths;
4321 move || {
4322 this.update(&mut cx, |this, cx| {
4323 for (buffer, _) in buffers {
4324 this.buffers_being_formatted
4325 .remove(&buffer.read(cx).remote_id());
4326 }
4327 })
4328 .ok();
4329 }
4330 });
4331
4332 let mut project_transaction = ProjectTransaction::default();
4333 for (buffer, buffer_abs_path) in &buffers_with_paths {
4334 let adapters_and_servers: Vec<_> = project.update(&mut cx, |project, cx| {
4335 project
4336 .language_servers_for_buffer(&buffer.read(cx), cx)
4337 .map(|(adapter, lsp)| (adapter.clone(), lsp.clone()))
4338 .collect()
4339 })?;
4340
4341 let settings = buffer.update(&mut cx, |buffer, cx| {
4342 language_settings(buffer.language(), buffer.file(), cx).clone()
4343 })?;
4344
4345 let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4346 let ensure_final_newline = settings.ensure_final_newline_on_save;
4347 let tab_size = settings.tab_size;
4348
4349 // First, format buffer's whitespace according to the settings.
4350 let trailing_whitespace_diff = if remove_trailing_whitespace {
4351 Some(
4352 buffer
4353 .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
4354 .await,
4355 )
4356 } else {
4357 None
4358 };
4359 let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4360 buffer.finalize_last_transaction();
4361 buffer.start_transaction();
4362 if let Some(diff) = trailing_whitespace_diff {
4363 buffer.apply_diff(diff, cx);
4364 }
4365 if ensure_final_newline {
4366 buffer.ensure_final_newline(cx);
4367 }
4368 buffer.end_transaction(cx)
4369 })?;
4370
4371 for (lsp_adapter, language_server) in adapters_and_servers.iter() {
4372 // Apply the code actions on
4373 let code_actions: Vec<lsp::CodeActionKind> = settings
4374 .code_actions_on_format
4375 .iter()
4376 .flat_map(|(kind, enabled)| {
4377 if *enabled {
4378 Some(kind.clone().into())
4379 } else {
4380 None
4381 }
4382 })
4383 .collect();
4384
4385 #[allow(clippy::nonminimal_bool)]
4386 if !code_actions.is_empty()
4387 && !(trigger == FormatTrigger::Save
4388 && settings.format_on_save == FormatOnSave::Off)
4389 {
4390 let actions = project
4391 .update(&mut cx, |this, cx| {
4392 this.request_lsp(
4393 buffer.clone(),
4394 LanguageServerToQuery::Other(language_server.server_id()),
4395 GetCodeActions {
4396 range: text::Anchor::MIN..text::Anchor::MAX,
4397 kinds: Some(code_actions),
4398 },
4399 cx,
4400 )
4401 })?
4402 .await?;
4403
4404 for mut action in actions {
4405 Self::try_resolve_code_action(&language_server, &mut action)
4406 .await
4407 .context("resolving a formatting code action")?;
4408 if let Some(edit) = action.lsp_action.edit {
4409 if edit.changes.is_none() && edit.document_changes.is_none() {
4410 continue;
4411 }
4412
4413 let new = Self::deserialize_workspace_edit(
4414 project
4415 .upgrade()
4416 .ok_or_else(|| anyhow!("project dropped"))?,
4417 edit,
4418 push_to_history,
4419 lsp_adapter.clone(),
4420 language_server.clone(),
4421 &mut cx,
4422 )
4423 .await?;
4424 project_transaction.0.extend(new.0);
4425 }
4426
4427 if let Some(command) = action.lsp_action.command {
4428 project.update(&mut cx, |this, _| {
4429 this.last_workspace_edits_by_language_server
4430 .remove(&language_server.server_id());
4431 })?;
4432
4433 language_server
4434 .request::<lsp::request::ExecuteCommand>(
4435 lsp::ExecuteCommandParams {
4436 command: command.command,
4437 arguments: command.arguments.unwrap_or_default(),
4438 ..Default::default()
4439 },
4440 )
4441 .await?;
4442
4443 project.update(&mut cx, |this, _| {
4444 project_transaction.0.extend(
4445 this.last_workspace_edits_by_language_server
4446 .remove(&language_server.server_id())
4447 .unwrap_or_default()
4448 .0,
4449 )
4450 })?;
4451 }
4452 }
4453 }
4454 }
4455
4456 // Apply language-specific formatting using either the primary language server
4457 // or external command.
4458 let primary_language_server = adapters_and_servers
4459 .first()
4460 .cloned()
4461 .map(|(_, lsp)| lsp.clone());
4462 let server_and_buffer = primary_language_server
4463 .as_ref()
4464 .zip(buffer_abs_path.as_ref());
4465
4466 let mut format_operation = None;
4467 match (&settings.formatter, &settings.format_on_save) {
4468 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4469
4470 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4471 | (_, FormatOnSave::LanguageServer) => {
4472 if let Some((language_server, buffer_abs_path)) = server_and_buffer {
4473 format_operation = Some(FormatOperation::Lsp(
4474 Self::format_via_lsp(
4475 &project,
4476 buffer,
4477 buffer_abs_path,
4478 language_server,
4479 tab_size,
4480 &mut cx,
4481 )
4482 .await
4483 .context("failed to format via language server")?,
4484 ));
4485 }
4486 }
4487
4488 (
4489 Formatter::External { command, arguments },
4490 FormatOnSave::On | FormatOnSave::Off,
4491 )
4492 | (_, FormatOnSave::External { command, arguments }) => {
4493 if let Some(buffer_abs_path) = buffer_abs_path {
4494 format_operation = Self::format_via_external_command(
4495 buffer,
4496 buffer_abs_path,
4497 command,
4498 arguments,
4499 &mut cx,
4500 )
4501 .await
4502 .context(format!(
4503 "failed to format via external command {:?}",
4504 command
4505 ))?
4506 .map(FormatOperation::External);
4507 }
4508 }
4509 (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4510 if let Some(new_operation) =
4511 prettier_support::format_with_prettier(&project, buffer, &mut cx)
4512 .await
4513 {
4514 format_operation = Some(new_operation);
4515 } else if let Some((language_server, buffer_abs_path)) =
4516 server_and_buffer
4517 {
4518 format_operation = Some(FormatOperation::Lsp(
4519 Self::format_via_lsp(
4520 &project,
4521 buffer,
4522 buffer_abs_path,
4523 language_server,
4524 tab_size,
4525 &mut cx,
4526 )
4527 .await
4528 .context("failed to format via language server")?,
4529 ));
4530 }
4531 }
4532 (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4533 if let Some(new_operation) =
4534 prettier_support::format_with_prettier(&project, buffer, &mut cx)
4535 .await
4536 {
4537 format_operation = Some(new_operation);
4538 }
4539 }
4540 };
4541
4542 buffer.update(&mut cx, |b, cx| {
4543 // If the buffer had its whitespace formatted and was edited while the language-specific
4544 // formatting was being computed, avoid applying the language-specific formatting, because
4545 // it can't be grouped with the whitespace formatting in the undo history.
4546 if let Some(transaction_id) = whitespace_transaction_id {
4547 if b.peek_undo_stack()
4548 .map_or(true, |e| e.transaction_id() != transaction_id)
4549 {
4550 format_operation.take();
4551 }
4552 }
4553
4554 // Apply any language-specific formatting, and group the two formatting operations
4555 // in the buffer's undo history.
4556 if let Some(operation) = format_operation {
4557 match operation {
4558 FormatOperation::Lsp(edits) => {
4559 b.edit(edits, None, cx);
4560 }
4561 FormatOperation::External(diff) => {
4562 b.apply_diff(diff, cx);
4563 }
4564 FormatOperation::Prettier(diff) => {
4565 b.apply_diff(diff, cx);
4566 }
4567 }
4568
4569 if let Some(transaction_id) = whitespace_transaction_id {
4570 b.group_until_transaction(transaction_id);
4571 } else if let Some(transaction) = project_transaction.0.get(buffer) {
4572 b.group_until_transaction(transaction.id)
4573 }
4574 }
4575
4576 if let Some(transaction) = b.finalize_last_transaction().cloned() {
4577 if !push_to_history {
4578 b.forget_transaction(transaction.id);
4579 }
4580 project_transaction.0.insert(buffer.clone(), transaction);
4581 }
4582 })?;
4583 }
4584
4585 Ok(project_transaction)
4586 })
4587 } else {
4588 let remote_id = self.remote_id();
4589 let client = self.client.clone();
4590 cx.spawn(move |this, mut cx| async move {
4591 let mut project_transaction = ProjectTransaction::default();
4592 if let Some(project_id) = remote_id {
4593 let response = client
4594 .request(proto::FormatBuffers {
4595 project_id,
4596 trigger: trigger as i32,
4597 buffer_ids: buffers
4598 .iter()
4599 .map(|buffer| {
4600 buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
4601 })
4602 .collect::<Result<_>>()?,
4603 })
4604 .await?
4605 .transaction
4606 .ok_or_else(|| anyhow!("missing transaction"))?;
4607 project_transaction = this
4608 .update(&mut cx, |this, cx| {
4609 this.deserialize_project_transaction(response, push_to_history, cx)
4610 })?
4611 .await?;
4612 }
4613 Ok(project_transaction)
4614 })
4615 }
4616 }
4617
4618 async fn format_via_lsp(
4619 this: &WeakModel<Self>,
4620 buffer: &Model<Buffer>,
4621 abs_path: &Path,
4622 language_server: &Arc<LanguageServer>,
4623 tab_size: NonZeroU32,
4624 cx: &mut AsyncAppContext,
4625 ) -> Result<Vec<(Range<Anchor>, String)>> {
4626 let uri = lsp::Url::from_file_path(abs_path)
4627 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4628 let text_document = lsp::TextDocumentIdentifier::new(uri);
4629 let capabilities = &language_server.capabilities();
4630
4631 let formatting_provider = capabilities.document_formatting_provider.as_ref();
4632 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4633
4634 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4635 language_server
4636 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4637 text_document,
4638 options: lsp_command::lsp_formatting_options(tab_size.get()),
4639 work_done_progress_params: Default::default(),
4640 })
4641 .await?
4642 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4643 let buffer_start = lsp::Position::new(0, 0);
4644 let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4645
4646 language_server
4647 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4648 text_document,
4649 range: lsp::Range::new(buffer_start, buffer_end),
4650 options: lsp_command::lsp_formatting_options(tab_size.get()),
4651 work_done_progress_params: Default::default(),
4652 })
4653 .await?
4654 } else {
4655 None
4656 };
4657
4658 if let Some(lsp_edits) = lsp_edits {
4659 this.update(cx, |this, cx| {
4660 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4661 })?
4662 .await
4663 } else {
4664 Ok(Vec::new())
4665 }
4666 }
4667
4668 async fn format_via_external_command(
4669 buffer: &Model<Buffer>,
4670 buffer_abs_path: &Path,
4671 command: &str,
4672 arguments: &[String],
4673 cx: &mut AsyncAppContext,
4674 ) -> Result<Option<Diff>> {
4675 let working_dir_path = buffer.update(cx, |buffer, cx| {
4676 let file = File::from_dyn(buffer.file())?;
4677 let worktree = file.worktree.read(cx).as_local()?;
4678 let mut worktree_path = worktree.abs_path().to_path_buf();
4679 if worktree.root_entry()?.is_file() {
4680 worktree_path.pop();
4681 }
4682 Some(worktree_path)
4683 })?;
4684
4685 if let Some(working_dir_path) = working_dir_path {
4686 let mut child =
4687 smol::process::Command::new(command)
4688 .args(arguments.iter().map(|arg| {
4689 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4690 }))
4691 .current_dir(&working_dir_path)
4692 .stdin(smol::process::Stdio::piped())
4693 .stdout(smol::process::Stdio::piped())
4694 .stderr(smol::process::Stdio::piped())
4695 .spawn()?;
4696 let stdin = child
4697 .stdin
4698 .as_mut()
4699 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4700 let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4701 for chunk in text.chunks() {
4702 stdin.write_all(chunk.as_bytes()).await?;
4703 }
4704 stdin.flush().await?;
4705
4706 let output = child.output().await?;
4707 if !output.status.success() {
4708 return Err(anyhow!(
4709 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4710 output.status.code(),
4711 String::from_utf8_lossy(&output.stdout),
4712 String::from_utf8_lossy(&output.stderr),
4713 ));
4714 }
4715
4716 let stdout = String::from_utf8(output.stdout)?;
4717 Ok(Some(
4718 buffer
4719 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
4720 .await,
4721 ))
4722 } else {
4723 Ok(None)
4724 }
4725 }
4726
4727 #[inline(never)]
4728 fn definition_impl(
4729 &self,
4730 buffer: &Model<Buffer>,
4731 position: PointUtf16,
4732 cx: &mut ModelContext<Self>,
4733 ) -> Task<Result<Vec<LocationLink>>> {
4734 self.request_lsp(
4735 buffer.clone(),
4736 LanguageServerToQuery::Primary,
4737 GetDefinition { position },
4738 cx,
4739 )
4740 }
4741 pub fn definition<T: ToPointUtf16>(
4742 &self,
4743 buffer: &Model<Buffer>,
4744 position: T,
4745 cx: &mut ModelContext<Self>,
4746 ) -> Task<Result<Vec<LocationLink>>> {
4747 let position = position.to_point_utf16(buffer.read(cx));
4748 self.definition_impl(buffer, position, cx)
4749 }
4750
4751 fn type_definition_impl(
4752 &self,
4753 buffer: &Model<Buffer>,
4754 position: PointUtf16,
4755 cx: &mut ModelContext<Self>,
4756 ) -> Task<Result<Vec<LocationLink>>> {
4757 self.request_lsp(
4758 buffer.clone(),
4759 LanguageServerToQuery::Primary,
4760 GetTypeDefinition { position },
4761 cx,
4762 )
4763 }
4764
4765 pub fn type_definition<T: ToPointUtf16>(
4766 &self,
4767 buffer: &Model<Buffer>,
4768 position: T,
4769 cx: &mut ModelContext<Self>,
4770 ) -> Task<Result<Vec<LocationLink>>> {
4771 let position = position.to_point_utf16(buffer.read(cx));
4772 self.type_definition_impl(buffer, position, cx)
4773 }
4774
4775 fn implementation_impl(
4776 &self,
4777 buffer: &Model<Buffer>,
4778 position: PointUtf16,
4779 cx: &mut ModelContext<Self>,
4780 ) -> Task<Result<Vec<LocationLink>>> {
4781 self.request_lsp(
4782 buffer.clone(),
4783 LanguageServerToQuery::Primary,
4784 GetImplementation { position },
4785 cx,
4786 )
4787 }
4788
4789 pub fn implementation<T: ToPointUtf16>(
4790 &self,
4791 buffer: &Model<Buffer>,
4792 position: T,
4793 cx: &mut ModelContext<Self>,
4794 ) -> Task<Result<Vec<LocationLink>>> {
4795 let position = position.to_point_utf16(buffer.read(cx));
4796 self.implementation_impl(buffer, position, cx)
4797 }
4798
4799 fn references_impl(
4800 &self,
4801 buffer: &Model<Buffer>,
4802 position: PointUtf16,
4803 cx: &mut ModelContext<Self>,
4804 ) -> Task<Result<Vec<Location>>> {
4805 self.request_lsp(
4806 buffer.clone(),
4807 LanguageServerToQuery::Primary,
4808 GetReferences { position },
4809 cx,
4810 )
4811 }
4812 pub fn references<T: ToPointUtf16>(
4813 &self,
4814 buffer: &Model<Buffer>,
4815 position: T,
4816 cx: &mut ModelContext<Self>,
4817 ) -> Task<Result<Vec<Location>>> {
4818 let position = position.to_point_utf16(buffer.read(cx));
4819 self.references_impl(buffer, position, cx)
4820 }
4821
4822 fn document_highlights_impl(
4823 &self,
4824 buffer: &Model<Buffer>,
4825 position: PointUtf16,
4826 cx: &mut ModelContext<Self>,
4827 ) -> Task<Result<Vec<DocumentHighlight>>> {
4828 self.request_lsp(
4829 buffer.clone(),
4830 LanguageServerToQuery::Primary,
4831 GetDocumentHighlights { position },
4832 cx,
4833 )
4834 }
4835
4836 pub fn document_highlights<T: ToPointUtf16>(
4837 &self,
4838 buffer: &Model<Buffer>,
4839 position: T,
4840 cx: &mut ModelContext<Self>,
4841 ) -> Task<Result<Vec<DocumentHighlight>>> {
4842 let position = position.to_point_utf16(buffer.read(cx));
4843 self.document_highlights_impl(buffer, position, cx)
4844 }
4845
4846 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4847 if self.is_local() {
4848 let mut requests = Vec::new();
4849 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4850 let worktree_id = *worktree_id;
4851 let worktree_handle = self.worktree_for_id(worktree_id, cx);
4852 let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4853 Some(worktree) => worktree,
4854 None => continue,
4855 };
4856 let worktree_abs_path = worktree.abs_path().clone();
4857
4858 let (adapter, language, server) = match self.language_servers.get(server_id) {
4859 Some(LanguageServerState::Running {
4860 adapter,
4861 language,
4862 server,
4863 ..
4864 }) => (adapter.clone(), language.clone(), server),
4865
4866 _ => continue,
4867 };
4868
4869 requests.push(
4870 server
4871 .request::<lsp::request::WorkspaceSymbolRequest>(
4872 lsp::WorkspaceSymbolParams {
4873 query: query.to_string(),
4874 ..Default::default()
4875 },
4876 )
4877 .log_err()
4878 .map(move |response| {
4879 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4880 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4881 flat_responses.into_iter().map(|lsp_symbol| {
4882 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4883 }).collect::<Vec<_>>()
4884 }
4885 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4886 nested_responses.into_iter().filter_map(|lsp_symbol| {
4887 let location = match lsp_symbol.location {
4888 OneOf::Left(location) => location,
4889 OneOf::Right(_) => {
4890 error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4891 return None
4892 }
4893 };
4894 Some((lsp_symbol.name, lsp_symbol.kind, location))
4895 }).collect::<Vec<_>>()
4896 }
4897 }).unwrap_or_default();
4898
4899 (
4900 adapter,
4901 language,
4902 worktree_id,
4903 worktree_abs_path,
4904 lsp_symbols,
4905 )
4906 }),
4907 );
4908 }
4909
4910 cx.spawn(move |this, mut cx| async move {
4911 let responses = futures::future::join_all(requests).await;
4912 let this = match this.upgrade() {
4913 Some(this) => this,
4914 None => return Ok(Vec::new()),
4915 };
4916
4917 let symbols = this.update(&mut cx, |this, cx| {
4918 let mut symbols = Vec::new();
4919 for (
4920 adapter,
4921 adapter_language,
4922 source_worktree_id,
4923 worktree_abs_path,
4924 lsp_symbols,
4925 ) in responses
4926 {
4927 symbols.extend(lsp_symbols.into_iter().filter_map(
4928 |(symbol_name, symbol_kind, symbol_location)| {
4929 let abs_path = symbol_location.uri.to_file_path().ok()?;
4930 let mut worktree_id = source_worktree_id;
4931 let path;
4932 if let Some((worktree, rel_path)) =
4933 this.find_local_worktree(&abs_path, cx)
4934 {
4935 worktree_id = worktree.read(cx).id();
4936 path = rel_path;
4937 } else {
4938 path = relativize_path(&worktree_abs_path, &abs_path);
4939 }
4940
4941 let project_path = ProjectPath {
4942 worktree_id,
4943 path: path.into(),
4944 };
4945 let signature = this.symbol_signature(&project_path);
4946 let adapter_language = adapter_language.clone();
4947 let language = this
4948 .languages
4949 .language_for_file(&project_path.path, None)
4950 .unwrap_or_else(move |_| adapter_language);
4951 let adapter = adapter.clone();
4952 Some(async move {
4953 let language = language.await;
4954 let label = adapter
4955 .label_for_symbol(&symbol_name, symbol_kind, &language)
4956 .await;
4957
4958 Symbol {
4959 language_server_name: adapter.name.clone(),
4960 source_worktree_id,
4961 path: project_path,
4962 label: label.unwrap_or_else(|| {
4963 CodeLabel::plain(symbol_name.clone(), None)
4964 }),
4965 kind: symbol_kind,
4966 name: symbol_name,
4967 range: range_from_lsp(symbol_location.range),
4968 signature,
4969 }
4970 })
4971 },
4972 ));
4973 }
4974
4975 symbols
4976 })?;
4977
4978 Ok(futures::future::join_all(symbols).await)
4979 })
4980 } else if let Some(project_id) = self.remote_id() {
4981 let request = self.client.request(proto::GetProjectSymbols {
4982 project_id,
4983 query: query.to_string(),
4984 });
4985 cx.spawn(move |this, mut cx| async move {
4986 let response = request.await?;
4987 let mut symbols = Vec::new();
4988 if let Some(this) = this.upgrade() {
4989 let new_symbols = this.update(&mut cx, |this, _| {
4990 response
4991 .symbols
4992 .into_iter()
4993 .map(|symbol| this.deserialize_symbol(symbol))
4994 .collect::<Vec<_>>()
4995 })?;
4996 symbols = futures::future::join_all(new_symbols)
4997 .await
4998 .into_iter()
4999 .filter_map(|symbol| symbol.log_err())
5000 .collect::<Vec<_>>();
5001 }
5002 Ok(symbols)
5003 })
5004 } else {
5005 Task::ready(Ok(Default::default()))
5006 }
5007 }
5008
5009 pub fn open_buffer_for_symbol(
5010 &mut self,
5011 symbol: &Symbol,
5012 cx: &mut ModelContext<Self>,
5013 ) -> Task<Result<Model<Buffer>>> {
5014 if self.is_local() {
5015 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
5016 symbol.source_worktree_id,
5017 symbol.language_server_name.clone(),
5018 )) {
5019 *id
5020 } else {
5021 return Task::ready(Err(anyhow!(
5022 "language server for worktree and language not found"
5023 )));
5024 };
5025
5026 let worktree_abs_path = if let Some(worktree_abs_path) = self
5027 .worktree_for_id(symbol.path.worktree_id, cx)
5028 .and_then(|worktree| worktree.read(cx).as_local())
5029 .map(|local_worktree| local_worktree.abs_path())
5030 {
5031 worktree_abs_path
5032 } else {
5033 return Task::ready(Err(anyhow!("worktree not found for symbol")));
5034 };
5035
5036 let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
5037 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
5038 uri
5039 } else {
5040 return Task::ready(Err(anyhow!("invalid symbol path")));
5041 };
5042
5043 self.open_local_buffer_via_lsp(
5044 symbol_uri,
5045 language_server_id,
5046 symbol.language_server_name.clone(),
5047 cx,
5048 )
5049 } else if let Some(project_id) = self.remote_id() {
5050 let request = self.client.request(proto::OpenBufferForSymbol {
5051 project_id,
5052 symbol: Some(serialize_symbol(symbol)),
5053 });
5054 cx.spawn(move |this, mut cx| async move {
5055 let response = request.await?;
5056 let buffer_id = BufferId::new(response.buffer_id)?;
5057 this.update(&mut cx, |this, cx| {
5058 this.wait_for_remote_buffer(buffer_id, cx)
5059 })?
5060 .await
5061 })
5062 } else {
5063 Task::ready(Err(anyhow!("project does not have a remote id")))
5064 }
5065 }
5066
5067 fn hover_impl(
5068 &self,
5069 buffer: &Model<Buffer>,
5070 position: PointUtf16,
5071 cx: &mut ModelContext<Self>,
5072 ) -> Task<Result<Option<Hover>>> {
5073 self.request_lsp(
5074 buffer.clone(),
5075 LanguageServerToQuery::Primary,
5076 GetHover { position },
5077 cx,
5078 )
5079 }
5080 pub fn hover<T: ToPointUtf16>(
5081 &self,
5082 buffer: &Model<Buffer>,
5083 position: T,
5084 cx: &mut ModelContext<Self>,
5085 ) -> Task<Result<Option<Hover>>> {
5086 let position = position.to_point_utf16(buffer.read(cx));
5087 self.hover_impl(buffer, position, cx)
5088 }
5089
5090 #[inline(never)]
5091 fn completions_impl(
5092 &self,
5093 buffer: &Model<Buffer>,
5094 position: PointUtf16,
5095 cx: &mut ModelContext<Self>,
5096 ) -> Task<Result<Vec<Completion>>> {
5097 if self.is_local() {
5098 let snapshot = buffer.read(cx).snapshot();
5099 let offset = position.to_offset(&snapshot);
5100 let scope = snapshot.language_scope_at(offset);
5101
5102 let server_ids: Vec<_> = self
5103 .language_servers_for_buffer(buffer.read(cx), cx)
5104 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5105 .filter(|(adapter, _)| {
5106 scope
5107 .as_ref()
5108 .map(|scope| scope.language_allowed(&adapter.name))
5109 .unwrap_or(true)
5110 })
5111 .map(|(_, server)| server.server_id())
5112 .collect();
5113
5114 let buffer = buffer.clone();
5115 cx.spawn(move |this, mut cx| async move {
5116 let mut tasks = Vec::with_capacity(server_ids.len());
5117 this.update(&mut cx, |this, cx| {
5118 for server_id in server_ids {
5119 tasks.push(this.request_lsp(
5120 buffer.clone(),
5121 LanguageServerToQuery::Other(server_id),
5122 GetCompletions { position },
5123 cx,
5124 ));
5125 }
5126 })?;
5127
5128 let mut completions = Vec::new();
5129 for task in tasks {
5130 if let Ok(new_completions) = task.await {
5131 completions.extend_from_slice(&new_completions);
5132 }
5133 }
5134
5135 Ok(completions)
5136 })
5137 } else if let Some(project_id) = self.remote_id() {
5138 self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
5139 } else {
5140 Task::ready(Ok(Default::default()))
5141 }
5142 }
5143 pub fn completions<T: ToOffset + ToPointUtf16>(
5144 &self,
5145 buffer: &Model<Buffer>,
5146 position: T,
5147 cx: &mut ModelContext<Self>,
5148 ) -> Task<Result<Vec<Completion>>> {
5149 let position = position.to_point_utf16(buffer.read(cx));
5150 self.completions_impl(buffer, position, cx)
5151 }
5152
5153 pub fn resolve_completions(
5154 &self,
5155 completion_indices: Vec<usize>,
5156 completions: Arc<RwLock<Box<[Completion]>>>,
5157 cx: &mut ModelContext<Self>,
5158 ) -> Task<Result<bool>> {
5159 let client = self.client();
5160 let language_registry = self.languages().clone();
5161
5162 let is_remote = self.is_remote();
5163 let project_id = self.remote_id();
5164
5165 cx.spawn(move |this, mut cx| async move {
5166 let mut did_resolve = false;
5167 if is_remote {
5168 let project_id =
5169 project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
5170
5171 for completion_index in completion_indices {
5172 let completions_guard = completions.read();
5173 let completion = &completions_guard[completion_index];
5174 if completion.documentation.is_some() {
5175 continue;
5176 }
5177
5178 did_resolve = true;
5179 let server_id = completion.server_id;
5180 let completion = completion.lsp_completion.clone();
5181 drop(completions_guard);
5182
5183 Self::resolve_completion_documentation_remote(
5184 project_id,
5185 server_id,
5186 completions.clone(),
5187 completion_index,
5188 completion,
5189 client.clone(),
5190 language_registry.clone(),
5191 )
5192 .await;
5193 }
5194 } else {
5195 for completion_index in completion_indices {
5196 let completions_guard = completions.read();
5197 let completion = &completions_guard[completion_index];
5198 if completion.documentation.is_some() {
5199 continue;
5200 }
5201
5202 let server_id = completion.server_id;
5203 let completion = completion.lsp_completion.clone();
5204 drop(completions_guard);
5205
5206 let server = this
5207 .read_with(&mut cx, |project, _| {
5208 project.language_server_for_id(server_id)
5209 })
5210 .ok()
5211 .flatten();
5212 let Some(server) = server else {
5213 continue;
5214 };
5215
5216 did_resolve = true;
5217 Self::resolve_completion_documentation_local(
5218 server,
5219 completions.clone(),
5220 completion_index,
5221 completion,
5222 language_registry.clone(),
5223 )
5224 .await;
5225 }
5226 }
5227
5228 Ok(did_resolve)
5229 })
5230 }
5231
5232 async fn resolve_completion_documentation_local(
5233 server: Arc<lsp::LanguageServer>,
5234 completions: Arc<RwLock<Box<[Completion]>>>,
5235 completion_index: usize,
5236 completion: lsp::CompletionItem,
5237 language_registry: Arc<LanguageRegistry>,
5238 ) {
5239 let can_resolve = server
5240 .capabilities()
5241 .completion_provider
5242 .as_ref()
5243 .and_then(|options| options.resolve_provider)
5244 .unwrap_or(false);
5245 if !can_resolve {
5246 return;
5247 }
5248
5249 let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
5250 let Some(completion_item) = request.await.log_err() else {
5251 return;
5252 };
5253
5254 if let Some(lsp_documentation) = completion_item.documentation {
5255 let documentation = language::prepare_completion_documentation(
5256 &lsp_documentation,
5257 &language_registry,
5258 None, // TODO: Try to reasonably work out which language the completion is for
5259 )
5260 .await;
5261
5262 let mut completions = completions.write();
5263 let completion = &mut completions[completion_index];
5264 completion.documentation = Some(documentation);
5265 } else {
5266 let mut completions = completions.write();
5267 let completion = &mut completions[completion_index];
5268 completion.documentation = Some(Documentation::Undocumented);
5269 }
5270 }
5271
5272 async fn resolve_completion_documentation_remote(
5273 project_id: u64,
5274 server_id: LanguageServerId,
5275 completions: Arc<RwLock<Box<[Completion]>>>,
5276 completion_index: usize,
5277 completion: lsp::CompletionItem,
5278 client: Arc<Client>,
5279 language_registry: Arc<LanguageRegistry>,
5280 ) {
5281 let request = proto::ResolveCompletionDocumentation {
5282 project_id,
5283 language_server_id: server_id.0 as u64,
5284 lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
5285 };
5286
5287 let Some(response) = client
5288 .request(request)
5289 .await
5290 .context("completion documentation resolve proto request")
5291 .log_err()
5292 else {
5293 return;
5294 };
5295
5296 if response.text.is_empty() {
5297 let mut completions = completions.write();
5298 let completion = &mut completions[completion_index];
5299 completion.documentation = Some(Documentation::Undocumented);
5300 }
5301
5302 let documentation = if response.is_markdown {
5303 Documentation::MultiLineMarkdown(
5304 markdown::parse_markdown(&response.text, &language_registry, None).await,
5305 )
5306 } else if response.text.lines().count() <= 1 {
5307 Documentation::SingleLine(response.text)
5308 } else {
5309 Documentation::MultiLinePlainText(response.text)
5310 };
5311
5312 let mut completions = completions.write();
5313 let completion = &mut completions[completion_index];
5314 completion.documentation = Some(documentation);
5315 }
5316
5317 pub fn apply_additional_edits_for_completion(
5318 &self,
5319 buffer_handle: Model<Buffer>,
5320 completion: Completion,
5321 push_to_history: bool,
5322 cx: &mut ModelContext<Self>,
5323 ) -> Task<Result<Option<Transaction>>> {
5324 let buffer = buffer_handle.read(cx);
5325 let buffer_id = buffer.remote_id();
5326
5327 if self.is_local() {
5328 let server_id = completion.server_id;
5329 let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
5330 Some((_, server)) => server.clone(),
5331 _ => return Task::ready(Ok(Default::default())),
5332 };
5333
5334 cx.spawn(move |this, mut cx| async move {
5335 let can_resolve = lang_server
5336 .capabilities()
5337 .completion_provider
5338 .as_ref()
5339 .and_then(|options| options.resolve_provider)
5340 .unwrap_or(false);
5341 let additional_text_edits = if can_resolve {
5342 lang_server
5343 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
5344 .await?
5345 .additional_text_edits
5346 } else {
5347 completion.lsp_completion.additional_text_edits
5348 };
5349 if let Some(edits) = additional_text_edits {
5350 let edits = this
5351 .update(&mut cx, |this, cx| {
5352 this.edits_from_lsp(
5353 &buffer_handle,
5354 edits,
5355 lang_server.server_id(),
5356 None,
5357 cx,
5358 )
5359 })?
5360 .await?;
5361
5362 buffer_handle.update(&mut cx, |buffer, cx| {
5363 buffer.finalize_last_transaction();
5364 buffer.start_transaction();
5365
5366 for (range, text) in edits {
5367 let primary = &completion.old_range;
5368 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5369 && primary.end.cmp(&range.start, buffer).is_ge();
5370 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5371 && range.end.cmp(&primary.end, buffer).is_ge();
5372
5373 //Skip additional edits which overlap with the primary completion edit
5374 //https://github.com/zed-industries/zed/pull/1871
5375 if !start_within && !end_within {
5376 buffer.edit([(range, text)], None, cx);
5377 }
5378 }
5379
5380 let transaction = if buffer.end_transaction(cx).is_some() {
5381 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5382 if !push_to_history {
5383 buffer.forget_transaction(transaction.id);
5384 }
5385 Some(transaction)
5386 } else {
5387 None
5388 };
5389 Ok(transaction)
5390 })?
5391 } else {
5392 Ok(None)
5393 }
5394 })
5395 } else if let Some(project_id) = self.remote_id() {
5396 let client = self.client.clone();
5397 cx.spawn(move |_, mut cx| async move {
5398 let response = client
5399 .request(proto::ApplyCompletionAdditionalEdits {
5400 project_id,
5401 buffer_id: buffer_id.into(),
5402 completion: Some(language::proto::serialize_completion(&completion)),
5403 })
5404 .await?;
5405
5406 if let Some(transaction) = response.transaction {
5407 let transaction = language::proto::deserialize_transaction(transaction)?;
5408 buffer_handle
5409 .update(&mut cx, |buffer, _| {
5410 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5411 })?
5412 .await?;
5413 if push_to_history {
5414 buffer_handle.update(&mut cx, |buffer, _| {
5415 buffer.push_transaction(transaction.clone(), Instant::now());
5416 })?;
5417 }
5418 Ok(Some(transaction))
5419 } else {
5420 Ok(None)
5421 }
5422 })
5423 } else {
5424 Task::ready(Err(anyhow!("project does not have a remote id")))
5425 }
5426 }
5427
5428 fn code_actions_impl(
5429 &self,
5430 buffer_handle: &Model<Buffer>,
5431 range: Range<Anchor>,
5432 cx: &mut ModelContext<Self>,
5433 ) -> Task<Result<Vec<CodeAction>>> {
5434 self.request_lsp(
5435 buffer_handle.clone(),
5436 LanguageServerToQuery::Primary,
5437 GetCodeActions { range, kinds: None },
5438 cx,
5439 )
5440 }
5441
5442 pub fn code_actions<T: Clone + ToOffset>(
5443 &self,
5444 buffer_handle: &Model<Buffer>,
5445 range: Range<T>,
5446 cx: &mut ModelContext<Self>,
5447 ) -> Task<Result<Vec<CodeAction>>> {
5448 let buffer = buffer_handle.read(cx);
5449 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5450 self.code_actions_impl(buffer_handle, range, cx)
5451 }
5452
5453 pub fn apply_code_action(
5454 &self,
5455 buffer_handle: Model<Buffer>,
5456 mut action: CodeAction,
5457 push_to_history: bool,
5458 cx: &mut ModelContext<Self>,
5459 ) -> Task<Result<ProjectTransaction>> {
5460 if self.is_local() {
5461 let buffer = buffer_handle.read(cx);
5462 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
5463 self.language_server_for_buffer(buffer, action.server_id, cx)
5464 {
5465 (adapter.clone(), server.clone())
5466 } else {
5467 return Task::ready(Ok(Default::default()));
5468 };
5469 cx.spawn(move |this, mut cx| async move {
5470 Self::try_resolve_code_action(&lang_server, &mut action)
5471 .await
5472 .context("resolving a code action")?;
5473 if let Some(edit) = action.lsp_action.edit {
5474 if edit.changes.is_some() || edit.document_changes.is_some() {
5475 return Self::deserialize_workspace_edit(
5476 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5477 edit,
5478 push_to_history,
5479 lsp_adapter.clone(),
5480 lang_server.clone(),
5481 &mut cx,
5482 )
5483 .await;
5484 }
5485 }
5486
5487 if let Some(command) = action.lsp_action.command {
5488 this.update(&mut cx, |this, _| {
5489 this.last_workspace_edits_by_language_server
5490 .remove(&lang_server.server_id());
5491 })?;
5492
5493 let result = lang_server
5494 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5495 command: command.command,
5496 arguments: command.arguments.unwrap_or_default(),
5497 ..Default::default()
5498 })
5499 .await;
5500
5501 if let Err(err) = result {
5502 // TODO: LSP ERROR
5503 return Err(err);
5504 }
5505
5506 return this.update(&mut cx, |this, _| {
5507 this.last_workspace_edits_by_language_server
5508 .remove(&lang_server.server_id())
5509 .unwrap_or_default()
5510 });
5511 }
5512
5513 Ok(ProjectTransaction::default())
5514 })
5515 } else if let Some(project_id) = self.remote_id() {
5516 let client = self.client.clone();
5517 let request = proto::ApplyCodeAction {
5518 project_id,
5519 buffer_id: buffer_handle.read(cx).remote_id().into(),
5520 action: Some(language::proto::serialize_code_action(&action)),
5521 };
5522 cx.spawn(move |this, mut cx| async move {
5523 let response = client
5524 .request(request)
5525 .await?
5526 .transaction
5527 .ok_or_else(|| anyhow!("missing transaction"))?;
5528 this.update(&mut cx, |this, cx| {
5529 this.deserialize_project_transaction(response, push_to_history, cx)
5530 })?
5531 .await
5532 })
5533 } else {
5534 Task::ready(Err(anyhow!("project does not have a remote id")))
5535 }
5536 }
5537
5538 fn apply_on_type_formatting(
5539 &self,
5540 buffer: Model<Buffer>,
5541 position: Anchor,
5542 trigger: String,
5543 cx: &mut ModelContext<Self>,
5544 ) -> Task<Result<Option<Transaction>>> {
5545 if self.is_local() {
5546 cx.spawn(move |this, mut cx| async move {
5547 // Do not allow multiple concurrent formatting requests for the
5548 // same buffer.
5549 this.update(&mut cx, |this, cx| {
5550 this.buffers_being_formatted
5551 .insert(buffer.read(cx).remote_id())
5552 })?;
5553
5554 let _cleanup = defer({
5555 let this = this.clone();
5556 let mut cx = cx.clone();
5557 let closure_buffer = buffer.clone();
5558 move || {
5559 this.update(&mut cx, |this, cx| {
5560 this.buffers_being_formatted
5561 .remove(&closure_buffer.read(cx).remote_id());
5562 })
5563 .ok();
5564 }
5565 });
5566
5567 buffer
5568 .update(&mut cx, |buffer, _| {
5569 buffer.wait_for_edits(Some(position.timestamp))
5570 })?
5571 .await?;
5572 this.update(&mut cx, |this, cx| {
5573 let position = position.to_point_utf16(buffer.read(cx));
5574 this.on_type_format(buffer, position, trigger, false, cx)
5575 })?
5576 .await
5577 })
5578 } else if let Some(project_id) = self.remote_id() {
5579 let client = self.client.clone();
5580 let request = proto::OnTypeFormatting {
5581 project_id,
5582 buffer_id: buffer.read(cx).remote_id().into(),
5583 position: Some(serialize_anchor(&position)),
5584 trigger,
5585 version: serialize_version(&buffer.read(cx).version()),
5586 };
5587 cx.spawn(move |_, _| async move {
5588 client
5589 .request(request)
5590 .await?
5591 .transaction
5592 .map(language::proto::deserialize_transaction)
5593 .transpose()
5594 })
5595 } else {
5596 Task::ready(Err(anyhow!("project does not have a remote id")))
5597 }
5598 }
5599
5600 async fn deserialize_edits(
5601 this: Model<Self>,
5602 buffer_to_edit: Model<Buffer>,
5603 edits: Vec<lsp::TextEdit>,
5604 push_to_history: bool,
5605 _: Arc<CachedLspAdapter>,
5606 language_server: Arc<LanguageServer>,
5607 cx: &mut AsyncAppContext,
5608 ) -> Result<Option<Transaction>> {
5609 let edits = this
5610 .update(cx, |this, cx| {
5611 this.edits_from_lsp(
5612 &buffer_to_edit,
5613 edits,
5614 language_server.server_id(),
5615 None,
5616 cx,
5617 )
5618 })?
5619 .await?;
5620
5621 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5622 buffer.finalize_last_transaction();
5623 buffer.start_transaction();
5624 for (range, text) in edits {
5625 buffer.edit([(range, text)], None, cx);
5626 }
5627
5628 if buffer.end_transaction(cx).is_some() {
5629 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5630 if !push_to_history {
5631 buffer.forget_transaction(transaction.id);
5632 }
5633 Some(transaction)
5634 } else {
5635 None
5636 }
5637 })?;
5638
5639 Ok(transaction)
5640 }
5641
5642 async fn deserialize_workspace_edit(
5643 this: Model<Self>,
5644 edit: lsp::WorkspaceEdit,
5645 push_to_history: bool,
5646 lsp_adapter: Arc<CachedLspAdapter>,
5647 language_server: Arc<LanguageServer>,
5648 cx: &mut AsyncAppContext,
5649 ) -> Result<ProjectTransaction> {
5650 let fs = this.update(cx, |this, _| this.fs.clone())?;
5651 let mut operations = Vec::new();
5652 if let Some(document_changes) = edit.document_changes {
5653 match document_changes {
5654 lsp::DocumentChanges::Edits(edits) => {
5655 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5656 }
5657 lsp::DocumentChanges::Operations(ops) => operations = ops,
5658 }
5659 } else if let Some(changes) = edit.changes {
5660 operations.extend(changes.into_iter().map(|(uri, edits)| {
5661 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5662 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5663 uri,
5664 version: None,
5665 },
5666 edits: edits.into_iter().map(OneOf::Left).collect(),
5667 })
5668 }));
5669 }
5670
5671 let mut project_transaction = ProjectTransaction::default();
5672 for operation in operations {
5673 match operation {
5674 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5675 let abs_path = op
5676 .uri
5677 .to_file_path()
5678 .map_err(|_| anyhow!("can't convert URI to path"))?;
5679
5680 if let Some(parent_path) = abs_path.parent() {
5681 fs.create_dir(parent_path).await?;
5682 }
5683 if abs_path.ends_with("/") {
5684 fs.create_dir(&abs_path).await?;
5685 } else {
5686 fs.create_file(
5687 &abs_path,
5688 op.options
5689 .map(|options| fs::CreateOptions {
5690 overwrite: options.overwrite.unwrap_or(false),
5691 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5692 })
5693 .unwrap_or_default(),
5694 )
5695 .await?;
5696 }
5697 }
5698
5699 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5700 let source_abs_path = op
5701 .old_uri
5702 .to_file_path()
5703 .map_err(|_| anyhow!("can't convert URI to path"))?;
5704 let target_abs_path = op
5705 .new_uri
5706 .to_file_path()
5707 .map_err(|_| anyhow!("can't convert URI to path"))?;
5708 fs.rename(
5709 &source_abs_path,
5710 &target_abs_path,
5711 op.options
5712 .map(|options| fs::RenameOptions {
5713 overwrite: options.overwrite.unwrap_or(false),
5714 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5715 })
5716 .unwrap_or_default(),
5717 )
5718 .await?;
5719 }
5720
5721 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5722 let abs_path = op
5723 .uri
5724 .to_file_path()
5725 .map_err(|_| anyhow!("can't convert URI to path"))?;
5726 let options = op
5727 .options
5728 .map(|options| fs::RemoveOptions {
5729 recursive: options.recursive.unwrap_or(false),
5730 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5731 })
5732 .unwrap_or_default();
5733 if abs_path.ends_with("/") {
5734 fs.remove_dir(&abs_path, options).await?;
5735 } else {
5736 fs.remove_file(&abs_path, options).await?;
5737 }
5738 }
5739
5740 lsp::DocumentChangeOperation::Edit(op) => {
5741 let buffer_to_edit = this
5742 .update(cx, |this, cx| {
5743 this.open_local_buffer_via_lsp(
5744 op.text_document.uri,
5745 language_server.server_id(),
5746 lsp_adapter.name.clone(),
5747 cx,
5748 )
5749 })?
5750 .await?;
5751
5752 let edits = this
5753 .update(cx, |this, cx| {
5754 let edits = op.edits.into_iter().map(|edit| match edit {
5755 OneOf::Left(edit) => edit,
5756 OneOf::Right(edit) => edit.text_edit,
5757 });
5758 this.edits_from_lsp(
5759 &buffer_to_edit,
5760 edits,
5761 language_server.server_id(),
5762 op.text_document.version,
5763 cx,
5764 )
5765 })?
5766 .await?;
5767
5768 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5769 buffer.finalize_last_transaction();
5770 buffer.start_transaction();
5771 for (range, text) in edits {
5772 buffer.edit([(range, text)], None, cx);
5773 }
5774 let transaction = if buffer.end_transaction(cx).is_some() {
5775 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5776 if !push_to_history {
5777 buffer.forget_transaction(transaction.id);
5778 }
5779 Some(transaction)
5780 } else {
5781 None
5782 };
5783
5784 transaction
5785 })?;
5786 if let Some(transaction) = transaction {
5787 project_transaction.0.insert(buffer_to_edit, transaction);
5788 }
5789 }
5790 }
5791 }
5792
5793 Ok(project_transaction)
5794 }
5795
5796 fn prepare_rename_impl(
5797 &self,
5798 buffer: Model<Buffer>,
5799 position: PointUtf16,
5800 cx: &mut ModelContext<Self>,
5801 ) -> Task<Result<Option<Range<Anchor>>>> {
5802 self.request_lsp(
5803 buffer,
5804 LanguageServerToQuery::Primary,
5805 PrepareRename { position },
5806 cx,
5807 )
5808 }
5809 pub fn prepare_rename<T: ToPointUtf16>(
5810 &self,
5811 buffer: Model<Buffer>,
5812 position: T,
5813 cx: &mut ModelContext<Self>,
5814 ) -> Task<Result<Option<Range<Anchor>>>> {
5815 let position = position.to_point_utf16(buffer.read(cx));
5816 self.prepare_rename_impl(buffer, position, cx)
5817 }
5818
5819 fn perform_rename_impl(
5820 &self,
5821 buffer: Model<Buffer>,
5822 position: PointUtf16,
5823 new_name: String,
5824 push_to_history: bool,
5825 cx: &mut ModelContext<Self>,
5826 ) -> Task<Result<ProjectTransaction>> {
5827 let position = position.to_point_utf16(buffer.read(cx));
5828 self.request_lsp(
5829 buffer,
5830 LanguageServerToQuery::Primary,
5831 PerformRename {
5832 position,
5833 new_name,
5834 push_to_history,
5835 },
5836 cx,
5837 )
5838 }
5839 pub fn perform_rename<T: ToPointUtf16>(
5840 &self,
5841 buffer: Model<Buffer>,
5842 position: T,
5843 new_name: String,
5844 push_to_history: bool,
5845 cx: &mut ModelContext<Self>,
5846 ) -> Task<Result<ProjectTransaction>> {
5847 let position = position.to_point_utf16(buffer.read(cx));
5848 self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
5849 }
5850
5851 pub fn on_type_format_impl(
5852 &self,
5853 buffer: Model<Buffer>,
5854 position: PointUtf16,
5855 trigger: String,
5856 push_to_history: bool,
5857 cx: &mut ModelContext<Self>,
5858 ) -> Task<Result<Option<Transaction>>> {
5859 let tab_size = buffer.update(cx, |buffer, cx| {
5860 language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
5861 });
5862 self.request_lsp(
5863 buffer.clone(),
5864 LanguageServerToQuery::Primary,
5865 OnTypeFormatting {
5866 position,
5867 trigger,
5868 options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5869 push_to_history,
5870 },
5871 cx,
5872 )
5873 }
5874
5875 pub fn on_type_format<T: ToPointUtf16>(
5876 &self,
5877 buffer: Model<Buffer>,
5878 position: T,
5879 trigger: String,
5880 push_to_history: bool,
5881 cx: &mut ModelContext<Self>,
5882 ) -> Task<Result<Option<Transaction>>> {
5883 let position = position.to_point_utf16(buffer.read(cx));
5884 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5885 }
5886
5887 pub fn inlay_hints<T: ToOffset>(
5888 &self,
5889 buffer_handle: Model<Buffer>,
5890 range: Range<T>,
5891 cx: &mut ModelContext<Self>,
5892 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5893 let buffer = buffer_handle.read(cx);
5894 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5895 self.inlay_hints_impl(buffer_handle, range, cx)
5896 }
5897 fn inlay_hints_impl(
5898 &self,
5899 buffer_handle: Model<Buffer>,
5900 range: Range<Anchor>,
5901 cx: &mut ModelContext<Self>,
5902 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5903 let buffer = buffer_handle.read(cx);
5904 let range_start = range.start;
5905 let range_end = range.end;
5906 let buffer_id = buffer.remote_id().into();
5907 let lsp_request = InlayHints { range };
5908
5909 if self.is_local() {
5910 let lsp_request_task = self.request_lsp(
5911 buffer_handle.clone(),
5912 LanguageServerToQuery::Primary,
5913 lsp_request,
5914 cx,
5915 );
5916 cx.spawn(move |_, mut cx| async move {
5917 buffer_handle
5918 .update(&mut cx, |buffer, _| {
5919 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5920 })?
5921 .await
5922 .context("waiting for inlay hint request range edits")?;
5923 lsp_request_task.await.context("inlay hints LSP request")
5924 })
5925 } else if let Some(project_id) = self.remote_id() {
5926 let client = self.client.clone();
5927 let request = proto::InlayHints {
5928 project_id,
5929 buffer_id,
5930 start: Some(serialize_anchor(&range_start)),
5931 end: Some(serialize_anchor(&range_end)),
5932 version: serialize_version(&buffer_handle.read(cx).version()),
5933 };
5934 cx.spawn(move |project, cx| async move {
5935 let response = client
5936 .request(request)
5937 .await
5938 .context("inlay hints proto request")?;
5939 LspCommand::response_from_proto(
5940 lsp_request,
5941 response,
5942 project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5943 buffer_handle.clone(),
5944 cx.clone(),
5945 )
5946 .await
5947 .context("inlay hints proto response conversion")
5948 })
5949 } else {
5950 Task::ready(Err(anyhow!("project does not have a remote id")))
5951 }
5952 }
5953
5954 pub fn resolve_inlay_hint(
5955 &self,
5956 hint: InlayHint,
5957 buffer_handle: Model<Buffer>,
5958 server_id: LanguageServerId,
5959 cx: &mut ModelContext<Self>,
5960 ) -> Task<anyhow::Result<InlayHint>> {
5961 if self.is_local() {
5962 let buffer = buffer_handle.read(cx);
5963 let (_, lang_server) = if let Some((adapter, server)) =
5964 self.language_server_for_buffer(buffer, server_id, cx)
5965 {
5966 (adapter.clone(), server.clone())
5967 } else {
5968 return Task::ready(Ok(hint));
5969 };
5970 if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5971 return Task::ready(Ok(hint));
5972 }
5973
5974 let buffer_snapshot = buffer.snapshot();
5975 cx.spawn(move |_, mut cx| async move {
5976 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5977 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5978 );
5979 let resolved_hint = resolve_task
5980 .await
5981 .context("inlay hint resolve LSP request")?;
5982 let resolved_hint = InlayHints::lsp_to_project_hint(
5983 resolved_hint,
5984 &buffer_handle,
5985 server_id,
5986 ResolveState::Resolved,
5987 false,
5988 &mut cx,
5989 )
5990 .await?;
5991 Ok(resolved_hint)
5992 })
5993 } else if let Some(project_id) = self.remote_id() {
5994 let client = self.client.clone();
5995 let request = proto::ResolveInlayHint {
5996 project_id,
5997 buffer_id: buffer_handle.read(cx).remote_id().into(),
5998 language_server_id: server_id.0 as u64,
5999 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
6000 };
6001 cx.spawn(move |_, _| async move {
6002 let response = client
6003 .request(request)
6004 .await
6005 .context("inlay hints proto request")?;
6006 match response.hint {
6007 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
6008 .context("inlay hints proto resolve response conversion"),
6009 None => Ok(hint),
6010 }
6011 })
6012 } else {
6013 Task::ready(Err(anyhow!("project does not have a remote id")))
6014 }
6015 }
6016
6017 #[allow(clippy::type_complexity)]
6018 pub fn search(
6019 &self,
6020 query: SearchQuery,
6021 cx: &mut ModelContext<Self>,
6022 ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
6023 if self.is_local() {
6024 self.search_local(query, cx)
6025 } else if let Some(project_id) = self.remote_id() {
6026 let (tx, rx) = smol::channel::unbounded();
6027 let request = self.client.request(query.to_proto(project_id));
6028 cx.spawn(move |this, mut cx| async move {
6029 let response = request.await?;
6030 let mut result = HashMap::default();
6031 for location in response.locations {
6032 let buffer_id = BufferId::new(location.buffer_id)?;
6033 let target_buffer = this
6034 .update(&mut cx, |this, cx| {
6035 this.wait_for_remote_buffer(buffer_id, cx)
6036 })?
6037 .await?;
6038 let start = location
6039 .start
6040 .and_then(deserialize_anchor)
6041 .ok_or_else(|| anyhow!("missing target start"))?;
6042 let end = location
6043 .end
6044 .and_then(deserialize_anchor)
6045 .ok_or_else(|| anyhow!("missing target end"))?;
6046 result
6047 .entry(target_buffer)
6048 .or_insert(Vec::new())
6049 .push(start..end)
6050 }
6051 for (buffer, ranges) in result {
6052 let _ = tx.send((buffer, ranges)).await;
6053 }
6054 Result::<(), anyhow::Error>::Ok(())
6055 })
6056 .detach_and_log_err(cx);
6057 rx
6058 } else {
6059 unimplemented!();
6060 }
6061 }
6062
6063 pub fn search_local(
6064 &self,
6065 query: SearchQuery,
6066 cx: &mut ModelContext<Self>,
6067 ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
6068 // Local search is split into several phases.
6069 // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
6070 // and the second phase that finds positions of all the matches found in the candidate files.
6071 // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
6072 //
6073 // It gets a bit hairy though, because we must account for files that do not have a persistent representation
6074 // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
6075 //
6076 // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
6077 // Then, we go through a worktree and check for files that do match a predicate. If the file had an opened version, we skip the scan
6078 // of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
6079 // 2. At this point, we have a list of all potentially matching buffers/files.
6080 // We sort that list by buffer path - this list is retained for later use.
6081 // We ensure that all buffers are now opened and available in project.
6082 // 3. We run a scan over all the candidate buffers on multiple background threads.
6083 // We cannot assume that there will even be a match - while at least one match
6084 // is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
6085 // There is also an auxiliary background thread responsible for result gathering.
6086 // This is where the sorted list of buffers comes into play to maintain sorted order; Whenever this background thread receives a notification (buffer has/doesn't have matches),
6087 // it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
6088 // As soon as the match info on next position in sorted order becomes available, it reports it (if it's a match) or skips to the next
6089 // entry - which might already be available thanks to out-of-order processing.
6090 //
6091 // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
6092 // This however would mean that project search (that is the main user of this function) would have to do the sorting itself, on the go.
6093 // This isn't as straightforward as running an insertion sort sadly, and would also mean that it would have to care about maintaining match index
6094 // in face of constantly updating list of sorted matches.
6095 // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
6096 let snapshots = self
6097 .visible_worktrees(cx)
6098 .filter_map(|tree| {
6099 let tree = tree.read(cx).as_local()?;
6100 Some(tree.snapshot())
6101 })
6102 .collect::<Vec<_>>();
6103
6104 let background = cx.background_executor().clone();
6105 let path_count: usize = snapshots
6106 .iter()
6107 .map(|s| {
6108 if query.include_ignored() {
6109 s.file_count()
6110 } else {
6111 s.visible_file_count()
6112 }
6113 })
6114 .sum();
6115 if path_count == 0 {
6116 let (_, rx) = smol::channel::bounded(1024);
6117 return rx;
6118 }
6119 let workers = background.num_cpus().min(path_count);
6120 let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
6121 let mut unnamed_files = vec![];
6122 let opened_buffers = self
6123 .opened_buffers
6124 .iter()
6125 .filter_map(|(_, b)| {
6126 let buffer = b.upgrade()?;
6127 let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
6128 let is_ignored = buffer
6129 .project_path(cx)
6130 .and_then(|path| self.entry_for_path(&path, cx))
6131 .map_or(false, |entry| entry.is_ignored);
6132 (is_ignored, buffer.snapshot())
6133 });
6134 if is_ignored && !query.include_ignored() {
6135 return None;
6136 } else if let Some(path) = snapshot.file().map(|file| file.path()) {
6137 Some((path.clone(), (buffer, snapshot)))
6138 } else {
6139 unnamed_files.push(buffer);
6140 None
6141 }
6142 })
6143 .collect();
6144 cx.background_executor()
6145 .spawn(Self::background_search(
6146 unnamed_files,
6147 opened_buffers,
6148 cx.background_executor().clone(),
6149 self.fs.clone(),
6150 workers,
6151 query.clone(),
6152 path_count,
6153 snapshots,
6154 matching_paths_tx,
6155 ))
6156 .detach();
6157
6158 let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
6159 let background = cx.background_executor().clone();
6160 let (result_tx, result_rx) = smol::channel::bounded(1024);
6161 cx.background_executor()
6162 .spawn(async move {
6163 let Ok(buffers) = buffers.await else {
6164 return;
6165 };
6166
6167 let buffers_len = buffers.len();
6168 if buffers_len == 0 {
6169 return;
6170 }
6171 let query = &query;
6172 let (finished_tx, mut finished_rx) = smol::channel::unbounded();
6173 background
6174 .scoped(|scope| {
6175 #[derive(Clone)]
6176 struct FinishedStatus {
6177 entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
6178 buffer_index: SearchMatchCandidateIndex,
6179 }
6180
6181 for _ in 0..workers {
6182 let finished_tx = finished_tx.clone();
6183 let mut buffers_rx = buffers_rx.clone();
6184 scope.spawn(async move {
6185 while let Some((entry, buffer_index)) = buffers_rx.next().await {
6186 let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
6187 {
6188 if query.file_matches(
6189 snapshot.file().map(|file| file.path().as_ref()),
6190 ) {
6191 query
6192 .search(snapshot, None)
6193 .await
6194 .iter()
6195 .map(|range| {
6196 snapshot.anchor_before(range.start)
6197 ..snapshot.anchor_after(range.end)
6198 })
6199 .collect()
6200 } else {
6201 Vec::new()
6202 }
6203 } else {
6204 Vec::new()
6205 };
6206
6207 let status = if !buffer_matches.is_empty() {
6208 let entry = if let Some((buffer, _)) = entry.as_ref() {
6209 Some((buffer.clone(), buffer_matches))
6210 } else {
6211 None
6212 };
6213 FinishedStatus {
6214 entry,
6215 buffer_index,
6216 }
6217 } else {
6218 FinishedStatus {
6219 entry: None,
6220 buffer_index,
6221 }
6222 };
6223 if finished_tx.send(status).await.is_err() {
6224 break;
6225 }
6226 }
6227 });
6228 }
6229 // Report sorted matches
6230 scope.spawn(async move {
6231 let mut current_index = 0;
6232 let mut scratch = vec![None; buffers_len];
6233 while let Some(status) = finished_rx.next().await {
6234 debug_assert!(
6235 scratch[status.buffer_index].is_none(),
6236 "Got match status of position {} twice",
6237 status.buffer_index
6238 );
6239 let index = status.buffer_index;
6240 scratch[index] = Some(status);
6241 while current_index < buffers_len {
6242 let Some(current_entry) = scratch[current_index].take() else {
6243 // We intentionally **do not** increment `current_index` here. When next element arrives
6244 // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
6245 // this time.
6246 break;
6247 };
6248 if let Some(entry) = current_entry.entry {
6249 result_tx.send(entry).await.log_err();
6250 }
6251 current_index += 1;
6252 }
6253 if current_index == buffers_len {
6254 break;
6255 }
6256 }
6257 });
6258 })
6259 .await;
6260 })
6261 .detach();
6262 result_rx
6263 }
6264
6265 /// Pick paths that might potentially contain a match of a given search query.
6266 #[allow(clippy::too_many_arguments)]
6267 async fn background_search(
6268 unnamed_buffers: Vec<Model<Buffer>>,
6269 opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
6270 executor: BackgroundExecutor,
6271 fs: Arc<dyn Fs>,
6272 workers: usize,
6273 query: SearchQuery,
6274 path_count: usize,
6275 snapshots: Vec<LocalSnapshot>,
6276 matching_paths_tx: Sender<SearchMatchCandidate>,
6277 ) {
6278 let fs = &fs;
6279 let query = &query;
6280 let matching_paths_tx = &matching_paths_tx;
6281 let snapshots = &snapshots;
6282 let paths_per_worker = (path_count + workers - 1) / workers;
6283 for buffer in unnamed_buffers {
6284 matching_paths_tx
6285 .send(SearchMatchCandidate::OpenBuffer {
6286 buffer: buffer.clone(),
6287 path: None,
6288 })
6289 .await
6290 .log_err();
6291 }
6292 for (path, (buffer, _)) in opened_buffers.iter() {
6293 matching_paths_tx
6294 .send(SearchMatchCandidate::OpenBuffer {
6295 buffer: buffer.clone(),
6296 path: Some(path.clone()),
6297 })
6298 .await
6299 .log_err();
6300 }
6301 executor
6302 .scoped(|scope| {
6303 let max_concurrent_workers = Arc::new(Semaphore::new(workers));
6304
6305 for worker_ix in 0..workers {
6306 let worker_start_ix = worker_ix * paths_per_worker;
6307 let worker_end_ix = worker_start_ix + paths_per_worker;
6308 let unnamed_buffers = opened_buffers.clone();
6309 let limiter = Arc::clone(&max_concurrent_workers);
6310 scope.spawn(async move {
6311 let _guard = limiter.acquire().await;
6312 let mut snapshot_start_ix = 0;
6313 let mut abs_path = PathBuf::new();
6314 for snapshot in snapshots {
6315 let snapshot_end_ix = snapshot_start_ix
6316 + if query.include_ignored() {
6317 snapshot.file_count()
6318 } else {
6319 snapshot.visible_file_count()
6320 };
6321 if worker_end_ix <= snapshot_start_ix {
6322 break;
6323 } else if worker_start_ix > snapshot_end_ix {
6324 snapshot_start_ix = snapshot_end_ix;
6325 continue;
6326 } else {
6327 let start_in_snapshot =
6328 worker_start_ix.saturating_sub(snapshot_start_ix);
6329 let end_in_snapshot =
6330 cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
6331
6332 for entry in snapshot
6333 .files(query.include_ignored(), start_in_snapshot)
6334 .take(end_in_snapshot - start_in_snapshot)
6335 {
6336 if matching_paths_tx.is_closed() {
6337 break;
6338 }
6339 if unnamed_buffers.contains_key(&entry.path) {
6340 continue;
6341 }
6342 let matches = if query.file_matches(Some(&entry.path)) {
6343 abs_path.clear();
6344 abs_path.push(&snapshot.abs_path());
6345 abs_path.push(&entry.path);
6346 if let Some(file) = fs.open_sync(&abs_path).await.log_err()
6347 {
6348 query.detect(file).unwrap_or(false)
6349 } else {
6350 false
6351 }
6352 } else {
6353 false
6354 };
6355
6356 if matches {
6357 let project_path = SearchMatchCandidate::Path {
6358 worktree_id: snapshot.id(),
6359 path: entry.path.clone(),
6360 is_ignored: entry.is_ignored,
6361 };
6362 if matching_paths_tx.send(project_path).await.is_err() {
6363 break;
6364 }
6365 }
6366 }
6367
6368 snapshot_start_ix = snapshot_end_ix;
6369 }
6370 }
6371 });
6372 }
6373
6374 if query.include_ignored() {
6375 for snapshot in snapshots {
6376 for ignored_entry in snapshot
6377 .entries(query.include_ignored())
6378 .filter(|e| e.is_ignored)
6379 {
6380 let limiter = Arc::clone(&max_concurrent_workers);
6381 scope.spawn(async move {
6382 let _guard = limiter.acquire().await;
6383 let mut ignored_paths_to_process =
6384 VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
6385 while let Some(ignored_abs_path) =
6386 ignored_paths_to_process.pop_front()
6387 {
6388 if let Some(fs_metadata) = fs
6389 .metadata(&ignored_abs_path)
6390 .await
6391 .with_context(|| {
6392 format!("fetching fs metadata for {ignored_abs_path:?}")
6393 })
6394 .log_err()
6395 .flatten()
6396 {
6397 if fs_metadata.is_dir {
6398 if let Some(mut subfiles) = fs
6399 .read_dir(&ignored_abs_path)
6400 .await
6401 .with_context(|| {
6402 format!(
6403 "listing ignored path {ignored_abs_path:?}"
6404 )
6405 })
6406 .log_err()
6407 {
6408 while let Some(subfile) = subfiles.next().await {
6409 if let Some(subfile) = subfile.log_err() {
6410 ignored_paths_to_process.push_back(subfile);
6411 }
6412 }
6413 }
6414 } else if !fs_metadata.is_symlink {
6415 if !query.file_matches(Some(&ignored_abs_path))
6416 || snapshot.is_path_excluded(
6417 ignored_entry.path.to_path_buf(),
6418 )
6419 {
6420 continue;
6421 }
6422 let matches = if let Some(file) = fs
6423 .open_sync(&ignored_abs_path)
6424 .await
6425 .with_context(|| {
6426 format!(
6427 "Opening ignored path {ignored_abs_path:?}"
6428 )
6429 })
6430 .log_err()
6431 {
6432 query.detect(file).unwrap_or(false)
6433 } else {
6434 false
6435 };
6436 if matches {
6437 let project_path = SearchMatchCandidate::Path {
6438 worktree_id: snapshot.id(),
6439 path: Arc::from(
6440 ignored_abs_path
6441 .strip_prefix(snapshot.abs_path())
6442 .expect(
6443 "scanning worktree-related files",
6444 ),
6445 ),
6446 is_ignored: true,
6447 };
6448 if matching_paths_tx
6449 .send(project_path)
6450 .await
6451 .is_err()
6452 {
6453 return;
6454 }
6455 }
6456 }
6457 }
6458 }
6459 });
6460 }
6461 }
6462 }
6463 })
6464 .await;
6465 }
6466
6467 pub fn request_lsp<R: LspCommand>(
6468 &self,
6469 buffer_handle: Model<Buffer>,
6470 server: LanguageServerToQuery,
6471 request: R,
6472 cx: &mut ModelContext<Self>,
6473 ) -> Task<Result<R::Response>>
6474 where
6475 <R::LspRequest as lsp::request::Request>::Result: Send,
6476 <R::LspRequest as lsp::request::Request>::Params: Send,
6477 {
6478 let buffer = buffer_handle.read(cx);
6479 if self.is_local() {
6480 let language_server = match server {
6481 LanguageServerToQuery::Primary => {
6482 match self.primary_language_server_for_buffer(buffer, cx) {
6483 Some((_, server)) => Some(Arc::clone(server)),
6484 None => return Task::ready(Ok(Default::default())),
6485 }
6486 }
6487 LanguageServerToQuery::Other(id) => self
6488 .language_server_for_buffer(buffer, id, cx)
6489 .map(|(_, server)| Arc::clone(server)),
6490 };
6491 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
6492 if let (Some(file), Some(language_server)) = (file, language_server) {
6493 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
6494 return cx.spawn(move |this, cx| async move {
6495 if !request.check_capabilities(language_server.capabilities()) {
6496 return Ok(Default::default());
6497 }
6498
6499 let result = language_server.request::<R::LspRequest>(lsp_params).await;
6500 let response = match result {
6501 Ok(response) => response,
6502
6503 Err(err) => {
6504 log::warn!(
6505 "Generic lsp request to {} failed: {}",
6506 language_server.name(),
6507 err
6508 );
6509 return Err(err);
6510 }
6511 };
6512
6513 request
6514 .response_from_lsp(
6515 response,
6516 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6517 buffer_handle,
6518 language_server.server_id(),
6519 cx,
6520 )
6521 .await
6522 });
6523 }
6524 } else if let Some(project_id) = self.remote_id() {
6525 return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6526 }
6527
6528 Task::ready(Ok(Default::default()))
6529 }
6530
6531 fn send_lsp_proto_request<R: LspCommand>(
6532 &self,
6533 buffer: Model<Buffer>,
6534 project_id: u64,
6535 request: R,
6536 cx: &mut ModelContext<'_, Project>,
6537 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6538 let rpc = self.client.clone();
6539 let message = request.to_proto(project_id, buffer.read(cx));
6540 cx.spawn(move |this, mut cx| async move {
6541 // Ensure the project is still alive by the time the task
6542 // is scheduled.
6543 this.upgrade().context("project dropped")?;
6544 let response = rpc.request(message).await?;
6545 let this = this.upgrade().context("project dropped")?;
6546 if this.update(&mut cx, |this, _| this.is_disconnected())? {
6547 Err(anyhow!("disconnected before completing request"))
6548 } else {
6549 request
6550 .response_from_proto(response, this, buffer, cx)
6551 .await
6552 }
6553 })
6554 }
6555
6556 fn sort_candidates_and_open_buffers(
6557 mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6558 cx: &mut ModelContext<Self>,
6559 ) -> (
6560 futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6561 Receiver<(
6562 Option<(Model<Buffer>, BufferSnapshot)>,
6563 SearchMatchCandidateIndex,
6564 )>,
6565 ) {
6566 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6567 let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6568 cx.spawn(move |this, cx| async move {
6569 let mut buffers = Vec::new();
6570 let mut ignored_buffers = Vec::new();
6571 while let Some(entry) = matching_paths_rx.next().await {
6572 if matches!(
6573 entry,
6574 SearchMatchCandidate::Path {
6575 is_ignored: true,
6576 ..
6577 }
6578 ) {
6579 ignored_buffers.push(entry);
6580 } else {
6581 buffers.push(entry);
6582 }
6583 }
6584 buffers.sort_by_key(|candidate| candidate.path());
6585 ignored_buffers.sort_by_key(|candidate| candidate.path());
6586 buffers.extend(ignored_buffers);
6587 let matching_paths = buffers.clone();
6588 let _ = sorted_buffers_tx.send(buffers);
6589 for (index, candidate) in matching_paths.into_iter().enumerate() {
6590 if buffers_tx.is_closed() {
6591 break;
6592 }
6593 let this = this.clone();
6594 let buffers_tx = buffers_tx.clone();
6595 cx.spawn(move |mut cx| async move {
6596 let buffer = match candidate {
6597 SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6598 SearchMatchCandidate::Path {
6599 worktree_id, path, ..
6600 } => this
6601 .update(&mut cx, |this, cx| {
6602 this.open_buffer((worktree_id, path), cx)
6603 })?
6604 .await
6605 .log_err(),
6606 };
6607 if let Some(buffer) = buffer {
6608 let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6609 buffers_tx
6610 .send((Some((buffer, snapshot)), index))
6611 .await
6612 .log_err();
6613 } else {
6614 buffers_tx.send((None, index)).await.log_err();
6615 }
6616
6617 Ok::<_, anyhow::Error>(())
6618 })
6619 .detach();
6620 }
6621 })
6622 .detach();
6623 (sorted_buffers_rx, buffers_rx)
6624 }
6625
6626 pub fn find_or_create_local_worktree(
6627 &mut self,
6628 abs_path: impl AsRef<Path>,
6629 visible: bool,
6630 cx: &mut ModelContext<Self>,
6631 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6632 let abs_path = abs_path.as_ref();
6633 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6634 Task::ready(Ok((tree, relative_path)))
6635 } else {
6636 let worktree = self.create_local_worktree(abs_path, visible, cx);
6637 cx.background_executor()
6638 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6639 }
6640 }
6641
6642 pub fn find_local_worktree(
6643 &self,
6644 abs_path: &Path,
6645 cx: &AppContext,
6646 ) -> Option<(Model<Worktree>, PathBuf)> {
6647 for tree in &self.worktrees {
6648 if let Some(tree) = tree.upgrade() {
6649 if let Some(relative_path) = tree
6650 .read(cx)
6651 .as_local()
6652 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6653 {
6654 return Some((tree.clone(), relative_path.into()));
6655 }
6656 }
6657 }
6658 None
6659 }
6660
6661 pub fn is_shared(&self) -> bool {
6662 match &self.client_state {
6663 ProjectClientState::Shared { .. } => true,
6664 ProjectClientState::Local | ProjectClientState::Remote { .. } => false,
6665 }
6666 }
6667
6668 fn create_local_worktree(
6669 &mut self,
6670 abs_path: impl AsRef<Path>,
6671 visible: bool,
6672 cx: &mut ModelContext<Self>,
6673 ) -> Task<Result<Model<Worktree>>> {
6674 let fs = self.fs.clone();
6675 let client = self.client.clone();
6676 let next_entry_id = self.next_entry_id.clone();
6677 let path: Arc<Path> = abs_path.as_ref().into();
6678 let task = self
6679 .loading_local_worktrees
6680 .entry(path.clone())
6681 .or_insert_with(|| {
6682 cx.spawn(move |project, mut cx| {
6683 async move {
6684 let worktree = Worktree::local(
6685 client.clone(),
6686 path.clone(),
6687 visible,
6688 fs,
6689 next_entry_id,
6690 &mut cx,
6691 )
6692 .await;
6693
6694 project.update(&mut cx, |project, _| {
6695 project.loading_local_worktrees.remove(&path);
6696 })?;
6697
6698 let worktree = worktree?;
6699 project
6700 .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6701 Ok(worktree)
6702 }
6703 .map_err(Arc::new)
6704 })
6705 .shared()
6706 })
6707 .clone();
6708 cx.background_executor().spawn(async move {
6709 match task.await {
6710 Ok(worktree) => Ok(worktree),
6711 Err(err) => Err(anyhow!("{}", err)),
6712 }
6713 })
6714 }
6715
6716 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6717 let mut servers_to_remove = HashMap::default();
6718 let mut servers_to_preserve = HashSet::default();
6719 for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
6720 if worktree_id == &id_to_remove {
6721 servers_to_remove.insert(server_id, server_name.clone());
6722 } else {
6723 servers_to_preserve.insert(server_id);
6724 }
6725 }
6726 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
6727 for (server_id_to_remove, server_name) in servers_to_remove {
6728 self.language_server_ids
6729 .remove(&(id_to_remove, server_name));
6730 self.language_server_statuses.remove(&server_id_to_remove);
6731 self.language_server_watched_paths
6732 .remove(&server_id_to_remove);
6733 self.last_workspace_edits_by_language_server
6734 .remove(&server_id_to_remove);
6735 self.language_servers.remove(&server_id_to_remove);
6736 cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
6737 }
6738
6739 let mut prettier_instances_to_clean = FuturesUnordered::new();
6740 if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
6741 for path in prettier_paths.iter().flatten() {
6742 if let Some(prettier_instance) = self.prettier_instances.remove(path) {
6743 prettier_instances_to_clean.push(async move {
6744 prettier_instance
6745 .server()
6746 .await
6747 .map(|server| server.server_id())
6748 });
6749 }
6750 }
6751 }
6752 cx.spawn(|project, mut cx| async move {
6753 while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
6754 if let Some(prettier_server_id) = prettier_server_id {
6755 project
6756 .update(&mut cx, |project, cx| {
6757 project
6758 .supplementary_language_servers
6759 .remove(&prettier_server_id);
6760 cx.emit(Event::LanguageServerRemoved(prettier_server_id));
6761 })
6762 .ok();
6763 }
6764 }
6765 })
6766 .detach();
6767
6768 self.task_inventory().update(cx, |inventory, _| {
6769 inventory.remove_worktree_sources(id_to_remove);
6770 });
6771
6772 self.worktrees.retain(|worktree| {
6773 if let Some(worktree) = worktree.upgrade() {
6774 let id = worktree.read(cx).id();
6775 if id == id_to_remove {
6776 cx.emit(Event::WorktreeRemoved(id));
6777 false
6778 } else {
6779 true
6780 }
6781 } else {
6782 false
6783 }
6784 });
6785 self.metadata_changed(cx);
6786 }
6787
6788 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6789 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6790 cx.subscribe(worktree, |this, worktree, event, cx| {
6791 let is_local = worktree.read(cx).is_local();
6792 match event {
6793 worktree::Event::UpdatedEntries(changes) => {
6794 if is_local {
6795 this.update_local_worktree_buffers(&worktree, changes, cx);
6796 this.update_local_worktree_language_servers(&worktree, changes, cx);
6797 this.update_local_worktree_settings(&worktree, changes, cx);
6798 this.update_prettier_settings(&worktree, changes, cx);
6799 }
6800
6801 cx.emit(Event::WorktreeUpdatedEntries(
6802 worktree.read(cx).id(),
6803 changes.clone(),
6804 ));
6805 }
6806 worktree::Event::UpdatedGitRepositories(updated_repos) => {
6807 if is_local {
6808 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6809 }
6810 }
6811 }
6812 })
6813 .detach();
6814
6815 let push_strong_handle = {
6816 let worktree = worktree.read(cx);
6817 self.is_shared() || worktree.is_visible() || worktree.is_remote()
6818 };
6819 if push_strong_handle {
6820 self.worktrees
6821 .push(WorktreeHandle::Strong(worktree.clone()));
6822 } else {
6823 self.worktrees
6824 .push(WorktreeHandle::Weak(worktree.downgrade()));
6825 }
6826
6827 let handle_id = worktree.entity_id();
6828 cx.observe_release(worktree, move |this, worktree, cx| {
6829 let _ = this.remove_worktree(worktree.id(), cx);
6830 cx.update_global::<SettingsStore, _>(|store, cx| {
6831 store
6832 .clear_local_settings(handle_id.as_u64() as usize, cx)
6833 .log_err()
6834 });
6835 })
6836 .detach();
6837
6838 cx.emit(Event::WorktreeAdded);
6839 self.metadata_changed(cx);
6840 }
6841
6842 fn update_local_worktree_buffers(
6843 &mut self,
6844 worktree_handle: &Model<Worktree>,
6845 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6846 cx: &mut ModelContext<Self>,
6847 ) {
6848 let snapshot = worktree_handle.read(cx).snapshot();
6849
6850 let mut renamed_buffers = Vec::new();
6851 for (path, entry_id, _) in changes {
6852 let worktree_id = worktree_handle.read(cx).id();
6853 let project_path = ProjectPath {
6854 worktree_id,
6855 path: path.clone(),
6856 };
6857
6858 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6859 Some(&buffer_id) => buffer_id,
6860 None => match self.local_buffer_ids_by_path.get(&project_path) {
6861 Some(&buffer_id) => buffer_id,
6862 None => {
6863 continue;
6864 }
6865 },
6866 };
6867
6868 let open_buffer = self.opened_buffers.get(&buffer_id);
6869 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6870 buffer
6871 } else {
6872 self.opened_buffers.remove(&buffer_id);
6873 self.local_buffer_ids_by_path.remove(&project_path);
6874 self.local_buffer_ids_by_entry_id.remove(entry_id);
6875 continue;
6876 };
6877
6878 buffer.update(cx, |buffer, cx| {
6879 if let Some(old_file) = File::from_dyn(buffer.file()) {
6880 if old_file.worktree != *worktree_handle {
6881 return;
6882 }
6883
6884 let new_file = if let Some(entry) = old_file
6885 .entry_id
6886 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6887 {
6888 File {
6889 is_local: true,
6890 entry_id: Some(entry.id),
6891 mtime: entry.mtime,
6892 path: entry.path.clone(),
6893 worktree: worktree_handle.clone(),
6894 is_deleted: false,
6895 is_private: entry.is_private,
6896 }
6897 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6898 File {
6899 is_local: true,
6900 entry_id: Some(entry.id),
6901 mtime: entry.mtime,
6902 path: entry.path.clone(),
6903 worktree: worktree_handle.clone(),
6904 is_deleted: false,
6905 is_private: entry.is_private,
6906 }
6907 } else {
6908 File {
6909 is_local: true,
6910 entry_id: old_file.entry_id,
6911 path: old_file.path().clone(),
6912 mtime: old_file.mtime(),
6913 worktree: worktree_handle.clone(),
6914 is_deleted: true,
6915 is_private: old_file.is_private,
6916 }
6917 };
6918
6919 let old_path = old_file.abs_path(cx);
6920 if new_file.abs_path(cx) != old_path {
6921 renamed_buffers.push((cx.handle(), old_file.clone()));
6922 self.local_buffer_ids_by_path.remove(&project_path);
6923 self.local_buffer_ids_by_path.insert(
6924 ProjectPath {
6925 worktree_id,
6926 path: path.clone(),
6927 },
6928 buffer_id,
6929 );
6930 }
6931
6932 if new_file.entry_id != Some(*entry_id) {
6933 self.local_buffer_ids_by_entry_id.remove(entry_id);
6934 if let Some(entry_id) = new_file.entry_id {
6935 self.local_buffer_ids_by_entry_id
6936 .insert(entry_id, buffer_id);
6937 }
6938 }
6939
6940 if new_file != *old_file {
6941 if let Some(project_id) = self.remote_id() {
6942 self.client
6943 .send(proto::UpdateBufferFile {
6944 project_id,
6945 buffer_id: buffer_id.into(),
6946 file: Some(new_file.to_proto()),
6947 })
6948 .log_err();
6949 }
6950
6951 buffer.file_updated(Arc::new(new_file), cx);
6952 }
6953 }
6954 });
6955 }
6956
6957 for (buffer, old_file) in renamed_buffers {
6958 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6959 self.detect_language_for_buffer(&buffer, cx);
6960 self.register_buffer_with_language_servers(&buffer, cx);
6961 }
6962 }
6963
6964 fn update_local_worktree_language_servers(
6965 &mut self,
6966 worktree_handle: &Model<Worktree>,
6967 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6968 cx: &mut ModelContext<Self>,
6969 ) {
6970 if changes.is_empty() {
6971 return;
6972 }
6973
6974 let worktree_id = worktree_handle.read(cx).id();
6975 let mut language_server_ids = self
6976 .language_server_ids
6977 .iter()
6978 .filter_map(|((server_worktree_id, _), server_id)| {
6979 (*server_worktree_id == worktree_id).then_some(*server_id)
6980 })
6981 .collect::<Vec<_>>();
6982 language_server_ids.sort();
6983 language_server_ids.dedup();
6984
6985 let abs_path = worktree_handle.read(cx).abs_path();
6986 for server_id in &language_server_ids {
6987 if let Some(LanguageServerState::Running { server, .. }) =
6988 self.language_servers.get(server_id)
6989 {
6990 if let Some(watched_paths) = self
6991 .language_server_watched_paths
6992 .get(&server_id)
6993 .and_then(|paths| paths.get(&worktree_id))
6994 {
6995 let params = lsp::DidChangeWatchedFilesParams {
6996 changes: changes
6997 .iter()
6998 .filter_map(|(path, _, change)| {
6999 if !watched_paths.is_match(&path) {
7000 return None;
7001 }
7002 let typ = match change {
7003 PathChange::Loaded => return None,
7004 PathChange::Added => lsp::FileChangeType::CREATED,
7005 PathChange::Removed => lsp::FileChangeType::DELETED,
7006 PathChange::Updated => lsp::FileChangeType::CHANGED,
7007 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
7008 };
7009 Some(lsp::FileEvent {
7010 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
7011 typ,
7012 })
7013 })
7014 .collect(),
7015 };
7016 if !params.changes.is_empty() {
7017 server
7018 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
7019 .log_err();
7020 }
7021 }
7022 }
7023 }
7024 }
7025
7026 fn update_local_worktree_buffers_git_repos(
7027 &mut self,
7028 worktree_handle: Model<Worktree>,
7029 changed_repos: &UpdatedGitRepositoriesSet,
7030 cx: &mut ModelContext<Self>,
7031 ) {
7032 debug_assert!(worktree_handle.read(cx).is_local());
7033
7034 // Identify the loading buffers whose containing repository that has changed.
7035 let future_buffers = self
7036 .loading_buffers_by_path
7037 .iter()
7038 .filter_map(|(project_path, receiver)| {
7039 if project_path.worktree_id != worktree_handle.read(cx).id() {
7040 return None;
7041 }
7042 let path = &project_path.path;
7043 changed_repos
7044 .iter()
7045 .find(|(work_dir, _)| path.starts_with(work_dir))?;
7046 let receiver = receiver.clone();
7047 let path = path.clone();
7048 Some(async move {
7049 wait_for_loading_buffer(receiver)
7050 .await
7051 .ok()
7052 .map(|buffer| (buffer, path))
7053 })
7054 })
7055 .collect::<FuturesUnordered<_>>();
7056
7057 // Identify the current buffers whose containing repository has changed.
7058 let current_buffers = self
7059 .opened_buffers
7060 .values()
7061 .filter_map(|buffer| {
7062 let buffer = buffer.upgrade()?;
7063 let file = File::from_dyn(buffer.read(cx).file())?;
7064 if file.worktree != worktree_handle {
7065 return None;
7066 }
7067 let path = file.path();
7068 changed_repos
7069 .iter()
7070 .find(|(work_dir, _)| path.starts_with(work_dir))?;
7071 Some((buffer, path.clone()))
7072 })
7073 .collect::<Vec<_>>();
7074
7075 if future_buffers.len() + current_buffers.len() == 0 {
7076 return;
7077 }
7078
7079 let remote_id = self.remote_id();
7080 let client = self.client.clone();
7081 cx.spawn(move |_, mut cx| async move {
7082 // Wait for all of the buffers to load.
7083 let future_buffers = future_buffers.collect::<Vec<_>>().await;
7084
7085 // Reload the diff base for every buffer whose containing git repository has changed.
7086 let snapshot =
7087 worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
7088 let diff_bases_by_buffer = cx
7089 .background_executor()
7090 .spawn(async move {
7091 future_buffers
7092 .into_iter()
7093 .flatten()
7094 .chain(current_buffers)
7095 .filter_map(|(buffer, path)| {
7096 let (work_directory, repo) =
7097 snapshot.repository_and_work_directory_for_path(&path)?;
7098 let repo = snapshot.get_local_repo(&repo)?;
7099 let relative_path = path.strip_prefix(&work_directory).ok()?;
7100 let base_text = repo.load_index_text(relative_path);
7101 Some((buffer, base_text))
7102 })
7103 .collect::<Vec<_>>()
7104 })
7105 .await;
7106
7107 // Assign the new diff bases on all of the buffers.
7108 for (buffer, diff_base) in diff_bases_by_buffer {
7109 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
7110 buffer.set_diff_base(diff_base.clone(), cx);
7111 buffer.remote_id().into()
7112 })?;
7113 if let Some(project_id) = remote_id {
7114 client
7115 .send(proto::UpdateDiffBase {
7116 project_id,
7117 buffer_id,
7118 diff_base,
7119 })
7120 .log_err();
7121 }
7122 }
7123
7124 anyhow::Ok(())
7125 })
7126 .detach();
7127 }
7128
7129 fn update_local_worktree_settings(
7130 &mut self,
7131 worktree: &Model<Worktree>,
7132 changes: &UpdatedEntriesSet,
7133 cx: &mut ModelContext<Self>,
7134 ) {
7135 if worktree.read(cx).as_local().is_none() {
7136 return;
7137 }
7138 let project_id = self.remote_id();
7139 let worktree_id = worktree.entity_id();
7140 let remote_worktree_id = worktree.read(cx).id();
7141
7142 let mut settings_contents = Vec::new();
7143 for (path, _, change) in changes.iter() {
7144 let removed = change == &PathChange::Removed;
7145 let abs_path = match worktree.read(cx).absolutize(path) {
7146 Ok(abs_path) => abs_path,
7147 Err(e) => {
7148 log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
7149 continue;
7150 }
7151 };
7152
7153 if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
7154 let settings_dir = Arc::from(
7155 path.ancestors()
7156 .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
7157 .unwrap(),
7158 );
7159 let fs = self.fs.clone();
7160 settings_contents.push(async move {
7161 (
7162 settings_dir,
7163 if removed {
7164 None
7165 } else {
7166 Some(async move { fs.load(&abs_path).await }.await)
7167 },
7168 )
7169 });
7170 } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
7171 self.task_inventory().update(cx, |task_inventory, cx| {
7172 if removed {
7173 task_inventory.remove_local_static_source(&abs_path);
7174 } else {
7175 let fs = self.fs.clone();
7176 let task_abs_path = abs_path.clone();
7177 task_inventory.add_source(
7178 TaskSourceKind::Worktree {
7179 id: remote_worktree_id,
7180 abs_path,
7181 },
7182 |cx| {
7183 let tasks_file_rx =
7184 watch_config_file(&cx.background_executor(), fs, task_abs_path);
7185 StaticSource::new(
7186 format!("local_tasks_for_workspace_{remote_worktree_id}"),
7187 tasks_file_rx,
7188 cx,
7189 )
7190 },
7191 cx,
7192 );
7193 }
7194 })
7195 }
7196 }
7197
7198 if settings_contents.is_empty() {
7199 return;
7200 }
7201
7202 let client = self.client.clone();
7203 cx.spawn(move |_, cx| async move {
7204 let settings_contents: Vec<(Arc<Path>, _)> =
7205 futures::future::join_all(settings_contents).await;
7206 cx.update(|cx| {
7207 cx.update_global::<SettingsStore, _>(|store, cx| {
7208 for (directory, file_content) in settings_contents {
7209 let file_content = file_content.and_then(|content| content.log_err());
7210 store
7211 .set_local_settings(
7212 worktree_id.as_u64() as usize,
7213 directory.clone(),
7214 file_content.as_deref(),
7215 cx,
7216 )
7217 .log_err();
7218 if let Some(remote_id) = project_id {
7219 client
7220 .send(proto::UpdateWorktreeSettings {
7221 project_id: remote_id,
7222 worktree_id: remote_worktree_id.to_proto(),
7223 path: directory.to_string_lossy().into_owned(),
7224 content: file_content,
7225 })
7226 .log_err();
7227 }
7228 }
7229 });
7230 })
7231 .ok();
7232 })
7233 .detach();
7234 }
7235
7236 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
7237 let new_active_entry = entry.and_then(|project_path| {
7238 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
7239 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
7240 Some(entry.id)
7241 });
7242 if new_active_entry != self.active_entry {
7243 self.active_entry = new_active_entry;
7244 cx.emit(Event::ActiveEntryChanged(new_active_entry));
7245 }
7246 }
7247
7248 pub fn language_servers_running_disk_based_diagnostics(
7249 &self,
7250 ) -> impl Iterator<Item = LanguageServerId> + '_ {
7251 self.language_server_statuses
7252 .iter()
7253 .filter_map(|(id, status)| {
7254 if status.has_pending_diagnostic_updates {
7255 Some(*id)
7256 } else {
7257 None
7258 }
7259 })
7260 }
7261
7262 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
7263 let mut summary = DiagnosticSummary::default();
7264 for (_, _, path_summary) in
7265 self.diagnostic_summaries(include_ignored, cx)
7266 .filter(|(path, _, _)| {
7267 let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
7268 include_ignored || worktree == Some(false)
7269 })
7270 {
7271 summary.error_count += path_summary.error_count;
7272 summary.warning_count += path_summary.warning_count;
7273 }
7274 summary
7275 }
7276
7277 pub fn diagnostic_summaries<'a>(
7278 &'a self,
7279 include_ignored: bool,
7280 cx: &'a AppContext,
7281 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
7282 self.visible_worktrees(cx)
7283 .flat_map(move |worktree| {
7284 let worktree = worktree.read(cx);
7285 let worktree_id = worktree.id();
7286 worktree
7287 .diagnostic_summaries()
7288 .map(move |(path, server_id, summary)| {
7289 (ProjectPath { worktree_id, path }, server_id, summary)
7290 })
7291 })
7292 .filter(move |(path, _, _)| {
7293 let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
7294 include_ignored || worktree == Some(false)
7295 })
7296 }
7297
7298 pub fn disk_based_diagnostics_started(
7299 &mut self,
7300 language_server_id: LanguageServerId,
7301 cx: &mut ModelContext<Self>,
7302 ) {
7303 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
7304 }
7305
7306 pub fn disk_based_diagnostics_finished(
7307 &mut self,
7308 language_server_id: LanguageServerId,
7309 cx: &mut ModelContext<Self>,
7310 ) {
7311 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
7312 }
7313
7314 pub fn active_entry(&self) -> Option<ProjectEntryId> {
7315 self.active_entry
7316 }
7317
7318 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
7319 self.worktree_for_id(path.worktree_id, cx)?
7320 .read(cx)
7321 .entry_for_path(&path.path)
7322 .cloned()
7323 }
7324
7325 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
7326 let worktree = self.worktree_for_entry(entry_id, cx)?;
7327 let worktree = worktree.read(cx);
7328 let worktree_id = worktree.id();
7329 let path = worktree.entry_for_id(entry_id)?.path.clone();
7330 Some(ProjectPath { worktree_id, path })
7331 }
7332
7333 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
7334 let workspace_root = self
7335 .worktree_for_id(project_path.worktree_id, cx)?
7336 .read(cx)
7337 .abs_path();
7338 let project_path = project_path.path.as_ref();
7339
7340 Some(if project_path == Path::new("") {
7341 workspace_root.to_path_buf()
7342 } else {
7343 workspace_root.join(project_path)
7344 })
7345 }
7346
7347 pub fn get_repo(
7348 &self,
7349 project_path: &ProjectPath,
7350 cx: &AppContext,
7351 ) -> Option<Arc<Mutex<dyn GitRepository>>> {
7352 self.worktree_for_id(project_path.worktree_id, cx)?
7353 .read(cx)
7354 .as_local()?
7355 .snapshot()
7356 .local_git_repo(&project_path.path)
7357 }
7358
7359 // RPC message handlers
7360
7361 async fn handle_unshare_project(
7362 this: Model<Self>,
7363 _: TypedEnvelope<proto::UnshareProject>,
7364 _: Arc<Client>,
7365 mut cx: AsyncAppContext,
7366 ) -> Result<()> {
7367 this.update(&mut cx, |this, cx| {
7368 if this.is_local() {
7369 this.unshare(cx)?;
7370 } else {
7371 this.disconnected_from_host(cx);
7372 }
7373 Ok(())
7374 })?
7375 }
7376
7377 async fn handle_add_collaborator(
7378 this: Model<Self>,
7379 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
7380 _: Arc<Client>,
7381 mut cx: AsyncAppContext,
7382 ) -> Result<()> {
7383 let collaborator = envelope
7384 .payload
7385 .collaborator
7386 .take()
7387 .ok_or_else(|| anyhow!("empty collaborator"))?;
7388
7389 let collaborator = Collaborator::from_proto(collaborator)?;
7390 this.update(&mut cx, |this, cx| {
7391 this.shared_buffers.remove(&collaborator.peer_id);
7392 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
7393 this.collaborators
7394 .insert(collaborator.peer_id, collaborator);
7395 cx.notify();
7396 })?;
7397
7398 Ok(())
7399 }
7400
7401 async fn handle_update_project_collaborator(
7402 this: Model<Self>,
7403 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
7404 _: Arc<Client>,
7405 mut cx: AsyncAppContext,
7406 ) -> Result<()> {
7407 let old_peer_id = envelope
7408 .payload
7409 .old_peer_id
7410 .ok_or_else(|| anyhow!("missing old peer id"))?;
7411 let new_peer_id = envelope
7412 .payload
7413 .new_peer_id
7414 .ok_or_else(|| anyhow!("missing new peer id"))?;
7415 this.update(&mut cx, |this, cx| {
7416 let collaborator = this
7417 .collaborators
7418 .remove(&old_peer_id)
7419 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
7420 let is_host = collaborator.replica_id == 0;
7421 this.collaborators.insert(new_peer_id, collaborator);
7422
7423 let buffers = this.shared_buffers.remove(&old_peer_id);
7424 log::info!(
7425 "peer {} became {}. moving buffers {:?}",
7426 old_peer_id,
7427 new_peer_id,
7428 &buffers
7429 );
7430 if let Some(buffers) = buffers {
7431 this.shared_buffers.insert(new_peer_id, buffers);
7432 }
7433
7434 if is_host {
7435 this.opened_buffers
7436 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
7437 this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
7438 .unwrap();
7439 }
7440
7441 cx.emit(Event::CollaboratorUpdated {
7442 old_peer_id,
7443 new_peer_id,
7444 });
7445 cx.notify();
7446 Ok(())
7447 })?
7448 }
7449
7450 async fn handle_remove_collaborator(
7451 this: Model<Self>,
7452 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
7453 _: Arc<Client>,
7454 mut cx: AsyncAppContext,
7455 ) -> Result<()> {
7456 this.update(&mut cx, |this, cx| {
7457 let peer_id = envelope
7458 .payload
7459 .peer_id
7460 .ok_or_else(|| anyhow!("invalid peer id"))?;
7461 let replica_id = this
7462 .collaborators
7463 .remove(&peer_id)
7464 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
7465 .replica_id;
7466 for buffer in this.opened_buffers.values() {
7467 if let Some(buffer) = buffer.upgrade() {
7468 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
7469 }
7470 }
7471 this.shared_buffers.remove(&peer_id);
7472
7473 cx.emit(Event::CollaboratorLeft(peer_id));
7474 cx.notify();
7475 Ok(())
7476 })?
7477 }
7478
7479 async fn handle_update_project(
7480 this: Model<Self>,
7481 envelope: TypedEnvelope<proto::UpdateProject>,
7482 _: Arc<Client>,
7483 mut cx: AsyncAppContext,
7484 ) -> Result<()> {
7485 this.update(&mut cx, |this, cx| {
7486 // Don't handle messages that were sent before the response to us joining the project
7487 if envelope.message_id > this.join_project_response_message_id {
7488 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
7489 }
7490 Ok(())
7491 })?
7492 }
7493
7494 async fn handle_update_worktree(
7495 this: Model<Self>,
7496 envelope: TypedEnvelope<proto::UpdateWorktree>,
7497 _: Arc<Client>,
7498 mut cx: AsyncAppContext,
7499 ) -> Result<()> {
7500 this.update(&mut cx, |this, cx| {
7501 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7502 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7503 worktree.update(cx, |worktree, _| {
7504 let worktree = worktree.as_remote_mut().unwrap();
7505 worktree.update_from_remote(envelope.payload);
7506 });
7507 }
7508 Ok(())
7509 })?
7510 }
7511
7512 async fn handle_update_worktree_settings(
7513 this: Model<Self>,
7514 envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
7515 _: Arc<Client>,
7516 mut cx: AsyncAppContext,
7517 ) -> Result<()> {
7518 this.update(&mut cx, |this, cx| {
7519 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7520 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7521 cx.update_global::<SettingsStore, _>(|store, cx| {
7522 store
7523 .set_local_settings(
7524 worktree.entity_id().as_u64() as usize,
7525 PathBuf::from(&envelope.payload.path).into(),
7526 envelope.payload.content.as_deref(),
7527 cx,
7528 )
7529 .log_err();
7530 });
7531 }
7532 Ok(())
7533 })?
7534 }
7535
7536 async fn handle_create_project_entry(
7537 this: Model<Self>,
7538 envelope: TypedEnvelope<proto::CreateProjectEntry>,
7539 _: Arc<Client>,
7540 mut cx: AsyncAppContext,
7541 ) -> Result<proto::ProjectEntryResponse> {
7542 let worktree = this.update(&mut cx, |this, cx| {
7543 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7544 this.worktree_for_id(worktree_id, cx)
7545 .ok_or_else(|| anyhow!("worktree not found"))
7546 })??;
7547 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7548 let entry = worktree
7549 .update(&mut cx, |worktree, cx| {
7550 let worktree = worktree.as_local_mut().unwrap();
7551 let path = PathBuf::from(envelope.payload.path);
7552 worktree.create_entry(path, envelope.payload.is_directory, cx)
7553 })?
7554 .await?;
7555 Ok(proto::ProjectEntryResponse {
7556 entry: entry.as_ref().map(|e| e.into()),
7557 worktree_scan_id: worktree_scan_id as u64,
7558 })
7559 }
7560
7561 async fn handle_rename_project_entry(
7562 this: Model<Self>,
7563 envelope: TypedEnvelope<proto::RenameProjectEntry>,
7564 _: Arc<Client>,
7565 mut cx: AsyncAppContext,
7566 ) -> Result<proto::ProjectEntryResponse> {
7567 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7568 let worktree = this.update(&mut cx, |this, cx| {
7569 this.worktree_for_entry(entry_id, cx)
7570 .ok_or_else(|| anyhow!("worktree not found"))
7571 })??;
7572 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7573 let entry = worktree
7574 .update(&mut cx, |worktree, cx| {
7575 let new_path = PathBuf::from(envelope.payload.new_path);
7576 worktree
7577 .as_local_mut()
7578 .unwrap()
7579 .rename_entry(entry_id, new_path, cx)
7580 })?
7581 .await?;
7582 Ok(proto::ProjectEntryResponse {
7583 entry: entry.as_ref().map(|e| e.into()),
7584 worktree_scan_id: worktree_scan_id as u64,
7585 })
7586 }
7587
7588 async fn handle_copy_project_entry(
7589 this: Model<Self>,
7590 envelope: TypedEnvelope<proto::CopyProjectEntry>,
7591 _: Arc<Client>,
7592 mut cx: AsyncAppContext,
7593 ) -> Result<proto::ProjectEntryResponse> {
7594 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7595 let worktree = this.update(&mut cx, |this, cx| {
7596 this.worktree_for_entry(entry_id, cx)
7597 .ok_or_else(|| anyhow!("worktree not found"))
7598 })??;
7599 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7600 let entry = worktree
7601 .update(&mut cx, |worktree, cx| {
7602 let new_path = PathBuf::from(envelope.payload.new_path);
7603 worktree
7604 .as_local_mut()
7605 .unwrap()
7606 .copy_entry(entry_id, new_path, cx)
7607 })?
7608 .await?;
7609 Ok(proto::ProjectEntryResponse {
7610 entry: entry.as_ref().map(|e| e.into()),
7611 worktree_scan_id: worktree_scan_id as u64,
7612 })
7613 }
7614
7615 async fn handle_delete_project_entry(
7616 this: Model<Self>,
7617 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
7618 _: Arc<Client>,
7619 mut cx: AsyncAppContext,
7620 ) -> Result<proto::ProjectEntryResponse> {
7621 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7622
7623 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7624
7625 let worktree = this.update(&mut cx, |this, cx| {
7626 this.worktree_for_entry(entry_id, cx)
7627 .ok_or_else(|| anyhow!("worktree not found"))
7628 })??;
7629 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7630 worktree
7631 .update(&mut cx, |worktree, cx| {
7632 worktree
7633 .as_local_mut()
7634 .unwrap()
7635 .delete_entry(entry_id, cx)
7636 .ok_or_else(|| anyhow!("invalid entry"))
7637 })??
7638 .await?;
7639 Ok(proto::ProjectEntryResponse {
7640 entry: None,
7641 worktree_scan_id: worktree_scan_id as u64,
7642 })
7643 }
7644
7645 async fn handle_expand_project_entry(
7646 this: Model<Self>,
7647 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7648 _: Arc<Client>,
7649 mut cx: AsyncAppContext,
7650 ) -> Result<proto::ExpandProjectEntryResponse> {
7651 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7652 let worktree = this
7653 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7654 .ok_or_else(|| anyhow!("invalid request"))?;
7655 worktree
7656 .update(&mut cx, |worktree, cx| {
7657 worktree
7658 .as_local_mut()
7659 .unwrap()
7660 .expand_entry(entry_id, cx)
7661 .ok_or_else(|| anyhow!("invalid entry"))
7662 })??
7663 .await?;
7664 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7665 Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7666 }
7667
7668 async fn handle_update_diagnostic_summary(
7669 this: Model<Self>,
7670 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7671 _: Arc<Client>,
7672 mut cx: AsyncAppContext,
7673 ) -> Result<()> {
7674 this.update(&mut cx, |this, cx| {
7675 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7676 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7677 if let Some(summary) = envelope.payload.summary {
7678 let project_path = ProjectPath {
7679 worktree_id,
7680 path: Path::new(&summary.path).into(),
7681 };
7682 worktree.update(cx, |worktree, _| {
7683 worktree
7684 .as_remote_mut()
7685 .unwrap()
7686 .update_diagnostic_summary(project_path.path.clone(), &summary);
7687 });
7688 cx.emit(Event::DiagnosticsUpdated {
7689 language_server_id: LanguageServerId(summary.language_server_id as usize),
7690 path: project_path,
7691 });
7692 }
7693 }
7694 Ok(())
7695 })?
7696 }
7697
7698 async fn handle_start_language_server(
7699 this: Model<Self>,
7700 envelope: TypedEnvelope<proto::StartLanguageServer>,
7701 _: Arc<Client>,
7702 mut cx: AsyncAppContext,
7703 ) -> Result<()> {
7704 let server = envelope
7705 .payload
7706 .server
7707 .ok_or_else(|| anyhow!("invalid server"))?;
7708 this.update(&mut cx, |this, cx| {
7709 this.language_server_statuses.insert(
7710 LanguageServerId(server.id as usize),
7711 LanguageServerStatus {
7712 name: server.name,
7713 pending_work: Default::default(),
7714 has_pending_diagnostic_updates: false,
7715 progress_tokens: Default::default(),
7716 },
7717 );
7718 cx.notify();
7719 })?;
7720 Ok(())
7721 }
7722
7723 async fn handle_update_language_server(
7724 this: Model<Self>,
7725 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7726 _: Arc<Client>,
7727 mut cx: AsyncAppContext,
7728 ) -> Result<()> {
7729 this.update(&mut cx, |this, cx| {
7730 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7731
7732 match envelope
7733 .payload
7734 .variant
7735 .ok_or_else(|| anyhow!("invalid variant"))?
7736 {
7737 proto::update_language_server::Variant::WorkStart(payload) => {
7738 this.on_lsp_work_start(
7739 language_server_id,
7740 payload.token,
7741 LanguageServerProgress {
7742 message: payload.message,
7743 percentage: payload.percentage.map(|p| p as usize),
7744 last_update_at: Instant::now(),
7745 },
7746 cx,
7747 );
7748 }
7749
7750 proto::update_language_server::Variant::WorkProgress(payload) => {
7751 this.on_lsp_work_progress(
7752 language_server_id,
7753 payload.token,
7754 LanguageServerProgress {
7755 message: payload.message,
7756 percentage: payload.percentage.map(|p| p as usize),
7757 last_update_at: Instant::now(),
7758 },
7759 cx,
7760 );
7761 }
7762
7763 proto::update_language_server::Variant::WorkEnd(payload) => {
7764 this.on_lsp_work_end(language_server_id, payload.token, cx);
7765 }
7766
7767 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7768 this.disk_based_diagnostics_started(language_server_id, cx);
7769 }
7770
7771 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7772 this.disk_based_diagnostics_finished(language_server_id, cx)
7773 }
7774 }
7775
7776 Ok(())
7777 })?
7778 }
7779
7780 async fn handle_update_buffer(
7781 this: Model<Self>,
7782 envelope: TypedEnvelope<proto::UpdateBuffer>,
7783 _: Arc<Client>,
7784 mut cx: AsyncAppContext,
7785 ) -> Result<proto::Ack> {
7786 this.update(&mut cx, |this, cx| {
7787 let payload = envelope.payload.clone();
7788 let buffer_id = BufferId::new(payload.buffer_id)?;
7789 let ops = payload
7790 .operations
7791 .into_iter()
7792 .map(language::proto::deserialize_operation)
7793 .collect::<Result<Vec<_>, _>>()?;
7794 let is_remote = this.is_remote();
7795 match this.opened_buffers.entry(buffer_id) {
7796 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7797 OpenBuffer::Strong(buffer) => {
7798 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7799 }
7800 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7801 OpenBuffer::Weak(_) => {}
7802 },
7803 hash_map::Entry::Vacant(e) => {
7804 assert!(
7805 is_remote,
7806 "received buffer update from {:?}",
7807 envelope.original_sender_id
7808 );
7809 e.insert(OpenBuffer::Operations(ops));
7810 }
7811 }
7812 Ok(proto::Ack {})
7813 })?
7814 }
7815
7816 async fn handle_create_buffer_for_peer(
7817 this: Model<Self>,
7818 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7819 _: Arc<Client>,
7820 mut cx: AsyncAppContext,
7821 ) -> Result<()> {
7822 this.update(&mut cx, |this, cx| {
7823 match envelope
7824 .payload
7825 .variant
7826 .ok_or_else(|| anyhow!("missing variant"))?
7827 {
7828 proto::create_buffer_for_peer::Variant::State(mut state) => {
7829 let mut buffer_file = None;
7830 if let Some(file) = state.file.take() {
7831 let worktree_id = WorktreeId::from_proto(file.worktree_id);
7832 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7833 anyhow!("no worktree found for id {}", file.worktree_id)
7834 })?;
7835 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7836 as Arc<dyn language::File>);
7837 }
7838
7839 let buffer_id = BufferId::new(state.id)?;
7840 let buffer = cx.new_model(|_| {
7841 Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7842 .unwrap()
7843 });
7844 this.incomplete_remote_buffers
7845 .insert(buffer_id, Some(buffer));
7846 }
7847 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7848 let buffer_id = BufferId::new(chunk.buffer_id)?;
7849 let buffer = this
7850 .incomplete_remote_buffers
7851 .get(&buffer_id)
7852 .cloned()
7853 .flatten()
7854 .ok_or_else(|| {
7855 anyhow!(
7856 "received chunk for buffer {} without initial state",
7857 chunk.buffer_id
7858 )
7859 })?;
7860 let operations = chunk
7861 .operations
7862 .into_iter()
7863 .map(language::proto::deserialize_operation)
7864 .collect::<Result<Vec<_>>>()?;
7865 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7866
7867 if chunk.is_last {
7868 this.incomplete_remote_buffers.remove(&buffer_id);
7869 this.register_buffer(&buffer, cx)?;
7870 }
7871 }
7872 }
7873
7874 Ok(())
7875 })?
7876 }
7877
7878 async fn handle_update_diff_base(
7879 this: Model<Self>,
7880 envelope: TypedEnvelope<proto::UpdateDiffBase>,
7881 _: Arc<Client>,
7882 mut cx: AsyncAppContext,
7883 ) -> Result<()> {
7884 this.update(&mut cx, |this, cx| {
7885 let buffer_id = envelope.payload.buffer_id;
7886 let buffer_id = BufferId::new(buffer_id)?;
7887 let diff_base = envelope.payload.diff_base;
7888 if let Some(buffer) = this
7889 .opened_buffers
7890 .get_mut(&buffer_id)
7891 .and_then(|b| b.upgrade())
7892 .or_else(|| {
7893 this.incomplete_remote_buffers
7894 .get(&buffer_id)
7895 .cloned()
7896 .flatten()
7897 })
7898 {
7899 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7900 }
7901 Ok(())
7902 })?
7903 }
7904
7905 async fn handle_update_buffer_file(
7906 this: Model<Self>,
7907 envelope: TypedEnvelope<proto::UpdateBufferFile>,
7908 _: Arc<Client>,
7909 mut cx: AsyncAppContext,
7910 ) -> Result<()> {
7911 let buffer_id = envelope.payload.buffer_id;
7912 let buffer_id = BufferId::new(buffer_id)?;
7913
7914 this.update(&mut cx, |this, cx| {
7915 let payload = envelope.payload.clone();
7916 if let Some(buffer) = this
7917 .opened_buffers
7918 .get(&buffer_id)
7919 .and_then(|b| b.upgrade())
7920 .or_else(|| {
7921 this.incomplete_remote_buffers
7922 .get(&buffer_id)
7923 .cloned()
7924 .flatten()
7925 })
7926 {
7927 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7928 let worktree = this
7929 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7930 .ok_or_else(|| anyhow!("no such worktree"))?;
7931 let file = File::from_proto(file, worktree, cx)?;
7932 buffer.update(cx, |buffer, cx| {
7933 buffer.file_updated(Arc::new(file), cx);
7934 });
7935 this.detect_language_for_buffer(&buffer, cx);
7936 }
7937 Ok(())
7938 })?
7939 }
7940
7941 async fn handle_save_buffer(
7942 this: Model<Self>,
7943 envelope: TypedEnvelope<proto::SaveBuffer>,
7944 _: Arc<Client>,
7945 mut cx: AsyncAppContext,
7946 ) -> Result<proto::BufferSaved> {
7947 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7948 let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7949 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7950 let buffer = this
7951 .opened_buffers
7952 .get(&buffer_id)
7953 .and_then(|buffer| buffer.upgrade())
7954 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7955 anyhow::Ok((project_id, buffer))
7956 })??;
7957 buffer
7958 .update(&mut cx, |buffer, _| {
7959 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7960 })?
7961 .await?;
7962 let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7963
7964 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7965 .await?;
7966 buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7967 project_id,
7968 buffer_id: buffer_id.into(),
7969 version: serialize_version(buffer.saved_version()),
7970 mtime: Some(buffer.saved_mtime().into()),
7971 fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7972 })
7973 }
7974
7975 async fn handle_reload_buffers(
7976 this: Model<Self>,
7977 envelope: TypedEnvelope<proto::ReloadBuffers>,
7978 _: Arc<Client>,
7979 mut cx: AsyncAppContext,
7980 ) -> Result<proto::ReloadBuffersResponse> {
7981 let sender_id = envelope.original_sender_id()?;
7982 let reload = this.update(&mut cx, |this, cx| {
7983 let mut buffers = HashSet::default();
7984 for buffer_id in &envelope.payload.buffer_ids {
7985 let buffer_id = BufferId::new(*buffer_id)?;
7986 buffers.insert(
7987 this.opened_buffers
7988 .get(&buffer_id)
7989 .and_then(|buffer| buffer.upgrade())
7990 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7991 );
7992 }
7993 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7994 })??;
7995
7996 let project_transaction = reload.await?;
7997 let project_transaction = this.update(&mut cx, |this, cx| {
7998 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7999 })?;
8000 Ok(proto::ReloadBuffersResponse {
8001 transaction: Some(project_transaction),
8002 })
8003 }
8004
8005 async fn handle_synchronize_buffers(
8006 this: Model<Self>,
8007 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
8008 _: Arc<Client>,
8009 mut cx: AsyncAppContext,
8010 ) -> Result<proto::SynchronizeBuffersResponse> {
8011 let project_id = envelope.payload.project_id;
8012 let mut response = proto::SynchronizeBuffersResponse {
8013 buffers: Default::default(),
8014 };
8015
8016 this.update(&mut cx, |this, cx| {
8017 let Some(guest_id) = envelope.original_sender_id else {
8018 error!("missing original_sender_id on SynchronizeBuffers request");
8019 bail!("missing original_sender_id on SynchronizeBuffers request");
8020 };
8021
8022 this.shared_buffers.entry(guest_id).or_default().clear();
8023 for buffer in envelope.payload.buffers {
8024 let buffer_id = BufferId::new(buffer.id)?;
8025 let remote_version = language::proto::deserialize_version(&buffer.version);
8026 if let Some(buffer) = this.buffer_for_id(buffer_id) {
8027 this.shared_buffers
8028 .entry(guest_id)
8029 .or_default()
8030 .insert(buffer_id);
8031
8032 let buffer = buffer.read(cx);
8033 response.buffers.push(proto::BufferVersion {
8034 id: buffer_id.into(),
8035 version: language::proto::serialize_version(&buffer.version),
8036 });
8037
8038 let operations = buffer.serialize_ops(Some(remote_version), cx);
8039 let client = this.client.clone();
8040 if let Some(file) = buffer.file() {
8041 client
8042 .send(proto::UpdateBufferFile {
8043 project_id,
8044 buffer_id: buffer_id.into(),
8045 file: Some(file.to_proto()),
8046 })
8047 .log_err();
8048 }
8049
8050 client
8051 .send(proto::UpdateDiffBase {
8052 project_id,
8053 buffer_id: buffer_id.into(),
8054 diff_base: buffer.diff_base().map(Into::into),
8055 })
8056 .log_err();
8057
8058 client
8059 .send(proto::BufferReloaded {
8060 project_id,
8061 buffer_id: buffer_id.into(),
8062 version: language::proto::serialize_version(buffer.saved_version()),
8063 mtime: Some(buffer.saved_mtime().into()),
8064 fingerprint: language::proto::serialize_fingerprint(
8065 buffer.saved_version_fingerprint(),
8066 ),
8067 line_ending: language::proto::serialize_line_ending(
8068 buffer.line_ending(),
8069 ) as i32,
8070 })
8071 .log_err();
8072
8073 cx.background_executor()
8074 .spawn(
8075 async move {
8076 let operations = operations.await;
8077 for chunk in split_operations(operations) {
8078 client
8079 .request(proto::UpdateBuffer {
8080 project_id,
8081 buffer_id: buffer_id.into(),
8082 operations: chunk,
8083 })
8084 .await?;
8085 }
8086 anyhow::Ok(())
8087 }
8088 .log_err(),
8089 )
8090 .detach();
8091 }
8092 }
8093 Ok(())
8094 })??;
8095
8096 Ok(response)
8097 }
8098
8099 async fn handle_format_buffers(
8100 this: Model<Self>,
8101 envelope: TypedEnvelope<proto::FormatBuffers>,
8102 _: Arc<Client>,
8103 mut cx: AsyncAppContext,
8104 ) -> Result<proto::FormatBuffersResponse> {
8105 let sender_id = envelope.original_sender_id()?;
8106 let format = this.update(&mut cx, |this, cx| {
8107 let mut buffers = HashSet::default();
8108 for buffer_id in &envelope.payload.buffer_ids {
8109 let buffer_id = BufferId::new(*buffer_id)?;
8110 buffers.insert(
8111 this.opened_buffers
8112 .get(&buffer_id)
8113 .and_then(|buffer| buffer.upgrade())
8114 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
8115 );
8116 }
8117 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
8118 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
8119 })??;
8120
8121 let project_transaction = format.await?;
8122 let project_transaction = this.update(&mut cx, |this, cx| {
8123 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8124 })?;
8125 Ok(proto::FormatBuffersResponse {
8126 transaction: Some(project_transaction),
8127 })
8128 }
8129
8130 async fn handle_apply_additional_edits_for_completion(
8131 this: Model<Self>,
8132 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
8133 _: Arc<Client>,
8134 mut cx: AsyncAppContext,
8135 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
8136 let languages = this.update(&mut cx, |this, _| this.languages.clone())?;
8137 let (buffer, completion) = this.update(&mut cx, |this, cx| {
8138 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8139 let buffer = this
8140 .opened_buffers
8141 .get(&buffer_id)
8142 .and_then(|buffer| buffer.upgrade())
8143 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8144 let language = buffer.read(cx).language();
8145 let completion = language::proto::deserialize_completion(
8146 envelope
8147 .payload
8148 .completion
8149 .ok_or_else(|| anyhow!("invalid completion"))?,
8150 language.cloned(),
8151 &languages,
8152 );
8153 Ok::<_, anyhow::Error>((buffer, completion))
8154 })??;
8155
8156 let completion = completion.await?;
8157
8158 let apply_additional_edits = this.update(&mut cx, |this, cx| {
8159 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
8160 })?;
8161
8162 Ok(proto::ApplyCompletionAdditionalEditsResponse {
8163 transaction: apply_additional_edits
8164 .await?
8165 .as_ref()
8166 .map(language::proto::serialize_transaction),
8167 })
8168 }
8169
8170 async fn handle_resolve_completion_documentation(
8171 this: Model<Self>,
8172 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
8173 _: Arc<Client>,
8174 mut cx: AsyncAppContext,
8175 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
8176 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
8177
8178 let completion = this
8179 .read_with(&mut cx, |this, _| {
8180 let id = LanguageServerId(envelope.payload.language_server_id as usize);
8181 let Some(server) = this.language_server_for_id(id) else {
8182 return Err(anyhow!("No language server {id}"));
8183 };
8184
8185 Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
8186 })??
8187 .await?;
8188
8189 let mut is_markdown = false;
8190 let text = match completion.documentation {
8191 Some(lsp::Documentation::String(text)) => text,
8192
8193 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
8194 is_markdown = kind == lsp::MarkupKind::Markdown;
8195 value
8196 }
8197
8198 _ => String::new(),
8199 };
8200
8201 Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
8202 }
8203
8204 async fn handle_apply_code_action(
8205 this: Model<Self>,
8206 envelope: TypedEnvelope<proto::ApplyCodeAction>,
8207 _: Arc<Client>,
8208 mut cx: AsyncAppContext,
8209 ) -> Result<proto::ApplyCodeActionResponse> {
8210 let sender_id = envelope.original_sender_id()?;
8211 let action = language::proto::deserialize_code_action(
8212 envelope
8213 .payload
8214 .action
8215 .ok_or_else(|| anyhow!("invalid action"))?,
8216 )?;
8217 let apply_code_action = this.update(&mut cx, |this, cx| {
8218 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8219 let buffer = this
8220 .opened_buffers
8221 .get(&buffer_id)
8222 .and_then(|buffer| buffer.upgrade())
8223 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
8224 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
8225 })??;
8226
8227 let project_transaction = apply_code_action.await?;
8228 let project_transaction = this.update(&mut cx, |this, cx| {
8229 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8230 })?;
8231 Ok(proto::ApplyCodeActionResponse {
8232 transaction: Some(project_transaction),
8233 })
8234 }
8235
8236 async fn handle_on_type_formatting(
8237 this: Model<Self>,
8238 envelope: TypedEnvelope<proto::OnTypeFormatting>,
8239 _: Arc<Client>,
8240 mut cx: AsyncAppContext,
8241 ) -> Result<proto::OnTypeFormattingResponse> {
8242 let on_type_formatting = this.update(&mut cx, |this, cx| {
8243 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8244 let buffer = this
8245 .opened_buffers
8246 .get(&buffer_id)
8247 .and_then(|buffer| buffer.upgrade())
8248 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8249 let position = envelope
8250 .payload
8251 .position
8252 .and_then(deserialize_anchor)
8253 .ok_or_else(|| anyhow!("invalid position"))?;
8254 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
8255 buffer,
8256 position,
8257 envelope.payload.trigger.clone(),
8258 cx,
8259 ))
8260 })??;
8261
8262 let transaction = on_type_formatting
8263 .await?
8264 .as_ref()
8265 .map(language::proto::serialize_transaction);
8266 Ok(proto::OnTypeFormattingResponse { transaction })
8267 }
8268
8269 async fn handle_inlay_hints(
8270 this: Model<Self>,
8271 envelope: TypedEnvelope<proto::InlayHints>,
8272 _: Arc<Client>,
8273 mut cx: AsyncAppContext,
8274 ) -> Result<proto::InlayHintsResponse> {
8275 let sender_id = envelope.original_sender_id()?;
8276 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8277 let buffer = this.update(&mut cx, |this, _| {
8278 this.opened_buffers
8279 .get(&buffer_id)
8280 .and_then(|buffer| buffer.upgrade())
8281 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
8282 })??;
8283 buffer
8284 .update(&mut cx, |buffer, _| {
8285 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
8286 })?
8287 .await
8288 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
8289
8290 let start = envelope
8291 .payload
8292 .start
8293 .and_then(deserialize_anchor)
8294 .context("missing range start")?;
8295 let end = envelope
8296 .payload
8297 .end
8298 .and_then(deserialize_anchor)
8299 .context("missing range end")?;
8300 let buffer_hints = this
8301 .update(&mut cx, |project, cx| {
8302 project.inlay_hints(buffer.clone(), start..end, cx)
8303 })?
8304 .await
8305 .context("inlay hints fetch")?;
8306
8307 this.update(&mut cx, |project, cx| {
8308 InlayHints::response_to_proto(
8309 buffer_hints,
8310 project,
8311 sender_id,
8312 &buffer.read(cx).version(),
8313 cx,
8314 )
8315 })
8316 }
8317
8318 async fn handle_resolve_inlay_hint(
8319 this: Model<Self>,
8320 envelope: TypedEnvelope<proto::ResolveInlayHint>,
8321 _: Arc<Client>,
8322 mut cx: AsyncAppContext,
8323 ) -> Result<proto::ResolveInlayHintResponse> {
8324 let proto_hint = envelope
8325 .payload
8326 .hint
8327 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
8328 let hint = InlayHints::proto_to_project_hint(proto_hint)
8329 .context("resolved proto inlay hint conversion")?;
8330 let buffer = this.update(&mut cx, |this, _cx| {
8331 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8332 this.opened_buffers
8333 .get(&buffer_id)
8334 .and_then(|buffer| buffer.upgrade())
8335 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8336 })??;
8337 let response_hint = this
8338 .update(&mut cx, |project, cx| {
8339 project.resolve_inlay_hint(
8340 hint,
8341 buffer,
8342 LanguageServerId(envelope.payload.language_server_id as usize),
8343 cx,
8344 )
8345 })?
8346 .await
8347 .context("inlay hints fetch")?;
8348 Ok(proto::ResolveInlayHintResponse {
8349 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
8350 })
8351 }
8352
8353 async fn try_resolve_code_action(
8354 lang_server: &LanguageServer,
8355 action: &mut CodeAction,
8356 ) -> anyhow::Result<()> {
8357 if GetCodeActions::can_resolve_actions(&lang_server.capabilities()) {
8358 if action.lsp_action.data.is_some()
8359 && (action.lsp_action.command.is_none() || action.lsp_action.edit.is_none())
8360 {
8361 action.lsp_action = lang_server
8362 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action.clone())
8363 .await?;
8364 }
8365 }
8366
8367 anyhow::Ok(())
8368 }
8369
8370 async fn handle_refresh_inlay_hints(
8371 this: Model<Self>,
8372 _: TypedEnvelope<proto::RefreshInlayHints>,
8373 _: Arc<Client>,
8374 mut cx: AsyncAppContext,
8375 ) -> Result<proto::Ack> {
8376 this.update(&mut cx, |_, cx| {
8377 cx.emit(Event::RefreshInlayHints);
8378 })?;
8379 Ok(proto::Ack {})
8380 }
8381
8382 async fn handle_lsp_command<T: LspCommand>(
8383 this: Model<Self>,
8384 envelope: TypedEnvelope<T::ProtoRequest>,
8385 _: Arc<Client>,
8386 mut cx: AsyncAppContext,
8387 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
8388 where
8389 <T::LspRequest as lsp::request::Request>::Params: Send,
8390 <T::LspRequest as lsp::request::Request>::Result: Send,
8391 {
8392 let sender_id = envelope.original_sender_id()?;
8393 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
8394 let buffer_handle = this.update(&mut cx, |this, _cx| {
8395 this.opened_buffers
8396 .get(&buffer_id)
8397 .and_then(|buffer| buffer.upgrade())
8398 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8399 })??;
8400 let request = T::from_proto(
8401 envelope.payload,
8402 this.clone(),
8403 buffer_handle.clone(),
8404 cx.clone(),
8405 )
8406 .await?;
8407 let response = this
8408 .update(&mut cx, |this, cx| {
8409 this.request_lsp(
8410 buffer_handle.clone(),
8411 LanguageServerToQuery::Primary,
8412 request,
8413 cx,
8414 )
8415 })?
8416 .await?;
8417 this.update(&mut cx, |this, cx| {
8418 Ok(T::response_to_proto(
8419 response,
8420 this,
8421 sender_id,
8422 &buffer_handle.read(cx).version(),
8423 cx,
8424 ))
8425 })?
8426 }
8427
8428 async fn handle_get_project_symbols(
8429 this: Model<Self>,
8430 envelope: TypedEnvelope<proto::GetProjectSymbols>,
8431 _: Arc<Client>,
8432 mut cx: AsyncAppContext,
8433 ) -> Result<proto::GetProjectSymbolsResponse> {
8434 let symbols = this
8435 .update(&mut cx, |this, cx| {
8436 this.symbols(&envelope.payload.query, cx)
8437 })?
8438 .await?;
8439
8440 Ok(proto::GetProjectSymbolsResponse {
8441 symbols: symbols.iter().map(serialize_symbol).collect(),
8442 })
8443 }
8444
8445 async fn handle_search_project(
8446 this: Model<Self>,
8447 envelope: TypedEnvelope<proto::SearchProject>,
8448 _: Arc<Client>,
8449 mut cx: AsyncAppContext,
8450 ) -> Result<proto::SearchProjectResponse> {
8451 let peer_id = envelope.original_sender_id()?;
8452 let query = SearchQuery::from_proto(envelope.payload)?;
8453 let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
8454
8455 cx.spawn(move |mut cx| async move {
8456 let mut locations = Vec::new();
8457 while let Some((buffer, ranges)) = result.next().await {
8458 for range in ranges {
8459 let start = serialize_anchor(&range.start);
8460 let end = serialize_anchor(&range.end);
8461 let buffer_id = this.update(&mut cx, |this, cx| {
8462 this.create_buffer_for_peer(&buffer, peer_id, cx).into()
8463 })?;
8464 locations.push(proto::Location {
8465 buffer_id,
8466 start: Some(start),
8467 end: Some(end),
8468 });
8469 }
8470 }
8471 Ok(proto::SearchProjectResponse { locations })
8472 })
8473 .await
8474 }
8475
8476 async fn handle_open_buffer_for_symbol(
8477 this: Model<Self>,
8478 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
8479 _: Arc<Client>,
8480 mut cx: AsyncAppContext,
8481 ) -> Result<proto::OpenBufferForSymbolResponse> {
8482 let peer_id = envelope.original_sender_id()?;
8483 let symbol = envelope
8484 .payload
8485 .symbol
8486 .ok_or_else(|| anyhow!("invalid symbol"))?;
8487 let symbol = this
8488 .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
8489 .await?;
8490 let symbol = this.update(&mut cx, |this, _| {
8491 let signature = this.symbol_signature(&symbol.path);
8492 if signature == symbol.signature {
8493 Ok(symbol)
8494 } else {
8495 Err(anyhow!("invalid symbol signature"))
8496 }
8497 })??;
8498 let buffer = this
8499 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
8500 .await?;
8501
8502 this.update(&mut cx, |this, cx| {
8503 let is_private = buffer
8504 .read(cx)
8505 .file()
8506 .map(|f| f.is_private())
8507 .unwrap_or_default();
8508 if is_private {
8509 Err(anyhow!(ErrorCode::UnsharedItem))
8510 } else {
8511 Ok(proto::OpenBufferForSymbolResponse {
8512 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8513 })
8514 }
8515 })?
8516 }
8517
8518 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8519 let mut hasher = Sha256::new();
8520 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8521 hasher.update(project_path.path.to_string_lossy().as_bytes());
8522 hasher.update(self.nonce.to_be_bytes());
8523 hasher.finalize().as_slice().try_into().unwrap()
8524 }
8525
8526 async fn handle_open_buffer_by_id(
8527 this: Model<Self>,
8528 envelope: TypedEnvelope<proto::OpenBufferById>,
8529 _: Arc<Client>,
8530 mut cx: AsyncAppContext,
8531 ) -> Result<proto::OpenBufferResponse> {
8532 let peer_id = envelope.original_sender_id()?;
8533 let buffer_id = BufferId::new(envelope.payload.id)?;
8534 let buffer = this
8535 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
8536 .await?;
8537 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8538 }
8539
8540 async fn handle_open_buffer_by_path(
8541 this: Model<Self>,
8542 envelope: TypedEnvelope<proto::OpenBufferByPath>,
8543 _: Arc<Client>,
8544 mut cx: AsyncAppContext,
8545 ) -> Result<proto::OpenBufferResponse> {
8546 let peer_id = envelope.original_sender_id()?;
8547 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8548 let open_buffer = this.update(&mut cx, |this, cx| {
8549 this.open_buffer(
8550 ProjectPath {
8551 worktree_id,
8552 path: PathBuf::from(envelope.payload.path).into(),
8553 },
8554 cx,
8555 )
8556 })?;
8557
8558 let buffer = open_buffer.await?;
8559 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8560 }
8561
8562 fn respond_to_open_buffer_request(
8563 this: Model<Self>,
8564 buffer: Model<Buffer>,
8565 peer_id: proto::PeerId,
8566 cx: &mut AsyncAppContext,
8567 ) -> Result<proto::OpenBufferResponse> {
8568 this.update(cx, |this, cx| {
8569 let is_private = buffer
8570 .read(cx)
8571 .file()
8572 .map(|f| f.is_private())
8573 .unwrap_or_default();
8574 if is_private {
8575 Err(anyhow!(ErrorCode::UnsharedItem))
8576 } else {
8577 Ok(proto::OpenBufferResponse {
8578 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8579 })
8580 }
8581 })?
8582 }
8583
8584 fn serialize_project_transaction_for_peer(
8585 &mut self,
8586 project_transaction: ProjectTransaction,
8587 peer_id: proto::PeerId,
8588 cx: &mut AppContext,
8589 ) -> proto::ProjectTransaction {
8590 let mut serialized_transaction = proto::ProjectTransaction {
8591 buffer_ids: Default::default(),
8592 transactions: Default::default(),
8593 };
8594 for (buffer, transaction) in project_transaction.0 {
8595 serialized_transaction
8596 .buffer_ids
8597 .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
8598 serialized_transaction
8599 .transactions
8600 .push(language::proto::serialize_transaction(&transaction));
8601 }
8602 serialized_transaction
8603 }
8604
8605 fn deserialize_project_transaction(
8606 &mut self,
8607 message: proto::ProjectTransaction,
8608 push_to_history: bool,
8609 cx: &mut ModelContext<Self>,
8610 ) -> Task<Result<ProjectTransaction>> {
8611 cx.spawn(move |this, mut cx| async move {
8612 let mut project_transaction = ProjectTransaction::default();
8613 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
8614 {
8615 let buffer_id = BufferId::new(buffer_id)?;
8616 let buffer = this
8617 .update(&mut cx, |this, cx| {
8618 this.wait_for_remote_buffer(buffer_id, cx)
8619 })?
8620 .await?;
8621 let transaction = language::proto::deserialize_transaction(transaction)?;
8622 project_transaction.0.insert(buffer, transaction);
8623 }
8624
8625 for (buffer, transaction) in &project_transaction.0 {
8626 buffer
8627 .update(&mut cx, |buffer, _| {
8628 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
8629 })?
8630 .await?;
8631
8632 if push_to_history {
8633 buffer.update(&mut cx, |buffer, _| {
8634 buffer.push_transaction(transaction.clone(), Instant::now());
8635 })?;
8636 }
8637 }
8638
8639 Ok(project_transaction)
8640 })
8641 }
8642
8643 fn create_buffer_for_peer(
8644 &mut self,
8645 buffer: &Model<Buffer>,
8646 peer_id: proto::PeerId,
8647 cx: &mut AppContext,
8648 ) -> BufferId {
8649 let buffer_id = buffer.read(cx).remote_id();
8650 if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
8651 updates_tx
8652 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
8653 .ok();
8654 }
8655 buffer_id
8656 }
8657
8658 fn wait_for_remote_buffer(
8659 &mut self,
8660 id: BufferId,
8661 cx: &mut ModelContext<Self>,
8662 ) -> Task<Result<Model<Buffer>>> {
8663 let mut opened_buffer_rx = self.opened_buffer.1.clone();
8664
8665 cx.spawn(move |this, mut cx| async move {
8666 let buffer = loop {
8667 let Some(this) = this.upgrade() else {
8668 return Err(anyhow!("project dropped"));
8669 };
8670
8671 let buffer = this.update(&mut cx, |this, _cx| {
8672 this.opened_buffers
8673 .get(&id)
8674 .and_then(|buffer| buffer.upgrade())
8675 })?;
8676
8677 if let Some(buffer) = buffer {
8678 break buffer;
8679 } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
8680 return Err(anyhow!("disconnected before buffer {} could be opened", id));
8681 }
8682
8683 this.update(&mut cx, |this, _| {
8684 this.incomplete_remote_buffers.entry(id).or_default();
8685 })?;
8686 drop(this);
8687
8688 opened_buffer_rx
8689 .next()
8690 .await
8691 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
8692 };
8693
8694 Ok(buffer)
8695 })
8696 }
8697
8698 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
8699 let project_id = match self.client_state {
8700 ProjectClientState::Remote {
8701 sharing_has_stopped,
8702 remote_id,
8703 ..
8704 } => {
8705 if sharing_has_stopped {
8706 return Task::ready(Err(anyhow!(
8707 "can't synchronize remote buffers on a readonly project"
8708 )));
8709 } else {
8710 remote_id
8711 }
8712 }
8713 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
8714 return Task::ready(Err(anyhow!(
8715 "can't synchronize remote buffers on a local project"
8716 )))
8717 }
8718 };
8719
8720 let client = self.client.clone();
8721 cx.spawn(move |this, mut cx| async move {
8722 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8723 let buffers = this
8724 .opened_buffers
8725 .iter()
8726 .filter_map(|(id, buffer)| {
8727 let buffer = buffer.upgrade()?;
8728 Some(proto::BufferVersion {
8729 id: (*id).into(),
8730 version: language::proto::serialize_version(&buffer.read(cx).version),
8731 })
8732 })
8733 .collect();
8734 let incomplete_buffer_ids = this
8735 .incomplete_remote_buffers
8736 .keys()
8737 .copied()
8738 .collect::<Vec<_>>();
8739
8740 (buffers, incomplete_buffer_ids)
8741 })?;
8742 let response = client
8743 .request(proto::SynchronizeBuffers {
8744 project_id,
8745 buffers,
8746 })
8747 .await?;
8748
8749 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8750 response
8751 .buffers
8752 .into_iter()
8753 .map(|buffer| {
8754 let client = client.clone();
8755 let buffer_id = match BufferId::new(buffer.id) {
8756 Ok(id) => id,
8757 Err(e) => {
8758 return Task::ready(Err(e));
8759 }
8760 };
8761 let remote_version = language::proto::deserialize_version(&buffer.version);
8762 if let Some(buffer) = this.buffer_for_id(buffer_id) {
8763 let operations =
8764 buffer.read(cx).serialize_ops(Some(remote_version), cx);
8765 cx.background_executor().spawn(async move {
8766 let operations = operations.await;
8767 for chunk in split_operations(operations) {
8768 client
8769 .request(proto::UpdateBuffer {
8770 project_id,
8771 buffer_id: buffer_id.into(),
8772 operations: chunk,
8773 })
8774 .await?;
8775 }
8776 anyhow::Ok(())
8777 })
8778 } else {
8779 Task::ready(Ok(()))
8780 }
8781 })
8782 .collect::<Vec<_>>()
8783 })?;
8784
8785 // Any incomplete buffers have open requests waiting. Request that the host sends
8786 // creates these buffers for us again to unblock any waiting futures.
8787 for id in incomplete_buffer_ids {
8788 cx.background_executor()
8789 .spawn(client.request(proto::OpenBufferById {
8790 project_id,
8791 id: id.into(),
8792 }))
8793 .detach();
8794 }
8795
8796 futures::future::join_all(send_updates_for_buffers)
8797 .await
8798 .into_iter()
8799 .collect()
8800 })
8801 }
8802
8803 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8804 self.worktrees()
8805 .map(|worktree| {
8806 let worktree = worktree.read(cx);
8807 proto::WorktreeMetadata {
8808 id: worktree.id().to_proto(),
8809 root_name: worktree.root_name().into(),
8810 visible: worktree.is_visible(),
8811 abs_path: worktree.abs_path().to_string_lossy().into(),
8812 }
8813 })
8814 .collect()
8815 }
8816
8817 fn set_worktrees_from_proto(
8818 &mut self,
8819 worktrees: Vec<proto::WorktreeMetadata>,
8820 cx: &mut ModelContext<Project>,
8821 ) -> Result<()> {
8822 let replica_id = self.replica_id();
8823 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8824
8825 let mut old_worktrees_by_id = self
8826 .worktrees
8827 .drain(..)
8828 .filter_map(|worktree| {
8829 let worktree = worktree.upgrade()?;
8830 Some((worktree.read(cx).id(), worktree))
8831 })
8832 .collect::<HashMap<_, _>>();
8833
8834 for worktree in worktrees {
8835 if let Some(old_worktree) =
8836 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8837 {
8838 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8839 } else {
8840 let worktree =
8841 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8842 let _ = self.add_worktree(&worktree, cx);
8843 }
8844 }
8845
8846 self.metadata_changed(cx);
8847 for id in old_worktrees_by_id.keys() {
8848 cx.emit(Event::WorktreeRemoved(*id));
8849 }
8850
8851 Ok(())
8852 }
8853
8854 fn set_collaborators_from_proto(
8855 &mut self,
8856 messages: Vec<proto::Collaborator>,
8857 cx: &mut ModelContext<Self>,
8858 ) -> Result<()> {
8859 let mut collaborators = HashMap::default();
8860 for message in messages {
8861 let collaborator = Collaborator::from_proto(message)?;
8862 collaborators.insert(collaborator.peer_id, collaborator);
8863 }
8864 for old_peer_id in self.collaborators.keys() {
8865 if !collaborators.contains_key(old_peer_id) {
8866 cx.emit(Event::CollaboratorLeft(*old_peer_id));
8867 }
8868 }
8869 self.collaborators = collaborators;
8870 Ok(())
8871 }
8872
8873 fn deserialize_symbol(
8874 &self,
8875 serialized_symbol: proto::Symbol,
8876 ) -> impl Future<Output = Result<Symbol>> {
8877 let languages = self.languages.clone();
8878 async move {
8879 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8880 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8881 let start = serialized_symbol
8882 .start
8883 .ok_or_else(|| anyhow!("invalid start"))?;
8884 let end = serialized_symbol
8885 .end
8886 .ok_or_else(|| anyhow!("invalid end"))?;
8887 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8888 let path = ProjectPath {
8889 worktree_id,
8890 path: PathBuf::from(serialized_symbol.path).into(),
8891 };
8892 let language = languages
8893 .language_for_file(&path.path, None)
8894 .await
8895 .log_err();
8896 let adapter = language
8897 .as_ref()
8898 .and_then(|language| languages.lsp_adapters(language).first().cloned());
8899 Ok(Symbol {
8900 language_server_name: LanguageServerName(
8901 serialized_symbol.language_server_name.into(),
8902 ),
8903 source_worktree_id,
8904 path,
8905 label: {
8906 match language.as_ref().zip(adapter.as_ref()) {
8907 Some((language, adapter)) => {
8908 adapter
8909 .label_for_symbol(&serialized_symbol.name, kind, language)
8910 .await
8911 }
8912 None => None,
8913 }
8914 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8915 },
8916
8917 name: serialized_symbol.name,
8918 range: Unclipped(PointUtf16::new(start.row, start.column))
8919 ..Unclipped(PointUtf16::new(end.row, end.column)),
8920 kind,
8921 signature: serialized_symbol
8922 .signature
8923 .try_into()
8924 .map_err(|_| anyhow!("invalid signature"))?,
8925 })
8926 }
8927 }
8928
8929 async fn handle_buffer_saved(
8930 this: Model<Self>,
8931 envelope: TypedEnvelope<proto::BufferSaved>,
8932 _: Arc<Client>,
8933 mut cx: AsyncAppContext,
8934 ) -> Result<()> {
8935 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8936 let version = deserialize_version(&envelope.payload.version);
8937 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8938 let mtime = envelope
8939 .payload
8940 .mtime
8941 .ok_or_else(|| anyhow!("missing mtime"))?
8942 .into();
8943
8944 this.update(&mut cx, |this, cx| {
8945 let buffer = this
8946 .opened_buffers
8947 .get(&buffer_id)
8948 .and_then(|buffer| buffer.upgrade())
8949 .or_else(|| {
8950 this.incomplete_remote_buffers
8951 .get(&buffer_id)
8952 .and_then(|b| b.clone())
8953 });
8954 if let Some(buffer) = buffer {
8955 buffer.update(cx, |buffer, cx| {
8956 buffer.did_save(version, fingerprint, mtime, cx);
8957 });
8958 }
8959 Ok(())
8960 })?
8961 }
8962
8963 async fn handle_buffer_reloaded(
8964 this: Model<Self>,
8965 envelope: TypedEnvelope<proto::BufferReloaded>,
8966 _: Arc<Client>,
8967 mut cx: AsyncAppContext,
8968 ) -> Result<()> {
8969 let payload = envelope.payload;
8970 let version = deserialize_version(&payload.version);
8971 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8972 let line_ending = deserialize_line_ending(
8973 proto::LineEnding::from_i32(payload.line_ending)
8974 .ok_or_else(|| anyhow!("missing line ending"))?,
8975 );
8976 let mtime = payload
8977 .mtime
8978 .ok_or_else(|| anyhow!("missing mtime"))?
8979 .into();
8980 let buffer_id = BufferId::new(payload.buffer_id)?;
8981 this.update(&mut cx, |this, cx| {
8982 let buffer = this
8983 .opened_buffers
8984 .get(&buffer_id)
8985 .and_then(|buffer| buffer.upgrade())
8986 .or_else(|| {
8987 this.incomplete_remote_buffers
8988 .get(&buffer_id)
8989 .cloned()
8990 .flatten()
8991 });
8992 if let Some(buffer) = buffer {
8993 buffer.update(cx, |buffer, cx| {
8994 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8995 });
8996 }
8997 Ok(())
8998 })?
8999 }
9000
9001 #[allow(clippy::type_complexity)]
9002 fn edits_from_lsp(
9003 &mut self,
9004 buffer: &Model<Buffer>,
9005 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
9006 server_id: LanguageServerId,
9007 version: Option<i32>,
9008 cx: &mut ModelContext<Self>,
9009 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
9010 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
9011 cx.background_executor().spawn(async move {
9012 let snapshot = snapshot?;
9013 let mut lsp_edits = lsp_edits
9014 .into_iter()
9015 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
9016 .collect::<Vec<_>>();
9017 lsp_edits.sort_by_key(|(range, _)| range.start);
9018
9019 let mut lsp_edits = lsp_edits.into_iter().peekable();
9020 let mut edits = Vec::new();
9021 while let Some((range, mut new_text)) = lsp_edits.next() {
9022 // Clip invalid ranges provided by the language server.
9023 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
9024 ..snapshot.clip_point_utf16(range.end, Bias::Left);
9025
9026 // Combine any LSP edits that are adjacent.
9027 //
9028 // Also, combine LSP edits that are separated from each other by only
9029 // a newline. This is important because for some code actions,
9030 // Rust-analyzer rewrites the entire buffer via a series of edits that
9031 // are separated by unchanged newline characters.
9032 //
9033 // In order for the diffing logic below to work properly, any edits that
9034 // cancel each other out must be combined into one.
9035 while let Some((next_range, next_text)) = lsp_edits.peek() {
9036 if next_range.start.0 > range.end {
9037 if next_range.start.0.row > range.end.row + 1
9038 || next_range.start.0.column > 0
9039 || snapshot.clip_point_utf16(
9040 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
9041 Bias::Left,
9042 ) > range.end
9043 {
9044 break;
9045 }
9046 new_text.push('\n');
9047 }
9048 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
9049 new_text.push_str(next_text);
9050 lsp_edits.next();
9051 }
9052
9053 // For multiline edits, perform a diff of the old and new text so that
9054 // we can identify the changes more precisely, preserving the locations
9055 // of any anchors positioned in the unchanged regions.
9056 if range.end.row > range.start.row {
9057 let mut offset = range.start.to_offset(&snapshot);
9058 let old_text = snapshot.text_for_range(range).collect::<String>();
9059
9060 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
9061 let mut moved_since_edit = true;
9062 for change in diff.iter_all_changes() {
9063 let tag = change.tag();
9064 let value = change.value();
9065 match tag {
9066 ChangeTag::Equal => {
9067 offset += value.len();
9068 moved_since_edit = true;
9069 }
9070 ChangeTag::Delete => {
9071 let start = snapshot.anchor_after(offset);
9072 let end = snapshot.anchor_before(offset + value.len());
9073 if moved_since_edit {
9074 edits.push((start..end, String::new()));
9075 } else {
9076 edits.last_mut().unwrap().0.end = end;
9077 }
9078 offset += value.len();
9079 moved_since_edit = false;
9080 }
9081 ChangeTag::Insert => {
9082 if moved_since_edit {
9083 let anchor = snapshot.anchor_after(offset);
9084 edits.push((anchor..anchor, value.to_string()));
9085 } else {
9086 edits.last_mut().unwrap().1.push_str(value);
9087 }
9088 moved_since_edit = false;
9089 }
9090 }
9091 }
9092 } else if range.end == range.start {
9093 let anchor = snapshot.anchor_after(range.start);
9094 edits.push((anchor..anchor, new_text));
9095 } else {
9096 let edit_start = snapshot.anchor_after(range.start);
9097 let edit_end = snapshot.anchor_before(range.end);
9098 edits.push((edit_start..edit_end, new_text));
9099 }
9100 }
9101
9102 Ok(edits)
9103 })
9104 }
9105
9106 fn buffer_snapshot_for_lsp_version(
9107 &mut self,
9108 buffer: &Model<Buffer>,
9109 server_id: LanguageServerId,
9110 version: Option<i32>,
9111 cx: &AppContext,
9112 ) -> Result<TextBufferSnapshot> {
9113 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
9114
9115 if let Some(version) = version {
9116 let buffer_id = buffer.read(cx).remote_id();
9117 let snapshots = self
9118 .buffer_snapshots
9119 .get_mut(&buffer_id)
9120 .and_then(|m| m.get_mut(&server_id))
9121 .ok_or_else(|| {
9122 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
9123 })?;
9124
9125 let found_snapshot = snapshots
9126 .binary_search_by_key(&version, |e| e.version)
9127 .map(|ix| snapshots[ix].snapshot.clone())
9128 .map_err(|_| {
9129 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
9130 })?;
9131
9132 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
9133 Ok(found_snapshot)
9134 } else {
9135 Ok((buffer.read(cx)).text_snapshot())
9136 }
9137 }
9138
9139 pub fn language_servers(
9140 &self,
9141 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
9142 self.language_server_ids
9143 .iter()
9144 .map(|((worktree_id, server_name), server_id)| {
9145 (*server_id, server_name.clone(), *worktree_id)
9146 })
9147 }
9148
9149 pub fn supplementary_language_servers(
9150 &self,
9151 ) -> impl '_
9152 + Iterator<
9153 Item = (
9154 &LanguageServerId,
9155 &(LanguageServerName, Arc<LanguageServer>),
9156 ),
9157 > {
9158 self.supplementary_language_servers.iter()
9159 }
9160
9161 pub fn language_server_adapter_for_id(
9162 &self,
9163 id: LanguageServerId,
9164 ) -> Option<Arc<CachedLspAdapter>> {
9165 if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
9166 Some(adapter.clone())
9167 } else {
9168 None
9169 }
9170 }
9171
9172 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
9173 if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
9174 Some(server.clone())
9175 } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
9176 Some(Arc::clone(server))
9177 } else {
9178 None
9179 }
9180 }
9181
9182 pub fn language_servers_for_buffer(
9183 &self,
9184 buffer: &Buffer,
9185 cx: &AppContext,
9186 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9187 self.language_server_ids_for_buffer(buffer, cx)
9188 .into_iter()
9189 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
9190 LanguageServerState::Running {
9191 adapter, server, ..
9192 } => Some((adapter, server)),
9193 _ => None,
9194 })
9195 }
9196
9197 fn primary_language_server_for_buffer(
9198 &self,
9199 buffer: &Buffer,
9200 cx: &AppContext,
9201 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9202 self.language_servers_for_buffer(buffer, cx).next()
9203 }
9204
9205 pub fn language_server_for_buffer(
9206 &self,
9207 buffer: &Buffer,
9208 server_id: LanguageServerId,
9209 cx: &AppContext,
9210 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9211 self.language_servers_for_buffer(buffer, cx)
9212 .find(|(_, s)| s.server_id() == server_id)
9213 }
9214
9215 fn language_server_ids_for_buffer(
9216 &self,
9217 buffer: &Buffer,
9218 cx: &AppContext,
9219 ) -> Vec<LanguageServerId> {
9220 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
9221 let worktree_id = file.worktree_id(cx);
9222 self.languages
9223 .lsp_adapters(&language)
9224 .iter()
9225 .flat_map(|adapter| {
9226 let key = (worktree_id, adapter.name.clone());
9227 self.language_server_ids.get(&key).copied()
9228 })
9229 .collect()
9230 } else {
9231 Vec::new()
9232 }
9233 }
9234}
9235
9236fn subscribe_for_copilot_events(
9237 copilot: &Model<Copilot>,
9238 cx: &mut ModelContext<'_, Project>,
9239) -> gpui::Subscription {
9240 cx.subscribe(
9241 copilot,
9242 |project, copilot, copilot_event, cx| match copilot_event {
9243 copilot::Event::CopilotLanguageServerStarted => {
9244 match copilot.read(cx).language_server() {
9245 Some((name, copilot_server)) => {
9246 // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
9247 if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
9248 let new_server_id = copilot_server.server_id();
9249 let weak_project = cx.weak_model();
9250 let copilot_log_subscription = copilot_server
9251 .on_notification::<copilot::request::LogMessage, _>(
9252 move |params, mut cx| {
9253 weak_project.update(&mut cx, |_, cx| {
9254 cx.emit(Event::LanguageServerLog(
9255 new_server_id,
9256 params.message,
9257 ));
9258 }).ok();
9259 },
9260 );
9261 project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
9262 project.copilot_log_subscription = Some(copilot_log_subscription);
9263 cx.emit(Event::LanguageServerAdded(new_server_id));
9264 }
9265 }
9266 None => debug_panic!("Received Copilot language server started event, but no language server is running"),
9267 }
9268 }
9269 },
9270 )
9271}
9272
9273fn glob_literal_prefix(glob: &str) -> &str {
9274 let mut literal_end = 0;
9275 for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
9276 if part.contains(&['*', '?', '{', '}']) {
9277 break;
9278 } else {
9279 if i > 0 {
9280 // Account for separator prior to this part
9281 literal_end += path::MAIN_SEPARATOR.len_utf8();
9282 }
9283 literal_end += part.len();
9284 }
9285 }
9286 &glob[..literal_end]
9287}
9288
9289impl WorktreeHandle {
9290 pub fn upgrade(&self) -> Option<Model<Worktree>> {
9291 match self {
9292 WorktreeHandle::Strong(handle) => Some(handle.clone()),
9293 WorktreeHandle::Weak(handle) => handle.upgrade(),
9294 }
9295 }
9296
9297 pub fn handle_id(&self) -> usize {
9298 match self {
9299 WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
9300 WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
9301 }
9302 }
9303}
9304
9305impl OpenBuffer {
9306 pub fn upgrade(&self) -> Option<Model<Buffer>> {
9307 match self {
9308 OpenBuffer::Strong(handle) => Some(handle.clone()),
9309 OpenBuffer::Weak(handle) => handle.upgrade(),
9310 OpenBuffer::Operations(_) => None,
9311 }
9312 }
9313}
9314
9315pub struct PathMatchCandidateSet {
9316 pub snapshot: Snapshot,
9317 pub include_ignored: bool,
9318 pub include_root_name: bool,
9319}
9320
9321impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
9322 type Candidates = PathMatchCandidateSetIter<'a>;
9323
9324 fn id(&self) -> usize {
9325 self.snapshot.id().to_usize()
9326 }
9327
9328 fn len(&self) -> usize {
9329 if self.include_ignored {
9330 self.snapshot.file_count()
9331 } else {
9332 self.snapshot.visible_file_count()
9333 }
9334 }
9335
9336 fn prefix(&self) -> Arc<str> {
9337 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
9338 self.snapshot.root_name().into()
9339 } else if self.include_root_name {
9340 format!("{}/", self.snapshot.root_name()).into()
9341 } else {
9342 "".into()
9343 }
9344 }
9345
9346 fn candidates(&'a self, start: usize) -> Self::Candidates {
9347 PathMatchCandidateSetIter {
9348 traversal: self.snapshot.files(self.include_ignored, start),
9349 }
9350 }
9351}
9352
9353pub struct PathMatchCandidateSetIter<'a> {
9354 traversal: Traversal<'a>,
9355}
9356
9357impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
9358 type Item = fuzzy::PathMatchCandidate<'a>;
9359
9360 fn next(&mut self) -> Option<Self::Item> {
9361 self.traversal.next().map(|entry| {
9362 if let EntryKind::File(char_bag) = entry.kind {
9363 fuzzy::PathMatchCandidate {
9364 path: &entry.path,
9365 char_bag,
9366 }
9367 } else {
9368 unreachable!()
9369 }
9370 })
9371 }
9372}
9373
9374impl EventEmitter<Event> for Project {}
9375
9376impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
9377 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
9378 Self {
9379 worktree_id,
9380 path: path.as_ref().into(),
9381 }
9382 }
9383}
9384
9385struct ProjectLspAdapterDelegate {
9386 project: WeakModel<Project>,
9387 worktree: worktree::Snapshot,
9388 fs: Arc<dyn Fs>,
9389 http_client: Arc<dyn HttpClient>,
9390 language_registry: Arc<LanguageRegistry>,
9391 shell_env: Mutex<Option<HashMap<String, String>>>,
9392}
9393
9394impl ProjectLspAdapterDelegate {
9395 fn new(project: &Project, worktree: &Model<Worktree>, cx: &ModelContext<Project>) -> Arc<Self> {
9396 Arc::new(Self {
9397 project: cx.weak_model(),
9398 worktree: worktree.read(cx).snapshot(),
9399 fs: project.fs.clone(),
9400 http_client: project.client.http_client(),
9401 language_registry: project.languages.clone(),
9402 shell_env: Default::default(),
9403 })
9404 }
9405
9406 async fn load_shell_env(&self) {
9407 let worktree_abs_path = self.worktree.abs_path();
9408 let shell_env = load_shell_environment(&worktree_abs_path)
9409 .await
9410 .with_context(|| {
9411 format!("failed to determine load login shell environment in {worktree_abs_path:?}")
9412 })
9413 .log_err()
9414 .unwrap_or_default();
9415 *self.shell_env.lock() = Some(shell_env);
9416 }
9417}
9418
9419#[async_trait]
9420impl LspAdapterDelegate for ProjectLspAdapterDelegate {
9421 fn show_notification(&self, message: &str, cx: &mut AppContext) {
9422 self.project
9423 .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())))
9424 .ok();
9425 }
9426
9427 fn http_client(&self) -> Arc<dyn HttpClient> {
9428 self.http_client.clone()
9429 }
9430
9431 async fn shell_env(&self) -> HashMap<String, String> {
9432 self.load_shell_env().await;
9433 self.shell_env.lock().as_ref().cloned().unwrap_or_default()
9434 }
9435
9436 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
9437 let worktree_abs_path = self.worktree.abs_path();
9438 self.load_shell_env().await;
9439 let shell_path = self
9440 .shell_env
9441 .lock()
9442 .as_ref()
9443 .and_then(|shell_env| shell_env.get("PATH").cloned());
9444 which::which_in(command, shell_path.as_ref(), &worktree_abs_path).ok()
9445 }
9446
9447 fn update_status(
9448 &self,
9449 server_name: LanguageServerName,
9450 status: language::LanguageServerBinaryStatus,
9451 ) {
9452 self.language_registry
9453 .update_lsp_status(server_name, status);
9454 }
9455
9456 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
9457 if self.worktree.entry_for_path(&path).is_none() {
9458 return Err(anyhow!("no such path {path:?}"));
9459 }
9460 let path = self.worktree.absolutize(path.as_ref())?;
9461 let content = self.fs.load(&path).await?;
9462 Ok(content)
9463 }
9464}
9465
9466fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9467 proto::Symbol {
9468 language_server_name: symbol.language_server_name.0.to_string(),
9469 source_worktree_id: symbol.source_worktree_id.to_proto(),
9470 worktree_id: symbol.path.worktree_id.to_proto(),
9471 path: symbol.path.path.to_string_lossy().to_string(),
9472 name: symbol.name.clone(),
9473 kind: unsafe { mem::transmute(symbol.kind) },
9474 start: Some(proto::PointUtf16 {
9475 row: symbol.range.start.0.row,
9476 column: symbol.range.start.0.column,
9477 }),
9478 end: Some(proto::PointUtf16 {
9479 row: symbol.range.end.0.row,
9480 column: symbol.range.end.0.column,
9481 }),
9482 signature: symbol.signature.to_vec(),
9483 }
9484}
9485
9486fn relativize_path(base: &Path, path: &Path) -> PathBuf {
9487 let mut path_components = path.components();
9488 let mut base_components = base.components();
9489 let mut components: Vec<Component> = Vec::new();
9490 loop {
9491 match (path_components.next(), base_components.next()) {
9492 (None, None) => break,
9493 (Some(a), None) => {
9494 components.push(a);
9495 components.extend(path_components.by_ref());
9496 break;
9497 }
9498 (None, _) => components.push(Component::ParentDir),
9499 (Some(a), Some(b)) if components.is_empty() && a == b => (),
9500 (Some(a), Some(Component::CurDir)) => components.push(a),
9501 (Some(a), Some(_)) => {
9502 components.push(Component::ParentDir);
9503 for _ in base_components {
9504 components.push(Component::ParentDir);
9505 }
9506 components.push(a);
9507 components.extend(path_components.by_ref());
9508 break;
9509 }
9510 }
9511 }
9512 components.iter().map(|c| c.as_os_str()).collect()
9513}
9514
9515fn resolve_path(base: &Path, path: &Path) -> PathBuf {
9516 let mut result = base.to_path_buf();
9517 for component in path.components() {
9518 match component {
9519 Component::ParentDir => {
9520 result.pop();
9521 }
9522 Component::CurDir => (),
9523 _ => result.push(component),
9524 }
9525 }
9526 result
9527}
9528
9529impl Item for Buffer {
9530 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
9531 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
9532 }
9533
9534 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
9535 File::from_dyn(self.file()).map(|file| ProjectPath {
9536 worktree_id: file.worktree_id(cx),
9537 path: file.path().clone(),
9538 })
9539 }
9540}
9541
9542async fn wait_for_loading_buffer(
9543 mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
9544) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
9545 loop {
9546 if let Some(result) = receiver.borrow().as_ref() {
9547 match result {
9548 Ok(buffer) => return Ok(buffer.to_owned()),
9549 Err(e) => return Err(e.to_owned()),
9550 }
9551 }
9552 receiver.next().await;
9553 }
9554}
9555
9556fn include_text(server: &lsp::LanguageServer) -> bool {
9557 server
9558 .capabilities()
9559 .text_document_sync
9560 .as_ref()
9561 .and_then(|sync| match sync {
9562 lsp::TextDocumentSyncCapability::Kind(_) => None,
9563 lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9564 })
9565 .and_then(|save_options| match save_options {
9566 lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9567 lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9568 })
9569 .unwrap_or(false)
9570}
9571
9572async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
9573 let marker = "ZED_SHELL_START";
9574 let shell = env::var("SHELL").context(
9575 "SHELL environment variable is not assigned so we can't source login environment variables",
9576 )?;
9577
9578 // What we're doing here is to spawn a shell and then `cd` into
9579 // the project directory to get the env in there as if the user
9580 // `cd`'d into it. We do that because tools like direnv, asdf, ...
9581 // hook into `cd` and only set up the env after that.
9582 //
9583 // In certain shells we need to execute additional_command in order to
9584 // trigger the behavior of direnv, etc.
9585 //
9586 //
9587 // The `exit 0` is the result of hours of debugging, trying to find out
9588 // why running this command here, without `exit 0`, would mess
9589 // up signal process for our process so that `ctrl-c` doesn't work
9590 // anymore.
9591 //
9592 // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'` would
9593 // do that, but it does, and `exit 0` helps.
9594 let additional_command = PathBuf::from(&shell)
9595 .file_name()
9596 .and_then(|f| f.to_str())
9597 .and_then(|shell| match shell {
9598 "fish" => Some("emit fish_prompt;"),
9599 _ => None,
9600 });
9601
9602 let command = format!(
9603 "cd '{}';{} echo {marker}; /usr/bin/env -0; exit 0;",
9604 dir.display(),
9605 additional_command.unwrap_or("")
9606 );
9607
9608 let output = smol::process::Command::new(&shell)
9609 .args(["-i", "-c", &command])
9610 .output()
9611 .await
9612 .context("failed to spawn login shell to source login environment variables")?;
9613
9614 anyhow::ensure!(
9615 output.status.success(),
9616 "login shell exited with error {:?}",
9617 output.status
9618 );
9619
9620 let stdout = String::from_utf8_lossy(&output.stdout);
9621 let env_output_start = stdout.find(marker).ok_or_else(|| {
9622 anyhow!(
9623 "failed to parse output of `env` command in login shell: {}",
9624 stdout
9625 )
9626 })?;
9627
9628 let mut parsed_env = HashMap::default();
9629 let env_output = &stdout[env_output_start + marker.len()..];
9630 for line in env_output.split_terminator('\0') {
9631 if let Some(separator_index) = line.find('=') {
9632 let key = line[..separator_index].to_string();
9633 let value = line[separator_index + 1..].to_string();
9634 parsed_env.insert(key, value);
9635 }
9636 }
9637 Ok(parsed_env)
9638}