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 #[allow(clippy::nonminimal_bool)]
4287 if !code_actions.is_empty()
4288 && !(trigger == FormatTrigger::Save
4289 && settings.format_on_save == FormatOnSave::Off)
4290 {
4291 let actions = project
4292 .update(&mut cx, |this, cx| {
4293 this.request_lsp(
4294 buffer.clone(),
4295 LanguageServerToQuery::Other(language_server.server_id()),
4296 GetCodeActions {
4297 range: text::Anchor::MIN..text::Anchor::MAX,
4298 kinds: Some(code_actions),
4299 },
4300 cx,
4301 )
4302 })?
4303 .await?;
4304
4305 for action in actions {
4306 if let Some(edit) = action.lsp_action.edit {
4307 if edit.changes.is_none() && edit.document_changes.is_none() {
4308 continue;
4309 }
4310
4311 let new = Self::deserialize_workspace_edit(
4312 project
4313 .upgrade()
4314 .ok_or_else(|| anyhow!("project dropped"))?,
4315 edit,
4316 push_to_history,
4317 lsp_adapter.clone(),
4318 language_server.clone(),
4319 &mut cx,
4320 )
4321 .await?;
4322 project_transaction.0.extend(new.0);
4323 }
4324
4325 if let Some(command) = action.lsp_action.command {
4326 project.update(&mut cx, |this, _| {
4327 this.last_workspace_edits_by_language_server
4328 .remove(&language_server.server_id());
4329 })?;
4330
4331 language_server
4332 .request::<lsp::request::ExecuteCommand>(
4333 lsp::ExecuteCommandParams {
4334 command: command.command,
4335 arguments: command.arguments.unwrap_or_default(),
4336 ..Default::default()
4337 },
4338 )
4339 .await?;
4340
4341 project.update(&mut cx, |this, _| {
4342 project_transaction.0.extend(
4343 this.last_workspace_edits_by_language_server
4344 .remove(&language_server.server_id())
4345 .unwrap_or_default()
4346 .0,
4347 )
4348 })?;
4349 }
4350 }
4351 }
4352 }
4353
4354 // Apply language-specific formatting using either the primary language server
4355 // or external command.
4356 let primary_language_server = adapters_and_servers
4357 .first()
4358 .cloned()
4359 .map(|(_, lsp)| lsp.clone());
4360 let server_and_buffer = primary_language_server
4361 .as_ref()
4362 .zip(buffer_abs_path.as_ref());
4363
4364 let mut format_operation = None;
4365 match (&settings.formatter, &settings.format_on_save) {
4366 (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4367
4368 (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4369 | (_, FormatOnSave::LanguageServer) => {
4370 if let Some((language_server, buffer_abs_path)) = server_and_buffer {
4371 format_operation = Some(FormatOperation::Lsp(
4372 Self::format_via_lsp(
4373 &project,
4374 buffer,
4375 buffer_abs_path,
4376 language_server,
4377 tab_size,
4378 &mut cx,
4379 )
4380 .await
4381 .context("failed to format via language server")?,
4382 ));
4383 }
4384 }
4385
4386 (
4387 Formatter::External { command, arguments },
4388 FormatOnSave::On | FormatOnSave::Off,
4389 )
4390 | (_, FormatOnSave::External { command, arguments }) => {
4391 if let Some(buffer_abs_path) = buffer_abs_path {
4392 format_operation = Self::format_via_external_command(
4393 buffer,
4394 buffer_abs_path,
4395 command,
4396 arguments,
4397 &mut cx,
4398 )
4399 .await
4400 .context(format!(
4401 "failed to format via external command {:?}",
4402 command
4403 ))?
4404 .map(FormatOperation::External);
4405 }
4406 }
4407 (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4408 if let Some(new_operation) =
4409 prettier_support::format_with_prettier(&project, buffer, &mut cx)
4410 .await
4411 {
4412 format_operation = Some(new_operation);
4413 } else if let Some((language_server, buffer_abs_path)) =
4414 server_and_buffer
4415 {
4416 format_operation = Some(FormatOperation::Lsp(
4417 Self::format_via_lsp(
4418 &project,
4419 buffer,
4420 buffer_abs_path,
4421 language_server,
4422 tab_size,
4423 &mut cx,
4424 )
4425 .await
4426 .context("failed to format via language server")?,
4427 ));
4428 }
4429 }
4430 (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4431 if let Some(new_operation) =
4432 prettier_support::format_with_prettier(&project, buffer, &mut cx)
4433 .await
4434 {
4435 format_operation = Some(new_operation);
4436 }
4437 }
4438 };
4439
4440 buffer.update(&mut cx, |b, cx| {
4441 // If the buffer had its whitespace formatted and was edited while the language-specific
4442 // formatting was being computed, avoid applying the language-specific formatting, because
4443 // it can't be grouped with the whitespace formatting in the undo history.
4444 if let Some(transaction_id) = whitespace_transaction_id {
4445 if b.peek_undo_stack()
4446 .map_or(true, |e| e.transaction_id() != transaction_id)
4447 {
4448 format_operation.take();
4449 }
4450 }
4451
4452 // Apply any language-specific formatting, and group the two formatting operations
4453 // in the buffer's undo history.
4454 if let Some(operation) = format_operation {
4455 match operation {
4456 FormatOperation::Lsp(edits) => {
4457 b.edit(edits, None, cx);
4458 }
4459 FormatOperation::External(diff) => {
4460 b.apply_diff(diff, cx);
4461 }
4462 FormatOperation::Prettier(diff) => {
4463 b.apply_diff(diff, cx);
4464 }
4465 }
4466
4467 if let Some(transaction_id) = whitespace_transaction_id {
4468 b.group_until_transaction(transaction_id);
4469 } else if let Some(transaction) = project_transaction.0.get(buffer) {
4470 b.group_until_transaction(transaction.id)
4471 }
4472 }
4473
4474 if let Some(transaction) = b.finalize_last_transaction().cloned() {
4475 if !push_to_history {
4476 b.forget_transaction(transaction.id);
4477 }
4478 project_transaction.0.insert(buffer.clone(), transaction);
4479 }
4480 })?;
4481 }
4482
4483 Ok(project_transaction)
4484 })
4485 } else {
4486 let remote_id = self.remote_id();
4487 let client = self.client.clone();
4488 cx.spawn(move |this, mut cx| async move {
4489 let mut project_transaction = ProjectTransaction::default();
4490 if let Some(project_id) = remote_id {
4491 let response = client
4492 .request(proto::FormatBuffers {
4493 project_id,
4494 trigger: trigger as i32,
4495 buffer_ids: buffers
4496 .iter()
4497 .map(|buffer| {
4498 buffer.update(&mut cx, |buffer, _| buffer.remote_id().into())
4499 })
4500 .collect::<Result<_>>()?,
4501 })
4502 .await?
4503 .transaction
4504 .ok_or_else(|| anyhow!("missing transaction"))?;
4505 project_transaction = this
4506 .update(&mut cx, |this, cx| {
4507 this.deserialize_project_transaction(response, push_to_history, cx)
4508 })?
4509 .await?;
4510 }
4511 Ok(project_transaction)
4512 })
4513 }
4514 }
4515
4516 async fn format_via_lsp(
4517 this: &WeakModel<Self>,
4518 buffer: &Model<Buffer>,
4519 abs_path: &Path,
4520 language_server: &Arc<LanguageServer>,
4521 tab_size: NonZeroU32,
4522 cx: &mut AsyncAppContext,
4523 ) -> Result<Vec<(Range<Anchor>, String)>> {
4524 let uri = lsp::Url::from_file_path(abs_path)
4525 .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4526 let text_document = lsp::TextDocumentIdentifier::new(uri);
4527 let capabilities = &language_server.capabilities();
4528
4529 let formatting_provider = capabilities.document_formatting_provider.as_ref();
4530 let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4531
4532 let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4533 language_server
4534 .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4535 text_document,
4536 options: lsp_command::lsp_formatting_options(tab_size.get()),
4537 work_done_progress_params: Default::default(),
4538 })
4539 .await?
4540 } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4541 let buffer_start = lsp::Position::new(0, 0);
4542 let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4543
4544 language_server
4545 .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4546 text_document,
4547 range: lsp::Range::new(buffer_start, buffer_end),
4548 options: lsp_command::lsp_formatting_options(tab_size.get()),
4549 work_done_progress_params: Default::default(),
4550 })
4551 .await?
4552 } else {
4553 None
4554 };
4555
4556 if let Some(lsp_edits) = lsp_edits {
4557 this.update(cx, |this, cx| {
4558 this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4559 })?
4560 .await
4561 } else {
4562 Ok(Vec::new())
4563 }
4564 }
4565
4566 async fn format_via_external_command(
4567 buffer: &Model<Buffer>,
4568 buffer_abs_path: &Path,
4569 command: &str,
4570 arguments: &[String],
4571 cx: &mut AsyncAppContext,
4572 ) -> Result<Option<Diff>> {
4573 let working_dir_path = buffer.update(cx, |buffer, cx| {
4574 let file = File::from_dyn(buffer.file())?;
4575 let worktree = file.worktree.read(cx).as_local()?;
4576 let mut worktree_path = worktree.abs_path().to_path_buf();
4577 if worktree.root_entry()?.is_file() {
4578 worktree_path.pop();
4579 }
4580 Some(worktree_path)
4581 })?;
4582
4583 if let Some(working_dir_path) = working_dir_path {
4584 let mut child =
4585 smol::process::Command::new(command)
4586 .args(arguments.iter().map(|arg| {
4587 arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4588 }))
4589 .current_dir(&working_dir_path)
4590 .stdin(smol::process::Stdio::piped())
4591 .stdout(smol::process::Stdio::piped())
4592 .stderr(smol::process::Stdio::piped())
4593 .spawn()?;
4594 let stdin = child
4595 .stdin
4596 .as_mut()
4597 .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4598 let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4599 for chunk in text.chunks() {
4600 stdin.write_all(chunk.as_bytes()).await?;
4601 }
4602 stdin.flush().await?;
4603
4604 let output = child.output().await?;
4605 if !output.status.success() {
4606 return Err(anyhow!(
4607 "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4608 output.status.code(),
4609 String::from_utf8_lossy(&output.stdout),
4610 String::from_utf8_lossy(&output.stderr),
4611 ));
4612 }
4613
4614 let stdout = String::from_utf8(output.stdout)?;
4615 Ok(Some(
4616 buffer
4617 .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
4618 .await,
4619 ))
4620 } else {
4621 Ok(None)
4622 }
4623 }
4624
4625 #[inline(never)]
4626 fn definition_impl(
4627 &self,
4628 buffer: &Model<Buffer>,
4629 position: PointUtf16,
4630 cx: &mut ModelContext<Self>,
4631 ) -> Task<Result<Vec<LocationLink>>> {
4632 self.request_lsp(
4633 buffer.clone(),
4634 LanguageServerToQuery::Primary,
4635 GetDefinition { position },
4636 cx,
4637 )
4638 }
4639 pub fn definition<T: ToPointUtf16>(
4640 &self,
4641 buffer: &Model<Buffer>,
4642 position: T,
4643 cx: &mut ModelContext<Self>,
4644 ) -> Task<Result<Vec<LocationLink>>> {
4645 let position = position.to_point_utf16(buffer.read(cx));
4646 self.definition_impl(buffer, position, cx)
4647 }
4648
4649 fn type_definition_impl(
4650 &self,
4651 buffer: &Model<Buffer>,
4652 position: PointUtf16,
4653 cx: &mut ModelContext<Self>,
4654 ) -> Task<Result<Vec<LocationLink>>> {
4655 self.request_lsp(
4656 buffer.clone(),
4657 LanguageServerToQuery::Primary,
4658 GetTypeDefinition { position },
4659 cx,
4660 )
4661 }
4662
4663 pub fn type_definition<T: ToPointUtf16>(
4664 &self,
4665 buffer: &Model<Buffer>,
4666 position: T,
4667 cx: &mut ModelContext<Self>,
4668 ) -> Task<Result<Vec<LocationLink>>> {
4669 let position = position.to_point_utf16(buffer.read(cx));
4670 self.type_definition_impl(buffer, position, cx)
4671 }
4672
4673 fn implementation_impl(
4674 &self,
4675 buffer: &Model<Buffer>,
4676 position: PointUtf16,
4677 cx: &mut ModelContext<Self>,
4678 ) -> Task<Result<Vec<LocationLink>>> {
4679 self.request_lsp(
4680 buffer.clone(),
4681 LanguageServerToQuery::Primary,
4682 GetImplementation { position },
4683 cx,
4684 )
4685 }
4686
4687 pub fn implementation<T: ToPointUtf16>(
4688 &self,
4689 buffer: &Model<Buffer>,
4690 position: T,
4691 cx: &mut ModelContext<Self>,
4692 ) -> Task<Result<Vec<LocationLink>>> {
4693 let position = position.to_point_utf16(buffer.read(cx));
4694 self.implementation_impl(buffer, position, cx)
4695 }
4696
4697 fn references_impl(
4698 &self,
4699 buffer: &Model<Buffer>,
4700 position: PointUtf16,
4701 cx: &mut ModelContext<Self>,
4702 ) -> Task<Result<Vec<Location>>> {
4703 self.request_lsp(
4704 buffer.clone(),
4705 LanguageServerToQuery::Primary,
4706 GetReferences { position },
4707 cx,
4708 )
4709 }
4710 pub fn references<T: ToPointUtf16>(
4711 &self,
4712 buffer: &Model<Buffer>,
4713 position: T,
4714 cx: &mut ModelContext<Self>,
4715 ) -> Task<Result<Vec<Location>>> {
4716 let position = position.to_point_utf16(buffer.read(cx));
4717 self.references_impl(buffer, position, cx)
4718 }
4719
4720 fn document_highlights_impl(
4721 &self,
4722 buffer: &Model<Buffer>,
4723 position: PointUtf16,
4724 cx: &mut ModelContext<Self>,
4725 ) -> Task<Result<Vec<DocumentHighlight>>> {
4726 self.request_lsp(
4727 buffer.clone(),
4728 LanguageServerToQuery::Primary,
4729 GetDocumentHighlights { position },
4730 cx,
4731 )
4732 }
4733
4734 pub fn document_highlights<T: ToPointUtf16>(
4735 &self,
4736 buffer: &Model<Buffer>,
4737 position: T,
4738 cx: &mut ModelContext<Self>,
4739 ) -> Task<Result<Vec<DocumentHighlight>>> {
4740 let position = position.to_point_utf16(buffer.read(cx));
4741 self.document_highlights_impl(buffer, position, cx)
4742 }
4743
4744 pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4745 if self.is_local() {
4746 let mut requests = Vec::new();
4747 for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4748 let worktree_id = *worktree_id;
4749 let worktree_handle = self.worktree_for_id(worktree_id, cx);
4750 let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4751 Some(worktree) => worktree,
4752 None => continue,
4753 };
4754 let worktree_abs_path = worktree.abs_path().clone();
4755
4756 let (adapter, language, server) = match self.language_servers.get(server_id) {
4757 Some(LanguageServerState::Running {
4758 adapter,
4759 language,
4760 server,
4761 ..
4762 }) => (adapter.clone(), language.clone(), server),
4763
4764 _ => continue,
4765 };
4766
4767 requests.push(
4768 server
4769 .request::<lsp::request::WorkspaceSymbolRequest>(
4770 lsp::WorkspaceSymbolParams {
4771 query: query.to_string(),
4772 ..Default::default()
4773 },
4774 )
4775 .log_err()
4776 .map(move |response| {
4777 let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4778 lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4779 flat_responses.into_iter().map(|lsp_symbol| {
4780 (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4781 }).collect::<Vec<_>>()
4782 }
4783 lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4784 nested_responses.into_iter().filter_map(|lsp_symbol| {
4785 let location = match lsp_symbol.location {
4786 OneOf::Left(location) => location,
4787 OneOf::Right(_) => {
4788 error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4789 return None
4790 }
4791 };
4792 Some((lsp_symbol.name, lsp_symbol.kind, location))
4793 }).collect::<Vec<_>>()
4794 }
4795 }).unwrap_or_default();
4796
4797 (
4798 adapter,
4799 language,
4800 worktree_id,
4801 worktree_abs_path,
4802 lsp_symbols,
4803 )
4804 }),
4805 );
4806 }
4807
4808 cx.spawn(move |this, mut cx| async move {
4809 let responses = futures::future::join_all(requests).await;
4810 let this = match this.upgrade() {
4811 Some(this) => this,
4812 None => return Ok(Vec::new()),
4813 };
4814
4815 let symbols = this.update(&mut cx, |this, cx| {
4816 let mut symbols = Vec::new();
4817 for (
4818 adapter,
4819 adapter_language,
4820 source_worktree_id,
4821 worktree_abs_path,
4822 lsp_symbols,
4823 ) in responses
4824 {
4825 symbols.extend(lsp_symbols.into_iter().filter_map(
4826 |(symbol_name, symbol_kind, symbol_location)| {
4827 let abs_path = symbol_location.uri.to_file_path().ok()?;
4828 let mut worktree_id = source_worktree_id;
4829 let path;
4830 if let Some((worktree, rel_path)) =
4831 this.find_local_worktree(&abs_path, cx)
4832 {
4833 worktree_id = worktree.read(cx).id();
4834 path = rel_path;
4835 } else {
4836 path = relativize_path(&worktree_abs_path, &abs_path);
4837 }
4838
4839 let project_path = ProjectPath {
4840 worktree_id,
4841 path: path.into(),
4842 };
4843 let signature = this.symbol_signature(&project_path);
4844 let adapter_language = adapter_language.clone();
4845 let language = this
4846 .languages
4847 .language_for_file(&project_path.path, None)
4848 .unwrap_or_else(move |_| adapter_language);
4849 let adapter = adapter.clone();
4850 Some(async move {
4851 let language = language.await;
4852 let label = adapter
4853 .label_for_symbol(&symbol_name, symbol_kind, &language)
4854 .await;
4855
4856 Symbol {
4857 language_server_name: adapter.name.clone(),
4858 source_worktree_id,
4859 path: project_path,
4860 label: label.unwrap_or_else(|| {
4861 CodeLabel::plain(symbol_name.clone(), None)
4862 }),
4863 kind: symbol_kind,
4864 name: symbol_name,
4865 range: range_from_lsp(symbol_location.range),
4866 signature,
4867 }
4868 })
4869 },
4870 ));
4871 }
4872
4873 symbols
4874 })?;
4875
4876 Ok(futures::future::join_all(symbols).await)
4877 })
4878 } else if let Some(project_id) = self.remote_id() {
4879 let request = self.client.request(proto::GetProjectSymbols {
4880 project_id,
4881 query: query.to_string(),
4882 });
4883 cx.spawn(move |this, mut cx| async move {
4884 let response = request.await?;
4885 let mut symbols = Vec::new();
4886 if let Some(this) = this.upgrade() {
4887 let new_symbols = this.update(&mut cx, |this, _| {
4888 response
4889 .symbols
4890 .into_iter()
4891 .map(|symbol| this.deserialize_symbol(symbol))
4892 .collect::<Vec<_>>()
4893 })?;
4894 symbols = futures::future::join_all(new_symbols)
4895 .await
4896 .into_iter()
4897 .filter_map(|symbol| symbol.log_err())
4898 .collect::<Vec<_>>();
4899 }
4900 Ok(symbols)
4901 })
4902 } else {
4903 Task::ready(Ok(Default::default()))
4904 }
4905 }
4906
4907 pub fn open_buffer_for_symbol(
4908 &mut self,
4909 symbol: &Symbol,
4910 cx: &mut ModelContext<Self>,
4911 ) -> Task<Result<Model<Buffer>>> {
4912 if self.is_local() {
4913 let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4914 symbol.source_worktree_id,
4915 symbol.language_server_name.clone(),
4916 )) {
4917 *id
4918 } else {
4919 return Task::ready(Err(anyhow!(
4920 "language server for worktree and language not found"
4921 )));
4922 };
4923
4924 let worktree_abs_path = if let Some(worktree_abs_path) = self
4925 .worktree_for_id(symbol.path.worktree_id, cx)
4926 .and_then(|worktree| worktree.read(cx).as_local())
4927 .map(|local_worktree| local_worktree.abs_path())
4928 {
4929 worktree_abs_path
4930 } else {
4931 return Task::ready(Err(anyhow!("worktree not found for symbol")));
4932 };
4933
4934 let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
4935 let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4936 uri
4937 } else {
4938 return Task::ready(Err(anyhow!("invalid symbol path")));
4939 };
4940
4941 self.open_local_buffer_via_lsp(
4942 symbol_uri,
4943 language_server_id,
4944 symbol.language_server_name.clone(),
4945 cx,
4946 )
4947 } else if let Some(project_id) = self.remote_id() {
4948 let request = self.client.request(proto::OpenBufferForSymbol {
4949 project_id,
4950 symbol: Some(serialize_symbol(symbol)),
4951 });
4952 cx.spawn(move |this, mut cx| async move {
4953 let response = request.await?;
4954 let buffer_id = BufferId::new(response.buffer_id)?;
4955 this.update(&mut cx, |this, cx| {
4956 this.wait_for_remote_buffer(buffer_id, cx)
4957 })?
4958 .await
4959 })
4960 } else {
4961 Task::ready(Err(anyhow!("project does not have a remote id")))
4962 }
4963 }
4964
4965 fn hover_impl(
4966 &self,
4967 buffer: &Model<Buffer>,
4968 position: PointUtf16,
4969 cx: &mut ModelContext<Self>,
4970 ) -> Task<Result<Option<Hover>>> {
4971 self.request_lsp(
4972 buffer.clone(),
4973 LanguageServerToQuery::Primary,
4974 GetHover { position },
4975 cx,
4976 )
4977 }
4978 pub fn hover<T: ToPointUtf16>(
4979 &self,
4980 buffer: &Model<Buffer>,
4981 position: T,
4982 cx: &mut ModelContext<Self>,
4983 ) -> Task<Result<Option<Hover>>> {
4984 let position = position.to_point_utf16(buffer.read(cx));
4985 self.hover_impl(buffer, position, cx)
4986 }
4987
4988 #[inline(never)]
4989 fn completions_impl(
4990 &self,
4991 buffer: &Model<Buffer>,
4992 position: PointUtf16,
4993 cx: &mut ModelContext<Self>,
4994 ) -> Task<Result<Vec<Completion>>> {
4995 if self.is_local() {
4996 let snapshot = buffer.read(cx).snapshot();
4997 let offset = position.to_offset(&snapshot);
4998 let scope = snapshot.language_scope_at(offset);
4999
5000 let server_ids: Vec<_> = self
5001 .language_servers_for_buffer(buffer.read(cx), cx)
5002 .filter(|(_, server)| server.capabilities().completion_provider.is_some())
5003 .filter(|(adapter, _)| {
5004 scope
5005 .as_ref()
5006 .map(|scope| scope.language_allowed(&adapter.name))
5007 .unwrap_or(true)
5008 })
5009 .map(|(_, server)| server.server_id())
5010 .collect();
5011
5012 let buffer = buffer.clone();
5013 cx.spawn(move |this, mut cx| async move {
5014 let mut tasks = Vec::with_capacity(server_ids.len());
5015 this.update(&mut cx, |this, cx| {
5016 for server_id in server_ids {
5017 tasks.push(this.request_lsp(
5018 buffer.clone(),
5019 LanguageServerToQuery::Other(server_id),
5020 GetCompletions { position },
5021 cx,
5022 ));
5023 }
5024 })?;
5025
5026 let mut completions = Vec::new();
5027 for task in tasks {
5028 if let Ok(new_completions) = task.await {
5029 completions.extend_from_slice(&new_completions);
5030 }
5031 }
5032
5033 Ok(completions)
5034 })
5035 } else if let Some(project_id) = self.remote_id() {
5036 self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
5037 } else {
5038 Task::ready(Ok(Default::default()))
5039 }
5040 }
5041 pub fn completions<T: ToOffset + ToPointUtf16>(
5042 &self,
5043 buffer: &Model<Buffer>,
5044 position: T,
5045 cx: &mut ModelContext<Self>,
5046 ) -> Task<Result<Vec<Completion>>> {
5047 let position = position.to_point_utf16(buffer.read(cx));
5048 self.completions_impl(buffer, position, cx)
5049 }
5050
5051 pub fn resolve_completions(
5052 &self,
5053 completion_indices: Vec<usize>,
5054 completions: Arc<RwLock<Box<[Completion]>>>,
5055 cx: &mut ModelContext<Self>,
5056 ) -> Task<Result<bool>> {
5057 let client = self.client();
5058 let language_registry = self.languages().clone();
5059
5060 let is_remote = self.is_remote();
5061 let project_id = self.remote_id();
5062
5063 cx.spawn(move |this, mut cx| async move {
5064 let mut did_resolve = false;
5065 if is_remote {
5066 let project_id =
5067 project_id.ok_or_else(|| anyhow!("Remote project without remote_id"))?;
5068
5069 for completion_index in completion_indices {
5070 let completions_guard = completions.read();
5071 let completion = &completions_guard[completion_index];
5072 if completion.documentation.is_some() {
5073 continue;
5074 }
5075
5076 did_resolve = true;
5077 let server_id = completion.server_id;
5078 let completion = completion.lsp_completion.clone();
5079 drop(completions_guard);
5080
5081 Self::resolve_completion_documentation_remote(
5082 project_id,
5083 server_id,
5084 completions.clone(),
5085 completion_index,
5086 completion,
5087 client.clone(),
5088 language_registry.clone(),
5089 )
5090 .await;
5091 }
5092 } else {
5093 for completion_index in completion_indices {
5094 let completions_guard = completions.read();
5095 let completion = &completions_guard[completion_index];
5096 if completion.documentation.is_some() {
5097 continue;
5098 }
5099
5100 let server_id = completion.server_id;
5101 let completion = completion.lsp_completion.clone();
5102 drop(completions_guard);
5103
5104 let server = this
5105 .read_with(&mut cx, |project, _| {
5106 project.language_server_for_id(server_id)
5107 })
5108 .ok()
5109 .flatten();
5110 let Some(server) = server else {
5111 continue;
5112 };
5113
5114 did_resolve = true;
5115 Self::resolve_completion_documentation_local(
5116 server,
5117 completions.clone(),
5118 completion_index,
5119 completion,
5120 language_registry.clone(),
5121 )
5122 .await;
5123 }
5124 }
5125
5126 Ok(did_resolve)
5127 })
5128 }
5129
5130 async fn resolve_completion_documentation_local(
5131 server: Arc<lsp::LanguageServer>,
5132 completions: Arc<RwLock<Box<[Completion]>>>,
5133 completion_index: usize,
5134 completion: lsp::CompletionItem,
5135 language_registry: Arc<LanguageRegistry>,
5136 ) {
5137 let can_resolve = server
5138 .capabilities()
5139 .completion_provider
5140 .as_ref()
5141 .and_then(|options| options.resolve_provider)
5142 .unwrap_or(false);
5143 if !can_resolve {
5144 return;
5145 }
5146
5147 let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
5148 let Some(completion_item) = request.await.log_err() else {
5149 return;
5150 };
5151
5152 if let Some(lsp_documentation) = completion_item.documentation {
5153 let documentation = language::prepare_completion_documentation(
5154 &lsp_documentation,
5155 &language_registry,
5156 None, // TODO: Try to reasonably work out which language the completion is for
5157 )
5158 .await;
5159
5160 let mut completions = completions.write();
5161 let completion = &mut completions[completion_index];
5162 completion.documentation = Some(documentation);
5163 } else {
5164 let mut completions = completions.write();
5165 let completion = &mut completions[completion_index];
5166 completion.documentation = Some(Documentation::Undocumented);
5167 }
5168 }
5169
5170 async fn resolve_completion_documentation_remote(
5171 project_id: u64,
5172 server_id: LanguageServerId,
5173 completions: Arc<RwLock<Box<[Completion]>>>,
5174 completion_index: usize,
5175 completion: lsp::CompletionItem,
5176 client: Arc<Client>,
5177 language_registry: Arc<LanguageRegistry>,
5178 ) {
5179 let request = proto::ResolveCompletionDocumentation {
5180 project_id,
5181 language_server_id: server_id.0 as u64,
5182 lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
5183 };
5184
5185 let Some(response) = client
5186 .request(request)
5187 .await
5188 .context("completion documentation resolve proto request")
5189 .log_err()
5190 else {
5191 return;
5192 };
5193
5194 if response.text.is_empty() {
5195 let mut completions = completions.write();
5196 let completion = &mut completions[completion_index];
5197 completion.documentation = Some(Documentation::Undocumented);
5198 }
5199
5200 let documentation = if response.is_markdown {
5201 Documentation::MultiLineMarkdown(
5202 markdown::parse_markdown(&response.text, &language_registry, None).await,
5203 )
5204 } else if response.text.lines().count() <= 1 {
5205 Documentation::SingleLine(response.text)
5206 } else {
5207 Documentation::MultiLinePlainText(response.text)
5208 };
5209
5210 let mut completions = completions.write();
5211 let completion = &mut completions[completion_index];
5212 completion.documentation = Some(documentation);
5213 }
5214
5215 pub fn apply_additional_edits_for_completion(
5216 &self,
5217 buffer_handle: Model<Buffer>,
5218 completion: Completion,
5219 push_to_history: bool,
5220 cx: &mut ModelContext<Self>,
5221 ) -> Task<Result<Option<Transaction>>> {
5222 let buffer = buffer_handle.read(cx);
5223 let buffer_id = buffer.remote_id();
5224
5225 if self.is_local() {
5226 let server_id = completion.server_id;
5227 let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
5228 Some((_, server)) => server.clone(),
5229 _ => return Task::ready(Ok(Default::default())),
5230 };
5231
5232 cx.spawn(move |this, mut cx| async move {
5233 let can_resolve = lang_server
5234 .capabilities()
5235 .completion_provider
5236 .as_ref()
5237 .and_then(|options| options.resolve_provider)
5238 .unwrap_or(false);
5239 let additional_text_edits = if can_resolve {
5240 lang_server
5241 .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
5242 .await?
5243 .additional_text_edits
5244 } else {
5245 completion.lsp_completion.additional_text_edits
5246 };
5247 if let Some(edits) = additional_text_edits {
5248 let edits = this
5249 .update(&mut cx, |this, cx| {
5250 this.edits_from_lsp(
5251 &buffer_handle,
5252 edits,
5253 lang_server.server_id(),
5254 None,
5255 cx,
5256 )
5257 })?
5258 .await?;
5259
5260 buffer_handle.update(&mut cx, |buffer, cx| {
5261 buffer.finalize_last_transaction();
5262 buffer.start_transaction();
5263
5264 for (range, text) in edits {
5265 let primary = &completion.old_range;
5266 let start_within = primary.start.cmp(&range.start, buffer).is_le()
5267 && primary.end.cmp(&range.start, buffer).is_ge();
5268 let end_within = range.start.cmp(&primary.end, buffer).is_le()
5269 && range.end.cmp(&primary.end, buffer).is_ge();
5270
5271 //Skip additional edits which overlap with the primary completion edit
5272 //https://github.com/zed-industries/zed/pull/1871
5273 if !start_within && !end_within {
5274 buffer.edit([(range, text)], None, cx);
5275 }
5276 }
5277
5278 let transaction = if buffer.end_transaction(cx).is_some() {
5279 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5280 if !push_to_history {
5281 buffer.forget_transaction(transaction.id);
5282 }
5283 Some(transaction)
5284 } else {
5285 None
5286 };
5287 Ok(transaction)
5288 })?
5289 } else {
5290 Ok(None)
5291 }
5292 })
5293 } else if let Some(project_id) = self.remote_id() {
5294 let client = self.client.clone();
5295 cx.spawn(move |_, mut cx| async move {
5296 let response = client
5297 .request(proto::ApplyCompletionAdditionalEdits {
5298 project_id,
5299 buffer_id: buffer_id.into(),
5300 completion: Some(language::proto::serialize_completion(&completion)),
5301 })
5302 .await?;
5303
5304 if let Some(transaction) = response.transaction {
5305 let transaction = language::proto::deserialize_transaction(transaction)?;
5306 buffer_handle
5307 .update(&mut cx, |buffer, _| {
5308 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5309 })?
5310 .await?;
5311 if push_to_history {
5312 buffer_handle.update(&mut cx, |buffer, _| {
5313 buffer.push_transaction(transaction.clone(), Instant::now());
5314 })?;
5315 }
5316 Ok(Some(transaction))
5317 } else {
5318 Ok(None)
5319 }
5320 })
5321 } else {
5322 Task::ready(Err(anyhow!("project does not have a remote id")))
5323 }
5324 }
5325
5326 fn code_actions_impl(
5327 &self,
5328 buffer_handle: &Model<Buffer>,
5329 range: Range<Anchor>,
5330 cx: &mut ModelContext<Self>,
5331 ) -> Task<Result<Vec<CodeAction>>> {
5332 self.request_lsp(
5333 buffer_handle.clone(),
5334 LanguageServerToQuery::Primary,
5335 GetCodeActions { range, kinds: None },
5336 cx,
5337 )
5338 }
5339
5340 pub fn code_actions<T: Clone + ToOffset>(
5341 &self,
5342 buffer_handle: &Model<Buffer>,
5343 range: Range<T>,
5344 cx: &mut ModelContext<Self>,
5345 ) -> Task<Result<Vec<CodeAction>>> {
5346 let buffer = buffer_handle.read(cx);
5347 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5348 self.code_actions_impl(buffer_handle, range, cx)
5349 }
5350
5351 pub fn apply_code_action(
5352 &self,
5353 buffer_handle: Model<Buffer>,
5354 mut action: CodeAction,
5355 push_to_history: bool,
5356 cx: &mut ModelContext<Self>,
5357 ) -> Task<Result<ProjectTransaction>> {
5358 if self.is_local() {
5359 let buffer = buffer_handle.read(cx);
5360 let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
5361 self.language_server_for_buffer(buffer, action.server_id, cx)
5362 {
5363 (adapter.clone(), server.clone())
5364 } else {
5365 return Task::ready(Ok(Default::default()));
5366 };
5367 let range = action.range.to_point_utf16(buffer);
5368
5369 cx.spawn(move |this, mut cx| async move {
5370 if let Some(lsp_range) = action
5371 .lsp_action
5372 .data
5373 .as_mut()
5374 .and_then(|d| d.get_mut("codeActionParams"))
5375 .and_then(|d| d.get_mut("range"))
5376 {
5377 *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
5378 action.lsp_action = lang_server
5379 .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
5380 .await?;
5381 } else {
5382 let actions = this
5383 .update(&mut cx, |this, cx| {
5384 this.code_actions(&buffer_handle, action.range, cx)
5385 })?
5386 .await?;
5387 action.lsp_action = actions
5388 .into_iter()
5389 .find(|a| a.lsp_action.title == action.lsp_action.title)
5390 .ok_or_else(|| anyhow!("code action is outdated"))?
5391 .lsp_action;
5392 }
5393
5394 if let Some(edit) = action.lsp_action.edit {
5395 if edit.changes.is_some() || edit.document_changes.is_some() {
5396 return Self::deserialize_workspace_edit(
5397 this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5398 edit,
5399 push_to_history,
5400 lsp_adapter.clone(),
5401 lang_server.clone(),
5402 &mut cx,
5403 )
5404 .await;
5405 }
5406 }
5407
5408 if let Some(command) = action.lsp_action.command {
5409 this.update(&mut cx, |this, _| {
5410 this.last_workspace_edits_by_language_server
5411 .remove(&lang_server.server_id());
5412 })?;
5413
5414 let result = lang_server
5415 .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5416 command: command.command,
5417 arguments: command.arguments.unwrap_or_default(),
5418 ..Default::default()
5419 })
5420 .await;
5421
5422 if let Err(err) = result {
5423 // TODO: LSP ERROR
5424 return Err(err);
5425 }
5426
5427 return this.update(&mut cx, |this, _| {
5428 this.last_workspace_edits_by_language_server
5429 .remove(&lang_server.server_id())
5430 .unwrap_or_default()
5431 });
5432 }
5433
5434 Ok(ProjectTransaction::default())
5435 })
5436 } else if let Some(project_id) = self.remote_id() {
5437 let client = self.client.clone();
5438 let request = proto::ApplyCodeAction {
5439 project_id,
5440 buffer_id: buffer_handle.read(cx).remote_id().into(),
5441 action: Some(language::proto::serialize_code_action(&action)),
5442 };
5443 cx.spawn(move |this, mut cx| async move {
5444 let response = client
5445 .request(request)
5446 .await?
5447 .transaction
5448 .ok_or_else(|| anyhow!("missing transaction"))?;
5449 this.update(&mut cx, |this, cx| {
5450 this.deserialize_project_transaction(response, push_to_history, cx)
5451 })?
5452 .await
5453 })
5454 } else {
5455 Task::ready(Err(anyhow!("project does not have a remote id")))
5456 }
5457 }
5458
5459 fn apply_on_type_formatting(
5460 &self,
5461 buffer: Model<Buffer>,
5462 position: Anchor,
5463 trigger: String,
5464 cx: &mut ModelContext<Self>,
5465 ) -> Task<Result<Option<Transaction>>> {
5466 if self.is_local() {
5467 cx.spawn(move |this, mut cx| async move {
5468 // Do not allow multiple concurrent formatting requests for the
5469 // same buffer.
5470 this.update(&mut cx, |this, cx| {
5471 this.buffers_being_formatted
5472 .insert(buffer.read(cx).remote_id())
5473 })?;
5474
5475 let _cleanup = defer({
5476 let this = this.clone();
5477 let mut cx = cx.clone();
5478 let closure_buffer = buffer.clone();
5479 move || {
5480 this.update(&mut cx, |this, cx| {
5481 this.buffers_being_formatted
5482 .remove(&closure_buffer.read(cx).remote_id());
5483 })
5484 .ok();
5485 }
5486 });
5487
5488 buffer
5489 .update(&mut cx, |buffer, _| {
5490 buffer.wait_for_edits(Some(position.timestamp))
5491 })?
5492 .await?;
5493 this.update(&mut cx, |this, cx| {
5494 let position = position.to_point_utf16(buffer.read(cx));
5495 this.on_type_format(buffer, position, trigger, false, cx)
5496 })?
5497 .await
5498 })
5499 } else if let Some(project_id) = self.remote_id() {
5500 let client = self.client.clone();
5501 let request = proto::OnTypeFormatting {
5502 project_id,
5503 buffer_id: buffer.read(cx).remote_id().into(),
5504 position: Some(serialize_anchor(&position)),
5505 trigger,
5506 version: serialize_version(&buffer.read(cx).version()),
5507 };
5508 cx.spawn(move |_, _| async move {
5509 client
5510 .request(request)
5511 .await?
5512 .transaction
5513 .map(language::proto::deserialize_transaction)
5514 .transpose()
5515 })
5516 } else {
5517 Task::ready(Err(anyhow!("project does not have a remote id")))
5518 }
5519 }
5520
5521 async fn deserialize_edits(
5522 this: Model<Self>,
5523 buffer_to_edit: Model<Buffer>,
5524 edits: Vec<lsp::TextEdit>,
5525 push_to_history: bool,
5526 _: Arc<CachedLspAdapter>,
5527 language_server: Arc<LanguageServer>,
5528 cx: &mut AsyncAppContext,
5529 ) -> Result<Option<Transaction>> {
5530 let edits = this
5531 .update(cx, |this, cx| {
5532 this.edits_from_lsp(
5533 &buffer_to_edit,
5534 edits,
5535 language_server.server_id(),
5536 None,
5537 cx,
5538 )
5539 })?
5540 .await?;
5541
5542 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5543 buffer.finalize_last_transaction();
5544 buffer.start_transaction();
5545 for (range, text) in edits {
5546 buffer.edit([(range, text)], None, cx);
5547 }
5548
5549 if buffer.end_transaction(cx).is_some() {
5550 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5551 if !push_to_history {
5552 buffer.forget_transaction(transaction.id);
5553 }
5554 Some(transaction)
5555 } else {
5556 None
5557 }
5558 })?;
5559
5560 Ok(transaction)
5561 }
5562
5563 async fn deserialize_workspace_edit(
5564 this: Model<Self>,
5565 edit: lsp::WorkspaceEdit,
5566 push_to_history: bool,
5567 lsp_adapter: Arc<CachedLspAdapter>,
5568 language_server: Arc<LanguageServer>,
5569 cx: &mut AsyncAppContext,
5570 ) -> Result<ProjectTransaction> {
5571 let fs = this.update(cx, |this, _| this.fs.clone())?;
5572 let mut operations = Vec::new();
5573 if let Some(document_changes) = edit.document_changes {
5574 match document_changes {
5575 lsp::DocumentChanges::Edits(edits) => {
5576 operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5577 }
5578 lsp::DocumentChanges::Operations(ops) => operations = ops,
5579 }
5580 } else if let Some(changes) = edit.changes {
5581 operations.extend(changes.into_iter().map(|(uri, edits)| {
5582 lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5583 text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5584 uri,
5585 version: None,
5586 },
5587 edits: edits.into_iter().map(OneOf::Left).collect(),
5588 })
5589 }));
5590 }
5591
5592 let mut project_transaction = ProjectTransaction::default();
5593 for operation in operations {
5594 match operation {
5595 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5596 let abs_path = op
5597 .uri
5598 .to_file_path()
5599 .map_err(|_| anyhow!("can't convert URI to path"))?;
5600
5601 if let Some(parent_path) = abs_path.parent() {
5602 fs.create_dir(parent_path).await?;
5603 }
5604 if abs_path.ends_with("/") {
5605 fs.create_dir(&abs_path).await?;
5606 } else {
5607 fs.create_file(
5608 &abs_path,
5609 op.options
5610 .map(|options| fs::CreateOptions {
5611 overwrite: options.overwrite.unwrap_or(false),
5612 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5613 })
5614 .unwrap_or_default(),
5615 )
5616 .await?;
5617 }
5618 }
5619
5620 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5621 let source_abs_path = op
5622 .old_uri
5623 .to_file_path()
5624 .map_err(|_| anyhow!("can't convert URI to path"))?;
5625 let target_abs_path = op
5626 .new_uri
5627 .to_file_path()
5628 .map_err(|_| anyhow!("can't convert URI to path"))?;
5629 fs.rename(
5630 &source_abs_path,
5631 &target_abs_path,
5632 op.options
5633 .map(|options| fs::RenameOptions {
5634 overwrite: options.overwrite.unwrap_or(false),
5635 ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5636 })
5637 .unwrap_or_default(),
5638 )
5639 .await?;
5640 }
5641
5642 lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5643 let abs_path = op
5644 .uri
5645 .to_file_path()
5646 .map_err(|_| anyhow!("can't convert URI to path"))?;
5647 let options = op
5648 .options
5649 .map(|options| fs::RemoveOptions {
5650 recursive: options.recursive.unwrap_or(false),
5651 ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5652 })
5653 .unwrap_or_default();
5654 if abs_path.ends_with("/") {
5655 fs.remove_dir(&abs_path, options).await?;
5656 } else {
5657 fs.remove_file(&abs_path, options).await?;
5658 }
5659 }
5660
5661 lsp::DocumentChangeOperation::Edit(op) => {
5662 let buffer_to_edit = this
5663 .update(cx, |this, cx| {
5664 this.open_local_buffer_via_lsp(
5665 op.text_document.uri,
5666 language_server.server_id(),
5667 lsp_adapter.name.clone(),
5668 cx,
5669 )
5670 })?
5671 .await?;
5672
5673 let edits = this
5674 .update(cx, |this, cx| {
5675 let edits = op.edits.into_iter().map(|edit| match edit {
5676 OneOf::Left(edit) => edit,
5677 OneOf::Right(edit) => edit.text_edit,
5678 });
5679 this.edits_from_lsp(
5680 &buffer_to_edit,
5681 edits,
5682 language_server.server_id(),
5683 op.text_document.version,
5684 cx,
5685 )
5686 })?
5687 .await?;
5688
5689 let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5690 buffer.finalize_last_transaction();
5691 buffer.start_transaction();
5692 for (range, text) in edits {
5693 buffer.edit([(range, text)], None, cx);
5694 }
5695 let transaction = if buffer.end_transaction(cx).is_some() {
5696 let transaction = buffer.finalize_last_transaction().unwrap().clone();
5697 if !push_to_history {
5698 buffer.forget_transaction(transaction.id);
5699 }
5700 Some(transaction)
5701 } else {
5702 None
5703 };
5704
5705 transaction
5706 })?;
5707 if let Some(transaction) = transaction {
5708 project_transaction.0.insert(buffer_to_edit, transaction);
5709 }
5710 }
5711 }
5712 }
5713
5714 Ok(project_transaction)
5715 }
5716
5717 fn prepare_rename_impl(
5718 &self,
5719 buffer: Model<Buffer>,
5720 position: PointUtf16,
5721 cx: &mut ModelContext<Self>,
5722 ) -> Task<Result<Option<Range<Anchor>>>> {
5723 self.request_lsp(
5724 buffer,
5725 LanguageServerToQuery::Primary,
5726 PrepareRename { position },
5727 cx,
5728 )
5729 }
5730 pub fn prepare_rename<T: ToPointUtf16>(
5731 &self,
5732 buffer: Model<Buffer>,
5733 position: T,
5734 cx: &mut ModelContext<Self>,
5735 ) -> Task<Result<Option<Range<Anchor>>>> {
5736 let position = position.to_point_utf16(buffer.read(cx));
5737 self.prepare_rename_impl(buffer, position, cx)
5738 }
5739
5740 fn perform_rename_impl(
5741 &self,
5742 buffer: Model<Buffer>,
5743 position: PointUtf16,
5744 new_name: String,
5745 push_to_history: bool,
5746 cx: &mut ModelContext<Self>,
5747 ) -> Task<Result<ProjectTransaction>> {
5748 let position = position.to_point_utf16(buffer.read(cx));
5749 self.request_lsp(
5750 buffer,
5751 LanguageServerToQuery::Primary,
5752 PerformRename {
5753 position,
5754 new_name,
5755 push_to_history,
5756 },
5757 cx,
5758 )
5759 }
5760 pub fn perform_rename<T: ToPointUtf16>(
5761 &self,
5762 buffer: Model<Buffer>,
5763 position: T,
5764 new_name: String,
5765 push_to_history: bool,
5766 cx: &mut ModelContext<Self>,
5767 ) -> Task<Result<ProjectTransaction>> {
5768 let position = position.to_point_utf16(buffer.read(cx));
5769 self.perform_rename_impl(buffer, position, new_name, push_to_history, cx)
5770 }
5771
5772 pub fn on_type_format_impl(
5773 &self,
5774 buffer: Model<Buffer>,
5775 position: PointUtf16,
5776 trigger: String,
5777 push_to_history: bool,
5778 cx: &mut ModelContext<Self>,
5779 ) -> Task<Result<Option<Transaction>>> {
5780 let tab_size = buffer.update(cx, |buffer, cx| {
5781 language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx).tab_size
5782 });
5783 self.request_lsp(
5784 buffer.clone(),
5785 LanguageServerToQuery::Primary,
5786 OnTypeFormatting {
5787 position,
5788 trigger,
5789 options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5790 push_to_history,
5791 },
5792 cx,
5793 )
5794 }
5795
5796 pub fn on_type_format<T: ToPointUtf16>(
5797 &self,
5798 buffer: Model<Buffer>,
5799 position: T,
5800 trigger: String,
5801 push_to_history: bool,
5802 cx: &mut ModelContext<Self>,
5803 ) -> Task<Result<Option<Transaction>>> {
5804 let position = position.to_point_utf16(buffer.read(cx));
5805 self.on_type_format_impl(buffer, position, trigger, push_to_history, cx)
5806 }
5807
5808 pub fn inlay_hints<T: ToOffset>(
5809 &self,
5810 buffer_handle: Model<Buffer>,
5811 range: Range<T>,
5812 cx: &mut ModelContext<Self>,
5813 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5814 let buffer = buffer_handle.read(cx);
5815 let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5816 self.inlay_hints_impl(buffer_handle, range, cx)
5817 }
5818 fn inlay_hints_impl(
5819 &self,
5820 buffer_handle: Model<Buffer>,
5821 range: Range<Anchor>,
5822 cx: &mut ModelContext<Self>,
5823 ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5824 let buffer = buffer_handle.read(cx);
5825 let range_start = range.start;
5826 let range_end = range.end;
5827 let buffer_id = buffer.remote_id().into();
5828 let lsp_request = InlayHints { range };
5829
5830 if self.is_local() {
5831 let lsp_request_task = self.request_lsp(
5832 buffer_handle.clone(),
5833 LanguageServerToQuery::Primary,
5834 lsp_request,
5835 cx,
5836 );
5837 cx.spawn(move |_, mut cx| async move {
5838 buffer_handle
5839 .update(&mut cx, |buffer, _| {
5840 buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5841 })?
5842 .await
5843 .context("waiting for inlay hint request range edits")?;
5844 lsp_request_task.await.context("inlay hints LSP request")
5845 })
5846 } else if let Some(project_id) = self.remote_id() {
5847 let client = self.client.clone();
5848 let request = proto::InlayHints {
5849 project_id,
5850 buffer_id,
5851 start: Some(serialize_anchor(&range_start)),
5852 end: Some(serialize_anchor(&range_end)),
5853 version: serialize_version(&buffer_handle.read(cx).version()),
5854 };
5855 cx.spawn(move |project, cx| async move {
5856 let response = client
5857 .request(request)
5858 .await
5859 .context("inlay hints proto request")?;
5860 LspCommand::response_from_proto(
5861 lsp_request,
5862 response,
5863 project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5864 buffer_handle.clone(),
5865 cx.clone(),
5866 )
5867 .await
5868 .context("inlay hints proto response conversion")
5869 })
5870 } else {
5871 Task::ready(Err(anyhow!("project does not have a remote id")))
5872 }
5873 }
5874
5875 pub fn resolve_inlay_hint(
5876 &self,
5877 hint: InlayHint,
5878 buffer_handle: Model<Buffer>,
5879 server_id: LanguageServerId,
5880 cx: &mut ModelContext<Self>,
5881 ) -> Task<anyhow::Result<InlayHint>> {
5882 if self.is_local() {
5883 let buffer = buffer_handle.read(cx);
5884 let (_, lang_server) = if let Some((adapter, server)) =
5885 self.language_server_for_buffer(buffer, server_id, cx)
5886 {
5887 (adapter.clone(), server.clone())
5888 } else {
5889 return Task::ready(Ok(hint));
5890 };
5891 if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5892 return Task::ready(Ok(hint));
5893 }
5894
5895 let buffer_snapshot = buffer.snapshot();
5896 cx.spawn(move |_, mut cx| async move {
5897 let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5898 InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5899 );
5900 let resolved_hint = resolve_task
5901 .await
5902 .context("inlay hint resolve LSP request")?;
5903 let resolved_hint = InlayHints::lsp_to_project_hint(
5904 resolved_hint,
5905 &buffer_handle,
5906 server_id,
5907 ResolveState::Resolved,
5908 false,
5909 &mut cx,
5910 )
5911 .await?;
5912 Ok(resolved_hint)
5913 })
5914 } else if let Some(project_id) = self.remote_id() {
5915 let client = self.client.clone();
5916 let request = proto::ResolveInlayHint {
5917 project_id,
5918 buffer_id: buffer_handle.read(cx).remote_id().into(),
5919 language_server_id: server_id.0 as u64,
5920 hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5921 };
5922 cx.spawn(move |_, _| async move {
5923 let response = client
5924 .request(request)
5925 .await
5926 .context("inlay hints proto request")?;
5927 match response.hint {
5928 Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5929 .context("inlay hints proto resolve response conversion"),
5930 None => Ok(hint),
5931 }
5932 })
5933 } else {
5934 Task::ready(Err(anyhow!("project does not have a remote id")))
5935 }
5936 }
5937
5938 #[allow(clippy::type_complexity)]
5939 pub fn search(
5940 &self,
5941 query: SearchQuery,
5942 cx: &mut ModelContext<Self>,
5943 ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5944 if self.is_local() {
5945 self.search_local(query, cx)
5946 } else if let Some(project_id) = self.remote_id() {
5947 let (tx, rx) = smol::channel::unbounded();
5948 let request = self.client.request(query.to_proto(project_id));
5949 cx.spawn(move |this, mut cx| async move {
5950 let response = request.await?;
5951 let mut result = HashMap::default();
5952 for location in response.locations {
5953 let buffer_id = BufferId::new(location.buffer_id)?;
5954 let target_buffer = this
5955 .update(&mut cx, |this, cx| {
5956 this.wait_for_remote_buffer(buffer_id, cx)
5957 })?
5958 .await?;
5959 let start = location
5960 .start
5961 .and_then(deserialize_anchor)
5962 .ok_or_else(|| anyhow!("missing target start"))?;
5963 let end = location
5964 .end
5965 .and_then(deserialize_anchor)
5966 .ok_or_else(|| anyhow!("missing target end"))?;
5967 result
5968 .entry(target_buffer)
5969 .or_insert(Vec::new())
5970 .push(start..end)
5971 }
5972 for (buffer, ranges) in result {
5973 let _ = tx.send((buffer, ranges)).await;
5974 }
5975 Result::<(), anyhow::Error>::Ok(())
5976 })
5977 .detach_and_log_err(cx);
5978 rx
5979 } else {
5980 unimplemented!();
5981 }
5982 }
5983
5984 pub fn search_local(
5985 &self,
5986 query: SearchQuery,
5987 cx: &mut ModelContext<Self>,
5988 ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5989 // Local search is split into several phases.
5990 // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5991 // and the second phase that finds positions of all the matches found in the candidate files.
5992 // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5993 //
5994 // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5995 // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5996 //
5997 // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5998 // 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
5999 // of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
6000 // 2. At this point, we have a list of all potentially matching buffers/files.
6001 // We sort that list by buffer path - this list is retained for later use.
6002 // We ensure that all buffers are now opened and available in project.
6003 // 3. We run a scan over all the candidate buffers on multiple background threads.
6004 // We cannot assume that there will even be a match - while at least one match
6005 // is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
6006 // There is also an auxiliary background thread responsible for result gathering.
6007 // 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),
6008 // it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
6009 // 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
6010 // entry - which might already be available thanks to out-of-order processing.
6011 //
6012 // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
6013 // 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.
6014 // 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
6015 // in face of constantly updating list of sorted matches.
6016 // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
6017 let snapshots = self
6018 .visible_worktrees(cx)
6019 .filter_map(|tree| {
6020 let tree = tree.read(cx).as_local()?;
6021 Some(tree.snapshot())
6022 })
6023 .collect::<Vec<_>>();
6024
6025 let background = cx.background_executor().clone();
6026 let path_count: usize = snapshots
6027 .iter()
6028 .map(|s| {
6029 if query.include_ignored() {
6030 s.file_count()
6031 } else {
6032 s.visible_file_count()
6033 }
6034 })
6035 .sum();
6036 if path_count == 0 {
6037 let (_, rx) = smol::channel::bounded(1024);
6038 return rx;
6039 }
6040 let workers = background.num_cpus().min(path_count);
6041 let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
6042 let mut unnamed_files = vec![];
6043 let opened_buffers = self
6044 .opened_buffers
6045 .iter()
6046 .filter_map(|(_, b)| {
6047 let buffer = b.upgrade()?;
6048 let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
6049 let is_ignored = buffer
6050 .project_path(cx)
6051 .and_then(|path| self.entry_for_path(&path, cx))
6052 .map_or(false, |entry| entry.is_ignored);
6053 (is_ignored, buffer.snapshot())
6054 });
6055 if is_ignored && !query.include_ignored() {
6056 return None;
6057 } else if let Some(path) = snapshot.file().map(|file| file.path()) {
6058 Some((path.clone(), (buffer, snapshot)))
6059 } else {
6060 unnamed_files.push(buffer);
6061 None
6062 }
6063 })
6064 .collect();
6065 cx.background_executor()
6066 .spawn(Self::background_search(
6067 unnamed_files,
6068 opened_buffers,
6069 cx.background_executor().clone(),
6070 self.fs.clone(),
6071 workers,
6072 query.clone(),
6073 path_count,
6074 snapshots,
6075 matching_paths_tx,
6076 ))
6077 .detach();
6078
6079 let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
6080 let background = cx.background_executor().clone();
6081 let (result_tx, result_rx) = smol::channel::bounded(1024);
6082 cx.background_executor()
6083 .spawn(async move {
6084 let Ok(buffers) = buffers.await else {
6085 return;
6086 };
6087
6088 let buffers_len = buffers.len();
6089 if buffers_len == 0 {
6090 return;
6091 }
6092 let query = &query;
6093 let (finished_tx, mut finished_rx) = smol::channel::unbounded();
6094 background
6095 .scoped(|scope| {
6096 #[derive(Clone)]
6097 struct FinishedStatus {
6098 entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
6099 buffer_index: SearchMatchCandidateIndex,
6100 }
6101
6102 for _ in 0..workers {
6103 let finished_tx = finished_tx.clone();
6104 let mut buffers_rx = buffers_rx.clone();
6105 scope.spawn(async move {
6106 while let Some((entry, buffer_index)) = buffers_rx.next().await {
6107 let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
6108 {
6109 if query.file_matches(
6110 snapshot.file().map(|file| file.path().as_ref()),
6111 ) {
6112 query
6113 .search(snapshot, None)
6114 .await
6115 .iter()
6116 .map(|range| {
6117 snapshot.anchor_before(range.start)
6118 ..snapshot.anchor_after(range.end)
6119 })
6120 .collect()
6121 } else {
6122 Vec::new()
6123 }
6124 } else {
6125 Vec::new()
6126 };
6127
6128 let status = if !buffer_matches.is_empty() {
6129 let entry = if let Some((buffer, _)) = entry.as_ref() {
6130 Some((buffer.clone(), buffer_matches))
6131 } else {
6132 None
6133 };
6134 FinishedStatus {
6135 entry,
6136 buffer_index,
6137 }
6138 } else {
6139 FinishedStatus {
6140 entry: None,
6141 buffer_index,
6142 }
6143 };
6144 if finished_tx.send(status).await.is_err() {
6145 break;
6146 }
6147 }
6148 });
6149 }
6150 // Report sorted matches
6151 scope.spawn(async move {
6152 let mut current_index = 0;
6153 let mut scratch = vec![None; buffers_len];
6154 while let Some(status) = finished_rx.next().await {
6155 debug_assert!(
6156 scratch[status.buffer_index].is_none(),
6157 "Got match status of position {} twice",
6158 status.buffer_index
6159 );
6160 let index = status.buffer_index;
6161 scratch[index] = Some(status);
6162 while current_index < buffers_len {
6163 let Some(current_entry) = scratch[current_index].take() else {
6164 // We intentionally **do not** increment `current_index` here. When next element arrives
6165 // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
6166 // this time.
6167 break;
6168 };
6169 if let Some(entry) = current_entry.entry {
6170 result_tx.send(entry).await.log_err();
6171 }
6172 current_index += 1;
6173 }
6174 if current_index == buffers_len {
6175 break;
6176 }
6177 }
6178 });
6179 })
6180 .await;
6181 })
6182 .detach();
6183 result_rx
6184 }
6185
6186 /// Pick paths that might potentially contain a match of a given search query.
6187 #[allow(clippy::too_many_arguments)]
6188 async fn background_search(
6189 unnamed_buffers: Vec<Model<Buffer>>,
6190 opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
6191 executor: BackgroundExecutor,
6192 fs: Arc<dyn Fs>,
6193 workers: usize,
6194 query: SearchQuery,
6195 path_count: usize,
6196 snapshots: Vec<LocalSnapshot>,
6197 matching_paths_tx: Sender<SearchMatchCandidate>,
6198 ) {
6199 let fs = &fs;
6200 let query = &query;
6201 let matching_paths_tx = &matching_paths_tx;
6202 let snapshots = &snapshots;
6203 let paths_per_worker = (path_count + workers - 1) / workers;
6204 for buffer in unnamed_buffers {
6205 matching_paths_tx
6206 .send(SearchMatchCandidate::OpenBuffer {
6207 buffer: buffer.clone(),
6208 path: None,
6209 })
6210 .await
6211 .log_err();
6212 }
6213 for (path, (buffer, _)) in opened_buffers.iter() {
6214 matching_paths_tx
6215 .send(SearchMatchCandidate::OpenBuffer {
6216 buffer: buffer.clone(),
6217 path: Some(path.clone()),
6218 })
6219 .await
6220 .log_err();
6221 }
6222 executor
6223 .scoped(|scope| {
6224 let max_concurrent_workers = Arc::new(Semaphore::new(workers));
6225
6226 for worker_ix in 0..workers {
6227 let worker_start_ix = worker_ix * paths_per_worker;
6228 let worker_end_ix = worker_start_ix + paths_per_worker;
6229 let unnamed_buffers = opened_buffers.clone();
6230 let limiter = Arc::clone(&max_concurrent_workers);
6231 scope.spawn(async move {
6232 let _guard = limiter.acquire().await;
6233 let mut snapshot_start_ix = 0;
6234 let mut abs_path = PathBuf::new();
6235 for snapshot in snapshots {
6236 let snapshot_end_ix = snapshot_start_ix
6237 + if query.include_ignored() {
6238 snapshot.file_count()
6239 } else {
6240 snapshot.visible_file_count()
6241 };
6242 if worker_end_ix <= snapshot_start_ix {
6243 break;
6244 } else if worker_start_ix > snapshot_end_ix {
6245 snapshot_start_ix = snapshot_end_ix;
6246 continue;
6247 } else {
6248 let start_in_snapshot =
6249 worker_start_ix.saturating_sub(snapshot_start_ix);
6250 let end_in_snapshot =
6251 cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
6252
6253 for entry in snapshot
6254 .files(query.include_ignored(), start_in_snapshot)
6255 .take(end_in_snapshot - start_in_snapshot)
6256 {
6257 if matching_paths_tx.is_closed() {
6258 break;
6259 }
6260 if unnamed_buffers.contains_key(&entry.path) {
6261 continue;
6262 }
6263 let matches = if query.file_matches(Some(&entry.path)) {
6264 abs_path.clear();
6265 abs_path.push(&snapshot.abs_path());
6266 abs_path.push(&entry.path);
6267 if let Some(file) = fs.open_sync(&abs_path).await.log_err()
6268 {
6269 query.detect(file).unwrap_or(false)
6270 } else {
6271 false
6272 }
6273 } else {
6274 false
6275 };
6276
6277 if matches {
6278 let project_path = SearchMatchCandidate::Path {
6279 worktree_id: snapshot.id(),
6280 path: entry.path.clone(),
6281 is_ignored: entry.is_ignored,
6282 };
6283 if matching_paths_tx.send(project_path).await.is_err() {
6284 break;
6285 }
6286 }
6287 }
6288
6289 snapshot_start_ix = snapshot_end_ix;
6290 }
6291 }
6292 });
6293 }
6294
6295 if query.include_ignored() {
6296 for snapshot in snapshots {
6297 for ignored_entry in snapshot
6298 .entries(query.include_ignored())
6299 .filter(|e| e.is_ignored)
6300 {
6301 let limiter = Arc::clone(&max_concurrent_workers);
6302 scope.spawn(async move {
6303 let _guard = limiter.acquire().await;
6304 let mut ignored_paths_to_process =
6305 VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
6306 while let Some(ignored_abs_path) =
6307 ignored_paths_to_process.pop_front()
6308 {
6309 if let Some(fs_metadata) = fs
6310 .metadata(&ignored_abs_path)
6311 .await
6312 .with_context(|| {
6313 format!("fetching fs metadata for {ignored_abs_path:?}")
6314 })
6315 .log_err()
6316 .flatten()
6317 {
6318 if fs_metadata.is_dir {
6319 if let Some(mut subfiles) = fs
6320 .read_dir(&ignored_abs_path)
6321 .await
6322 .with_context(|| {
6323 format!(
6324 "listing ignored path {ignored_abs_path:?}"
6325 )
6326 })
6327 .log_err()
6328 {
6329 while let Some(subfile) = subfiles.next().await {
6330 if let Some(subfile) = subfile.log_err() {
6331 ignored_paths_to_process.push_back(subfile);
6332 }
6333 }
6334 }
6335 } else if !fs_metadata.is_symlink {
6336 if !query.file_matches(Some(&ignored_abs_path))
6337 || snapshot.is_path_excluded(
6338 ignored_entry.path.to_path_buf(),
6339 )
6340 {
6341 continue;
6342 }
6343 let matches = if let Some(file) = fs
6344 .open_sync(&ignored_abs_path)
6345 .await
6346 .with_context(|| {
6347 format!(
6348 "Opening ignored path {ignored_abs_path:?}"
6349 )
6350 })
6351 .log_err()
6352 {
6353 query.detect(file).unwrap_or(false)
6354 } else {
6355 false
6356 };
6357 if matches {
6358 let project_path = SearchMatchCandidate::Path {
6359 worktree_id: snapshot.id(),
6360 path: Arc::from(
6361 ignored_abs_path
6362 .strip_prefix(snapshot.abs_path())
6363 .expect(
6364 "scanning worktree-related files",
6365 ),
6366 ),
6367 is_ignored: true,
6368 };
6369 if matching_paths_tx
6370 .send(project_path)
6371 .await
6372 .is_err()
6373 {
6374 return;
6375 }
6376 }
6377 }
6378 }
6379 }
6380 });
6381 }
6382 }
6383 }
6384 })
6385 .await;
6386 }
6387
6388 pub fn request_lsp<R: LspCommand>(
6389 &self,
6390 buffer_handle: Model<Buffer>,
6391 server: LanguageServerToQuery,
6392 request: R,
6393 cx: &mut ModelContext<Self>,
6394 ) -> Task<Result<R::Response>>
6395 where
6396 <R::LspRequest as lsp::request::Request>::Result: Send,
6397 <R::LspRequest as lsp::request::Request>::Params: Send,
6398 {
6399 let buffer = buffer_handle.read(cx);
6400 if self.is_local() {
6401 let language_server = match server {
6402 LanguageServerToQuery::Primary => {
6403 match self.primary_language_server_for_buffer(buffer, cx) {
6404 Some((_, server)) => Some(Arc::clone(server)),
6405 None => return Task::ready(Ok(Default::default())),
6406 }
6407 }
6408 LanguageServerToQuery::Other(id) => self
6409 .language_server_for_buffer(buffer, id, cx)
6410 .map(|(_, server)| Arc::clone(server)),
6411 };
6412 let file = File::from_dyn(buffer.file()).and_then(File::as_local);
6413 if let (Some(file), Some(language_server)) = (file, language_server) {
6414 let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
6415 return cx.spawn(move |this, cx| async move {
6416 if !request.check_capabilities(language_server.capabilities()) {
6417 return Ok(Default::default());
6418 }
6419
6420 let result = language_server.request::<R::LspRequest>(lsp_params).await;
6421 let response = match result {
6422 Ok(response) => response,
6423
6424 Err(err) => {
6425 log::warn!(
6426 "Generic lsp request to {} failed: {}",
6427 language_server.name(),
6428 err
6429 );
6430 return Err(err);
6431 }
6432 };
6433
6434 request
6435 .response_from_lsp(
6436 response,
6437 this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6438 buffer_handle,
6439 language_server.server_id(),
6440 cx,
6441 )
6442 .await
6443 });
6444 }
6445 } else if let Some(project_id) = self.remote_id() {
6446 return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6447 }
6448
6449 Task::ready(Ok(Default::default()))
6450 }
6451
6452 fn send_lsp_proto_request<R: LspCommand>(
6453 &self,
6454 buffer: Model<Buffer>,
6455 project_id: u64,
6456 request: R,
6457 cx: &mut ModelContext<'_, Project>,
6458 ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6459 let rpc = self.client.clone();
6460 let message = request.to_proto(project_id, buffer.read(cx));
6461 cx.spawn(move |this, mut cx| async move {
6462 // Ensure the project is still alive by the time the task
6463 // is scheduled.
6464 this.upgrade().context("project dropped")?;
6465 let response = rpc.request(message).await?;
6466 let this = this.upgrade().context("project dropped")?;
6467 if this.update(&mut cx, |this, _| this.is_disconnected())? {
6468 Err(anyhow!("disconnected before completing request"))
6469 } else {
6470 request
6471 .response_from_proto(response, this, buffer, cx)
6472 .await
6473 }
6474 })
6475 }
6476
6477 fn sort_candidates_and_open_buffers(
6478 mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6479 cx: &mut ModelContext<Self>,
6480 ) -> (
6481 futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6482 Receiver<(
6483 Option<(Model<Buffer>, BufferSnapshot)>,
6484 SearchMatchCandidateIndex,
6485 )>,
6486 ) {
6487 let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6488 let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6489 cx.spawn(move |this, cx| async move {
6490 let mut buffers = Vec::new();
6491 let mut ignored_buffers = Vec::new();
6492 while let Some(entry) = matching_paths_rx.next().await {
6493 if matches!(
6494 entry,
6495 SearchMatchCandidate::Path {
6496 is_ignored: true,
6497 ..
6498 }
6499 ) {
6500 ignored_buffers.push(entry);
6501 } else {
6502 buffers.push(entry);
6503 }
6504 }
6505 buffers.sort_by_key(|candidate| candidate.path());
6506 ignored_buffers.sort_by_key(|candidate| candidate.path());
6507 buffers.extend(ignored_buffers);
6508 let matching_paths = buffers.clone();
6509 let _ = sorted_buffers_tx.send(buffers);
6510 for (index, candidate) in matching_paths.into_iter().enumerate() {
6511 if buffers_tx.is_closed() {
6512 break;
6513 }
6514 let this = this.clone();
6515 let buffers_tx = buffers_tx.clone();
6516 cx.spawn(move |mut cx| async move {
6517 let buffer = match candidate {
6518 SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6519 SearchMatchCandidate::Path {
6520 worktree_id, path, ..
6521 } => this
6522 .update(&mut cx, |this, cx| {
6523 this.open_buffer((worktree_id, path), cx)
6524 })?
6525 .await
6526 .log_err(),
6527 };
6528 if let Some(buffer) = buffer {
6529 let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6530 buffers_tx
6531 .send((Some((buffer, snapshot)), index))
6532 .await
6533 .log_err();
6534 } else {
6535 buffers_tx.send((None, index)).await.log_err();
6536 }
6537
6538 Ok::<_, anyhow::Error>(())
6539 })
6540 .detach();
6541 }
6542 })
6543 .detach();
6544 (sorted_buffers_rx, buffers_rx)
6545 }
6546
6547 pub fn find_or_create_local_worktree(
6548 &mut self,
6549 abs_path: impl AsRef<Path>,
6550 visible: bool,
6551 cx: &mut ModelContext<Self>,
6552 ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6553 let abs_path = abs_path.as_ref();
6554 if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6555 Task::ready(Ok((tree, relative_path)))
6556 } else {
6557 let worktree = self.create_local_worktree(abs_path, visible, cx);
6558 cx.background_executor()
6559 .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6560 }
6561 }
6562
6563 pub fn find_local_worktree(
6564 &self,
6565 abs_path: &Path,
6566 cx: &AppContext,
6567 ) -> Option<(Model<Worktree>, PathBuf)> {
6568 for tree in &self.worktrees {
6569 if let Some(tree) = tree.upgrade() {
6570 if let Some(relative_path) = tree
6571 .read(cx)
6572 .as_local()
6573 .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6574 {
6575 return Some((tree.clone(), relative_path.into()));
6576 }
6577 }
6578 }
6579 None
6580 }
6581
6582 pub fn is_shared(&self) -> bool {
6583 match &self.client_state {
6584 ProjectClientState::Shared { .. } => true,
6585 ProjectClientState::Local | ProjectClientState::Remote { .. } => false,
6586 }
6587 }
6588
6589 fn create_local_worktree(
6590 &mut self,
6591 abs_path: impl AsRef<Path>,
6592 visible: bool,
6593 cx: &mut ModelContext<Self>,
6594 ) -> Task<Result<Model<Worktree>>> {
6595 let fs = self.fs.clone();
6596 let client = self.client.clone();
6597 let next_entry_id = self.next_entry_id.clone();
6598 let path: Arc<Path> = abs_path.as_ref().into();
6599 let task = self
6600 .loading_local_worktrees
6601 .entry(path.clone())
6602 .or_insert_with(|| {
6603 cx.spawn(move |project, mut cx| {
6604 async move {
6605 let worktree = Worktree::local(
6606 client.clone(),
6607 path.clone(),
6608 visible,
6609 fs,
6610 next_entry_id,
6611 &mut cx,
6612 )
6613 .await;
6614
6615 project.update(&mut cx, |project, _| {
6616 project.loading_local_worktrees.remove(&path);
6617 })?;
6618
6619 let worktree = worktree?;
6620 project
6621 .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6622 Ok(worktree)
6623 }
6624 .map_err(Arc::new)
6625 })
6626 .shared()
6627 })
6628 .clone();
6629 cx.background_executor().spawn(async move {
6630 match task.await {
6631 Ok(worktree) => Ok(worktree),
6632 Err(err) => Err(anyhow!("{}", err)),
6633 }
6634 })
6635 }
6636
6637 pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6638 let mut servers_to_remove = HashMap::default();
6639 let mut servers_to_preserve = HashSet::default();
6640 for ((worktree_id, server_name), &server_id) in &self.language_server_ids {
6641 if worktree_id == &id_to_remove {
6642 servers_to_remove.insert(server_id, server_name.clone());
6643 } else {
6644 servers_to_preserve.insert(server_id);
6645 }
6646 }
6647 servers_to_remove.retain(|server_id, _| !servers_to_preserve.contains(server_id));
6648 for (server_id_to_remove, server_name) in servers_to_remove {
6649 self.language_server_ids
6650 .remove(&(id_to_remove, server_name));
6651 self.language_server_statuses.remove(&server_id_to_remove);
6652 self.last_workspace_edits_by_language_server
6653 .remove(&server_id_to_remove);
6654 self.language_servers.remove(&server_id_to_remove);
6655 cx.emit(Event::LanguageServerRemoved(server_id_to_remove));
6656 }
6657
6658 let mut prettier_instances_to_clean = FuturesUnordered::new();
6659 if let Some(prettier_paths) = self.prettiers_per_worktree.remove(&id_to_remove) {
6660 for path in prettier_paths.iter().flatten() {
6661 if let Some(prettier_instance) = self.prettier_instances.remove(path) {
6662 prettier_instances_to_clean.push(async move {
6663 prettier_instance
6664 .server()
6665 .await
6666 .map(|server| server.server_id())
6667 });
6668 }
6669 }
6670 }
6671 cx.spawn(|project, mut cx| async move {
6672 while let Some(prettier_server_id) = prettier_instances_to_clean.next().await {
6673 if let Some(prettier_server_id) = prettier_server_id {
6674 project
6675 .update(&mut cx, |project, cx| {
6676 project
6677 .supplementary_language_servers
6678 .remove(&prettier_server_id);
6679 cx.emit(Event::LanguageServerRemoved(prettier_server_id));
6680 })
6681 .ok();
6682 }
6683 }
6684 })
6685 .detach();
6686
6687 self.task_inventory().update(cx, |inventory, _| {
6688 inventory.remove_worktree_sources(id_to_remove);
6689 });
6690
6691 self.worktrees.retain(|worktree| {
6692 if let Some(worktree) = worktree.upgrade() {
6693 let id = worktree.read(cx).id();
6694 if id == id_to_remove {
6695 cx.emit(Event::WorktreeRemoved(id));
6696 false
6697 } else {
6698 true
6699 }
6700 } else {
6701 false
6702 }
6703 });
6704 self.metadata_changed(cx);
6705 }
6706
6707 fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6708 cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6709 if worktree.read(cx).is_local() {
6710 cx.subscribe(worktree, |this, worktree, event, cx| match event {
6711 worktree::Event::UpdatedEntries(changes) => {
6712 this.update_local_worktree_buffers(&worktree, changes, cx);
6713 this.update_local_worktree_language_servers(&worktree, changes, cx);
6714 this.update_local_worktree_settings(&worktree, changes, cx);
6715 this.update_prettier_settings(&worktree, changes, cx);
6716 cx.emit(Event::WorktreeUpdatedEntries(
6717 worktree.read(cx).id(),
6718 changes.clone(),
6719 ));
6720 }
6721 worktree::Event::UpdatedGitRepositories(updated_repos) => {
6722 this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6723 }
6724 })
6725 .detach();
6726 }
6727
6728 let push_strong_handle = {
6729 let worktree = worktree.read(cx);
6730 self.is_shared() || worktree.is_visible() || worktree.is_remote()
6731 };
6732 if push_strong_handle {
6733 self.worktrees
6734 .push(WorktreeHandle::Strong(worktree.clone()));
6735 } else {
6736 self.worktrees
6737 .push(WorktreeHandle::Weak(worktree.downgrade()));
6738 }
6739
6740 let handle_id = worktree.entity_id();
6741 cx.observe_release(worktree, move |this, worktree, cx| {
6742 let _ = this.remove_worktree(worktree.id(), cx);
6743 cx.update_global::<SettingsStore, _>(|store, cx| {
6744 store
6745 .clear_local_settings(handle_id.as_u64() as usize, cx)
6746 .log_err()
6747 });
6748 })
6749 .detach();
6750
6751 cx.emit(Event::WorktreeAdded);
6752 self.metadata_changed(cx);
6753 }
6754
6755 fn update_local_worktree_buffers(
6756 &mut self,
6757 worktree_handle: &Model<Worktree>,
6758 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6759 cx: &mut ModelContext<Self>,
6760 ) {
6761 let snapshot = worktree_handle.read(cx).snapshot();
6762
6763 let mut renamed_buffers = Vec::new();
6764 for (path, entry_id, _) in changes {
6765 let worktree_id = worktree_handle.read(cx).id();
6766 let project_path = ProjectPath {
6767 worktree_id,
6768 path: path.clone(),
6769 };
6770
6771 let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6772 Some(&buffer_id) => buffer_id,
6773 None => match self.local_buffer_ids_by_path.get(&project_path) {
6774 Some(&buffer_id) => buffer_id,
6775 None => {
6776 continue;
6777 }
6778 },
6779 };
6780
6781 let open_buffer = self.opened_buffers.get(&buffer_id);
6782 let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6783 buffer
6784 } else {
6785 self.opened_buffers.remove(&buffer_id);
6786 self.local_buffer_ids_by_path.remove(&project_path);
6787 self.local_buffer_ids_by_entry_id.remove(entry_id);
6788 continue;
6789 };
6790
6791 buffer.update(cx, |buffer, cx| {
6792 if let Some(old_file) = File::from_dyn(buffer.file()) {
6793 if old_file.worktree != *worktree_handle {
6794 return;
6795 }
6796
6797 let new_file = if let Some(entry) = old_file
6798 .entry_id
6799 .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6800 {
6801 File {
6802 is_local: true,
6803 entry_id: Some(entry.id),
6804 mtime: entry.mtime,
6805 path: entry.path.clone(),
6806 worktree: worktree_handle.clone(),
6807 is_deleted: false,
6808 is_private: entry.is_private,
6809 }
6810 } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6811 File {
6812 is_local: true,
6813 entry_id: Some(entry.id),
6814 mtime: entry.mtime,
6815 path: entry.path.clone(),
6816 worktree: worktree_handle.clone(),
6817 is_deleted: false,
6818 is_private: entry.is_private,
6819 }
6820 } else {
6821 File {
6822 is_local: true,
6823 entry_id: old_file.entry_id,
6824 path: old_file.path().clone(),
6825 mtime: old_file.mtime(),
6826 worktree: worktree_handle.clone(),
6827 is_deleted: true,
6828 is_private: old_file.is_private,
6829 }
6830 };
6831
6832 let old_path = old_file.abs_path(cx);
6833 if new_file.abs_path(cx) != old_path {
6834 renamed_buffers.push((cx.handle(), old_file.clone()));
6835 self.local_buffer_ids_by_path.remove(&project_path);
6836 self.local_buffer_ids_by_path.insert(
6837 ProjectPath {
6838 worktree_id,
6839 path: path.clone(),
6840 },
6841 buffer_id,
6842 );
6843 }
6844
6845 if new_file.entry_id != Some(*entry_id) {
6846 self.local_buffer_ids_by_entry_id.remove(entry_id);
6847 if let Some(entry_id) = new_file.entry_id {
6848 self.local_buffer_ids_by_entry_id
6849 .insert(entry_id, buffer_id);
6850 }
6851 }
6852
6853 if new_file != *old_file {
6854 if let Some(project_id) = self.remote_id() {
6855 self.client
6856 .send(proto::UpdateBufferFile {
6857 project_id,
6858 buffer_id: buffer_id.into(),
6859 file: Some(new_file.to_proto()),
6860 })
6861 .log_err();
6862 }
6863
6864 buffer.file_updated(Arc::new(new_file), cx);
6865 }
6866 }
6867 });
6868 }
6869
6870 for (buffer, old_file) in renamed_buffers {
6871 self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6872 self.detect_language_for_buffer(&buffer, cx);
6873 self.register_buffer_with_language_servers(&buffer, cx);
6874 }
6875 }
6876
6877 fn update_local_worktree_language_servers(
6878 &mut self,
6879 worktree_handle: &Model<Worktree>,
6880 changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6881 cx: &mut ModelContext<Self>,
6882 ) {
6883 if changes.is_empty() {
6884 return;
6885 }
6886
6887 let worktree_id = worktree_handle.read(cx).id();
6888 let mut language_server_ids = self
6889 .language_server_ids
6890 .iter()
6891 .filter_map(|((server_worktree_id, _), server_id)| {
6892 (*server_worktree_id == worktree_id).then_some(*server_id)
6893 })
6894 .collect::<Vec<_>>();
6895 language_server_ids.sort();
6896 language_server_ids.dedup();
6897
6898 let abs_path = worktree_handle.read(cx).abs_path();
6899 for server_id in &language_server_ids {
6900 if let Some(LanguageServerState::Running {
6901 server,
6902 watched_paths,
6903 ..
6904 }) = self.language_servers.get(server_id)
6905 {
6906 if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6907 let params = lsp::DidChangeWatchedFilesParams {
6908 changes: changes
6909 .iter()
6910 .filter_map(|(path, _, change)| {
6911 if !watched_paths.is_match(&path) {
6912 return None;
6913 }
6914 let typ = match change {
6915 PathChange::Loaded => return None,
6916 PathChange::Added => lsp::FileChangeType::CREATED,
6917 PathChange::Removed => lsp::FileChangeType::DELETED,
6918 PathChange::Updated => lsp::FileChangeType::CHANGED,
6919 PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6920 };
6921 Some(lsp::FileEvent {
6922 uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6923 typ,
6924 })
6925 })
6926 .collect(),
6927 };
6928
6929 if !params.changes.is_empty() {
6930 server
6931 .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6932 .log_err();
6933 }
6934 }
6935 }
6936 }
6937 }
6938
6939 fn update_local_worktree_buffers_git_repos(
6940 &mut self,
6941 worktree_handle: Model<Worktree>,
6942 changed_repos: &UpdatedGitRepositoriesSet,
6943 cx: &mut ModelContext<Self>,
6944 ) {
6945 debug_assert!(worktree_handle.read(cx).is_local());
6946
6947 // Identify the loading buffers whose containing repository that has changed.
6948 let future_buffers = self
6949 .loading_buffers_by_path
6950 .iter()
6951 .filter_map(|(project_path, receiver)| {
6952 if project_path.worktree_id != worktree_handle.read(cx).id() {
6953 return None;
6954 }
6955 let path = &project_path.path;
6956 changed_repos
6957 .iter()
6958 .find(|(work_dir, _)| path.starts_with(work_dir))?;
6959 let receiver = receiver.clone();
6960 let path = path.clone();
6961 Some(async move {
6962 wait_for_loading_buffer(receiver)
6963 .await
6964 .ok()
6965 .map(|buffer| (buffer, path))
6966 })
6967 })
6968 .collect::<FuturesUnordered<_>>();
6969
6970 // Identify the current buffers whose containing repository has changed.
6971 let current_buffers = self
6972 .opened_buffers
6973 .values()
6974 .filter_map(|buffer| {
6975 let buffer = buffer.upgrade()?;
6976 let file = File::from_dyn(buffer.read(cx).file())?;
6977 if file.worktree != worktree_handle {
6978 return None;
6979 }
6980 let path = file.path();
6981 changed_repos
6982 .iter()
6983 .find(|(work_dir, _)| path.starts_with(work_dir))?;
6984 Some((buffer, path.clone()))
6985 })
6986 .collect::<Vec<_>>();
6987
6988 if future_buffers.len() + current_buffers.len() == 0 {
6989 return;
6990 }
6991
6992 let remote_id = self.remote_id();
6993 let client = self.client.clone();
6994 cx.spawn(move |_, mut cx| async move {
6995 // Wait for all of the buffers to load.
6996 let future_buffers = future_buffers.collect::<Vec<_>>().await;
6997
6998 // Reload the diff base for every buffer whose containing git repository has changed.
6999 let snapshot =
7000 worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
7001 let diff_bases_by_buffer = cx
7002 .background_executor()
7003 .spawn(async move {
7004 future_buffers
7005 .into_iter()
7006 .flatten()
7007 .chain(current_buffers)
7008 .filter_map(|(buffer, path)| {
7009 let (work_directory, repo) =
7010 snapshot.repository_and_work_directory_for_path(&path)?;
7011 let repo = snapshot.get_local_repo(&repo)?;
7012 let relative_path = path.strip_prefix(&work_directory).ok()?;
7013 let base_text = repo.load_index_text(relative_path);
7014 Some((buffer, base_text))
7015 })
7016 .collect::<Vec<_>>()
7017 })
7018 .await;
7019
7020 // Assign the new diff bases on all of the buffers.
7021 for (buffer, diff_base) in diff_bases_by_buffer {
7022 let buffer_id = buffer.update(&mut cx, |buffer, cx| {
7023 buffer.set_diff_base(diff_base.clone(), cx);
7024 buffer.remote_id().into()
7025 })?;
7026 if let Some(project_id) = remote_id {
7027 client
7028 .send(proto::UpdateDiffBase {
7029 project_id,
7030 buffer_id,
7031 diff_base,
7032 })
7033 .log_err();
7034 }
7035 }
7036
7037 anyhow::Ok(())
7038 })
7039 .detach();
7040 }
7041
7042 fn update_local_worktree_settings(
7043 &mut self,
7044 worktree: &Model<Worktree>,
7045 changes: &UpdatedEntriesSet,
7046 cx: &mut ModelContext<Self>,
7047 ) {
7048 if worktree.read(cx).as_local().is_none() {
7049 return;
7050 }
7051 let project_id = self.remote_id();
7052 let worktree_id = worktree.entity_id();
7053 let remote_worktree_id = worktree.read(cx).id();
7054
7055 let mut settings_contents = Vec::new();
7056 for (path, _, change) in changes.iter() {
7057 let removed = change == &PathChange::Removed;
7058 let abs_path = match worktree.read(cx).absolutize(path) {
7059 Ok(abs_path) => abs_path,
7060 Err(e) => {
7061 log::warn!("Cannot absolutize {path:?} received as {change:?} FS change: {e}");
7062 continue;
7063 }
7064 };
7065
7066 if abs_path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
7067 let settings_dir = Arc::from(
7068 path.ancestors()
7069 .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
7070 .unwrap(),
7071 );
7072 let fs = self.fs.clone();
7073 settings_contents.push(async move {
7074 (
7075 settings_dir,
7076 if removed {
7077 None
7078 } else {
7079 Some(async move { fs.load(&abs_path).await }.await)
7080 },
7081 )
7082 });
7083 } else if abs_path.ends_with(&*LOCAL_TASKS_RELATIVE_PATH) {
7084 self.task_inventory().update(cx, |task_inventory, cx| {
7085 if removed {
7086 task_inventory.remove_local_static_source(&abs_path);
7087 } else {
7088 let fs = self.fs.clone();
7089 let task_abs_path = abs_path.clone();
7090 task_inventory.add_source(
7091 TaskSourceKind::Worktree {
7092 id: remote_worktree_id,
7093 abs_path,
7094 },
7095 |cx| {
7096 let tasks_file_rx =
7097 watch_config_file(&cx.background_executor(), fs, task_abs_path);
7098 StaticSource::new(
7099 format!("local_tasks_for_workspace_{remote_worktree_id}"),
7100 tasks_file_rx,
7101 cx,
7102 )
7103 },
7104 cx,
7105 );
7106 }
7107 })
7108 }
7109 }
7110
7111 if settings_contents.is_empty() {
7112 return;
7113 }
7114
7115 let client = self.client.clone();
7116 cx.spawn(move |_, cx| async move {
7117 let settings_contents: Vec<(Arc<Path>, _)> =
7118 futures::future::join_all(settings_contents).await;
7119 cx.update(|cx| {
7120 cx.update_global::<SettingsStore, _>(|store, cx| {
7121 for (directory, file_content) in settings_contents {
7122 let file_content = file_content.and_then(|content| content.log_err());
7123 store
7124 .set_local_settings(
7125 worktree_id.as_u64() as usize,
7126 directory.clone(),
7127 file_content.as_deref(),
7128 cx,
7129 )
7130 .log_err();
7131 if let Some(remote_id) = project_id {
7132 client
7133 .send(proto::UpdateWorktreeSettings {
7134 project_id: remote_id,
7135 worktree_id: remote_worktree_id.to_proto(),
7136 path: directory.to_string_lossy().into_owned(),
7137 content: file_content,
7138 })
7139 .log_err();
7140 }
7141 }
7142 });
7143 })
7144 .ok();
7145 })
7146 .detach();
7147 }
7148
7149 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
7150 let new_active_entry = entry.and_then(|project_path| {
7151 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
7152 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
7153 Some(entry.id)
7154 });
7155 if new_active_entry != self.active_entry {
7156 self.active_entry = new_active_entry;
7157 cx.emit(Event::ActiveEntryChanged(new_active_entry));
7158 }
7159 }
7160
7161 pub fn language_servers_running_disk_based_diagnostics(
7162 &self,
7163 ) -> impl Iterator<Item = LanguageServerId> + '_ {
7164 self.language_server_statuses
7165 .iter()
7166 .filter_map(|(id, status)| {
7167 if status.has_pending_diagnostic_updates {
7168 Some(*id)
7169 } else {
7170 None
7171 }
7172 })
7173 }
7174
7175 pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
7176 let mut summary = DiagnosticSummary::default();
7177 for (_, _, path_summary) in
7178 self.diagnostic_summaries(include_ignored, cx)
7179 .filter(|(path, _, _)| {
7180 let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
7181 include_ignored || worktree == Some(false)
7182 })
7183 {
7184 summary.error_count += path_summary.error_count;
7185 summary.warning_count += path_summary.warning_count;
7186 }
7187 summary
7188 }
7189
7190 pub fn diagnostic_summaries<'a>(
7191 &'a self,
7192 include_ignored: bool,
7193 cx: &'a AppContext,
7194 ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
7195 self.visible_worktrees(cx)
7196 .flat_map(move |worktree| {
7197 let worktree = worktree.read(cx);
7198 let worktree_id = worktree.id();
7199 worktree
7200 .diagnostic_summaries()
7201 .map(move |(path, server_id, summary)| {
7202 (ProjectPath { worktree_id, path }, server_id, summary)
7203 })
7204 })
7205 .filter(move |(path, _, _)| {
7206 let worktree = self.entry_for_path(path, cx).map(|entry| entry.is_ignored);
7207 include_ignored || worktree == Some(false)
7208 })
7209 }
7210
7211 pub fn disk_based_diagnostics_started(
7212 &mut self,
7213 language_server_id: LanguageServerId,
7214 cx: &mut ModelContext<Self>,
7215 ) {
7216 cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
7217 }
7218
7219 pub fn disk_based_diagnostics_finished(
7220 &mut self,
7221 language_server_id: LanguageServerId,
7222 cx: &mut ModelContext<Self>,
7223 ) {
7224 cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
7225 }
7226
7227 pub fn active_entry(&self) -> Option<ProjectEntryId> {
7228 self.active_entry
7229 }
7230
7231 pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
7232 self.worktree_for_id(path.worktree_id, cx)?
7233 .read(cx)
7234 .entry_for_path(&path.path)
7235 .cloned()
7236 }
7237
7238 pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
7239 let worktree = self.worktree_for_entry(entry_id, cx)?;
7240 let worktree = worktree.read(cx);
7241 let worktree_id = worktree.id();
7242 let path = worktree.entry_for_id(entry_id)?.path.clone();
7243 Some(ProjectPath { worktree_id, path })
7244 }
7245
7246 pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
7247 let workspace_root = self
7248 .worktree_for_id(project_path.worktree_id, cx)?
7249 .read(cx)
7250 .abs_path();
7251 let project_path = project_path.path.as_ref();
7252
7253 Some(if project_path == Path::new("") {
7254 workspace_root.to_path_buf()
7255 } else {
7256 workspace_root.join(project_path)
7257 })
7258 }
7259
7260 // RPC message handlers
7261
7262 async fn handle_unshare_project(
7263 this: Model<Self>,
7264 _: TypedEnvelope<proto::UnshareProject>,
7265 _: Arc<Client>,
7266 mut cx: AsyncAppContext,
7267 ) -> Result<()> {
7268 this.update(&mut cx, |this, cx| {
7269 if this.is_local() {
7270 this.unshare(cx)?;
7271 } else {
7272 this.disconnected_from_host(cx);
7273 }
7274 Ok(())
7275 })?
7276 }
7277
7278 async fn handle_add_collaborator(
7279 this: Model<Self>,
7280 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
7281 _: Arc<Client>,
7282 mut cx: AsyncAppContext,
7283 ) -> Result<()> {
7284 let collaborator = envelope
7285 .payload
7286 .collaborator
7287 .take()
7288 .ok_or_else(|| anyhow!("empty collaborator"))?;
7289
7290 let collaborator = Collaborator::from_proto(collaborator)?;
7291 this.update(&mut cx, |this, cx| {
7292 this.shared_buffers.remove(&collaborator.peer_id);
7293 cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
7294 this.collaborators
7295 .insert(collaborator.peer_id, collaborator);
7296 cx.notify();
7297 })?;
7298
7299 Ok(())
7300 }
7301
7302 async fn handle_update_project_collaborator(
7303 this: Model<Self>,
7304 envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
7305 _: Arc<Client>,
7306 mut cx: AsyncAppContext,
7307 ) -> Result<()> {
7308 let old_peer_id = envelope
7309 .payload
7310 .old_peer_id
7311 .ok_or_else(|| anyhow!("missing old peer id"))?;
7312 let new_peer_id = envelope
7313 .payload
7314 .new_peer_id
7315 .ok_or_else(|| anyhow!("missing new peer id"))?;
7316 this.update(&mut cx, |this, cx| {
7317 let collaborator = this
7318 .collaborators
7319 .remove(&old_peer_id)
7320 .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
7321 let is_host = collaborator.replica_id == 0;
7322 this.collaborators.insert(new_peer_id, collaborator);
7323
7324 let buffers = this.shared_buffers.remove(&old_peer_id);
7325 log::info!(
7326 "peer {} became {}. moving buffers {:?}",
7327 old_peer_id,
7328 new_peer_id,
7329 &buffers
7330 );
7331 if let Some(buffers) = buffers {
7332 this.shared_buffers.insert(new_peer_id, buffers);
7333 }
7334
7335 if is_host {
7336 this.opened_buffers
7337 .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
7338 this.buffer_ordered_messages_tx
7339 .unbounded_send(BufferOrderedMessage::Resync)
7340 .unwrap();
7341 }
7342
7343 cx.emit(Event::CollaboratorUpdated {
7344 old_peer_id,
7345 new_peer_id,
7346 });
7347 cx.notify();
7348 Ok(())
7349 })?
7350 }
7351
7352 async fn handle_remove_collaborator(
7353 this: Model<Self>,
7354 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
7355 _: Arc<Client>,
7356 mut cx: AsyncAppContext,
7357 ) -> Result<()> {
7358 this.update(&mut cx, |this, cx| {
7359 let peer_id = envelope
7360 .payload
7361 .peer_id
7362 .ok_or_else(|| anyhow!("invalid peer id"))?;
7363 let replica_id = this
7364 .collaborators
7365 .remove(&peer_id)
7366 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
7367 .replica_id;
7368 for buffer in this.opened_buffers.values() {
7369 if let Some(buffer) = buffer.upgrade() {
7370 buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
7371 }
7372 }
7373 this.shared_buffers.remove(&peer_id);
7374
7375 cx.emit(Event::CollaboratorLeft(peer_id));
7376 cx.notify();
7377 Ok(())
7378 })?
7379 }
7380
7381 async fn handle_update_project(
7382 this: Model<Self>,
7383 envelope: TypedEnvelope<proto::UpdateProject>,
7384 _: Arc<Client>,
7385 mut cx: AsyncAppContext,
7386 ) -> Result<()> {
7387 this.update(&mut cx, |this, cx| {
7388 // Don't handle messages that were sent before the response to us joining the project
7389 if envelope.message_id > this.join_project_response_message_id {
7390 this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
7391 }
7392 Ok(())
7393 })?
7394 }
7395
7396 async fn handle_update_worktree(
7397 this: Model<Self>,
7398 envelope: TypedEnvelope<proto::UpdateWorktree>,
7399 _: Arc<Client>,
7400 mut cx: AsyncAppContext,
7401 ) -> Result<()> {
7402 this.update(&mut cx, |this, cx| {
7403 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7404 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7405 worktree.update(cx, |worktree, _| {
7406 let worktree = worktree.as_remote_mut().unwrap();
7407 worktree.update_from_remote(envelope.payload);
7408 });
7409 }
7410 Ok(())
7411 })?
7412 }
7413
7414 async fn handle_update_worktree_settings(
7415 this: Model<Self>,
7416 envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
7417 _: Arc<Client>,
7418 mut cx: AsyncAppContext,
7419 ) -> Result<()> {
7420 this.update(&mut cx, |this, cx| {
7421 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7422 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7423 cx.update_global::<SettingsStore, _>(|store, cx| {
7424 store
7425 .set_local_settings(
7426 worktree.entity_id().as_u64() as usize,
7427 PathBuf::from(&envelope.payload.path).into(),
7428 envelope.payload.content.as_deref(),
7429 cx,
7430 )
7431 .log_err();
7432 });
7433 }
7434 Ok(())
7435 })?
7436 }
7437
7438 async fn handle_create_project_entry(
7439 this: Model<Self>,
7440 envelope: TypedEnvelope<proto::CreateProjectEntry>,
7441 _: Arc<Client>,
7442 mut cx: AsyncAppContext,
7443 ) -> Result<proto::ProjectEntryResponse> {
7444 let worktree = this.update(&mut cx, |this, cx| {
7445 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7446 this.worktree_for_id(worktree_id, cx)
7447 .ok_or_else(|| anyhow!("worktree not found"))
7448 })??;
7449 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7450 let entry = worktree
7451 .update(&mut cx, |worktree, cx| {
7452 let worktree = worktree.as_local_mut().unwrap();
7453 let path = PathBuf::from(envelope.payload.path);
7454 worktree.create_entry(path, envelope.payload.is_directory, cx)
7455 })?
7456 .await?;
7457 Ok(proto::ProjectEntryResponse {
7458 entry: entry.as_ref().map(|e| e.into()),
7459 worktree_scan_id: worktree_scan_id as u64,
7460 })
7461 }
7462
7463 async fn handle_rename_project_entry(
7464 this: Model<Self>,
7465 envelope: TypedEnvelope<proto::RenameProjectEntry>,
7466 _: Arc<Client>,
7467 mut cx: AsyncAppContext,
7468 ) -> Result<proto::ProjectEntryResponse> {
7469 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7470 let worktree = this.update(&mut cx, |this, cx| {
7471 this.worktree_for_entry(entry_id, cx)
7472 .ok_or_else(|| anyhow!("worktree not found"))
7473 })??;
7474 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7475 let entry = worktree
7476 .update(&mut cx, |worktree, cx| {
7477 let new_path = PathBuf::from(envelope.payload.new_path);
7478 worktree
7479 .as_local_mut()
7480 .unwrap()
7481 .rename_entry(entry_id, new_path, cx)
7482 })?
7483 .await?;
7484 Ok(proto::ProjectEntryResponse {
7485 entry: entry.as_ref().map(|e| e.into()),
7486 worktree_scan_id: worktree_scan_id as u64,
7487 })
7488 }
7489
7490 async fn handle_copy_project_entry(
7491 this: Model<Self>,
7492 envelope: TypedEnvelope<proto::CopyProjectEntry>,
7493 _: Arc<Client>,
7494 mut cx: AsyncAppContext,
7495 ) -> Result<proto::ProjectEntryResponse> {
7496 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7497 let worktree = this.update(&mut cx, |this, cx| {
7498 this.worktree_for_entry(entry_id, cx)
7499 .ok_or_else(|| anyhow!("worktree not found"))
7500 })??;
7501 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7502 let entry = worktree
7503 .update(&mut cx, |worktree, cx| {
7504 let new_path = PathBuf::from(envelope.payload.new_path);
7505 worktree
7506 .as_local_mut()
7507 .unwrap()
7508 .copy_entry(entry_id, new_path, cx)
7509 })?
7510 .await?;
7511 Ok(proto::ProjectEntryResponse {
7512 entry: entry.as_ref().map(|e| e.into()),
7513 worktree_scan_id: worktree_scan_id as u64,
7514 })
7515 }
7516
7517 async fn handle_delete_project_entry(
7518 this: Model<Self>,
7519 envelope: TypedEnvelope<proto::DeleteProjectEntry>,
7520 _: Arc<Client>,
7521 mut cx: AsyncAppContext,
7522 ) -> Result<proto::ProjectEntryResponse> {
7523 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7524
7525 this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7526
7527 let worktree = this.update(&mut cx, |this, cx| {
7528 this.worktree_for_entry(entry_id, cx)
7529 .ok_or_else(|| anyhow!("worktree not found"))
7530 })??;
7531 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7532 worktree
7533 .update(&mut cx, |worktree, cx| {
7534 worktree
7535 .as_local_mut()
7536 .unwrap()
7537 .delete_entry(entry_id, cx)
7538 .ok_or_else(|| anyhow!("invalid entry"))
7539 })??
7540 .await?;
7541 Ok(proto::ProjectEntryResponse {
7542 entry: None,
7543 worktree_scan_id: worktree_scan_id as u64,
7544 })
7545 }
7546
7547 async fn handle_expand_project_entry(
7548 this: Model<Self>,
7549 envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7550 _: Arc<Client>,
7551 mut cx: AsyncAppContext,
7552 ) -> Result<proto::ExpandProjectEntryResponse> {
7553 let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7554 let worktree = this
7555 .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7556 .ok_or_else(|| anyhow!("invalid request"))?;
7557 worktree
7558 .update(&mut cx, |worktree, cx| {
7559 worktree
7560 .as_local_mut()
7561 .unwrap()
7562 .expand_entry(entry_id, cx)
7563 .ok_or_else(|| anyhow!("invalid entry"))
7564 })??
7565 .await?;
7566 let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7567 Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7568 }
7569
7570 async fn handle_update_diagnostic_summary(
7571 this: Model<Self>,
7572 envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7573 _: Arc<Client>,
7574 mut cx: AsyncAppContext,
7575 ) -> Result<()> {
7576 this.update(&mut cx, |this, cx| {
7577 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7578 if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7579 if let Some(summary) = envelope.payload.summary {
7580 let project_path = ProjectPath {
7581 worktree_id,
7582 path: Path::new(&summary.path).into(),
7583 };
7584 worktree.update(cx, |worktree, _| {
7585 worktree
7586 .as_remote_mut()
7587 .unwrap()
7588 .update_diagnostic_summary(project_path.path.clone(), &summary);
7589 });
7590 cx.emit(Event::DiagnosticsUpdated {
7591 language_server_id: LanguageServerId(summary.language_server_id as usize),
7592 path: project_path,
7593 });
7594 }
7595 }
7596 Ok(())
7597 })?
7598 }
7599
7600 async fn handle_start_language_server(
7601 this: Model<Self>,
7602 envelope: TypedEnvelope<proto::StartLanguageServer>,
7603 _: Arc<Client>,
7604 mut cx: AsyncAppContext,
7605 ) -> Result<()> {
7606 let server = envelope
7607 .payload
7608 .server
7609 .ok_or_else(|| anyhow!("invalid server"))?;
7610 this.update(&mut cx, |this, cx| {
7611 this.language_server_statuses.insert(
7612 LanguageServerId(server.id as usize),
7613 LanguageServerStatus {
7614 name: server.name,
7615 pending_work: Default::default(),
7616 has_pending_diagnostic_updates: false,
7617 progress_tokens: Default::default(),
7618 },
7619 );
7620 cx.notify();
7621 })?;
7622 Ok(())
7623 }
7624
7625 async fn handle_update_language_server(
7626 this: Model<Self>,
7627 envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7628 _: Arc<Client>,
7629 mut cx: AsyncAppContext,
7630 ) -> Result<()> {
7631 this.update(&mut cx, |this, cx| {
7632 let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7633
7634 match envelope
7635 .payload
7636 .variant
7637 .ok_or_else(|| anyhow!("invalid variant"))?
7638 {
7639 proto::update_language_server::Variant::WorkStart(payload) => {
7640 this.on_lsp_work_start(
7641 language_server_id,
7642 payload.token,
7643 LanguageServerProgress {
7644 message: payload.message,
7645 percentage: payload.percentage.map(|p| p as usize),
7646 last_update_at: Instant::now(),
7647 },
7648 cx,
7649 );
7650 }
7651
7652 proto::update_language_server::Variant::WorkProgress(payload) => {
7653 this.on_lsp_work_progress(
7654 language_server_id,
7655 payload.token,
7656 LanguageServerProgress {
7657 message: payload.message,
7658 percentage: payload.percentage.map(|p| p as usize),
7659 last_update_at: Instant::now(),
7660 },
7661 cx,
7662 );
7663 }
7664
7665 proto::update_language_server::Variant::WorkEnd(payload) => {
7666 this.on_lsp_work_end(language_server_id, payload.token, cx);
7667 }
7668
7669 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7670 this.disk_based_diagnostics_started(language_server_id, cx);
7671 }
7672
7673 proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7674 this.disk_based_diagnostics_finished(language_server_id, cx)
7675 }
7676 }
7677
7678 Ok(())
7679 })?
7680 }
7681
7682 async fn handle_update_buffer(
7683 this: Model<Self>,
7684 envelope: TypedEnvelope<proto::UpdateBuffer>,
7685 _: Arc<Client>,
7686 mut cx: AsyncAppContext,
7687 ) -> Result<proto::Ack> {
7688 this.update(&mut cx, |this, cx| {
7689 let payload = envelope.payload.clone();
7690 let buffer_id = BufferId::new(payload.buffer_id)?;
7691 let ops = payload
7692 .operations
7693 .into_iter()
7694 .map(language::proto::deserialize_operation)
7695 .collect::<Result<Vec<_>, _>>()?;
7696 let is_remote = this.is_remote();
7697 match this.opened_buffers.entry(buffer_id) {
7698 hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7699 OpenBuffer::Strong(buffer) => {
7700 buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7701 }
7702 OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7703 OpenBuffer::Weak(_) => {}
7704 },
7705 hash_map::Entry::Vacant(e) => {
7706 assert!(
7707 is_remote,
7708 "received buffer update from {:?}",
7709 envelope.original_sender_id
7710 );
7711 e.insert(OpenBuffer::Operations(ops));
7712 }
7713 }
7714 Ok(proto::Ack {})
7715 })?
7716 }
7717
7718 async fn handle_create_buffer_for_peer(
7719 this: Model<Self>,
7720 envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7721 _: Arc<Client>,
7722 mut cx: AsyncAppContext,
7723 ) -> Result<()> {
7724 this.update(&mut cx, |this, cx| {
7725 match envelope
7726 .payload
7727 .variant
7728 .ok_or_else(|| anyhow!("missing variant"))?
7729 {
7730 proto::create_buffer_for_peer::Variant::State(mut state) => {
7731 let mut buffer_file = None;
7732 if let Some(file) = state.file.take() {
7733 let worktree_id = WorktreeId::from_proto(file.worktree_id);
7734 let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7735 anyhow!("no worktree found for id {}", file.worktree_id)
7736 })?;
7737 buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7738 as Arc<dyn language::File>);
7739 }
7740
7741 let buffer_id = BufferId::new(state.id)?;
7742 let buffer = cx.new_model(|_| {
7743 Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7744 .unwrap()
7745 });
7746 this.incomplete_remote_buffers
7747 .insert(buffer_id, Some(buffer));
7748 }
7749 proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7750 let buffer_id = BufferId::new(chunk.buffer_id)?;
7751 let buffer = this
7752 .incomplete_remote_buffers
7753 .get(&buffer_id)
7754 .cloned()
7755 .flatten()
7756 .ok_or_else(|| {
7757 anyhow!(
7758 "received chunk for buffer {} without initial state",
7759 chunk.buffer_id
7760 )
7761 })?;
7762 let operations = chunk
7763 .operations
7764 .into_iter()
7765 .map(language::proto::deserialize_operation)
7766 .collect::<Result<Vec<_>>>()?;
7767 buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7768
7769 if chunk.is_last {
7770 this.incomplete_remote_buffers.remove(&buffer_id);
7771 this.register_buffer(&buffer, cx)?;
7772 }
7773 }
7774 }
7775
7776 Ok(())
7777 })?
7778 }
7779
7780 async fn handle_update_diff_base(
7781 this: Model<Self>,
7782 envelope: TypedEnvelope<proto::UpdateDiffBase>,
7783 _: Arc<Client>,
7784 mut cx: AsyncAppContext,
7785 ) -> Result<()> {
7786 this.update(&mut cx, |this, cx| {
7787 let buffer_id = envelope.payload.buffer_id;
7788 let buffer_id = BufferId::new(buffer_id)?;
7789 let diff_base = envelope.payload.diff_base;
7790 if let Some(buffer) = this
7791 .opened_buffers
7792 .get_mut(&buffer_id)
7793 .and_then(|b| b.upgrade())
7794 .or_else(|| {
7795 this.incomplete_remote_buffers
7796 .get(&buffer_id)
7797 .cloned()
7798 .flatten()
7799 })
7800 {
7801 buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7802 }
7803 Ok(())
7804 })?
7805 }
7806
7807 async fn handle_update_buffer_file(
7808 this: Model<Self>,
7809 envelope: TypedEnvelope<proto::UpdateBufferFile>,
7810 _: Arc<Client>,
7811 mut cx: AsyncAppContext,
7812 ) -> Result<()> {
7813 let buffer_id = envelope.payload.buffer_id;
7814 let buffer_id = BufferId::new(buffer_id)?;
7815
7816 this.update(&mut cx, |this, cx| {
7817 let payload = envelope.payload.clone();
7818 if let Some(buffer) = this
7819 .opened_buffers
7820 .get(&buffer_id)
7821 .and_then(|b| b.upgrade())
7822 .or_else(|| {
7823 this.incomplete_remote_buffers
7824 .get(&buffer_id)
7825 .cloned()
7826 .flatten()
7827 })
7828 {
7829 let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7830 let worktree = this
7831 .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7832 .ok_or_else(|| anyhow!("no such worktree"))?;
7833 let file = File::from_proto(file, worktree, cx)?;
7834 buffer.update(cx, |buffer, cx| {
7835 buffer.file_updated(Arc::new(file), cx);
7836 });
7837 this.detect_language_for_buffer(&buffer, cx);
7838 }
7839 Ok(())
7840 })?
7841 }
7842
7843 async fn handle_save_buffer(
7844 this: Model<Self>,
7845 envelope: TypedEnvelope<proto::SaveBuffer>,
7846 _: Arc<Client>,
7847 mut cx: AsyncAppContext,
7848 ) -> Result<proto::BufferSaved> {
7849 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
7850 let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7851 let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7852 let buffer = this
7853 .opened_buffers
7854 .get(&buffer_id)
7855 .and_then(|buffer| buffer.upgrade())
7856 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7857 anyhow::Ok((project_id, buffer))
7858 })??;
7859 buffer
7860 .update(&mut cx, |buffer, _| {
7861 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7862 })?
7863 .await?;
7864 let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7865
7866 this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7867 .await?;
7868 buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7869 project_id,
7870 buffer_id: buffer_id.into(),
7871 version: serialize_version(buffer.saved_version()),
7872 mtime: Some(buffer.saved_mtime().into()),
7873 fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7874 })
7875 }
7876
7877 async fn handle_reload_buffers(
7878 this: Model<Self>,
7879 envelope: TypedEnvelope<proto::ReloadBuffers>,
7880 _: Arc<Client>,
7881 mut cx: AsyncAppContext,
7882 ) -> Result<proto::ReloadBuffersResponse> {
7883 let sender_id = envelope.original_sender_id()?;
7884 let reload = this.update(&mut cx, |this, cx| {
7885 let mut buffers = HashSet::default();
7886 for buffer_id in &envelope.payload.buffer_ids {
7887 let buffer_id = BufferId::new(*buffer_id)?;
7888 buffers.insert(
7889 this.opened_buffers
7890 .get(&buffer_id)
7891 .and_then(|buffer| buffer.upgrade())
7892 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7893 );
7894 }
7895 Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7896 })??;
7897
7898 let project_transaction = reload.await?;
7899 let project_transaction = this.update(&mut cx, |this, cx| {
7900 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7901 })?;
7902 Ok(proto::ReloadBuffersResponse {
7903 transaction: Some(project_transaction),
7904 })
7905 }
7906
7907 async fn handle_synchronize_buffers(
7908 this: Model<Self>,
7909 envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7910 _: Arc<Client>,
7911 mut cx: AsyncAppContext,
7912 ) -> Result<proto::SynchronizeBuffersResponse> {
7913 let project_id = envelope.payload.project_id;
7914 let mut response = proto::SynchronizeBuffersResponse {
7915 buffers: Default::default(),
7916 };
7917
7918 this.update(&mut cx, |this, cx| {
7919 let Some(guest_id) = envelope.original_sender_id else {
7920 error!("missing original_sender_id on SynchronizeBuffers request");
7921 bail!("missing original_sender_id on SynchronizeBuffers request");
7922 };
7923
7924 this.shared_buffers.entry(guest_id).or_default().clear();
7925 for buffer in envelope.payload.buffers {
7926 let buffer_id = BufferId::new(buffer.id)?;
7927 let remote_version = language::proto::deserialize_version(&buffer.version);
7928 if let Some(buffer) = this.buffer_for_id(buffer_id) {
7929 this.shared_buffers
7930 .entry(guest_id)
7931 .or_default()
7932 .insert(buffer_id);
7933
7934 let buffer = buffer.read(cx);
7935 response.buffers.push(proto::BufferVersion {
7936 id: buffer_id.into(),
7937 version: language::proto::serialize_version(&buffer.version),
7938 });
7939
7940 let operations = buffer.serialize_ops(Some(remote_version), cx);
7941 let client = this.client.clone();
7942 if let Some(file) = buffer.file() {
7943 client
7944 .send(proto::UpdateBufferFile {
7945 project_id,
7946 buffer_id: buffer_id.into(),
7947 file: Some(file.to_proto()),
7948 })
7949 .log_err();
7950 }
7951
7952 client
7953 .send(proto::UpdateDiffBase {
7954 project_id,
7955 buffer_id: buffer_id.into(),
7956 diff_base: buffer.diff_base().map(Into::into),
7957 })
7958 .log_err();
7959
7960 client
7961 .send(proto::BufferReloaded {
7962 project_id,
7963 buffer_id: buffer_id.into(),
7964 version: language::proto::serialize_version(buffer.saved_version()),
7965 mtime: Some(buffer.saved_mtime().into()),
7966 fingerprint: language::proto::serialize_fingerprint(
7967 buffer.saved_version_fingerprint(),
7968 ),
7969 line_ending: language::proto::serialize_line_ending(
7970 buffer.line_ending(),
7971 ) as i32,
7972 })
7973 .log_err();
7974
7975 cx.background_executor()
7976 .spawn(
7977 async move {
7978 let operations = operations.await;
7979 for chunk in split_operations(operations) {
7980 client
7981 .request(proto::UpdateBuffer {
7982 project_id,
7983 buffer_id: buffer_id.into(),
7984 operations: chunk,
7985 })
7986 .await?;
7987 }
7988 anyhow::Ok(())
7989 }
7990 .log_err(),
7991 )
7992 .detach();
7993 }
7994 }
7995 Ok(())
7996 })??;
7997
7998 Ok(response)
7999 }
8000
8001 async fn handle_format_buffers(
8002 this: Model<Self>,
8003 envelope: TypedEnvelope<proto::FormatBuffers>,
8004 _: Arc<Client>,
8005 mut cx: AsyncAppContext,
8006 ) -> Result<proto::FormatBuffersResponse> {
8007 let sender_id = envelope.original_sender_id()?;
8008 let format = this.update(&mut cx, |this, cx| {
8009 let mut buffers = HashSet::default();
8010 for buffer_id in &envelope.payload.buffer_ids {
8011 let buffer_id = BufferId::new(*buffer_id)?;
8012 buffers.insert(
8013 this.opened_buffers
8014 .get(&buffer_id)
8015 .and_then(|buffer| buffer.upgrade())
8016 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
8017 );
8018 }
8019 let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
8020 Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
8021 })??;
8022
8023 let project_transaction = format.await?;
8024 let project_transaction = this.update(&mut cx, |this, cx| {
8025 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8026 })?;
8027 Ok(proto::FormatBuffersResponse {
8028 transaction: Some(project_transaction),
8029 })
8030 }
8031
8032 async fn handle_apply_additional_edits_for_completion(
8033 this: Model<Self>,
8034 envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
8035 _: Arc<Client>,
8036 mut cx: AsyncAppContext,
8037 ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
8038 let languages = this.update(&mut cx, |this, _| this.languages.clone())?;
8039 let (buffer, completion) = this.update(&mut cx, |this, cx| {
8040 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8041 let buffer = this
8042 .opened_buffers
8043 .get(&buffer_id)
8044 .and_then(|buffer| buffer.upgrade())
8045 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8046 let language = buffer.read(cx).language();
8047 let completion = language::proto::deserialize_completion(
8048 envelope
8049 .payload
8050 .completion
8051 .ok_or_else(|| anyhow!("invalid completion"))?,
8052 language.cloned(),
8053 &languages,
8054 );
8055 Ok::<_, anyhow::Error>((buffer, completion))
8056 })??;
8057
8058 let completion = completion.await?;
8059
8060 let apply_additional_edits = this.update(&mut cx, |this, cx| {
8061 this.apply_additional_edits_for_completion(buffer, completion, false, cx)
8062 })?;
8063
8064 Ok(proto::ApplyCompletionAdditionalEditsResponse {
8065 transaction: apply_additional_edits
8066 .await?
8067 .as_ref()
8068 .map(language::proto::serialize_transaction),
8069 })
8070 }
8071
8072 async fn handle_resolve_completion_documentation(
8073 this: Model<Self>,
8074 envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
8075 _: Arc<Client>,
8076 mut cx: AsyncAppContext,
8077 ) -> Result<proto::ResolveCompletionDocumentationResponse> {
8078 let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
8079
8080 let completion = this
8081 .read_with(&mut cx, |this, _| {
8082 let id = LanguageServerId(envelope.payload.language_server_id as usize);
8083 let Some(server) = this.language_server_for_id(id) else {
8084 return Err(anyhow!("No language server {id}"));
8085 };
8086
8087 Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
8088 })??
8089 .await?;
8090
8091 let mut is_markdown = false;
8092 let text = match completion.documentation {
8093 Some(lsp::Documentation::String(text)) => text,
8094
8095 Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
8096 is_markdown = kind == lsp::MarkupKind::Markdown;
8097 value
8098 }
8099
8100 _ => String::new(),
8101 };
8102
8103 Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
8104 }
8105
8106 async fn handle_apply_code_action(
8107 this: Model<Self>,
8108 envelope: TypedEnvelope<proto::ApplyCodeAction>,
8109 _: Arc<Client>,
8110 mut cx: AsyncAppContext,
8111 ) -> Result<proto::ApplyCodeActionResponse> {
8112 let sender_id = envelope.original_sender_id()?;
8113 let action = language::proto::deserialize_code_action(
8114 envelope
8115 .payload
8116 .action
8117 .ok_or_else(|| anyhow!("invalid action"))?,
8118 )?;
8119 let apply_code_action = this.update(&mut cx, |this, cx| {
8120 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8121 let buffer = this
8122 .opened_buffers
8123 .get(&buffer_id)
8124 .and_then(|buffer| buffer.upgrade())
8125 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
8126 Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
8127 })??;
8128
8129 let project_transaction = apply_code_action.await?;
8130 let project_transaction = this.update(&mut cx, |this, cx| {
8131 this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
8132 })?;
8133 Ok(proto::ApplyCodeActionResponse {
8134 transaction: Some(project_transaction),
8135 })
8136 }
8137
8138 async fn handle_on_type_formatting(
8139 this: Model<Self>,
8140 envelope: TypedEnvelope<proto::OnTypeFormatting>,
8141 _: Arc<Client>,
8142 mut cx: AsyncAppContext,
8143 ) -> Result<proto::OnTypeFormattingResponse> {
8144 let on_type_formatting = this.update(&mut cx, |this, cx| {
8145 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8146 let buffer = this
8147 .opened_buffers
8148 .get(&buffer_id)
8149 .and_then(|buffer| buffer.upgrade())
8150 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
8151 let position = envelope
8152 .payload
8153 .position
8154 .and_then(deserialize_anchor)
8155 .ok_or_else(|| anyhow!("invalid position"))?;
8156 Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
8157 buffer,
8158 position,
8159 envelope.payload.trigger.clone(),
8160 cx,
8161 ))
8162 })??;
8163
8164 let transaction = on_type_formatting
8165 .await?
8166 .as_ref()
8167 .map(language::proto::serialize_transaction);
8168 Ok(proto::OnTypeFormattingResponse { transaction })
8169 }
8170
8171 async fn handle_inlay_hints(
8172 this: Model<Self>,
8173 envelope: TypedEnvelope<proto::InlayHints>,
8174 _: Arc<Client>,
8175 mut cx: AsyncAppContext,
8176 ) -> Result<proto::InlayHintsResponse> {
8177 let sender_id = envelope.original_sender_id()?;
8178 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8179 let buffer = this.update(&mut cx, |this, _| {
8180 this.opened_buffers
8181 .get(&buffer_id)
8182 .and_then(|buffer| buffer.upgrade())
8183 .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
8184 })??;
8185 buffer
8186 .update(&mut cx, |buffer, _| {
8187 buffer.wait_for_version(deserialize_version(&envelope.payload.version))
8188 })?
8189 .await
8190 .with_context(|| format!("waiting for version for buffer {}", buffer.entity_id()))?;
8191
8192 let start = envelope
8193 .payload
8194 .start
8195 .and_then(deserialize_anchor)
8196 .context("missing range start")?;
8197 let end = envelope
8198 .payload
8199 .end
8200 .and_then(deserialize_anchor)
8201 .context("missing range end")?;
8202 let buffer_hints = this
8203 .update(&mut cx, |project, cx| {
8204 project.inlay_hints(buffer.clone(), start..end, cx)
8205 })?
8206 .await
8207 .context("inlay hints fetch")?;
8208
8209 this.update(&mut cx, |project, cx| {
8210 InlayHints::response_to_proto(
8211 buffer_hints,
8212 project,
8213 sender_id,
8214 &buffer.read(cx).version(),
8215 cx,
8216 )
8217 })
8218 }
8219
8220 async fn handle_resolve_inlay_hint(
8221 this: Model<Self>,
8222 envelope: TypedEnvelope<proto::ResolveInlayHint>,
8223 _: Arc<Client>,
8224 mut cx: AsyncAppContext,
8225 ) -> Result<proto::ResolveInlayHintResponse> {
8226 let proto_hint = envelope
8227 .payload
8228 .hint
8229 .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
8230 let hint = InlayHints::proto_to_project_hint(proto_hint)
8231 .context("resolved proto inlay hint conversion")?;
8232 let buffer = this.update(&mut cx, |this, _cx| {
8233 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8234 this.opened_buffers
8235 .get(&buffer_id)
8236 .and_then(|buffer| buffer.upgrade())
8237 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8238 })??;
8239 let response_hint = this
8240 .update(&mut cx, |project, cx| {
8241 project.resolve_inlay_hint(
8242 hint,
8243 buffer,
8244 LanguageServerId(envelope.payload.language_server_id as usize),
8245 cx,
8246 )
8247 })?
8248 .await
8249 .context("inlay hints fetch")?;
8250 Ok(proto::ResolveInlayHintResponse {
8251 hint: Some(InlayHints::project_to_proto_hint(response_hint)),
8252 })
8253 }
8254
8255 async fn handle_refresh_inlay_hints(
8256 this: Model<Self>,
8257 _: TypedEnvelope<proto::RefreshInlayHints>,
8258 _: Arc<Client>,
8259 mut cx: AsyncAppContext,
8260 ) -> Result<proto::Ack> {
8261 this.update(&mut cx, |_, cx| {
8262 cx.emit(Event::RefreshInlayHints);
8263 })?;
8264 Ok(proto::Ack {})
8265 }
8266
8267 async fn handle_lsp_command<T: LspCommand>(
8268 this: Model<Self>,
8269 envelope: TypedEnvelope<T::ProtoRequest>,
8270 _: Arc<Client>,
8271 mut cx: AsyncAppContext,
8272 ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
8273 where
8274 <T::LspRequest as lsp::request::Request>::Params: Send,
8275 <T::LspRequest as lsp::request::Request>::Result: Send,
8276 {
8277 let sender_id = envelope.original_sender_id()?;
8278 let buffer_id = T::buffer_id_from_proto(&envelope.payload)?;
8279 let buffer_handle = this.update(&mut cx, |this, _cx| {
8280 this.opened_buffers
8281 .get(&buffer_id)
8282 .and_then(|buffer| buffer.upgrade())
8283 .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
8284 })??;
8285 let request = T::from_proto(
8286 envelope.payload,
8287 this.clone(),
8288 buffer_handle.clone(),
8289 cx.clone(),
8290 )
8291 .await?;
8292 let response = this
8293 .update(&mut cx, |this, cx| {
8294 this.request_lsp(
8295 buffer_handle.clone(),
8296 LanguageServerToQuery::Primary,
8297 request,
8298 cx,
8299 )
8300 })?
8301 .await?;
8302 this.update(&mut cx, |this, cx| {
8303 Ok(T::response_to_proto(
8304 response,
8305 this,
8306 sender_id,
8307 &buffer_handle.read(cx).version(),
8308 cx,
8309 ))
8310 })?
8311 }
8312
8313 async fn handle_get_project_symbols(
8314 this: Model<Self>,
8315 envelope: TypedEnvelope<proto::GetProjectSymbols>,
8316 _: Arc<Client>,
8317 mut cx: AsyncAppContext,
8318 ) -> Result<proto::GetProjectSymbolsResponse> {
8319 let symbols = this
8320 .update(&mut cx, |this, cx| {
8321 this.symbols(&envelope.payload.query, cx)
8322 })?
8323 .await?;
8324
8325 Ok(proto::GetProjectSymbolsResponse {
8326 symbols: symbols.iter().map(serialize_symbol).collect(),
8327 })
8328 }
8329
8330 async fn handle_search_project(
8331 this: Model<Self>,
8332 envelope: TypedEnvelope<proto::SearchProject>,
8333 _: Arc<Client>,
8334 mut cx: AsyncAppContext,
8335 ) -> Result<proto::SearchProjectResponse> {
8336 let peer_id = envelope.original_sender_id()?;
8337 let query = SearchQuery::from_proto(envelope.payload)?;
8338 let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
8339
8340 cx.spawn(move |mut cx| async move {
8341 let mut locations = Vec::new();
8342 while let Some((buffer, ranges)) = result.next().await {
8343 for range in ranges {
8344 let start = serialize_anchor(&range.start);
8345 let end = serialize_anchor(&range.end);
8346 let buffer_id = this.update(&mut cx, |this, cx| {
8347 this.create_buffer_for_peer(&buffer, peer_id, cx).into()
8348 })?;
8349 locations.push(proto::Location {
8350 buffer_id,
8351 start: Some(start),
8352 end: Some(end),
8353 });
8354 }
8355 }
8356 Ok(proto::SearchProjectResponse { locations })
8357 })
8358 .await
8359 }
8360
8361 async fn handle_open_buffer_for_symbol(
8362 this: Model<Self>,
8363 envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
8364 _: Arc<Client>,
8365 mut cx: AsyncAppContext,
8366 ) -> Result<proto::OpenBufferForSymbolResponse> {
8367 let peer_id = envelope.original_sender_id()?;
8368 let symbol = envelope
8369 .payload
8370 .symbol
8371 .ok_or_else(|| anyhow!("invalid symbol"))?;
8372 let symbol = this
8373 .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
8374 .await?;
8375 let symbol = this.update(&mut cx, |this, _| {
8376 let signature = this.symbol_signature(&symbol.path);
8377 if signature == symbol.signature {
8378 Ok(symbol)
8379 } else {
8380 Err(anyhow!("invalid symbol signature"))
8381 }
8382 })??;
8383 let buffer = this
8384 .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
8385 .await?;
8386
8387 this.update(&mut cx, |this, cx| {
8388 let is_private = buffer
8389 .read(cx)
8390 .file()
8391 .map(|f| f.is_private())
8392 .unwrap_or_default();
8393 if is_private {
8394 Err(anyhow!(ErrorCode::UnsharedItem))
8395 } else {
8396 Ok(proto::OpenBufferForSymbolResponse {
8397 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8398 })
8399 }
8400 })?
8401 }
8402
8403 fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
8404 let mut hasher = Sha256::new();
8405 hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
8406 hasher.update(project_path.path.to_string_lossy().as_bytes());
8407 hasher.update(self.nonce.to_be_bytes());
8408 hasher.finalize().as_slice().try_into().unwrap()
8409 }
8410
8411 async fn handle_open_buffer_by_id(
8412 this: Model<Self>,
8413 envelope: TypedEnvelope<proto::OpenBufferById>,
8414 _: Arc<Client>,
8415 mut cx: AsyncAppContext,
8416 ) -> Result<proto::OpenBufferResponse> {
8417 let peer_id = envelope.original_sender_id()?;
8418 let buffer_id = BufferId::new(envelope.payload.id)?;
8419 let buffer = this
8420 .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
8421 .await?;
8422 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8423 }
8424
8425 async fn handle_open_buffer_by_path(
8426 this: Model<Self>,
8427 envelope: TypedEnvelope<proto::OpenBufferByPath>,
8428 _: Arc<Client>,
8429 mut cx: AsyncAppContext,
8430 ) -> Result<proto::OpenBufferResponse> {
8431 let peer_id = envelope.original_sender_id()?;
8432 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
8433 let open_buffer = this.update(&mut cx, |this, cx| {
8434 this.open_buffer(
8435 ProjectPath {
8436 worktree_id,
8437 path: PathBuf::from(envelope.payload.path).into(),
8438 },
8439 cx,
8440 )
8441 })?;
8442
8443 let buffer = open_buffer.await?;
8444 Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
8445 }
8446
8447 fn respond_to_open_buffer_request(
8448 this: Model<Self>,
8449 buffer: Model<Buffer>,
8450 peer_id: proto::PeerId,
8451 cx: &mut AsyncAppContext,
8452 ) -> Result<proto::OpenBufferResponse> {
8453 this.update(cx, |this, cx| {
8454 let is_private = buffer
8455 .read(cx)
8456 .file()
8457 .map(|f| f.is_private())
8458 .unwrap_or_default();
8459 if is_private {
8460 Err(anyhow!(ErrorCode::UnsharedItem))
8461 } else {
8462 Ok(proto::OpenBufferResponse {
8463 buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
8464 })
8465 }
8466 })?
8467 }
8468
8469 fn serialize_project_transaction_for_peer(
8470 &mut self,
8471 project_transaction: ProjectTransaction,
8472 peer_id: proto::PeerId,
8473 cx: &mut AppContext,
8474 ) -> proto::ProjectTransaction {
8475 let mut serialized_transaction = proto::ProjectTransaction {
8476 buffer_ids: Default::default(),
8477 transactions: Default::default(),
8478 };
8479 for (buffer, transaction) in project_transaction.0 {
8480 serialized_transaction
8481 .buffer_ids
8482 .push(self.create_buffer_for_peer(&buffer, peer_id, cx).into());
8483 serialized_transaction
8484 .transactions
8485 .push(language::proto::serialize_transaction(&transaction));
8486 }
8487 serialized_transaction
8488 }
8489
8490 fn deserialize_project_transaction(
8491 &mut self,
8492 message: proto::ProjectTransaction,
8493 push_to_history: bool,
8494 cx: &mut ModelContext<Self>,
8495 ) -> Task<Result<ProjectTransaction>> {
8496 cx.spawn(move |this, mut cx| async move {
8497 let mut project_transaction = ProjectTransaction::default();
8498 for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
8499 {
8500 let buffer_id = BufferId::new(buffer_id)?;
8501 let buffer = this
8502 .update(&mut cx, |this, cx| {
8503 this.wait_for_remote_buffer(buffer_id, cx)
8504 })?
8505 .await?;
8506 let transaction = language::proto::deserialize_transaction(transaction)?;
8507 project_transaction.0.insert(buffer, transaction);
8508 }
8509
8510 for (buffer, transaction) in &project_transaction.0 {
8511 buffer
8512 .update(&mut cx, |buffer, _| {
8513 buffer.wait_for_edits(transaction.edit_ids.iter().copied())
8514 })?
8515 .await?;
8516
8517 if push_to_history {
8518 buffer.update(&mut cx, |buffer, _| {
8519 buffer.push_transaction(transaction.clone(), Instant::now());
8520 })?;
8521 }
8522 }
8523
8524 Ok(project_transaction)
8525 })
8526 }
8527
8528 fn create_buffer_for_peer(
8529 &mut self,
8530 buffer: &Model<Buffer>,
8531 peer_id: proto::PeerId,
8532 cx: &mut AppContext,
8533 ) -> BufferId {
8534 let buffer_id = buffer.read(cx).remote_id();
8535 if let ProjectClientState::Shared { updates_tx, .. } = &self.client_state {
8536 updates_tx
8537 .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
8538 .ok();
8539 }
8540 buffer_id
8541 }
8542
8543 fn wait_for_remote_buffer(
8544 &mut self,
8545 id: BufferId,
8546 cx: &mut ModelContext<Self>,
8547 ) -> Task<Result<Model<Buffer>>> {
8548 let mut opened_buffer_rx = self.opened_buffer.1.clone();
8549
8550 cx.spawn(move |this, mut cx| async move {
8551 let buffer = loop {
8552 let Some(this) = this.upgrade() else {
8553 return Err(anyhow!("project dropped"));
8554 };
8555
8556 let buffer = this.update(&mut cx, |this, _cx| {
8557 this.opened_buffers
8558 .get(&id)
8559 .and_then(|buffer| buffer.upgrade())
8560 })?;
8561
8562 if let Some(buffer) = buffer {
8563 break buffer;
8564 } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
8565 return Err(anyhow!("disconnected before buffer {} could be opened", id));
8566 }
8567
8568 this.update(&mut cx, |this, _| {
8569 this.incomplete_remote_buffers.entry(id).or_default();
8570 })?;
8571 drop(this);
8572
8573 opened_buffer_rx
8574 .next()
8575 .await
8576 .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
8577 };
8578
8579 Ok(buffer)
8580 })
8581 }
8582
8583 fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
8584 let project_id = match self.client_state {
8585 ProjectClientState::Remote {
8586 sharing_has_stopped,
8587 remote_id,
8588 ..
8589 } => {
8590 if sharing_has_stopped {
8591 return Task::ready(Err(anyhow!(
8592 "can't synchronize remote buffers on a readonly project"
8593 )));
8594 } else {
8595 remote_id
8596 }
8597 }
8598 ProjectClientState::Shared { .. } | ProjectClientState::Local => {
8599 return Task::ready(Err(anyhow!(
8600 "can't synchronize remote buffers on a local project"
8601 )))
8602 }
8603 };
8604
8605 let client = self.client.clone();
8606 cx.spawn(move |this, mut cx| async move {
8607 let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8608 let buffers = this
8609 .opened_buffers
8610 .iter()
8611 .filter_map(|(id, buffer)| {
8612 let buffer = buffer.upgrade()?;
8613 Some(proto::BufferVersion {
8614 id: (*id).into(),
8615 version: language::proto::serialize_version(&buffer.read(cx).version),
8616 })
8617 })
8618 .collect();
8619 let incomplete_buffer_ids = this
8620 .incomplete_remote_buffers
8621 .keys()
8622 .copied()
8623 .collect::<Vec<_>>();
8624
8625 (buffers, incomplete_buffer_ids)
8626 })?;
8627 let response = client
8628 .request(proto::SynchronizeBuffers {
8629 project_id,
8630 buffers,
8631 })
8632 .await?;
8633
8634 let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8635 response
8636 .buffers
8637 .into_iter()
8638 .map(|buffer| {
8639 let client = client.clone();
8640 let buffer_id = match BufferId::new(buffer.id) {
8641 Ok(id) => id,
8642 Err(e) => {
8643 return Task::ready(Err(e));
8644 }
8645 };
8646 let remote_version = language::proto::deserialize_version(&buffer.version);
8647 if let Some(buffer) = this.buffer_for_id(buffer_id) {
8648 let operations =
8649 buffer.read(cx).serialize_ops(Some(remote_version), cx);
8650 cx.background_executor().spawn(async move {
8651 let operations = operations.await;
8652 for chunk in split_operations(operations) {
8653 client
8654 .request(proto::UpdateBuffer {
8655 project_id,
8656 buffer_id: buffer_id.into(),
8657 operations: chunk,
8658 })
8659 .await?;
8660 }
8661 anyhow::Ok(())
8662 })
8663 } else {
8664 Task::ready(Ok(()))
8665 }
8666 })
8667 .collect::<Vec<_>>()
8668 })?;
8669
8670 // Any incomplete buffers have open requests waiting. Request that the host sends
8671 // creates these buffers for us again to unblock any waiting futures.
8672 for id in incomplete_buffer_ids {
8673 cx.background_executor()
8674 .spawn(client.request(proto::OpenBufferById {
8675 project_id,
8676 id: id.into(),
8677 }))
8678 .detach();
8679 }
8680
8681 futures::future::join_all(send_updates_for_buffers)
8682 .await
8683 .into_iter()
8684 .collect()
8685 })
8686 }
8687
8688 pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8689 self.worktrees()
8690 .map(|worktree| {
8691 let worktree = worktree.read(cx);
8692 proto::WorktreeMetadata {
8693 id: worktree.id().to_proto(),
8694 root_name: worktree.root_name().into(),
8695 visible: worktree.is_visible(),
8696 abs_path: worktree.abs_path().to_string_lossy().into(),
8697 }
8698 })
8699 .collect()
8700 }
8701
8702 fn set_worktrees_from_proto(
8703 &mut self,
8704 worktrees: Vec<proto::WorktreeMetadata>,
8705 cx: &mut ModelContext<Project>,
8706 ) -> Result<()> {
8707 let replica_id = self.replica_id();
8708 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8709
8710 let mut old_worktrees_by_id = self
8711 .worktrees
8712 .drain(..)
8713 .filter_map(|worktree| {
8714 let worktree = worktree.upgrade()?;
8715 Some((worktree.read(cx).id(), worktree))
8716 })
8717 .collect::<HashMap<_, _>>();
8718
8719 for worktree in worktrees {
8720 if let Some(old_worktree) =
8721 old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8722 {
8723 self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8724 } else {
8725 let worktree =
8726 Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8727 let _ = self.add_worktree(&worktree, cx);
8728 }
8729 }
8730
8731 self.metadata_changed(cx);
8732 for id in old_worktrees_by_id.keys() {
8733 cx.emit(Event::WorktreeRemoved(*id));
8734 }
8735
8736 Ok(())
8737 }
8738
8739 fn set_collaborators_from_proto(
8740 &mut self,
8741 messages: Vec<proto::Collaborator>,
8742 cx: &mut ModelContext<Self>,
8743 ) -> Result<()> {
8744 let mut collaborators = HashMap::default();
8745 for message in messages {
8746 let collaborator = Collaborator::from_proto(message)?;
8747 collaborators.insert(collaborator.peer_id, collaborator);
8748 }
8749 for old_peer_id in self.collaborators.keys() {
8750 if !collaborators.contains_key(old_peer_id) {
8751 cx.emit(Event::CollaboratorLeft(*old_peer_id));
8752 }
8753 }
8754 self.collaborators = collaborators;
8755 Ok(())
8756 }
8757
8758 fn deserialize_symbol(
8759 &self,
8760 serialized_symbol: proto::Symbol,
8761 ) -> impl Future<Output = Result<Symbol>> {
8762 let languages = self.languages.clone();
8763 async move {
8764 let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8765 let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8766 let start = serialized_symbol
8767 .start
8768 .ok_or_else(|| anyhow!("invalid start"))?;
8769 let end = serialized_symbol
8770 .end
8771 .ok_or_else(|| anyhow!("invalid end"))?;
8772 let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8773 let path = ProjectPath {
8774 worktree_id,
8775 path: PathBuf::from(serialized_symbol.path).into(),
8776 };
8777 let language = languages
8778 .language_for_file(&path.path, None)
8779 .await
8780 .log_err();
8781 let adapter = language
8782 .as_ref()
8783 .and_then(|language| languages.lsp_adapters(language).first().cloned());
8784 Ok(Symbol {
8785 language_server_name: LanguageServerName(
8786 serialized_symbol.language_server_name.into(),
8787 ),
8788 source_worktree_id,
8789 path,
8790 label: {
8791 match language.as_ref().zip(adapter.as_ref()) {
8792 Some((language, adapter)) => {
8793 adapter
8794 .label_for_symbol(&serialized_symbol.name, kind, language)
8795 .await
8796 }
8797 None => None,
8798 }
8799 .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8800 },
8801
8802 name: serialized_symbol.name,
8803 range: Unclipped(PointUtf16::new(start.row, start.column))
8804 ..Unclipped(PointUtf16::new(end.row, end.column)),
8805 kind,
8806 signature: serialized_symbol
8807 .signature
8808 .try_into()
8809 .map_err(|_| anyhow!("invalid signature"))?,
8810 })
8811 }
8812 }
8813
8814 async fn handle_buffer_saved(
8815 this: Model<Self>,
8816 envelope: TypedEnvelope<proto::BufferSaved>,
8817 _: Arc<Client>,
8818 mut cx: AsyncAppContext,
8819 ) -> Result<()> {
8820 let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8821 let version = deserialize_version(&envelope.payload.version);
8822 let buffer_id = BufferId::new(envelope.payload.buffer_id)?;
8823 let mtime = envelope
8824 .payload
8825 .mtime
8826 .ok_or_else(|| anyhow!("missing mtime"))?
8827 .into();
8828
8829 this.update(&mut cx, |this, cx| {
8830 let buffer = this
8831 .opened_buffers
8832 .get(&buffer_id)
8833 .and_then(|buffer| buffer.upgrade())
8834 .or_else(|| {
8835 this.incomplete_remote_buffers
8836 .get(&buffer_id)
8837 .and_then(|b| b.clone())
8838 });
8839 if let Some(buffer) = buffer {
8840 buffer.update(cx, |buffer, cx| {
8841 buffer.did_save(version, fingerprint, mtime, cx);
8842 });
8843 }
8844 Ok(())
8845 })?
8846 }
8847
8848 async fn handle_buffer_reloaded(
8849 this: Model<Self>,
8850 envelope: TypedEnvelope<proto::BufferReloaded>,
8851 _: Arc<Client>,
8852 mut cx: AsyncAppContext,
8853 ) -> Result<()> {
8854 let payload = envelope.payload;
8855 let version = deserialize_version(&payload.version);
8856 let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8857 let line_ending = deserialize_line_ending(
8858 proto::LineEnding::from_i32(payload.line_ending)
8859 .ok_or_else(|| anyhow!("missing line ending"))?,
8860 );
8861 let mtime = payload
8862 .mtime
8863 .ok_or_else(|| anyhow!("missing mtime"))?
8864 .into();
8865 let buffer_id = BufferId::new(payload.buffer_id)?;
8866 this.update(&mut cx, |this, cx| {
8867 let buffer = this
8868 .opened_buffers
8869 .get(&buffer_id)
8870 .and_then(|buffer| buffer.upgrade())
8871 .or_else(|| {
8872 this.incomplete_remote_buffers
8873 .get(&buffer_id)
8874 .cloned()
8875 .flatten()
8876 });
8877 if let Some(buffer) = buffer {
8878 buffer.update(cx, |buffer, cx| {
8879 buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8880 });
8881 }
8882 Ok(())
8883 })?
8884 }
8885
8886 #[allow(clippy::type_complexity)]
8887 fn edits_from_lsp(
8888 &mut self,
8889 buffer: &Model<Buffer>,
8890 lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8891 server_id: LanguageServerId,
8892 version: Option<i32>,
8893 cx: &mut ModelContext<Self>,
8894 ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8895 let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8896 cx.background_executor().spawn(async move {
8897 let snapshot = snapshot?;
8898 let mut lsp_edits = lsp_edits
8899 .into_iter()
8900 .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8901 .collect::<Vec<_>>();
8902 lsp_edits.sort_by_key(|(range, _)| range.start);
8903
8904 let mut lsp_edits = lsp_edits.into_iter().peekable();
8905 let mut edits = Vec::new();
8906 while let Some((range, mut new_text)) = lsp_edits.next() {
8907 // Clip invalid ranges provided by the language server.
8908 let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8909 ..snapshot.clip_point_utf16(range.end, Bias::Left);
8910
8911 // Combine any LSP edits that are adjacent.
8912 //
8913 // Also, combine LSP edits that are separated from each other by only
8914 // a newline. This is important because for some code actions,
8915 // Rust-analyzer rewrites the entire buffer via a series of edits that
8916 // are separated by unchanged newline characters.
8917 //
8918 // In order for the diffing logic below to work properly, any edits that
8919 // cancel each other out must be combined into one.
8920 while let Some((next_range, next_text)) = lsp_edits.peek() {
8921 if next_range.start.0 > range.end {
8922 if next_range.start.0.row > range.end.row + 1
8923 || next_range.start.0.column > 0
8924 || snapshot.clip_point_utf16(
8925 Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8926 Bias::Left,
8927 ) > range.end
8928 {
8929 break;
8930 }
8931 new_text.push('\n');
8932 }
8933 range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8934 new_text.push_str(next_text);
8935 lsp_edits.next();
8936 }
8937
8938 // For multiline edits, perform a diff of the old and new text so that
8939 // we can identify the changes more precisely, preserving the locations
8940 // of any anchors positioned in the unchanged regions.
8941 if range.end.row > range.start.row {
8942 let mut offset = range.start.to_offset(&snapshot);
8943 let old_text = snapshot.text_for_range(range).collect::<String>();
8944
8945 let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8946 let mut moved_since_edit = true;
8947 for change in diff.iter_all_changes() {
8948 let tag = change.tag();
8949 let value = change.value();
8950 match tag {
8951 ChangeTag::Equal => {
8952 offset += value.len();
8953 moved_since_edit = true;
8954 }
8955 ChangeTag::Delete => {
8956 let start = snapshot.anchor_after(offset);
8957 let end = snapshot.anchor_before(offset + value.len());
8958 if moved_since_edit {
8959 edits.push((start..end, String::new()));
8960 } else {
8961 edits.last_mut().unwrap().0.end = end;
8962 }
8963 offset += value.len();
8964 moved_since_edit = false;
8965 }
8966 ChangeTag::Insert => {
8967 if moved_since_edit {
8968 let anchor = snapshot.anchor_after(offset);
8969 edits.push((anchor..anchor, value.to_string()));
8970 } else {
8971 edits.last_mut().unwrap().1.push_str(value);
8972 }
8973 moved_since_edit = false;
8974 }
8975 }
8976 }
8977 } else if range.end == range.start {
8978 let anchor = snapshot.anchor_after(range.start);
8979 edits.push((anchor..anchor, new_text));
8980 } else {
8981 let edit_start = snapshot.anchor_after(range.start);
8982 let edit_end = snapshot.anchor_before(range.end);
8983 edits.push((edit_start..edit_end, new_text));
8984 }
8985 }
8986
8987 Ok(edits)
8988 })
8989 }
8990
8991 fn buffer_snapshot_for_lsp_version(
8992 &mut self,
8993 buffer: &Model<Buffer>,
8994 server_id: LanguageServerId,
8995 version: Option<i32>,
8996 cx: &AppContext,
8997 ) -> Result<TextBufferSnapshot> {
8998 const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8999
9000 if let Some(version) = version {
9001 let buffer_id = buffer.read(cx).remote_id();
9002 let snapshots = self
9003 .buffer_snapshots
9004 .get_mut(&buffer_id)
9005 .and_then(|m| m.get_mut(&server_id))
9006 .ok_or_else(|| {
9007 anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
9008 })?;
9009
9010 let found_snapshot = snapshots
9011 .binary_search_by_key(&version, |e| e.version)
9012 .map(|ix| snapshots[ix].snapshot.clone())
9013 .map_err(|_| {
9014 anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
9015 })?;
9016
9017 snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
9018 Ok(found_snapshot)
9019 } else {
9020 Ok((buffer.read(cx)).text_snapshot())
9021 }
9022 }
9023
9024 pub fn language_servers(
9025 &self,
9026 ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
9027 self.language_server_ids
9028 .iter()
9029 .map(|((worktree_id, server_name), server_id)| {
9030 (*server_id, server_name.clone(), *worktree_id)
9031 })
9032 }
9033
9034 pub fn supplementary_language_servers(
9035 &self,
9036 ) -> impl '_
9037 + Iterator<
9038 Item = (
9039 &LanguageServerId,
9040 &(LanguageServerName, Arc<LanguageServer>),
9041 ),
9042 > {
9043 self.supplementary_language_servers.iter()
9044 }
9045
9046 pub fn language_server_adapter_for_id(
9047 &self,
9048 id: LanguageServerId,
9049 ) -> Option<Arc<CachedLspAdapter>> {
9050 if let Some(LanguageServerState::Running { adapter, .. }) = self.language_servers.get(&id) {
9051 Some(adapter.clone())
9052 } else {
9053 None
9054 }
9055 }
9056
9057 pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
9058 if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
9059 Some(server.clone())
9060 } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
9061 Some(Arc::clone(server))
9062 } else {
9063 None
9064 }
9065 }
9066
9067 pub fn language_servers_for_buffer(
9068 &self,
9069 buffer: &Buffer,
9070 cx: &AppContext,
9071 ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9072 self.language_server_ids_for_buffer(buffer, cx)
9073 .into_iter()
9074 .filter_map(|server_id| match self.language_servers.get(&server_id)? {
9075 LanguageServerState::Running {
9076 adapter, server, ..
9077 } => Some((adapter, server)),
9078 _ => None,
9079 })
9080 }
9081
9082 fn primary_language_server_for_buffer(
9083 &self,
9084 buffer: &Buffer,
9085 cx: &AppContext,
9086 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9087 self.language_servers_for_buffer(buffer, cx).next()
9088 }
9089
9090 pub fn language_server_for_buffer(
9091 &self,
9092 buffer: &Buffer,
9093 server_id: LanguageServerId,
9094 cx: &AppContext,
9095 ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
9096 self.language_servers_for_buffer(buffer, cx)
9097 .find(|(_, s)| s.server_id() == server_id)
9098 }
9099
9100 fn language_server_ids_for_buffer(
9101 &self,
9102 buffer: &Buffer,
9103 cx: &AppContext,
9104 ) -> Vec<LanguageServerId> {
9105 if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
9106 let worktree_id = file.worktree_id(cx);
9107 self.languages
9108 .lsp_adapters(&language)
9109 .iter()
9110 .flat_map(|adapter| {
9111 let key = (worktree_id, adapter.name.clone());
9112 self.language_server_ids.get(&key).copied()
9113 })
9114 .collect()
9115 } else {
9116 Vec::new()
9117 }
9118 }
9119}
9120
9121fn subscribe_for_copilot_events(
9122 copilot: &Model<Copilot>,
9123 cx: &mut ModelContext<'_, Project>,
9124) -> gpui::Subscription {
9125 cx.subscribe(
9126 copilot,
9127 |project, copilot, copilot_event, cx| match copilot_event {
9128 copilot::Event::CopilotLanguageServerStarted => {
9129 match copilot.read(cx).language_server() {
9130 Some((name, copilot_server)) => {
9131 // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
9132 if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
9133 let new_server_id = copilot_server.server_id();
9134 let weak_project = cx.weak_model();
9135 let copilot_log_subscription = copilot_server
9136 .on_notification::<copilot::request::LogMessage, _>(
9137 move |params, mut cx| {
9138 weak_project.update(&mut cx, |_, cx| {
9139 cx.emit(Event::LanguageServerLog(
9140 new_server_id,
9141 params.message,
9142 ));
9143 }).ok();
9144 },
9145 );
9146 project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
9147 project.copilot_log_subscription = Some(copilot_log_subscription);
9148 cx.emit(Event::LanguageServerAdded(new_server_id));
9149 }
9150 }
9151 None => debug_panic!("Received Copilot language server started event, but no language server is running"),
9152 }
9153 }
9154 },
9155 )
9156}
9157
9158fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
9159 let mut literal_end = 0;
9160 for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
9161 if part.contains(&['*', '?', '{', '}']) {
9162 break;
9163 } else {
9164 if i > 0 {
9165 // Account for separator prior to this part
9166 literal_end += path::MAIN_SEPARATOR.len_utf8();
9167 }
9168 literal_end += part.len();
9169 }
9170 }
9171 &glob[..literal_end]
9172}
9173
9174impl WorktreeHandle {
9175 pub fn upgrade(&self) -> Option<Model<Worktree>> {
9176 match self {
9177 WorktreeHandle::Strong(handle) => Some(handle.clone()),
9178 WorktreeHandle::Weak(handle) => handle.upgrade(),
9179 }
9180 }
9181
9182 pub fn handle_id(&self) -> usize {
9183 match self {
9184 WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
9185 WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
9186 }
9187 }
9188}
9189
9190impl OpenBuffer {
9191 pub fn upgrade(&self) -> Option<Model<Buffer>> {
9192 match self {
9193 OpenBuffer::Strong(handle) => Some(handle.clone()),
9194 OpenBuffer::Weak(handle) => handle.upgrade(),
9195 OpenBuffer::Operations(_) => None,
9196 }
9197 }
9198}
9199
9200pub struct PathMatchCandidateSet {
9201 pub snapshot: Snapshot,
9202 pub include_ignored: bool,
9203 pub include_root_name: bool,
9204}
9205
9206impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
9207 type Candidates = PathMatchCandidateSetIter<'a>;
9208
9209 fn id(&self) -> usize {
9210 self.snapshot.id().to_usize()
9211 }
9212
9213 fn len(&self) -> usize {
9214 if self.include_ignored {
9215 self.snapshot.file_count()
9216 } else {
9217 self.snapshot.visible_file_count()
9218 }
9219 }
9220
9221 fn prefix(&self) -> Arc<str> {
9222 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
9223 self.snapshot.root_name().into()
9224 } else if self.include_root_name {
9225 format!("{}/", self.snapshot.root_name()).into()
9226 } else {
9227 "".into()
9228 }
9229 }
9230
9231 fn candidates(&'a self, start: usize) -> Self::Candidates {
9232 PathMatchCandidateSetIter {
9233 traversal: self.snapshot.files(self.include_ignored, start),
9234 }
9235 }
9236}
9237
9238pub struct PathMatchCandidateSetIter<'a> {
9239 traversal: Traversal<'a>,
9240}
9241
9242impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
9243 type Item = fuzzy::PathMatchCandidate<'a>;
9244
9245 fn next(&mut self) -> Option<Self::Item> {
9246 self.traversal.next().map(|entry| {
9247 if let EntryKind::File(char_bag) = entry.kind {
9248 fuzzy::PathMatchCandidate {
9249 path: &entry.path,
9250 char_bag,
9251 }
9252 } else {
9253 unreachable!()
9254 }
9255 })
9256 }
9257}
9258
9259impl EventEmitter<Event> for Project {}
9260
9261impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
9262 fn from((worktree_id, path): (WorktreeId, P)) -> Self {
9263 Self {
9264 worktree_id,
9265 path: path.as_ref().into(),
9266 }
9267 }
9268}
9269
9270struct ProjectLspAdapterDelegate {
9271 project: Model<Project>,
9272 worktree: worktree::Snapshot,
9273 fs: Arc<dyn Fs>,
9274 http_client: Arc<dyn HttpClient>,
9275 language_registry: Arc<LanguageRegistry>,
9276}
9277
9278impl ProjectLspAdapterDelegate {
9279 fn new(project: &Project, worktree: &Model<Worktree>, cx: &ModelContext<Project>) -> Arc<Self> {
9280 Arc::new(Self {
9281 project: cx.handle(),
9282 worktree: worktree.read(cx).snapshot(),
9283 fs: project.fs.clone(),
9284 http_client: project.client.http_client(),
9285 language_registry: project.languages.clone(),
9286 })
9287 }
9288}
9289
9290#[async_trait]
9291impl LspAdapterDelegate for ProjectLspAdapterDelegate {
9292 fn show_notification(&self, message: &str, cx: &mut AppContext) {
9293 self.project
9294 .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
9295 }
9296
9297 fn http_client(&self) -> Arc<dyn HttpClient> {
9298 self.http_client.clone()
9299 }
9300
9301 async fn which_command(&self, command: OsString) -> Option<(PathBuf, HashMap<String, String>)> {
9302 let worktree_abs_path = self.worktree.abs_path();
9303
9304 let shell_env = load_shell_environment(&worktree_abs_path)
9305 .await
9306 .with_context(|| {
9307 format!("failed to determine load login shell environment in {worktree_abs_path:?}")
9308 })
9309 .log_err();
9310
9311 if let Some(shell_env) = shell_env {
9312 let shell_path = shell_env.get("PATH");
9313 match which::which_in(&command, shell_path, &worktree_abs_path) {
9314 Ok(command_path) => Some((command_path, shell_env)),
9315 Err(error) => {
9316 log::warn!(
9317 "failed to determine path for command {:?} in shell PATH {:?}: {error}",
9318 command.to_string_lossy(),
9319 shell_path.map(String::as_str).unwrap_or("")
9320 );
9321 None
9322 }
9323 }
9324 } else {
9325 None
9326 }
9327 }
9328
9329 fn update_status(
9330 &self,
9331 server_name: LanguageServerName,
9332 status: language::LanguageServerBinaryStatus,
9333 ) {
9334 self.language_registry
9335 .update_lsp_status(server_name, status);
9336 }
9337
9338 async fn read_text_file(&self, path: PathBuf) -> Result<String> {
9339 if self.worktree.entry_for_path(&path).is_none() {
9340 return Err(anyhow!("no such path {path:?}"));
9341 }
9342 let path = self.worktree.absolutize(path.as_ref())?;
9343 let content = self.fs.load(&path).await?;
9344 Ok(content)
9345 }
9346}
9347
9348fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9349 proto::Symbol {
9350 language_server_name: symbol.language_server_name.0.to_string(),
9351 source_worktree_id: symbol.source_worktree_id.to_proto(),
9352 worktree_id: symbol.path.worktree_id.to_proto(),
9353 path: symbol.path.path.to_string_lossy().to_string(),
9354 name: symbol.name.clone(),
9355 kind: unsafe { mem::transmute(symbol.kind) },
9356 start: Some(proto::PointUtf16 {
9357 row: symbol.range.start.0.row,
9358 column: symbol.range.start.0.column,
9359 }),
9360 end: Some(proto::PointUtf16 {
9361 row: symbol.range.end.0.row,
9362 column: symbol.range.end.0.column,
9363 }),
9364 signature: symbol.signature.to_vec(),
9365 }
9366}
9367
9368fn relativize_path(base: &Path, path: &Path) -> PathBuf {
9369 let mut path_components = path.components();
9370 let mut base_components = base.components();
9371 let mut components: Vec<Component> = Vec::new();
9372 loop {
9373 match (path_components.next(), base_components.next()) {
9374 (None, None) => break,
9375 (Some(a), None) => {
9376 components.push(a);
9377 components.extend(path_components.by_ref());
9378 break;
9379 }
9380 (None, _) => components.push(Component::ParentDir),
9381 (Some(a), Some(b)) if components.is_empty() && a == b => (),
9382 (Some(a), Some(Component::CurDir)) => components.push(a),
9383 (Some(a), Some(_)) => {
9384 components.push(Component::ParentDir);
9385 for _ in base_components {
9386 components.push(Component::ParentDir);
9387 }
9388 components.push(a);
9389 components.extend(path_components.by_ref());
9390 break;
9391 }
9392 }
9393 }
9394 components.iter().map(|c| c.as_os_str()).collect()
9395}
9396
9397fn resolve_path(base: &Path, path: &Path) -> PathBuf {
9398 let mut result = base.to_path_buf();
9399 for component in path.components() {
9400 match component {
9401 Component::ParentDir => {
9402 result.pop();
9403 }
9404 Component::CurDir => (),
9405 _ => result.push(component),
9406 }
9407 }
9408 result
9409}
9410
9411impl Item for Buffer {
9412 fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
9413 File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
9414 }
9415
9416 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
9417 File::from_dyn(self.file()).map(|file| ProjectPath {
9418 worktree_id: file.worktree_id(cx),
9419 path: file.path().clone(),
9420 })
9421 }
9422}
9423
9424async fn wait_for_loading_buffer(
9425 mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
9426) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
9427 loop {
9428 if let Some(result) = receiver.borrow().as_ref() {
9429 match result {
9430 Ok(buffer) => return Ok(buffer.to_owned()),
9431 Err(e) => return Err(e.to_owned()),
9432 }
9433 }
9434 receiver.next().await;
9435 }
9436}
9437
9438fn include_text(server: &lsp::LanguageServer) -> bool {
9439 server
9440 .capabilities()
9441 .text_document_sync
9442 .as_ref()
9443 .and_then(|sync| match sync {
9444 lsp::TextDocumentSyncCapability::Kind(_) => None,
9445 lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9446 })
9447 .and_then(|save_options| match save_options {
9448 lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9449 lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9450 })
9451 .unwrap_or(false)
9452}
9453
9454async fn load_shell_environment(dir: &Path) -> Result<HashMap<String, String>> {
9455 let marker = "ZED_SHELL_START";
9456 let shell = env::var("SHELL").context(
9457 "SHELL environment variable is not assigned so we can't source login environment variables",
9458 )?;
9459 let output = smol::process::Command::new(&shell)
9460 .args([
9461 "-i",
9462 "-c",
9463 // What we're doing here is to spawn a shell and then `cd` into
9464 // the project directory to get the env in there as if the user
9465 // `cd`'d into it. We do that because tools like direnv, asdf, ...
9466 // hook into `cd` and only set up the env after that.
9467 //
9468 // The `exit 0` is the result of hours of debugging, trying to find out
9469 // why running this command here, without `exit 0`, would mess
9470 // up signal process for our process so that `ctrl-c` doesn't work
9471 // anymore.
9472 // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'` would
9473 // do that, but it does, and `exit 0` helps.
9474 &format!("cd {dir:?}; echo {marker}; /usr/bin/env -0; exit 0;"),
9475 ])
9476 .output()
9477 .await
9478 .context("failed to spawn login shell to source login environment variables")?;
9479
9480 anyhow::ensure!(
9481 output.status.success(),
9482 "login shell exited with error {:?}",
9483 output.status
9484 );
9485
9486 let stdout = String::from_utf8_lossy(&output.stdout);
9487 let env_output_start = stdout.find(marker).ok_or_else(|| {
9488 anyhow!(
9489 "failed to parse output of `env` command in login shell: {}",
9490 stdout
9491 )
9492 })?;
9493
9494 let mut parsed_env = HashMap::default();
9495 let env_output = &stdout[env_output_start + marker.len()..];
9496 for line in env_output.split_terminator('\0') {
9497 if let Some(separator_index) = line.find('=') {
9498 let key = line[..separator_index].to_string();
9499 let value = line[separator_index + 1..].to_string();
9500 parsed_env.insert(key, value);
9501 }
9502 }
9503 Ok(parsed_env)
9504}