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