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