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