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