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