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