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