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