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