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