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