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