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